xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision 15e6edf145a9c2bb0e0272cf8debe823bb97529b)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #pragma ident	"%Z%%M%	%I%	%E% SMI"
29 
30 #include <sys/types.h>
31 #include <sys/stream.h>
32 #include <sys/dlpi.h>
33 #include <sys/stropts.h>
34 #include <sys/sysmacros.h>
35 #include <sys/strsubr.h>
36 #include <sys/strlog.h>
37 #include <sys/strsun.h>
38 #include <sys/zone.h>
39 #define	_SUN_TPI_VERSION 2
40 #include <sys/tihdr.h>
41 #include <sys/xti_inet.h>
42 #include <sys/ddi.h>
43 #include <sys/sunddi.h>
44 #include <sys/cmn_err.h>
45 #include <sys/debug.h>
46 #include <sys/kobj.h>
47 #include <sys/modctl.h>
48 #include <sys/atomic.h>
49 #include <sys/policy.h>
50 #include <sys/priv.h>
51 
52 #include <sys/systm.h>
53 #include <sys/param.h>
54 #include <sys/kmem.h>
55 #include <sys/sdt.h>
56 #include <sys/socket.h>
57 #include <sys/vtrace.h>
58 #include <sys/isa_defs.h>
59 #include <sys/mac.h>
60 #include <net/if.h>
61 #include <net/if_arp.h>
62 #include <net/route.h>
63 #include <sys/sockio.h>
64 #include <netinet/in.h>
65 #include <net/if_dl.h>
66 
67 #include <inet/common.h>
68 #include <inet/mi.h>
69 #include <inet/mib2.h>
70 #include <inet/nd.h>
71 #include <inet/arp.h>
72 #include <inet/snmpcom.h>
73 #include <inet/optcom.h>
74 #include <inet/kstatcom.h>
75 
76 #include <netinet/igmp_var.h>
77 #include <netinet/ip6.h>
78 #include <netinet/icmp6.h>
79 #include <netinet/sctp.h>
80 
81 #include <inet/ip.h>
82 #include <inet/ip_impl.h>
83 #include <inet/ip6.h>
84 #include <inet/ip6_asp.h>
85 #include <inet/tcp.h>
86 #include <inet/tcp_impl.h>
87 #include <inet/ip_multi.h>
88 #include <inet/ip_if.h>
89 #include <inet/ip_ire.h>
90 #include <inet/ip_ftable.h>
91 #include <inet/ip_rts.h>
92 #include <inet/ip_ndp.h>
93 #include <inet/ip_listutils.h>
94 #include <netinet/igmp.h>
95 #include <netinet/ip_mroute.h>
96 #include <inet/ipp_common.h>
97 
98 #include <net/pfkeyv2.h>
99 #include <inet/ipsec_info.h>
100 #include <inet/sadb.h>
101 #include <inet/ipsec_impl.h>
102 #include <sys/iphada.h>
103 #include <inet/tun.h>
104 #include <inet/ipdrop.h>
105 #include <inet/ip_netinfo.h>
106 
107 #include <sys/ethernet.h>
108 #include <net/if_types.h>
109 #include <sys/cpuvar.h>
110 
111 #include <ipp/ipp.h>
112 #include <ipp/ipp_impl.h>
113 #include <ipp/ipgpc/ipgpc.h>
114 
115 #include <sys/multidata.h>
116 #include <sys/pattr.h>
117 
118 #include <inet/ipclassifier.h>
119 #include <inet/sctp_ip.h>
120 #include <inet/sctp/sctp_impl.h>
121 #include <inet/udp_impl.h>
122 #include <inet/rawip_impl.h>
123 #include <inet/rts_impl.h>
124 #include <sys/sunddi.h>
125 
126 #include <sys/tsol/label.h>
127 #include <sys/tsol/tnet.h>
128 
129 #include <rpc/pmap_prot.h>
130 
131 /*
132  * Values for squeue switch:
133  * IP_SQUEUE_ENTER_NODRAIN: squeue_enter_nodrain
134  * IP_SQUEUE_ENTER: squeue_enter
135  * IP_SQUEUE_FILL: squeue_fill
136  */
137 int ip_squeue_enter = 2;	/* Setable in /etc/system */
138 
139 squeue_func_t ip_input_proc;
140 #define	SET_BPREV_FLAG(x)	((mblk_t *)(uintptr_t)(x))
141 
142 /*
143  * Setable in /etc/system
144  */
145 int ip_poll_normal_ms = 100;
146 int ip_poll_normal_ticks = 0;
147 int ip_modclose_ackwait_ms = 3000;
148 
149 /*
150  * It would be nice to have these present only in DEBUG systems, but the
151  * current design of the global symbol checking logic requires them to be
152  * unconditionally present.
153  */
154 uint_t ip_thread_data;			/* TSD key for debug support */
155 krwlock_t ip_thread_rwlock;
156 list_t	ip_thread_list;
157 
158 /*
159  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
160  */
161 
162 struct listptr_s {
163 	mblk_t	*lp_head;	/* pointer to the head of the list */
164 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
165 };
166 
167 typedef struct listptr_s listptr_t;
168 
169 /*
170  * This is used by ip_snmp_get_mib2_ip_route_media and
171  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
172  */
173 typedef struct iproutedata_s {
174 	uint_t		ird_idx;
175 	listptr_t	ird_route;	/* ipRouteEntryTable */
176 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
177 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
178 } iproutedata_t;
179 
180 /*
181  * Cluster specific hooks. These should be NULL when booted as a non-cluster
182  */
183 
184 /*
185  * Hook functions to enable cluster networking
186  * On non-clustered systems these vectors must always be NULL.
187  *
188  * Hook function to Check ip specified ip address is a shared ip address
189  * in the cluster
190  *
191  */
192 int (*cl_inet_isclusterwide)(uint8_t protocol,
193     sa_family_t addr_family, uint8_t *laddrp) = NULL;
194 
195 /*
196  * Hook function to generate cluster wide ip fragment identifier
197  */
198 uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
199     uint8_t *laddrp, uint8_t *faddrp) = NULL;
200 
201 /*
202  * Synchronization notes:
203  *
204  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
205  * MT level protection given by STREAMS. IP uses a combination of its own
206  * internal serialization mechanism and standard Solaris locking techniques.
207  * The internal serialization is per phyint (no IPMP) or per IPMP group.
208  * This is used to serialize plumbing operations, IPMP operations, certain
209  * multicast operations, most set ioctls, igmp/mld timers etc.
210  *
211  * Plumbing is a long sequence of operations involving message
212  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
213  * involved in plumbing operations. A natural model is to serialize these
214  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
215  * parallel without any interference. But various set ioctls on hme0 are best
216  * serialized. However if the system uses IPMP, the operations are easier if
217  * they are serialized on a per IPMP group basis since IPMP operations
218  * happen across ill's of a group. Thus the lowest common denominator is to
219  * serialize most set ioctls, multicast join/leave operations, IPMP operations
220  * igmp/mld timer operations, and processing of DLPI control messages received
221  * from drivers on a per IPMP group basis. If the system does not employ
222  * IPMP the serialization is on a per phyint basis. This serialization is
223  * provided by the ipsq_t and primitives operating on this. Details can
224  * be found in ip_if.c above the core primitives operating on ipsq_t.
225  *
226  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
227  * Simiarly lookup of an ire by a thread also returns a refheld ire.
228  * In addition ipif's and ill's referenced by the ire are also indirectly
229  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
230  * the ipif's address or netmask change as long as an ipif is refheld
231  * directly or indirectly. For example an SIOCLIFADDR ioctl that changes the
232  * address of an ipif has to go through the ipsq_t. This ensures that only
233  * 1 such exclusive operation proceeds at any time on the ipif. It then
234  * deletes all ires associated with this ipif, and waits for all refcnts
235  * associated with this ipif to come down to zero. The address is changed
236  * only after the ipif has been quiesced. Then the ipif is brought up again.
237  * More details are described above the comment in ip_sioctl_flags.
238  *
239  * Packet processing is based mostly on IREs and are fully multi-threaded
240  * using standard Solaris MT techniques.
241  *
242  * There are explicit locks in IP to handle:
243  * - The ip_g_head list maintained by mi_open_link() and friends.
244  *
245  * - The reassembly data structures (one lock per hash bucket)
246  *
247  * - conn_lock is meant to protect conn_t fields. The fields actually
248  *   protected by conn_lock are documented in the conn_t definition.
249  *
250  * - ire_lock to protect some of the fields of the ire, IRE tables
251  *   (one lock per hash bucket). Refer to ip_ire.c for details.
252  *
253  * - ndp_g_lock and nce_lock for protecting NCEs.
254  *
255  * - ill_lock protects fields of the ill and ipif. Details in ip.h
256  *
257  * - ill_g_lock: This is a global reader/writer lock. Protects the following
258  *	* The AVL tree based global multi list of all ills.
259  *	* The linked list of all ipifs of an ill
260  *	* The <ill-ipsq> mapping
261  *	* The ipsq->ipsq_phyint_list threaded by phyint_ipsq_next
262  *	* The illgroup list threaded by ill_group_next.
263  *	* <ill-phyint> association
264  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
265  *   into an ill, changing the <ill-ipsq> mapping of an ill, insertion/deletion
266  *   of an ill into the illgrp list, changing the <ill-phyint> assoc of an ill
267  *   will all have to hold the ill_g_lock as writer for the actual duration
268  *   of the insertion/deletion/change. More details about the <ill-ipsq> mapping
269  *   may be found in the IPMP section.
270  *
271  * - ill_lock:  This is a per ill mutex.
272  *   It protects some members of the ill and is documented below.
273  *   It also protects the <ill-ipsq> mapping
274  *   It also protects the illgroup list threaded by ill_group_next.
275  *   It also protects the <ill-phyint> assoc.
276  *   It also protects the list of ipifs hanging off the ill.
277  *
278  * - ipsq_lock: This is a per ipsq_t mutex lock.
279  *   This protects all the other members of the ipsq struct except
280  *   ipsq_refs and ipsq_phyint_list which are protected by ill_g_lock
281  *
282  * - illgrp_lock: This is a per ill_group mutex lock.
283  *   The only thing it protects is the illgrp_ill_schednext member of ill_group
284  *   which dictates which is the next ill in an ill_group that is to be chosen
285  *   for sending outgoing packets, through creation of an IRE_CACHE that
286  *   references this ill.
287  *
288  * - phyint_lock: This is a per phyint mutex lock. Protects just the
289  *   phyint_flags
290  *
291  * - ip_g_nd_lock: This is a global reader/writer lock.
292  *   Any call to nd_load to load a new parameter to the ND table must hold the
293  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
294  *   as reader.
295  *
296  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
297  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
298  *   uniqueness check also done atomically.
299  *
300  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
301  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
302  *   as a writer when adding or deleting elements from these lists, and
303  *   as a reader when walking these lists to send a SADB update to the
304  *   IPsec capable ills.
305  *
306  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
307  *   group list linked by ill_usesrc_grp_next. It also protects the
308  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
309  *   group is being added or deleted.  This lock is taken as a reader when
310  *   walking the list/group(eg: to get the number of members in a usesrc group).
311  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
312  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
313  *   example, it is not necessary to take this lock in the initial portion
314  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_groupname and
315  *   ip_sioctl_flags since the these operations are executed exclusively and
316  *   that ensures that the "usesrc group state" cannot change. The "usesrc
317  *   group state" change can happen only in the latter part of
318  *   ip_sioctl_slifusesrc and in ill_delete.
319  *
320  * Changing <ill-phyint>, <ill-ipsq>, <ill-illgroup> assocications.
321  *
322  * To change the <ill-phyint> association, the ill_g_lock must be held
323  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
324  * must be held.
325  *
326  * To change the <ill-ipsq> association the ill_g_lock must be held as writer
327  * and the ill_lock of the ill in question must be held.
328  *
329  * To change the <ill-illgroup> association the ill_g_lock must be held as
330  * writer and the ill_lock of the ill in question must be held.
331  *
332  * To add or delete an ipif from the list of ipifs hanging off the ill,
333  * ill_g_lock (writer) and ill_lock must be held and the thread must be
334  * a writer on the associated ipsq,.
335  *
336  * To add or delete an ill to the system, the ill_g_lock must be held as
337  * writer and the thread must be a writer on the associated ipsq.
338  *
339  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
340  * must be a writer on the associated ipsq.
341  *
342  * Lock hierarchy
343  *
344  * Some lock hierarchy scenarios are listed below.
345  *
346  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock
347  * ill_g_lock -> illgrp_lock -> ill_lock
348  * ill_g_lock -> ill_lock(s) -> phyint_lock
349  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
350  * ill_g_lock -> ip_addr_avail_lock
351  * conn_lock -> irb_lock -> ill_lock -> ire_lock
352  * ill_g_lock -> ip_g_nd_lock
353  *
354  * When more than 1 ill lock is needed to be held, all ill lock addresses
355  * are sorted on address and locked starting from highest addressed lock
356  * downward.
357  *
358  * IPsec scenarios
359  *
360  * ipsa_lock -> ill_g_lock -> ill_lock
361  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
362  * ipsec_capab_ills_lock -> ipsa_lock
363  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
364  *
365  * Trusted Solaris scenarios
366  *
367  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
368  * igsa_lock -> gcdb_lock
369  * gcgrp_rwlock -> ire_lock
370  * gcgrp_rwlock -> gcdb_lock
371  *
372  *
373  * Routing/forwarding table locking notes:
374  *
375  * Lock acquisition order: Radix tree lock, irb_lock.
376  * Requirements:
377  * i.  Walker must not hold any locks during the walker callback.
378  * ii  Walker must not see a truncated tree during the walk because of any node
379  *     deletion.
380  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
381  *     in many places in the code to walk the irb list. Thus even if all the
382  *     ires in a bucket have been deleted, we still can't free the radix node
383  *     until the ires have actually been inactive'd (freed).
384  *
385  * Tree traversal - Need to hold the global tree lock in read mode.
386  * Before dropping the global tree lock, need to either increment the ire_refcnt
387  * to ensure that the radix node can't be deleted.
388  *
389  * Tree add - Need to hold the global tree lock in write mode to add a
390  * radix node. To prevent the node from being deleted, increment the
391  * irb_refcnt, after the node is added to the tree. The ire itself is
392  * added later while holding the irb_lock, but not the tree lock.
393  *
394  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
395  * All associated ires must be inactive (i.e. freed), and irb_refcnt
396  * must be zero.
397  *
398  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
399  * global tree lock (read mode) for traversal.
400  *
401  * IPsec notes :
402  *
403  * IP interacts with the IPsec code (AH/ESP) by tagging a M_CTL message
404  * in front of the actual packet. For outbound datagrams, the M_CTL
405  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
406  * information used by the IPsec code for applying the right level of
407  * protection. The information initialized by IP in the ipsec_out_t
408  * is determined by the per-socket policy or global policy in the system.
409  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
410  * ipsec_info.h) which starts out with nothing in it. It gets filled
411  * with the right information if it goes through the AH/ESP code, which
412  * happens if the incoming packet is secure. The information initialized
413  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
414  * the policy requirements needed by per-socket policy or global policy
415  * is met or not.
416  *
417  * If there is both per-socket policy (set using setsockopt) and there
418  * is also global policy match for the 5 tuples of the socket,
419  * ipsec_override_policy() makes the decision of which one to use.
420  *
421  * For fully connected sockets i.e dst, src [addr, port] is known,
422  * conn_policy_cached is set indicating that policy has been cached.
423  * conn_in_enforce_policy may or may not be set depending on whether
424  * there is a global policy match or per-socket policy match.
425  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
426  * Once the right policy is set on the conn_t, policy cannot change for
427  * this socket. This makes life simpler for TCP (UDP ?) where
428  * re-transmissions go out with the same policy. For symmetry, policy
429  * is cached for fully connected UDP sockets also. Thus if policy is cached,
430  * it also implies that policy is latched i.e policy cannot change
431  * on these sockets. As we have the right policy on the conn, we don't
432  * have to lookup global policy for every outbound and inbound datagram
433  * and thus serving as an optimization. Note that a global policy change
434  * does not affect fully connected sockets if they have policy. If fully
435  * connected sockets did not have any policy associated with it, global
436  * policy change may affect them.
437  *
438  * IP Flow control notes:
439  *
440  * Non-TCP streams are flow controlled by IP. On the send side, if the packet
441  * cannot be sent down to the driver by IP, because of a canput failure, IP
442  * does a putq on the conn_wq. This will cause ip_wsrv to run on the conn_wq.
443  * ip_wsrv in turn, inserts the conn in a list of conn's that need to be drained
444  * when the flowcontrol condition subsides. Ultimately STREAMS backenables the
445  * ip_wsrv on the IP module, which in turn does a qenable of the conn_wq of the
446  * first conn in the list of conn's to be drained. ip_wsrv on this conn drains
447  * the queued messages, and removes the conn from the drain list, if all
448  * messages were drained. It also qenables the next conn in the drain list to
449  * continue the drain process.
450  *
451  * In reality the drain list is not a single list, but a configurable number
452  * of lists. The ip_wsrv on the IP module, qenables the first conn in each
453  * list. If the ip_wsrv of the next qenabled conn does not run, because the
454  * stream closes, ip_close takes responsibility to qenable the next conn in
455  * the drain list. The directly called ip_wput path always does a putq, if
456  * it cannot putnext. Thus synchronization problems are handled between
457  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
458  * functions that manipulate this drain list. Furthermore conn_drain_insert
459  * is called only from ip_wsrv, and there can be only 1 instance of ip_wsrv
460  * running on a queue at any time. conn_drain_tail can be simultaneously called
461  * from both ip_wsrv and ip_close.
462  *
463  * IPQOS notes:
464  *
465  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
466  * and IPQoS modules. IPPF includes hooks in IP at different control points
467  * (callout positions) which direct packets to IPQoS modules for policy
468  * processing. Policies, if present, are global.
469  *
470  * The callout positions are located in the following paths:
471  *		o local_in (packets destined for this host)
472  *		o local_out (packets orginating from this host )
473  *		o fwd_in  (packets forwarded by this m/c - inbound)
474  *		o fwd_out (packets forwarded by this m/c - outbound)
475  * Hooks at these callout points can be enabled/disabled using the ndd variable
476  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
477  * By default all the callout positions are enabled.
478  *
479  * Outbound (local_out)
480  * Hooks are placed in ip_wput_ire and ipsec_out_process.
481  *
482  * Inbound (local_in)
483  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
484  * TCP and UDP fanout routines.
485  *
486  * Forwarding (in and out)
487  * Hooks are placed in ip_rput_forward.
488  *
489  * IP Policy Framework processing (IPPF processing)
490  * Policy processing for a packet is initiated by ip_process, which ascertains
491  * that the classifier (ipgpc) is loaded and configured, failing which the
492  * packet resumes normal processing in IP. If the clasifier is present, the
493  * packet is acted upon by one or more IPQoS modules (action instances), per
494  * filters configured in ipgpc and resumes normal IP processing thereafter.
495  * An action instance can drop a packet in course of its processing.
496  *
497  * A boolean variable, ip_policy, is used in all the fanout routines that can
498  * invoke ip_process for a packet. This variable indicates if the packet should
499  * to be sent for policy processing. The variable is set to B_TRUE by default,
500  * i.e. when the routines are invoked in the normal ip procesing path for a
501  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
502  * ip_policy is set to B_FALSE for all the routines called in these two
503  * functions because, in the former case,  we don't process loopback traffic
504  * currently while in the latter, the packets have already been processed in
505  * icmp_inbound.
506  *
507  * Zones notes:
508  *
509  * The partitioning rules for networking are as follows:
510  * 1) Packets coming from a zone must have a source address belonging to that
511  * zone.
512  * 2) Packets coming from a zone can only be sent on a physical interface on
513  * which the zone has an IP address.
514  * 3) Between two zones on the same machine, packet delivery is only allowed if
515  * there's a matching route for the destination and zone in the forwarding
516  * table.
517  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
518  * different zones can bind to the same port with the wildcard address
519  * (INADDR_ANY).
520  *
521  * The granularity of interface partitioning is at the logical interface level.
522  * Therefore, every zone has its own IP addresses, and incoming packets can be
523  * attributed to a zone unambiguously. A logical interface is placed into a zone
524  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
525  * structure. Rule (1) is implemented by modifying the source address selection
526  * algorithm so that the list of eligible addresses is filtered based on the
527  * sending process zone.
528  *
529  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
530  * across all zones, depending on their type. Here is the break-up:
531  *
532  * IRE type				Shared/exclusive
533  * --------				----------------
534  * IRE_BROADCAST			Exclusive
535  * IRE_DEFAULT (default routes)		Shared (*)
536  * IRE_LOCAL				Exclusive (x)
537  * IRE_LOOPBACK				Exclusive
538  * IRE_PREFIX (net routes)		Shared (*)
539  * IRE_CACHE				Exclusive
540  * IRE_IF_NORESOLVER (interface routes)	Exclusive
541  * IRE_IF_RESOLVER (interface routes)	Exclusive
542  * IRE_HOST (host routes)		Shared (*)
543  *
544  * (*) A zone can only use a default or off-subnet route if the gateway is
545  * directly reachable from the zone, that is, if the gateway's address matches
546  * one of the zone's logical interfaces.
547  *
548  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
549  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
550  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
551  * address of the zone itself (the destination). Since IRE_LOCAL is used
552  * for communication between zones, ip_wput_ire has special logic to set
553  * the right source address when sending using an IRE_LOCAL.
554  *
555  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
556  * ire_cache_lookup restricts loopback using an IRE_LOCAL
557  * between zone to the case when L2 would have conceptually looped the packet
558  * back, i.e. the loopback which is required since neither Ethernet drivers
559  * nor Ethernet hardware loops them back. This is the case when the normal
560  * routes (ignoring IREs with different zoneids) would send out the packet on
561  * the same ill (or ill group) as the ill with which is IRE_LOCAL is
562  * associated.
563  *
564  * Multiple zones can share a common broadcast address; typically all zones
565  * share the 255.255.255.255 address. Incoming as well as locally originated
566  * broadcast packets must be dispatched to all the zones on the broadcast
567  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
568  * since some zones may not be on the 10.16.72/24 network. To handle this, each
569  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
570  * sent to every zone that has an IRE_BROADCAST entry for the destination
571  * address on the input ill, see conn_wantpacket().
572  *
573  * Applications in different zones can join the same multicast group address.
574  * For IPv4, group memberships are per-logical interface, so they're already
575  * inherently part of a zone. For IPv6, group memberships are per-physical
576  * interface, so we distinguish IPv6 group memberships based on group address,
577  * interface and zoneid. In both cases, received multicast packets are sent to
578  * every zone for which a group membership entry exists. On IPv6 we need to
579  * check that the target zone still has an address on the receiving physical
580  * interface; it could have been removed since the application issued the
581  * IPV6_JOIN_GROUP.
582  */
583 
584 /*
585  * Squeue Fanout flags:
586  *	0: No fanout.
587  *	1: Fanout across all squeues
588  */
589 boolean_t	ip_squeue_fanout = 0;
590 
591 /*
592  * Maximum dups allowed per packet.
593  */
594 uint_t ip_max_frag_dups = 10;
595 
596 #define	IS_SIMPLE_IPH(ipha)						\
597 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
598 
599 /* RFC1122 Conformance */
600 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
601 
602 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
603 
604 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
605 
606 static int	ip_open(queue_t *q, dev_t *devp, int flag, int sflag,
607 		    cred_t *credp, boolean_t isv6);
608 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t,
609 		    ipha_t **);
610 
611 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t,
612 		    ip_stack_t *);
613 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
614 		    uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
615 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
616 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
617 		    mblk_t *, int, ip_stack_t *);
618 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
619 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
620 		    ill_t *, zoneid_t);
621 static void	icmp_options_update(ipha_t *);
622 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t,
623 		    ip_stack_t *);
624 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
625 		    zoneid_t zoneid, ip_stack_t *);
626 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_stack_t *);
627 static void	icmp_redirect(ill_t *, mblk_t *);
628 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t,
629 		    ip_stack_t *);
630 
631 static void	ip_arp_news(queue_t *, mblk_t *);
632 static boolean_t ip_bind_insert_ire(mblk_t *, ire_t *, iulp_t *,
633 		    ip_stack_t *);
634 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
635 char		*ip_dot_addr(ipaddr_t, char *);
636 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
637 int		ip_close(queue_t *, int);
638 static char	*ip_dot_saddr(uchar_t *, char *);
639 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
640 		    boolean_t, boolean_t, ill_t *, zoneid_t);
641 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
642 		    boolean_t, boolean_t, zoneid_t);
643 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
644 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
645 static void	ip_lrput(queue_t *, mblk_t *);
646 ipaddr_t	ip_net_mask(ipaddr_t);
647 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, conn_t *, zoneid_t,
648 		    ip_stack_t *);
649 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
650 		    conn_t *, uint32_t, zoneid_t, ip_opt_info_t *);
651 char		*ip_nv_lookup(nv_t *, int);
652 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
653 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
654 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
655 static boolean_t	ip_param_register(IDP *ndp, ipparam_t *, size_t,
656     ipndp_t *, size_t);
657 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
658 void	ip_rput(queue_t *, mblk_t *);
659 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
660 		    void *dummy_arg);
661 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
662 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *,
663     ip_stack_t *);
664 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
665 			    ire_t *, ip_stack_t *);
666 static boolean_t	ip_rput_multimblk_ipoptions(queue_t *, ill_t *,
667 			    mblk_t *, ipha_t **, ipaddr_t *, ip_stack_t *);
668 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *,
669     ip_stack_t *);
670 static boolean_t ip_rput_fragment(queue_t *, mblk_t **, ipha_t *, uint32_t *,
671 		    uint16_t *);
672 int		ip_snmp_get(queue_t *, mblk_t *, int);
673 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
674 		    mib2_ipIfStatsEntry_t *, ip_stack_t *);
675 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
676 		    ip_stack_t *);
677 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *);
678 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
679 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
680 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
681 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
682 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
683 		    ip_stack_t *ipst);
684 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
685 		    ip_stack_t *ipst);
686 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
687 		    ip_stack_t *ipst);
688 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
689 		    ip_stack_t *ipst);
690 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
691 		    ip_stack_t *ipst);
692 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
693 		    ip_stack_t *ipst);
694 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
695 		    ip_stack_t *ipst);
696 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
697 		    ip_stack_t *ipst);
698 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *,
699 		    ip_stack_t *ipst);
700 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *,
701 		    ip_stack_t *ipst);
702 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
703 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
704 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
705 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
706 static boolean_t	ip_source_routed(ipha_t *, ip_stack_t *);
707 static boolean_t	ip_source_route_included(ipha_t *);
708 static void	ip_trash_ire_reclaim_stack(ip_stack_t *);
709 
710 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
711 		    zoneid_t, ip_stack_t *);
712 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int, ip_stack_t *);
713 static void	ip_wput_local_options(ipha_t *, ip_stack_t *);
714 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
715 		    zoneid_t, ip_stack_t *);
716 
717 static void	conn_drain_init(ip_stack_t *);
718 static void	conn_drain_fini(ip_stack_t *);
719 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
720 
721 static void	conn_walk_drain(ip_stack_t *);
722 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
723     zoneid_t);
724 
725 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
726 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
727 static void	ip_stack_fini(netstackid_t stackid, void *arg);
728 
729 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
730     zoneid_t);
731 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
732     void *dummy_arg);
733 
734 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
735 
736 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
737     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
738     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
739 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
740 
741 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
742 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
743     caddr_t, cred_t *);
744 extern int	ip_squeue_bind_set(queue_t *q, mblk_t *mp, char *value,
745     caddr_t cp, cred_t *cr);
746 extern int	ip_squeue_profile_set(queue_t *, mblk_t *, char *, caddr_t,
747     cred_t *);
748 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
749     caddr_t cp, cred_t *cr);
750 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
751     cred_t *);
752 static int	ipmp_hook_emulation_set(queue_t *, mblk_t *, char *, caddr_t,
753     cred_t *);
754 static squeue_func_t ip_squeue_switch(int);
755 
756 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
757 static void	ip_kstat_fini(netstackid_t, kstat_t *);
758 static int	ip_kstat_update(kstat_t *kp, int rw);
759 static void	*icmp_kstat_init(netstackid_t);
760 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
761 static int	icmp_kstat_update(kstat_t *kp, int rw);
762 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
763 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
764 
765 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
766 
767 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
768     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
769 
770 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
771     ipha_t *, ill_t *, boolean_t);
772 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
773 
774 /* How long, in seconds, we allow frags to hang around. */
775 #define	IP_FRAG_TIMEOUT	60
776 
777 /*
778  * Threshold which determines whether MDT should be used when
779  * generating IP fragments; payload size must be greater than
780  * this threshold for MDT to take place.
781  */
782 #define	IP_WPUT_FRAG_MDT_MIN	32768
783 
784 /* Setable in /etc/system only */
785 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
786 
787 static long ip_rput_pullups;
788 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
789 
790 vmem_t *ip_minor_arena_sa; /* for minor nos. from INET_MIN_DEV+2 thru 2^^18-1 */
791 vmem_t *ip_minor_arena_la; /* for minor nos. from 2^^18 thru 2^^32-1 */
792 
793 int	ip_debug;
794 
795 #ifdef DEBUG
796 uint32_t ipsechw_debug = 0;
797 #endif
798 
799 /*
800  * Multirouting/CGTP stuff
801  */
802 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
803 
804 /*
805  * XXX following really should only be in a header. Would need more
806  * header and .c clean up first.
807  */
808 extern optdb_obj_t	ip_opt_obj;
809 
810 ulong_t ip_squeue_enter_unbound = 0;
811 
812 /*
813  * Named Dispatch Parameter Table.
814  * All of these are alterable, within the min/max values given, at run time.
815  */
816 static ipparam_t	lcl_param_arr[] = {
817 	/* min	max	value	name */
818 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
819 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
820 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
821 	{  0,	1,	0,	"ip_respond_to_timestamp"},
822 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
823 	{  0,	1,	1,	"ip_send_redirects"},
824 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
825 	{  0,	10,	0,	"ip_mrtdebug"},
826 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
827 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
828 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
829 	{  1,	255,	255,	"ip_def_ttl" },
830 	{  0,	1,	0,	"ip_forward_src_routed"},
831 	{  0,	256,	32,	"ip_wroff_extra" },
832 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
833 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
834 	{  0,	1,	1,	"ip_path_mtu_discovery" },
835 	{  0,	240,	30,	"ip_ignore_delete_time" },
836 	{  0,	1,	0,	"ip_ignore_redirect" },
837 	{  0,	1,	1,	"ip_output_queue" },
838 	{  1,	254,	1,	"ip_broadcast_ttl" },
839 	{  0,	99999,	100,	"ip_icmp_err_interval" },
840 	{  1,	99999,	10,	"ip_icmp_err_burst" },
841 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
842 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
843 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
844 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
845 	{  0,	1,	1,	"icmp_accept_clear_messages" },
846 	{  0,	1,	1,	"igmp_accept_clear_messages" },
847 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
848 				"ip_ndp_delay_first_probe_time"},
849 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
850 				"ip_ndp_max_unicast_solicit"},
851 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
852 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
853 	{  0,	1,	0,	"ip6_forward_src_routed"},
854 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
855 	{  0,	1,	1,	"ip6_send_redirects"},
856 	{  0,	1,	0,	"ip6_ignore_redirect" },
857 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
858 
859 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
860 
861 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
862 
863 	{  0,	1,	1,	"pim_accept_clear_messages" },
864 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
865 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
866 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
867 	{  0,	15,	0,	"ip_policy_mask" },
868 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
869 	{  0,	255,	1,	"ip_multirt_ttl" },
870 	{  0,	1,	1,	"ip_multidata_outbound" },
871 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
872 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
873 	{  0,	1000,	1,	"ip_max_temp_defend" },
874 	{  0,	1000,	3,	"ip_max_defend" },
875 	{  0,	999999,	30,	"ip_defend_interval" },
876 	{  0,	3600000, 300000, "ip_dup_recovery" },
877 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
878 	{  0,	1,	1,	"ip_lso_outbound" },
879 	{  IGMP_V1_ROUTER, IGMP_V3_ROUTER, IGMP_V3_ROUTER, "igmp_max_version" },
880 	{  MLD_V1_ROUTER, MLD_V2_ROUTER, MLD_V2_ROUTER, "mld_max_version" },
881 #ifdef DEBUG
882 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
883 #else
884 	{  0,	0,	0,	"" },
885 #endif
886 };
887 
888 /*
889  * Extended NDP table
890  * The addresses for the first two are filled in to be ips_ip_g_forward
891  * and ips_ipv6_forward at init time.
892  */
893 static ipndp_t	lcl_ndp_arr[] = {
894 	/* getf			setf		data			name */
895 #define	IPNDP_IP_FORWARDING_OFFSET	0
896 	{  ip_param_generic_get,	ip_forward_set,	NULL,
897 	    "ip_forwarding" },
898 #define	IPNDP_IP6_FORWARDING_OFFSET	1
899 	{  ip_param_generic_get,	ip_forward_set,	NULL,
900 	    "ip6_forwarding" },
901 	{  ip_ill_report,	NULL,		NULL,
902 	    "ip_ill_status" },
903 	{  ip_ipif_report,	NULL,		NULL,
904 	    "ip_ipif_status" },
905 	{  ip_conn_report,	NULL,		NULL,
906 	    "ip_conn_status" },
907 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
908 	    "ip_rput_pullups" },
909 	{  ip_srcid_report,	NULL,		NULL,
910 	    "ip_srcid_status" },
911 	{ ip_param_generic_get, ip_squeue_profile_set,
912 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
913 	{ ip_param_generic_get, ip_squeue_bind_set,
914 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
915 	{ ip_param_generic_get, ip_input_proc_set,
916 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
917 	{ ip_param_generic_get, ip_int_set,
918 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
919 #define	IPNDP_CGTP_FILTER_OFFSET	11
920 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
921 	    "ip_cgtp_filter" },
922 	{ ip_param_generic_get, ip_int_set,
923 	    (caddr_t)&ip_soft_rings_cnt, "ip_soft_rings_cnt" },
924 #define	IPNDP_IPMP_HOOK_OFFSET	13
925 	{  ip_param_generic_get, ipmp_hook_emulation_set, NULL,
926 	    "ipmp_hook_emulation" },
927 	{  ip_param_generic_get, ip_int_set, (caddr_t)&ip_debug,
928 	    "ip_debug" },
929 };
930 
931 /*
932  * Table of IP ioctls encoding the various properties of the ioctl and
933  * indexed based on the last byte of the ioctl command. Occasionally there
934  * is a clash, and there is more than 1 ioctl with the same last byte.
935  * In such a case 1 ioctl is encoded in the ndx table and the remaining
936  * ioctls are encoded in the misc table. An entry in the ndx table is
937  * retrieved by indexing on the last byte of the ioctl command and comparing
938  * the ioctl command with the value in the ndx table. In the event of a
939  * mismatch the misc table is then searched sequentially for the desired
940  * ioctl command.
941  *
942  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
943  */
944 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
945 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
946 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
947 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
948 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
949 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
950 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
951 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
952 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
953 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
954 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
955 
956 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
957 			MISC_CMD, ip_siocaddrt, NULL },
958 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
959 			MISC_CMD, ip_siocdelrt, NULL },
960 
961 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
962 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
963 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
964 			IF_CMD, ip_sioctl_get_addr, NULL },
965 
966 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
967 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
968 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
969 			IPI_GET_CMD | IPI_REPL,
970 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
971 
972 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
973 			IPI_PRIV | IPI_WR | IPI_REPL,
974 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
975 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
976 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
977 			IF_CMD, ip_sioctl_get_flags, NULL },
978 
979 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
980 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
981 
982 	/* copyin size cannot be coded for SIOCGIFCONF */
983 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
984 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
985 
986 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
987 			IF_CMD, ip_sioctl_mtu, NULL },
988 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
989 			IF_CMD, ip_sioctl_get_mtu, NULL },
990 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
991 			IPI_GET_CMD | IPI_REPL,
992 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
993 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
994 			IF_CMD, ip_sioctl_brdaddr, NULL },
995 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
996 			IPI_GET_CMD | IPI_REPL,
997 			IF_CMD, ip_sioctl_get_netmask, NULL },
998 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
999 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1000 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1001 			IPI_GET_CMD | IPI_REPL,
1002 			IF_CMD, ip_sioctl_get_metric, NULL },
1003 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1004 			IF_CMD, ip_sioctl_metric, NULL },
1005 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1006 
1007 	/* See 166-168 below for extended SIOC*XARP ioctls */
1008 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1009 			ARP_CMD, ip_sioctl_arp, NULL },
1010 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1011 			ARP_CMD, ip_sioctl_arp, NULL },
1012 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1013 			ARP_CMD, ip_sioctl_arp, NULL },
1014 
1015 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1016 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1017 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1018 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1019 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1020 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1021 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1022 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1023 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1024 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1025 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1026 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1027 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1028 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1029 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1030 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1031 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1032 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1033 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1034 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1035 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1036 
1037 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1038 			MISC_CMD, if_unitsel, if_unitsel_restart },
1039 
1040 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1041 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1042 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1043 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1044 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1045 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1046 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1047 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1048 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1049 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1050 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1051 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1052 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1053 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1054 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1055 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1056 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1057 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1058 
1059 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1060 			IPI_PRIV | IPI_WR | IPI_MODOK,
1061 			IF_CMD, ip_sioctl_sifname, NULL },
1062 
1063 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1064 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1065 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1066 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1067 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1068 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1069 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1070 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1071 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1072 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1073 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1074 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1075 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1076 
1077 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1078 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1079 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1080 			IF_CMD, ip_sioctl_get_muxid, NULL },
1081 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1082 			IPI_PRIV | IPI_WR | IPI_REPL,
1083 			IF_CMD, ip_sioctl_muxid, NULL },
1084 
1085 	/* Both if and lif variants share same func */
1086 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1087 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1088 	/* Both if and lif variants share same func */
1089 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1090 			IPI_PRIV | IPI_WR | IPI_REPL,
1091 			IF_CMD, ip_sioctl_slifindex, NULL },
1092 
1093 	/* copyin size cannot be coded for SIOCGIFCONF */
1094 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
1095 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1096 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1097 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1098 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1099 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1100 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1101 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1102 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1103 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1104 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1105 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1106 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1109 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1110 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1111 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1112 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1113 
1114 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1115 			IPI_PRIV | IPI_WR | IPI_REPL,
1116 			LIF_CMD, ip_sioctl_removeif,
1117 			ip_sioctl_removeif_restart },
1118 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1119 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1120 			LIF_CMD, ip_sioctl_addif, NULL },
1121 #define	SIOCLIFADDR_NDX 112
1122 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1123 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1124 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1125 			IPI_GET_CMD | IPI_REPL,
1126 			LIF_CMD, ip_sioctl_get_addr, NULL },
1127 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1128 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1129 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1130 			IPI_GET_CMD | IPI_REPL,
1131 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1132 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1133 			IPI_PRIV | IPI_WR | IPI_REPL,
1134 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1135 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1136 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1137 			LIF_CMD, ip_sioctl_get_flags, NULL },
1138 
1139 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1140 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1141 
1142 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1143 			ip_sioctl_get_lifconf, NULL },
1144 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1145 			LIF_CMD, ip_sioctl_mtu, NULL },
1146 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1147 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1148 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1149 			IPI_GET_CMD | IPI_REPL,
1150 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1151 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1152 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1153 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1154 			IPI_GET_CMD | IPI_REPL,
1155 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1156 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1157 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1158 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1159 			IPI_GET_CMD | IPI_REPL,
1160 			LIF_CMD, ip_sioctl_get_metric, NULL },
1161 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1162 			LIF_CMD, ip_sioctl_metric, NULL },
1163 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1164 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1165 			LIF_CMD, ip_sioctl_slifname,
1166 			ip_sioctl_slifname_restart },
1167 
1168 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1169 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1170 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1171 			IPI_GET_CMD | IPI_REPL,
1172 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1173 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1174 			IPI_PRIV | IPI_WR | IPI_REPL,
1175 			LIF_CMD, ip_sioctl_muxid, NULL },
1176 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1177 			IPI_GET_CMD | IPI_REPL,
1178 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1179 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1180 			IPI_PRIV | IPI_WR | IPI_REPL,
1181 			LIF_CMD, ip_sioctl_slifindex, 0 },
1182 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1183 			LIF_CMD, ip_sioctl_token, NULL },
1184 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1185 			IPI_GET_CMD | IPI_REPL,
1186 			LIF_CMD, ip_sioctl_get_token, NULL },
1187 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1188 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1189 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1190 			IPI_GET_CMD | IPI_REPL,
1191 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1192 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1193 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1194 
1195 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1196 			IPI_GET_CMD | IPI_REPL,
1197 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1198 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1199 			LIF_CMD, ip_siocdelndp_v6, NULL },
1200 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1201 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1202 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1203 			LIF_CMD, ip_siocsetndp_v6, NULL },
1204 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1205 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1206 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1207 			MISC_CMD, ip_sioctl_tonlink, NULL },
1208 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1209 			MISC_CMD, ip_sioctl_tmysite, NULL },
1210 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1211 			TUN_CMD, ip_sioctl_tunparam, NULL },
1212 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1213 			IPI_PRIV | IPI_WR,
1214 			TUN_CMD, ip_sioctl_tunparam, NULL },
1215 
1216 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1217 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1218 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1219 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1220 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1221 
1222 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1223 			IPI_PRIV | IPI_WR | IPI_REPL,
1224 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1225 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1226 			IPI_PRIV | IPI_WR | IPI_REPL,
1227 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1228 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1229 			IPI_PRIV | IPI_WR,
1230 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1231 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1232 			IPI_GET_CMD | IPI_REPL,
1233 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1234 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1235 			IPI_GET_CMD | IPI_REPL,
1236 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1237 
1238 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1239 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1240 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1241 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1242 
1243 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1244 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1245 
1246 	/* These are handled in ip_sioctl_copyin_setup itself */
1247 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1248 			MISC_CMD, NULL, NULL },
1249 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1250 			MISC_CMD, NULL, NULL },
1251 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1252 
1253 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1254 			ip_sioctl_get_lifconf, NULL },
1255 
1256 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1257 			XARP_CMD, ip_sioctl_arp, NULL },
1258 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1259 			XARP_CMD, ip_sioctl_arp, NULL },
1260 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1261 			XARP_CMD, ip_sioctl_arp, NULL },
1262 
1263 	/* SIOCPOPSOCKFS is not handled by IP */
1264 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1265 
1266 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1267 			IPI_GET_CMD | IPI_REPL,
1268 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1269 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1270 			IPI_PRIV | IPI_WR | IPI_REPL,
1271 			LIF_CMD, ip_sioctl_slifzone,
1272 			ip_sioctl_slifzone_restart },
1273 	/* 172-174 are SCTP ioctls and not handled by IP */
1274 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1275 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1276 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1277 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1278 			IPI_GET_CMD, LIF_CMD,
1279 			ip_sioctl_get_lifusesrc, 0 },
1280 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1281 			IPI_PRIV | IPI_WR,
1282 			LIF_CMD, ip_sioctl_slifusesrc,
1283 			NULL },
1284 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1285 			ip_sioctl_get_lifsrcof, NULL },
1286 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1287 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1288 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1289 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1290 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1291 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1292 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1293 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1294 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1295 			ip_sioctl_set_ipmpfailback, NULL },
1296 	/* SIOCSENABLESDP is handled by SDP */
1297 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1298 };
1299 
1300 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1301 
1302 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1303 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1304 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1305 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1306 		TUN_CMD, ip_sioctl_tunparam, NULL },
1307 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1308 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1309 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1310 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1311 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1312 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1313 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1314 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1315 		MISC_CMD, mrt_ioctl},
1316 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1317 		MISC_CMD, mrt_ioctl},
1318 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1319 		MISC_CMD, mrt_ioctl}
1320 };
1321 
1322 int ip_misc_ioctl_count =
1323     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1324 
1325 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1326 					/* Settable in /etc/system */
1327 /* Defined in ip_ire.c */
1328 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1329 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1330 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1331 
1332 static nv_t	ire_nv_arr[] = {
1333 	{ IRE_BROADCAST, "BROADCAST" },
1334 	{ IRE_LOCAL, "LOCAL" },
1335 	{ IRE_LOOPBACK, "LOOPBACK" },
1336 	{ IRE_CACHE, "CACHE" },
1337 	{ IRE_DEFAULT, "DEFAULT" },
1338 	{ IRE_PREFIX, "PREFIX" },
1339 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1340 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1341 	{ IRE_HOST, "HOST" },
1342 	{ 0 }
1343 };
1344 
1345 nv_t	*ire_nv_tbl = ire_nv_arr;
1346 
1347 /* Simple ICMP IP Header Template */
1348 static ipha_t icmp_ipha = {
1349 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1350 };
1351 
1352 struct module_info ip_mod_info = {
1353 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1354 };
1355 
1356 /*
1357  * Duplicate static symbols within a module confuses mdb; so we avoid the
1358  * problem by making the symbols here distinct from those in udp.c.
1359  */
1360 
1361 /*
1362  * Entry points for IP as a device and as a module.
1363  * FIXME: down the road we might want a separate module and driver qinit.
1364  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1365  */
1366 static struct qinit iprinitv4 = {
1367 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1368 	&ip_mod_info
1369 };
1370 
1371 struct qinit iprinitv6 = {
1372 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1373 	&ip_mod_info
1374 };
1375 
1376 static struct qinit ipwinitv4 = {
1377 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1378 	&ip_mod_info
1379 };
1380 
1381 struct qinit ipwinitv6 = {
1382 	(pfi_t)ip_wput_v6, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1383 	&ip_mod_info
1384 };
1385 
1386 static struct qinit iplrinit = {
1387 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1388 	&ip_mod_info
1389 };
1390 
1391 static struct qinit iplwinit = {
1392 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1393 	&ip_mod_info
1394 };
1395 
1396 /* For AF_INET aka /dev/ip */
1397 struct streamtab ipinfov4 = {
1398 	&iprinitv4, &ipwinitv4, &iplrinit, &iplwinit
1399 };
1400 
1401 /* For AF_INET6 aka /dev/ip6 */
1402 struct streamtab ipinfov6 = {
1403 	&iprinitv6, &ipwinitv6, &iplrinit, &iplwinit
1404 };
1405 
1406 #ifdef	DEBUG
1407 static boolean_t skip_sctp_cksum = B_FALSE;
1408 #endif
1409 
1410 /*
1411  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1412  * ip_rput_v6(), ip_output(), etc.  If the message
1413  * block already has a M_CTL at the front of it, then simply set the zoneid
1414  * appropriately.
1415  */
1416 mblk_t *
1417 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1418 {
1419 	mblk_t		*first_mp;
1420 	ipsec_out_t	*io;
1421 
1422 	ASSERT(zoneid != ALL_ZONES);
1423 	if (mp->b_datap->db_type == M_CTL) {
1424 		io = (ipsec_out_t *)mp->b_rptr;
1425 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1426 		io->ipsec_out_zoneid = zoneid;
1427 		return (mp);
1428 	}
1429 
1430 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1431 	if (first_mp == NULL)
1432 		return (NULL);
1433 	io = (ipsec_out_t *)first_mp->b_rptr;
1434 	/* This is not a secure packet */
1435 	io->ipsec_out_secure = B_FALSE;
1436 	io->ipsec_out_zoneid = zoneid;
1437 	first_mp->b_cont = mp;
1438 	return (first_mp);
1439 }
1440 
1441 /*
1442  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1443  */
1444 mblk_t *
1445 ip_copymsg(mblk_t *mp)
1446 {
1447 	mblk_t *nmp;
1448 	ipsec_info_t *in;
1449 
1450 	if (mp->b_datap->db_type != M_CTL)
1451 		return (copymsg(mp));
1452 
1453 	in = (ipsec_info_t *)mp->b_rptr;
1454 
1455 	/*
1456 	 * Note that M_CTL is also used for delivering ICMP error messages
1457 	 * upstream to transport layers.
1458 	 */
1459 	if (in->ipsec_info_type != IPSEC_OUT &&
1460 	    in->ipsec_info_type != IPSEC_IN)
1461 		return (copymsg(mp));
1462 
1463 	nmp = copymsg(mp->b_cont);
1464 
1465 	if (in->ipsec_info_type == IPSEC_OUT) {
1466 		return (ipsec_out_tag(mp, nmp,
1467 		    ((ipsec_out_t *)in)->ipsec_out_ns));
1468 	} else {
1469 		return (ipsec_in_tag(mp, nmp,
1470 		    ((ipsec_in_t *)in)->ipsec_in_ns));
1471 	}
1472 }
1473 
1474 /* Generate an ICMP fragmentation needed message. */
1475 static void
1476 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1477     ip_stack_t *ipst)
1478 {
1479 	icmph_t	icmph;
1480 	mblk_t *first_mp;
1481 	boolean_t mctl_present;
1482 
1483 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1484 
1485 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1486 		if (mctl_present)
1487 			freeb(first_mp);
1488 		return;
1489 	}
1490 
1491 	bzero(&icmph, sizeof (icmph_t));
1492 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1493 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1494 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1495 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1496 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1497 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1498 	    ipst);
1499 }
1500 
1501 /*
1502  * icmp_inbound deals with ICMP messages in the following ways.
1503  *
1504  * 1) It needs to send a reply back and possibly delivering it
1505  *    to the "interested" upper clients.
1506  * 2) It needs to send it to the upper clients only.
1507  * 3) It needs to change some values in IP only.
1508  * 4) It needs to change some values in IP and upper layers e.g TCP.
1509  *
1510  * We need to accomodate icmp messages coming in clear until we get
1511  * everything secure from the wire. If icmp_accept_clear_messages
1512  * is zero we check with the global policy and act accordingly. If
1513  * it is non-zero, we accept the message without any checks. But
1514  * *this does not mean* that this will be delivered to the upper
1515  * clients. By accepting we might send replies back, change our MTU
1516  * value etc. but delivery to the ULP/clients depends on their policy
1517  * dispositions.
1518  *
1519  * We handle the above 4 cases in the context of IPsec in the
1520  * following way :
1521  *
1522  * 1) Send the reply back in the same way as the request came in.
1523  *    If it came in encrypted, it goes out encrypted. If it came in
1524  *    clear, it goes out in clear. Thus, this will prevent chosen
1525  *    plain text attack.
1526  * 2) The client may or may not expect things to come in secure.
1527  *    If it comes in secure, the policy constraints are checked
1528  *    before delivering it to the upper layers. If it comes in
1529  *    clear, ipsec_inbound_accept_clear will decide whether to
1530  *    accept this in clear or not. In both the cases, if the returned
1531  *    message (IP header + 8 bytes) that caused the icmp message has
1532  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1533  *    sending up. If there are only 8 bytes of returned message, then
1534  *    upper client will not be notified.
1535  * 3) Check with global policy to see whether it matches the constaints.
1536  *    But this will be done only if icmp_accept_messages_in_clear is
1537  *    zero.
1538  * 4) If we need to change both in IP and ULP, then the decision taken
1539  *    while affecting the values in IP and while delivering up to TCP
1540  *    should be the same.
1541  *
1542  * 	There are two cases.
1543  *
1544  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1545  *	   failed), we will not deliver it to the ULP, even though they
1546  *	   are *willing* to accept in *clear*. This is fine as our global
1547  *	   disposition to icmp messages asks us reject the datagram.
1548  *
1549  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1550  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1551  *	   to deliver it to ULP (policy failed), it can lead to
1552  *	   consistency problems. The cases known at this time are
1553  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1554  *	   values :
1555  *
1556  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1557  *	     and Upper layer rejects. Then the communication will
1558  *	     come to a stop. This is solved by making similar decisions
1559  *	     at both levels. Currently, when we are unable to deliver
1560  *	     to the Upper Layer (due to policy failures) while IP has
1561  *	     adjusted ire_max_frag, the next outbound datagram would
1562  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1563  *	     will be with the right level of protection. Thus the right
1564  *	     value will be communicated even if we are not able to
1565  *	     communicate when we get from the wire initially. But this
1566  *	     assumes there would be at least one outbound datagram after
1567  *	     IP has adjusted its ire_max_frag value. To make things
1568  *	     simpler, we accept in clear after the validation of
1569  *	     AH/ESP headers.
1570  *
1571  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1572  *	     upper layer depending on the level of protection the upper
1573  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1574  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1575  *	     should be accepted in clear when the Upper layer expects secure.
1576  *	     Thus the communication may get aborted by some bad ICMP
1577  *	     packets.
1578  *
1579  * IPQoS Notes:
1580  * The only instance when a packet is sent for processing is when there
1581  * isn't an ICMP client and if we are interested in it.
1582  * If there is a client, IPPF processing will take place in the
1583  * ip_fanout_proto routine.
1584  *
1585  * Zones notes:
1586  * The packet is only processed in the context of the specified zone: typically
1587  * only this zone will reply to an echo request, and only interested clients in
1588  * this zone will receive a copy of the packet. This means that the caller must
1589  * call icmp_inbound() for each relevant zone.
1590  */
1591 static void
1592 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1593     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1594     ill_t *recv_ill, zoneid_t zoneid)
1595 {
1596 	icmph_t	*icmph;
1597 	ipha_t	*ipha;
1598 	int	iph_hdr_length;
1599 	int	hdr_length;
1600 	boolean_t	interested;
1601 	uint32_t	ts;
1602 	uchar_t	*wptr;
1603 	ipif_t	*ipif;
1604 	mblk_t *first_mp;
1605 	ipsec_in_t *ii;
1606 	ire_t *src_ire;
1607 	boolean_t onlink;
1608 	timestruc_t now;
1609 	uint32_t ill_index;
1610 	ip_stack_t *ipst;
1611 
1612 	ASSERT(ill != NULL);
1613 	ipst = ill->ill_ipst;
1614 
1615 	first_mp = mp;
1616 	if (mctl_present) {
1617 		mp = first_mp->b_cont;
1618 		ASSERT(mp != NULL);
1619 	}
1620 
1621 	ipha = (ipha_t *)mp->b_rptr;
1622 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1623 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1624 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1625 		if (first_mp == NULL)
1626 			return;
1627 	}
1628 
1629 	/*
1630 	 * On a labeled system, we have to check whether the zone itself is
1631 	 * permitted to receive raw traffic.
1632 	 */
1633 	if (is_system_labeled()) {
1634 		if (zoneid == ALL_ZONES)
1635 			zoneid = tsol_packet_to_zoneid(mp);
1636 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1637 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1638 			    zoneid));
1639 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1640 			freemsg(first_mp);
1641 			return;
1642 		}
1643 	}
1644 
1645 	/*
1646 	 * We have accepted the ICMP message. It means that we will
1647 	 * respond to the packet if needed. It may not be delivered
1648 	 * to the upper client depending on the policy constraints
1649 	 * and the disposition in ipsec_inbound_accept_clear.
1650 	 */
1651 
1652 	ASSERT(ill != NULL);
1653 
1654 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1655 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1656 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1657 		/* Last chance to get real. */
1658 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1659 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1660 			freemsg(first_mp);
1661 			return;
1662 		}
1663 		/* Refresh iph following the pullup. */
1664 		ipha = (ipha_t *)mp->b_rptr;
1665 	}
1666 	/* ICMP header checksum, including checksum field, should be zero. */
1667 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1668 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1669 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1670 		freemsg(first_mp);
1671 		return;
1672 	}
1673 	/* The IP header will always be a multiple of four bytes */
1674 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1675 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1676 	    icmph->icmph_code));
1677 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1678 	/* We will set "interested" to "true" if we want a copy */
1679 	interested = B_FALSE;
1680 	switch (icmph->icmph_type) {
1681 	case ICMP_ECHO_REPLY:
1682 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1683 		break;
1684 	case ICMP_DEST_UNREACHABLE:
1685 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1686 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1687 		interested = B_TRUE;	/* Pass up to transport */
1688 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1689 		break;
1690 	case ICMP_SOURCE_QUENCH:
1691 		interested = B_TRUE;	/* Pass up to transport */
1692 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1693 		break;
1694 	case ICMP_REDIRECT:
1695 		if (!ipst->ips_ip_ignore_redirect)
1696 			interested = B_TRUE;
1697 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1698 		break;
1699 	case ICMP_ECHO_REQUEST:
1700 		/*
1701 		 * Whether to respond to echo requests that come in as IP
1702 		 * broadcasts or as IP multicast is subject to debate
1703 		 * (what isn't?).  We aim to please, you pick it.
1704 		 * Default is do it.
1705 		 */
1706 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1707 			/* unicast: always respond */
1708 			interested = B_TRUE;
1709 		} else if (CLASSD(ipha->ipha_dst)) {
1710 			/* multicast: respond based on tunable */
1711 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1712 		} else if (broadcast) {
1713 			/* broadcast: respond based on tunable */
1714 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1715 		}
1716 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1717 		break;
1718 	case ICMP_ROUTER_ADVERTISEMENT:
1719 	case ICMP_ROUTER_SOLICITATION:
1720 		break;
1721 	case ICMP_TIME_EXCEEDED:
1722 		interested = B_TRUE;	/* Pass up to transport */
1723 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1724 		break;
1725 	case ICMP_PARAM_PROBLEM:
1726 		interested = B_TRUE;	/* Pass up to transport */
1727 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1728 		break;
1729 	case ICMP_TIME_STAMP_REQUEST:
1730 		/* Response to Time Stamp Requests is local policy. */
1731 		if (ipst->ips_ip_g_resp_to_timestamp &&
1732 		    /* So is whether to respond if it was an IP broadcast. */
1733 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1734 			int tstamp_len = 3 * sizeof (uint32_t);
1735 
1736 			if (wptr +  tstamp_len > mp->b_wptr) {
1737 				if (!pullupmsg(mp, wptr + tstamp_len -
1738 				    mp->b_rptr)) {
1739 					BUMP_MIB(ill->ill_ip_mib,
1740 					    ipIfStatsInDiscards);
1741 					freemsg(first_mp);
1742 					return;
1743 				}
1744 				/* Refresh ipha following the pullup. */
1745 				ipha = (ipha_t *)mp->b_rptr;
1746 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1747 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1748 			}
1749 			interested = B_TRUE;
1750 		}
1751 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1752 		break;
1753 	case ICMP_TIME_STAMP_REPLY:
1754 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1755 		break;
1756 	case ICMP_INFO_REQUEST:
1757 		/* Per RFC 1122 3.2.2.7, ignore this. */
1758 	case ICMP_INFO_REPLY:
1759 		break;
1760 	case ICMP_ADDRESS_MASK_REQUEST:
1761 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1762 		    !broadcast) &&
1763 		    /* TODO m_pullup of complete header? */
1764 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN) {
1765 			interested = B_TRUE;
1766 		}
1767 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1768 		break;
1769 	case ICMP_ADDRESS_MASK_REPLY:
1770 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1771 		break;
1772 	default:
1773 		interested = B_TRUE;	/* Pass up to transport */
1774 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1775 		break;
1776 	}
1777 	/* See if there is an ICMP client. */
1778 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1779 		/* If there is an ICMP client and we want one too, copy it. */
1780 		mblk_t *first_mp1;
1781 
1782 		if (!interested) {
1783 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1784 			    ip_policy, recv_ill, zoneid);
1785 			return;
1786 		}
1787 		first_mp1 = ip_copymsg(first_mp);
1788 		if (first_mp1 != NULL) {
1789 			ip_fanout_proto(q, first_mp1, ill, ipha,
1790 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1791 		}
1792 	} else if (!interested) {
1793 		freemsg(first_mp);
1794 		return;
1795 	} else {
1796 		/*
1797 		 * Initiate policy processing for this packet if ip_policy
1798 		 * is true.
1799 		 */
1800 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1801 			ill_index = ill->ill_phyint->phyint_ifindex;
1802 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1803 			if (mp == NULL) {
1804 				if (mctl_present) {
1805 					freeb(first_mp);
1806 				}
1807 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1808 				return;
1809 			}
1810 		}
1811 	}
1812 	/* We want to do something with it. */
1813 	/* Check db_ref to make sure we can modify the packet. */
1814 	if (mp->b_datap->db_ref > 1) {
1815 		mblk_t	*first_mp1;
1816 
1817 		first_mp1 = ip_copymsg(first_mp);
1818 		freemsg(first_mp);
1819 		if (!first_mp1) {
1820 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1821 			return;
1822 		}
1823 		first_mp = first_mp1;
1824 		if (mctl_present) {
1825 			mp = first_mp->b_cont;
1826 			ASSERT(mp != NULL);
1827 		} else {
1828 			mp = first_mp;
1829 		}
1830 		ipha = (ipha_t *)mp->b_rptr;
1831 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1832 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1833 	}
1834 	switch (icmph->icmph_type) {
1835 	case ICMP_ADDRESS_MASK_REQUEST:
1836 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1837 		if (ipif == NULL) {
1838 			freemsg(first_mp);
1839 			return;
1840 		}
1841 		/*
1842 		 * outging interface must be IPv4
1843 		 */
1844 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1845 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1846 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1847 		ipif_refrele(ipif);
1848 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1849 		break;
1850 	case ICMP_ECHO_REQUEST:
1851 		icmph->icmph_type = ICMP_ECHO_REPLY;
1852 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1853 		break;
1854 	case ICMP_TIME_STAMP_REQUEST: {
1855 		uint32_t *tsp;
1856 
1857 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1858 		tsp = (uint32_t *)wptr;
1859 		tsp++;		/* Skip past 'originate time' */
1860 		/* Compute # of milliseconds since midnight */
1861 		gethrestime(&now);
1862 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1863 		    now.tv_nsec / (NANOSEC / MILLISEC);
1864 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1865 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1866 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1867 		break;
1868 	}
1869 	default:
1870 		ipha = (ipha_t *)&icmph[1];
1871 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1872 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1873 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1874 				freemsg(first_mp);
1875 				return;
1876 			}
1877 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1878 			ipha = (ipha_t *)&icmph[1];
1879 		}
1880 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1881 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1882 			freemsg(first_mp);
1883 			return;
1884 		}
1885 		hdr_length = IPH_HDR_LENGTH(ipha);
1886 		if (hdr_length < sizeof (ipha_t)) {
1887 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1888 			freemsg(first_mp);
1889 			return;
1890 		}
1891 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1892 			if (!pullupmsg(mp,
1893 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1894 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1895 				freemsg(first_mp);
1896 				return;
1897 			}
1898 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1899 			ipha = (ipha_t *)&icmph[1];
1900 		}
1901 		switch (icmph->icmph_type) {
1902 		case ICMP_REDIRECT:
1903 			/*
1904 			 * As there is no upper client to deliver, we don't
1905 			 * need the first_mp any more.
1906 			 */
1907 			if (mctl_present) {
1908 				freeb(first_mp);
1909 			}
1910 			icmp_redirect(ill, mp);
1911 			return;
1912 		case ICMP_DEST_UNREACHABLE:
1913 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1914 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1915 				    zoneid, mp, iph_hdr_length, ipst)) {
1916 					freemsg(first_mp);
1917 					return;
1918 				}
1919 				/*
1920 				 * icmp_inbound_too_big() may alter mp.
1921 				 * Resynch ipha and icmph accordingly.
1922 				 */
1923 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1924 				ipha = (ipha_t *)&icmph[1];
1925 			}
1926 			/* FALLTHRU */
1927 		default :
1928 			/*
1929 			 * IPQoS notes: Since we have already done IPQoS
1930 			 * processing we don't want to do it again in
1931 			 * the fanout routines called by
1932 			 * icmp_inbound_error_fanout, hence the last
1933 			 * argument, ip_policy, is B_FALSE.
1934 			 */
1935 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1936 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1937 			    B_FALSE, recv_ill, zoneid);
1938 		}
1939 		return;
1940 	}
1941 	/* Send out an ICMP packet */
1942 	icmph->icmph_checksum = 0;
1943 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1944 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1945 		ipif_t	*ipif_chosen;
1946 		/*
1947 		 * Make it look like it was directed to us, so we don't look
1948 		 * like a fool with a broadcast or multicast source address.
1949 		 */
1950 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1951 		/*
1952 		 * Make sure that we haven't grabbed an interface that's DOWN.
1953 		 */
1954 		if (ipif != NULL) {
1955 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
1956 			    ipha->ipha_src, zoneid);
1957 			if (ipif_chosen != NULL) {
1958 				ipif_refrele(ipif);
1959 				ipif = ipif_chosen;
1960 			}
1961 		}
1962 		if (ipif == NULL) {
1963 			ip0dbg(("icmp_inbound: "
1964 			    "No source for broadcast/multicast:\n"
1965 			    "\tsrc 0x%x dst 0x%x ill %p "
1966 			    "ipif_lcl_addr 0x%x\n",
1967 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
1968 			    (void *)ill,
1969 			    ill->ill_ipif->ipif_lcl_addr));
1970 			freemsg(first_mp);
1971 			return;
1972 		}
1973 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1974 		ipha->ipha_dst = ipif->ipif_src_addr;
1975 		ipif_refrele(ipif);
1976 	}
1977 	/* Reset time to live. */
1978 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1979 	{
1980 		/* Swap source and destination addresses */
1981 		ipaddr_t tmp;
1982 
1983 		tmp = ipha->ipha_src;
1984 		ipha->ipha_src = ipha->ipha_dst;
1985 		ipha->ipha_dst = tmp;
1986 	}
1987 	ipha->ipha_ident = 0;
1988 	if (!IS_SIMPLE_IPH(ipha))
1989 		icmp_options_update(ipha);
1990 
1991 	/*
1992 	 * ICMP echo replies should go out on the same interface
1993 	 * the request came on as probes used by in.mpathd for detecting
1994 	 * NIC failures are ECHO packets. We turn-off load spreading
1995 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
1996 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
1997 	 * function. This is in turn handled by ip_wput and ip_newroute
1998 	 * to make sure that the packet goes out on the interface it came
1999 	 * in on. If we don't turnoff load spreading, the packets might get
2000 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
2001 	 * to go out and in.mpathd would wrongly detect a failure or
2002 	 * mis-detect a NIC failure for link failure. As load spreading
2003 	 * can happen only if ill_group is not NULL, we do only for
2004 	 * that case and this does not affect the normal case.
2005 	 *
2006 	 * We turn off load spreading only on echo packets that came from
2007 	 * on-link hosts. If the interface route has been deleted, this will
2008 	 * not be enforced as we can't do much. For off-link hosts, as the
2009 	 * default routes in IPv4 does not typically have an ire_ipif
2010 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2011 	 * Moreover, expecting a default route through this interface may
2012 	 * not be correct. We use ipha_dst because of the swap above.
2013 	 */
2014 	onlink = B_FALSE;
2015 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2016 		/*
2017 		 * First, we need to make sure that it is not one of our
2018 		 * local addresses. If we set onlink when it is one of
2019 		 * our local addresses, we will end up creating IRE_CACHES
2020 		 * for one of our local addresses. Then, we will never
2021 		 * accept packets for them afterwards.
2022 		 */
2023 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2024 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2025 		if (src_ire == NULL) {
2026 			ipif = ipif_get_next_ipif(NULL, ill);
2027 			if (ipif == NULL) {
2028 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2029 				freemsg(mp);
2030 				return;
2031 			}
2032 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2033 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2034 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE, ipst);
2035 			ipif_refrele(ipif);
2036 			if (src_ire != NULL) {
2037 				onlink = B_TRUE;
2038 				ire_refrele(src_ire);
2039 			}
2040 		} else {
2041 			ire_refrele(src_ire);
2042 		}
2043 	}
2044 	if (!mctl_present) {
2045 		/*
2046 		 * This packet should go out the same way as it
2047 		 * came in i.e in clear. To make sure that global
2048 		 * policy will not be applied to this in ip_wput_ire,
2049 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2050 		 */
2051 		ASSERT(first_mp == mp);
2052 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2053 		if (first_mp == NULL) {
2054 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2055 			freemsg(mp);
2056 			return;
2057 		}
2058 		ii = (ipsec_in_t *)first_mp->b_rptr;
2059 
2060 		/* This is not a secure packet */
2061 		ii->ipsec_in_secure = B_FALSE;
2062 		if (onlink) {
2063 			ii->ipsec_in_attach_if = B_TRUE;
2064 			ii->ipsec_in_ill_index =
2065 			    ill->ill_phyint->phyint_ifindex;
2066 			ii->ipsec_in_rill_index =
2067 			    recv_ill->ill_phyint->phyint_ifindex;
2068 		}
2069 		first_mp->b_cont = mp;
2070 	} else if (onlink) {
2071 		ii = (ipsec_in_t *)first_mp->b_rptr;
2072 		ii->ipsec_in_attach_if = B_TRUE;
2073 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2074 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2075 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2076 	} else {
2077 		ii = (ipsec_in_t *)first_mp->b_rptr;
2078 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2079 	}
2080 	ii->ipsec_in_zoneid = zoneid;
2081 	ASSERT(zoneid != ALL_ZONES);
2082 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2083 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2084 		return;
2085 	}
2086 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2087 	put(WR(q), first_mp);
2088 }
2089 
2090 static ipaddr_t
2091 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2092 {
2093 	conn_t *connp;
2094 	connf_t *connfp;
2095 	ipaddr_t nexthop_addr = INADDR_ANY;
2096 	int hdr_length = IPH_HDR_LENGTH(ipha);
2097 	uint16_t *up;
2098 	uint32_t ports;
2099 	ip_stack_t *ipst = ill->ill_ipst;
2100 
2101 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2102 	switch (ipha->ipha_protocol) {
2103 		case IPPROTO_TCP:
2104 		{
2105 			tcph_t *tcph;
2106 
2107 			/* do a reverse lookup */
2108 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2109 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2110 			    TCPS_LISTEN, ipst);
2111 			break;
2112 		}
2113 		case IPPROTO_UDP:
2114 		{
2115 			uint32_t dstport, srcport;
2116 
2117 			((uint16_t *)&ports)[0] = up[1];
2118 			((uint16_t *)&ports)[1] = up[0];
2119 
2120 			/* Extract ports in net byte order */
2121 			dstport = htons(ntohl(ports) & 0xFFFF);
2122 			srcport = htons(ntohl(ports) >> 16);
2123 
2124 			connfp = &ipst->ips_ipcl_udp_fanout[
2125 			    IPCL_UDP_HASH(dstport, ipst)];
2126 			mutex_enter(&connfp->connf_lock);
2127 			connp = connfp->connf_head;
2128 
2129 			/* do a reverse lookup */
2130 			while ((connp != NULL) &&
2131 			    (!IPCL_UDP_MATCH(connp, dstport,
2132 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2133 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2134 				connp = connp->conn_next;
2135 			}
2136 			if (connp != NULL)
2137 				CONN_INC_REF(connp);
2138 			mutex_exit(&connfp->connf_lock);
2139 			break;
2140 		}
2141 		case IPPROTO_SCTP:
2142 		{
2143 			in6_addr_t map_src, map_dst;
2144 
2145 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2146 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2147 			((uint16_t *)&ports)[0] = up[1];
2148 			((uint16_t *)&ports)[1] = up[0];
2149 
2150 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2151 			    zoneid, ipst->ips_netstack->netstack_sctp);
2152 			if (connp == NULL) {
2153 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2154 				    zoneid, ports, ipha, ipst);
2155 			} else {
2156 				CONN_INC_REF(connp);
2157 				SCTP_REFRELE(CONN2SCTP(connp));
2158 			}
2159 			break;
2160 		}
2161 		default:
2162 		{
2163 			ipha_t ripha;
2164 
2165 			ripha.ipha_src = ipha->ipha_dst;
2166 			ripha.ipha_dst = ipha->ipha_src;
2167 			ripha.ipha_protocol = ipha->ipha_protocol;
2168 
2169 			connfp = &ipst->ips_ipcl_proto_fanout[
2170 			    ipha->ipha_protocol];
2171 			mutex_enter(&connfp->connf_lock);
2172 			connp = connfp->connf_head;
2173 			for (connp = connfp->connf_head; connp != NULL;
2174 			    connp = connp->conn_next) {
2175 				if (IPCL_PROTO_MATCH(connp,
2176 				    ipha->ipha_protocol, &ripha, ill,
2177 				    0, zoneid)) {
2178 					CONN_INC_REF(connp);
2179 					break;
2180 				}
2181 			}
2182 			mutex_exit(&connfp->connf_lock);
2183 		}
2184 	}
2185 	if (connp != NULL) {
2186 		if (connp->conn_nexthop_set)
2187 			nexthop_addr = connp->conn_nexthop_v4;
2188 		CONN_DEC_REF(connp);
2189 	}
2190 	return (nexthop_addr);
2191 }
2192 
2193 /* Table from RFC 1191 */
2194 static int icmp_frag_size_table[] =
2195 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2196 
2197 /*
2198  * Process received ICMP Packet too big.
2199  * After updating any IRE it does the fanout to any matching transport streams.
2200  * Assumes the message has been pulled up till the IP header that caused
2201  * the error.
2202  *
2203  * Returns B_FALSE on failure and B_TRUE on success.
2204  */
2205 static boolean_t
2206 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2207     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2208     ip_stack_t *ipst)
2209 {
2210 	ire_t	*ire, *first_ire;
2211 	int	mtu;
2212 	int	hdr_length;
2213 	ipaddr_t nexthop_addr;
2214 
2215 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2216 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2217 	ASSERT(ill != NULL);
2218 
2219 	hdr_length = IPH_HDR_LENGTH(ipha);
2220 
2221 	/* Drop if the original packet contained a source route */
2222 	if (ip_source_route_included(ipha)) {
2223 		return (B_FALSE);
2224 	}
2225 	/*
2226 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2227 	 * header.
2228 	 */
2229 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2230 	    mp->b_wptr) {
2231 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2232 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2233 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2234 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2235 			return (B_FALSE);
2236 		}
2237 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2238 		ipha = (ipha_t *)&icmph[1];
2239 	}
2240 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2241 	if (nexthop_addr != INADDR_ANY) {
2242 		/* nexthop set */
2243 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2244 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2245 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2246 	} else {
2247 		/* nexthop not set */
2248 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2249 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2250 	}
2251 
2252 	if (!first_ire) {
2253 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2254 		    ntohl(ipha->ipha_dst)));
2255 		return (B_FALSE);
2256 	}
2257 	/* Check for MTU discovery advice as described in RFC 1191 */
2258 	mtu = ntohs(icmph->icmph_du_mtu);
2259 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2260 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2261 	    ire = ire->ire_next) {
2262 		/*
2263 		 * Look for the connection to which this ICMP message is
2264 		 * directed. If it has the IP_NEXTHOP option set, then the
2265 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2266 		 * option. Else the search is limited to regular IREs.
2267 		 */
2268 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2269 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2270 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2271 		    (nexthop_addr != INADDR_ANY)))
2272 			continue;
2273 
2274 		mutex_enter(&ire->ire_lock);
2275 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2276 			/* Reduce the IRE max frag value as advised. */
2277 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2278 			    mtu, ire->ire_max_frag));
2279 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2280 		} else {
2281 			uint32_t length;
2282 			int	i;
2283 
2284 			/*
2285 			 * Use the table from RFC 1191 to figure out
2286 			 * the next "plateau" based on the length in
2287 			 * the original IP packet.
2288 			 */
2289 			length = ntohs(ipha->ipha_length);
2290 			if (ire->ire_max_frag <= length &&
2291 			    ire->ire_max_frag >= length - hdr_length) {
2292 				/*
2293 				 * Handle broken BSD 4.2 systems that
2294 				 * return the wrong iph_length in ICMP
2295 				 * errors.
2296 				 */
2297 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2298 				    length, ire->ire_max_frag));
2299 				length -= hdr_length;
2300 			}
2301 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2302 				if (length > icmp_frag_size_table[i])
2303 					break;
2304 			}
2305 			if (i == A_CNT(icmp_frag_size_table)) {
2306 				/* Smaller than 68! */
2307 				ip1dbg(("Too big for packet size %d\n",
2308 				    length));
2309 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2310 				ire->ire_frag_flag = 0;
2311 			} else {
2312 				mtu = icmp_frag_size_table[i];
2313 				ip1dbg(("Calculated mtu %d, packet size %d, "
2314 				    "before %d", mtu, length,
2315 				    ire->ire_max_frag));
2316 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2317 				ip1dbg((", after %d\n", ire->ire_max_frag));
2318 			}
2319 			/* Record the new max frag size for the ULP. */
2320 			icmph->icmph_du_zero = 0;
2321 			icmph->icmph_du_mtu =
2322 			    htons((uint16_t)ire->ire_max_frag);
2323 		}
2324 		mutex_exit(&ire->ire_lock);
2325 	}
2326 	rw_exit(&first_ire->ire_bucket->irb_lock);
2327 	ire_refrele(first_ire);
2328 	return (B_TRUE);
2329 }
2330 
2331 /*
2332  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2333  * calls this function.
2334  */
2335 static mblk_t *
2336 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2337 {
2338 	ipha_t *ipha;
2339 	icmph_t *icmph;
2340 	ipha_t *in_ipha;
2341 	int length;
2342 
2343 	ASSERT(mp->b_datap->db_type == M_DATA);
2344 
2345 	/*
2346 	 * For Self-encapsulated packets, we added an extra IP header
2347 	 * without the options. Inner IP header is the one from which
2348 	 * the outer IP header was formed. Thus, we need to remove the
2349 	 * outer IP header. To do this, we pullup the whole message
2350 	 * and overlay whatever follows the outer IP header over the
2351 	 * outer IP header.
2352 	 */
2353 
2354 	if (!pullupmsg(mp, -1))
2355 		return (NULL);
2356 
2357 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2358 	ipha = (ipha_t *)&icmph[1];
2359 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2360 
2361 	/*
2362 	 * The length that we want to overlay is following the inner
2363 	 * IP header. Subtracting the IP header + icmp header + outer
2364 	 * IP header's length should give us the length that we want to
2365 	 * overlay.
2366 	 */
2367 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2368 	    hdr_length;
2369 	/*
2370 	 * Overlay whatever follows the inner header over the
2371 	 * outer header.
2372 	 */
2373 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2374 
2375 	/* Set the wptr to account for the outer header */
2376 	mp->b_wptr -= hdr_length;
2377 	return (mp);
2378 }
2379 
2380 /*
2381  * Try to pass the ICMP message upstream in case the ULP cares.
2382  *
2383  * If the packet that caused the ICMP error is secure, we send
2384  * it to AH/ESP to make sure that the attached packet has a
2385  * valid association. ipha in the code below points to the
2386  * IP header of the packet that caused the error.
2387  *
2388  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2389  * in the context of IPsec. Normally we tell the upper layer
2390  * whenever we send the ire (including ip_bind), the IPsec header
2391  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2392  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2393  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2394  * same thing. As TCP has the IPsec options size that needs to be
2395  * adjusted, we just pass the MTU unchanged.
2396  *
2397  * IFN could have been generated locally or by some router.
2398  *
2399  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2400  *	    This happens because IP adjusted its value of MTU on an
2401  *	    earlier IFN message and could not tell the upper layer,
2402  *	    the new adjusted value of MTU e.g. Packet was encrypted
2403  *	    or there was not enough information to fanout to upper
2404  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2405  *	    generates the IFN, where IPsec processing has *not* been
2406  *	    done.
2407  *
2408  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2409  *	    could have generated this. This happens because ire_max_frag
2410  *	    value in IP was set to a new value, while the IPsec processing
2411  *	    was being done and after we made the fragmentation check in
2412  *	    ip_wput_ire. Thus on return from IPsec processing,
2413  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2414  *	    and generates the IFN. As IPsec processing is over, we fanout
2415  *	    to AH/ESP to remove the header.
2416  *
2417  *	    In both these cases, ipsec_in_loopback will be set indicating
2418  *	    that IFN was generated locally.
2419  *
2420  * ROUTER : IFN could be secure or non-secure.
2421  *
2422  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2423  *	      packet in error has AH/ESP headers to validate the AH/ESP
2424  *	      headers. AH/ESP will verify whether there is a valid SA or
2425  *	      not and send it back. We will fanout again if we have more
2426  *	      data in the packet.
2427  *
2428  *	      If the packet in error does not have AH/ESP, we handle it
2429  *	      like any other case.
2430  *
2431  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2432  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2433  *	      for validation. AH/ESP will verify whether there is a
2434  *	      valid SA or not and send it back. We will fanout again if
2435  *	      we have more data in the packet.
2436  *
2437  *	      If the packet in error does not have AH/ESP, we handle it
2438  *	      like any other case.
2439  */
2440 static void
2441 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2442     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2443     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2444     zoneid_t zoneid)
2445 {
2446 	uint16_t *up;	/* Pointer to ports in ULP header */
2447 	uint32_t ports;	/* reversed ports for fanout */
2448 	ipha_t ripha;	/* With reversed addresses */
2449 	mblk_t *first_mp;
2450 	ipsec_in_t *ii;
2451 	tcph_t	*tcph;
2452 	conn_t	*connp;
2453 	ip_stack_t *ipst;
2454 
2455 	ASSERT(ill != NULL);
2456 
2457 	ASSERT(recv_ill != NULL);
2458 	ipst = recv_ill->ill_ipst;
2459 
2460 	first_mp = mp;
2461 	if (mctl_present) {
2462 		mp = first_mp->b_cont;
2463 		ASSERT(mp != NULL);
2464 
2465 		ii = (ipsec_in_t *)first_mp->b_rptr;
2466 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2467 	} else {
2468 		ii = NULL;
2469 	}
2470 
2471 	switch (ipha->ipha_protocol) {
2472 	case IPPROTO_UDP:
2473 		/*
2474 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2475 		 * transport header.
2476 		 */
2477 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2478 		    mp->b_wptr) {
2479 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2480 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2481 				goto discard_pkt;
2482 			}
2483 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2484 			ipha = (ipha_t *)&icmph[1];
2485 		}
2486 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2487 
2488 		/*
2489 		 * Attempt to find a client stream based on port.
2490 		 * Note that we do a reverse lookup since the header is
2491 		 * in the form we sent it out.
2492 		 * The ripha header is only used for the IP_UDP_MATCH and we
2493 		 * only set the src and dst addresses and protocol.
2494 		 */
2495 		ripha.ipha_src = ipha->ipha_dst;
2496 		ripha.ipha_dst = ipha->ipha_src;
2497 		ripha.ipha_protocol = ipha->ipha_protocol;
2498 		((uint16_t *)&ports)[0] = up[1];
2499 		((uint16_t *)&ports)[1] = up[0];
2500 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2501 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2502 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2503 		    icmph->icmph_type, icmph->icmph_code));
2504 
2505 		/* Have to change db_type after any pullupmsg */
2506 		DB_TYPE(mp) = M_CTL;
2507 
2508 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2509 		    mctl_present, ip_policy, recv_ill, zoneid);
2510 		return;
2511 
2512 	case IPPROTO_TCP:
2513 		/*
2514 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2515 		 * transport header.
2516 		 */
2517 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2518 		    mp->b_wptr) {
2519 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2520 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2521 				goto discard_pkt;
2522 			}
2523 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2524 			ipha = (ipha_t *)&icmph[1];
2525 		}
2526 		/*
2527 		 * Find a TCP client stream for this packet.
2528 		 * Note that we do a reverse lookup since the header is
2529 		 * in the form we sent it out.
2530 		 */
2531 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2532 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2533 		    ipst);
2534 		if (connp == NULL)
2535 			goto discard_pkt;
2536 
2537 		/* Have to change db_type after any pullupmsg */
2538 		DB_TYPE(mp) = M_CTL;
2539 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2540 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2541 		return;
2542 
2543 	case IPPROTO_SCTP:
2544 		/*
2545 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2546 		 * transport header.
2547 		 */
2548 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2549 		    mp->b_wptr) {
2550 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2551 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2552 				goto discard_pkt;
2553 			}
2554 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2555 			ipha = (ipha_t *)&icmph[1];
2556 		}
2557 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2558 		/*
2559 		 * Find a SCTP client stream for this packet.
2560 		 * Note that we do a reverse lookup since the header is
2561 		 * in the form we sent it out.
2562 		 * The ripha header is only used for the matching and we
2563 		 * only set the src and dst addresses, protocol, and version.
2564 		 */
2565 		ripha.ipha_src = ipha->ipha_dst;
2566 		ripha.ipha_dst = ipha->ipha_src;
2567 		ripha.ipha_protocol = ipha->ipha_protocol;
2568 		ripha.ipha_version_and_hdr_length =
2569 		    ipha->ipha_version_and_hdr_length;
2570 		((uint16_t *)&ports)[0] = up[1];
2571 		((uint16_t *)&ports)[1] = up[0];
2572 
2573 		/* Have to change db_type after any pullupmsg */
2574 		DB_TYPE(mp) = M_CTL;
2575 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2576 		    mctl_present, ip_policy, zoneid);
2577 		return;
2578 
2579 	case IPPROTO_ESP:
2580 	case IPPROTO_AH: {
2581 		int ipsec_rc;
2582 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2583 
2584 		/*
2585 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2586 		 * We will re-use the IPSEC_IN if it is already present as
2587 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2588 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2589 		 * one and attach it in the front.
2590 		 */
2591 		if (ii != NULL) {
2592 			/*
2593 			 * ip_fanout_proto_again converts the ICMP errors
2594 			 * that come back from AH/ESP to M_DATA so that
2595 			 * if it is non-AH/ESP and we do a pullupmsg in
2596 			 * this function, it would work. Convert it back
2597 			 * to M_CTL before we send up as this is a ICMP
2598 			 * error. This could have been generated locally or
2599 			 * by some router. Validate the inner IPsec
2600 			 * headers.
2601 			 *
2602 			 * NOTE : ill_index is used by ip_fanout_proto_again
2603 			 * to locate the ill.
2604 			 */
2605 			ASSERT(ill != NULL);
2606 			ii->ipsec_in_ill_index =
2607 			    ill->ill_phyint->phyint_ifindex;
2608 			ii->ipsec_in_rill_index =
2609 			    recv_ill->ill_phyint->phyint_ifindex;
2610 			DB_TYPE(first_mp->b_cont) = M_CTL;
2611 		} else {
2612 			/*
2613 			 * IPSEC_IN is not present. We attach a ipsec_in
2614 			 * message and send up to IPsec for validating
2615 			 * and removing the IPsec headers. Clear
2616 			 * ipsec_in_secure so that when we return
2617 			 * from IPsec, we don't mistakenly think that this
2618 			 * is a secure packet came from the network.
2619 			 *
2620 			 * NOTE : ill_index is used by ip_fanout_proto_again
2621 			 * to locate the ill.
2622 			 */
2623 			ASSERT(first_mp == mp);
2624 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2625 			if (first_mp == NULL) {
2626 				freemsg(mp);
2627 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2628 				return;
2629 			}
2630 			ii = (ipsec_in_t *)first_mp->b_rptr;
2631 
2632 			/* This is not a secure packet */
2633 			ii->ipsec_in_secure = B_FALSE;
2634 			first_mp->b_cont = mp;
2635 			DB_TYPE(mp) = M_CTL;
2636 			ASSERT(ill != NULL);
2637 			ii->ipsec_in_ill_index =
2638 			    ill->ill_phyint->phyint_ifindex;
2639 			ii->ipsec_in_rill_index =
2640 			    recv_ill->ill_phyint->phyint_ifindex;
2641 		}
2642 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2643 
2644 		if (!ipsec_loaded(ipss)) {
2645 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2646 			return;
2647 		}
2648 
2649 		if (ipha->ipha_protocol == IPPROTO_ESP)
2650 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2651 		else
2652 			ipsec_rc = ipsecah_icmp_error(first_mp);
2653 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2654 			return;
2655 
2656 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2657 		return;
2658 	}
2659 	default:
2660 		/*
2661 		 * The ripha header is only used for the lookup and we
2662 		 * only set the src and dst addresses and protocol.
2663 		 */
2664 		ripha.ipha_src = ipha->ipha_dst;
2665 		ripha.ipha_dst = ipha->ipha_src;
2666 		ripha.ipha_protocol = ipha->ipha_protocol;
2667 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2668 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2669 		    ntohl(ipha->ipha_dst),
2670 		    icmph->icmph_type, icmph->icmph_code));
2671 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2672 			ipha_t *in_ipha;
2673 
2674 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2675 			    mp->b_wptr) {
2676 				if (!pullupmsg(mp, (uchar_t *)ipha +
2677 				    hdr_length + sizeof (ipha_t) -
2678 				    mp->b_rptr)) {
2679 					goto discard_pkt;
2680 				}
2681 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2682 				ipha = (ipha_t *)&icmph[1];
2683 			}
2684 			/*
2685 			 * Caller has verified that length has to be
2686 			 * at least the size of IP header.
2687 			 */
2688 			ASSERT(hdr_length >= sizeof (ipha_t));
2689 			/*
2690 			 * Check the sanity of the inner IP header like
2691 			 * we did for the outer header.
2692 			 */
2693 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2694 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2695 				goto discard_pkt;
2696 			}
2697 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2698 				goto discard_pkt;
2699 			}
2700 			/* Check for Self-encapsulated tunnels */
2701 			if (in_ipha->ipha_src == ipha->ipha_src &&
2702 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2703 
2704 				mp = icmp_inbound_self_encap_error(mp,
2705 				    iph_hdr_length, hdr_length);
2706 				if (mp == NULL)
2707 					goto discard_pkt;
2708 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2709 				ipha = (ipha_t *)&icmph[1];
2710 				hdr_length = IPH_HDR_LENGTH(ipha);
2711 				/*
2712 				 * The packet in error is self-encapsualted.
2713 				 * And we are finding it further encapsulated
2714 				 * which we could not have possibly generated.
2715 				 */
2716 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2717 					goto discard_pkt;
2718 				}
2719 				icmp_inbound_error_fanout(q, ill, first_mp,
2720 				    icmph, ipha, iph_hdr_length, hdr_length,
2721 				    mctl_present, ip_policy, recv_ill, zoneid);
2722 				return;
2723 			}
2724 		}
2725 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2726 		    ipha->ipha_protocol == IPPROTO_IPV6) &&
2727 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2728 		    ii != NULL &&
2729 		    ii->ipsec_in_loopback &&
2730 		    ii->ipsec_in_secure) {
2731 			/*
2732 			 * For IP tunnels that get a looped-back
2733 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2734 			 * reported new MTU to take into account the IPsec
2735 			 * headers protecting this configured tunnel.
2736 			 *
2737 			 * This allows the tunnel module (tun.c) to blindly
2738 			 * accept the MTU reported in an ICMP "too big"
2739 			 * message.
2740 			 *
2741 			 * Non-looped back ICMP messages will just be
2742 			 * handled by the security protocols (if needed),
2743 			 * and the first subsequent packet will hit this
2744 			 * path.
2745 			 */
2746 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2747 			    ipsec_in_extra_length(first_mp));
2748 		}
2749 		/* Have to change db_type after any pullupmsg */
2750 		DB_TYPE(mp) = M_CTL;
2751 
2752 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2753 		    ip_policy, recv_ill, zoneid);
2754 		return;
2755 	}
2756 	/* NOTREACHED */
2757 discard_pkt:
2758 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2759 drop_pkt:;
2760 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2761 	freemsg(first_mp);
2762 }
2763 
2764 /*
2765  * Common IP options parser.
2766  *
2767  * Setup routine: fill in *optp with options-parsing state, then
2768  * tail-call ipoptp_next to return the first option.
2769  */
2770 uint8_t
2771 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2772 {
2773 	uint32_t totallen; /* total length of all options */
2774 
2775 	totallen = ipha->ipha_version_and_hdr_length -
2776 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2777 	totallen <<= 2;
2778 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2779 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2780 	optp->ipoptp_flags = 0;
2781 	return (ipoptp_next(optp));
2782 }
2783 
2784 /*
2785  * Common IP options parser: extract next option.
2786  */
2787 uint8_t
2788 ipoptp_next(ipoptp_t *optp)
2789 {
2790 	uint8_t *end = optp->ipoptp_end;
2791 	uint8_t *cur = optp->ipoptp_next;
2792 	uint8_t opt, len, pointer;
2793 
2794 	/*
2795 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2796 	 * has been corrupted.
2797 	 */
2798 	ASSERT(cur <= end);
2799 
2800 	if (cur == end)
2801 		return (IPOPT_EOL);
2802 
2803 	opt = cur[IPOPT_OPTVAL];
2804 
2805 	/*
2806 	 * Skip any NOP options.
2807 	 */
2808 	while (opt == IPOPT_NOP) {
2809 		cur++;
2810 		if (cur == end)
2811 			return (IPOPT_EOL);
2812 		opt = cur[IPOPT_OPTVAL];
2813 	}
2814 
2815 	if (opt == IPOPT_EOL)
2816 		return (IPOPT_EOL);
2817 
2818 	/*
2819 	 * Option requiring a length.
2820 	 */
2821 	if ((cur + 1) >= end) {
2822 		optp->ipoptp_flags |= IPOPTP_ERROR;
2823 		return (IPOPT_EOL);
2824 	}
2825 	len = cur[IPOPT_OLEN];
2826 	if (len < 2) {
2827 		optp->ipoptp_flags |= IPOPTP_ERROR;
2828 		return (IPOPT_EOL);
2829 	}
2830 	optp->ipoptp_cur = cur;
2831 	optp->ipoptp_len = len;
2832 	optp->ipoptp_next = cur + len;
2833 	if (cur + len > end) {
2834 		optp->ipoptp_flags |= IPOPTP_ERROR;
2835 		return (IPOPT_EOL);
2836 	}
2837 
2838 	/*
2839 	 * For the options which require a pointer field, make sure
2840 	 * its there, and make sure it points to either something
2841 	 * inside this option, or the end of the option.
2842 	 */
2843 	switch (opt) {
2844 	case IPOPT_RR:
2845 	case IPOPT_TS:
2846 	case IPOPT_LSRR:
2847 	case IPOPT_SSRR:
2848 		if (len <= IPOPT_OFFSET) {
2849 			optp->ipoptp_flags |= IPOPTP_ERROR;
2850 			return (opt);
2851 		}
2852 		pointer = cur[IPOPT_OFFSET];
2853 		if (pointer - 1 > len) {
2854 			optp->ipoptp_flags |= IPOPTP_ERROR;
2855 			return (opt);
2856 		}
2857 		break;
2858 	}
2859 
2860 	/*
2861 	 * Sanity check the pointer field based on the type of the
2862 	 * option.
2863 	 */
2864 	switch (opt) {
2865 	case IPOPT_RR:
2866 	case IPOPT_SSRR:
2867 	case IPOPT_LSRR:
2868 		if (pointer < IPOPT_MINOFF_SR)
2869 			optp->ipoptp_flags |= IPOPTP_ERROR;
2870 		break;
2871 	case IPOPT_TS:
2872 		if (pointer < IPOPT_MINOFF_IT)
2873 			optp->ipoptp_flags |= IPOPTP_ERROR;
2874 		/*
2875 		 * Note that the Internet Timestamp option also
2876 		 * contains two four bit fields (the Overflow field,
2877 		 * and the Flag field), which follow the pointer
2878 		 * field.  We don't need to check that these fields
2879 		 * fall within the length of the option because this
2880 		 * was implicitely done above.  We've checked that the
2881 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2882 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2883 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2884 		 */
2885 		ASSERT(len > IPOPT_POS_OV_FLG);
2886 		break;
2887 	}
2888 
2889 	return (opt);
2890 }
2891 
2892 /*
2893  * Use the outgoing IP header to create an IP_OPTIONS option the way
2894  * it was passed down from the application.
2895  */
2896 int
2897 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2898 {
2899 	ipoptp_t	opts;
2900 	const uchar_t	*opt;
2901 	uint8_t		optval;
2902 	uint8_t		optlen;
2903 	uint32_t	len = 0;
2904 	uchar_t	*buf1 = buf;
2905 
2906 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2907 	len += IP_ADDR_LEN;
2908 	bzero(buf1, IP_ADDR_LEN);
2909 
2910 	/*
2911 	 * OK to cast away const here, as we don't store through the returned
2912 	 * opts.ipoptp_cur pointer.
2913 	 */
2914 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2915 	    optval != IPOPT_EOL;
2916 	    optval = ipoptp_next(&opts)) {
2917 		int	off;
2918 
2919 		opt = opts.ipoptp_cur;
2920 		optlen = opts.ipoptp_len;
2921 		switch (optval) {
2922 		case IPOPT_SSRR:
2923 		case IPOPT_LSRR:
2924 
2925 			/*
2926 			 * Insert ipha_dst as the first entry in the source
2927 			 * route and move down the entries on step.
2928 			 * The last entry gets placed at buf1.
2929 			 */
2930 			buf[IPOPT_OPTVAL] = optval;
2931 			buf[IPOPT_OLEN] = optlen;
2932 			buf[IPOPT_OFFSET] = optlen;
2933 
2934 			off = optlen - IP_ADDR_LEN;
2935 			if (off < 0) {
2936 				/* No entries in source route */
2937 				break;
2938 			}
2939 			/* Last entry in source route */
2940 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2941 			off -= IP_ADDR_LEN;
2942 
2943 			while (off > 0) {
2944 				bcopy(opt + off,
2945 				    buf + off + IP_ADDR_LEN,
2946 				    IP_ADDR_LEN);
2947 				off -= IP_ADDR_LEN;
2948 			}
2949 			/* ipha_dst into first slot */
2950 			bcopy(&ipha->ipha_dst,
2951 			    buf + off + IP_ADDR_LEN,
2952 			    IP_ADDR_LEN);
2953 			buf += optlen;
2954 			len += optlen;
2955 			break;
2956 
2957 		case IPOPT_COMSEC:
2958 		case IPOPT_SECURITY:
2959 			/* if passing up a label is not ok, then remove */
2960 			if (is_system_labeled())
2961 				break;
2962 			/* FALLTHROUGH */
2963 		default:
2964 			bcopy(opt, buf, optlen);
2965 			buf += optlen;
2966 			len += optlen;
2967 			break;
2968 		}
2969 	}
2970 done:
2971 	/* Pad the resulting options */
2972 	while (len & 0x3) {
2973 		*buf++ = IPOPT_EOL;
2974 		len++;
2975 	}
2976 	return (len);
2977 }
2978 
2979 /*
2980  * Update any record route or timestamp options to include this host.
2981  * Reverse any source route option.
2982  * This routine assumes that the options are well formed i.e. that they
2983  * have already been checked.
2984  */
2985 static void
2986 icmp_options_update(ipha_t *ipha)
2987 {
2988 	ipoptp_t	opts;
2989 	uchar_t		*opt;
2990 	uint8_t		optval;
2991 	ipaddr_t	src;		/* Our local address */
2992 	ipaddr_t	dst;
2993 
2994 	ip2dbg(("icmp_options_update\n"));
2995 	src = ipha->ipha_src;
2996 	dst = ipha->ipha_dst;
2997 
2998 	for (optval = ipoptp_first(&opts, ipha);
2999 	    optval != IPOPT_EOL;
3000 	    optval = ipoptp_next(&opts)) {
3001 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
3002 		opt = opts.ipoptp_cur;
3003 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
3004 		    optval, opts.ipoptp_len));
3005 		switch (optval) {
3006 			int off1, off2;
3007 		case IPOPT_SSRR:
3008 		case IPOPT_LSRR:
3009 			/*
3010 			 * Reverse the source route.  The first entry
3011 			 * should be the next to last one in the current
3012 			 * source route (the last entry is our address).
3013 			 * The last entry should be the final destination.
3014 			 */
3015 			off1 = IPOPT_MINOFF_SR - 1;
3016 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3017 			if (off2 < 0) {
3018 				/* No entries in source route */
3019 				ip1dbg((
3020 				    "icmp_options_update: bad src route\n"));
3021 				break;
3022 			}
3023 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3024 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3025 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3026 			off2 -= IP_ADDR_LEN;
3027 
3028 			while (off1 < off2) {
3029 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3030 				bcopy((char *)opt + off2, (char *)opt + off1,
3031 				    IP_ADDR_LEN);
3032 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3033 				off1 += IP_ADDR_LEN;
3034 				off2 -= IP_ADDR_LEN;
3035 			}
3036 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3037 			break;
3038 		}
3039 	}
3040 }
3041 
3042 /*
3043  * Process received ICMP Redirect messages.
3044  */
3045 static void
3046 icmp_redirect(ill_t *ill, mblk_t *mp)
3047 {
3048 	ipha_t	*ipha;
3049 	int	iph_hdr_length;
3050 	icmph_t	*icmph;
3051 	ipha_t	*ipha_err;
3052 	ire_t	*ire;
3053 	ire_t	*prev_ire;
3054 	ire_t	*save_ire;
3055 	ipaddr_t  src, dst, gateway;
3056 	iulp_t	ulp_info = { 0 };
3057 	int	error;
3058 	ip_stack_t *ipst;
3059 
3060 	ASSERT(ill != NULL);
3061 	ipst = ill->ill_ipst;
3062 
3063 	ipha = (ipha_t *)mp->b_rptr;
3064 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3065 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3066 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3067 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3068 		freemsg(mp);
3069 		return;
3070 	}
3071 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3072 	ipha_err = (ipha_t *)&icmph[1];
3073 	src = ipha->ipha_src;
3074 	dst = ipha_err->ipha_dst;
3075 	gateway = icmph->icmph_rd_gateway;
3076 	/* Make sure the new gateway is reachable somehow. */
3077 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3078 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3079 	/*
3080 	 * Make sure we had a route for the dest in question and that
3081 	 * that route was pointing to the old gateway (the source of the
3082 	 * redirect packet.)
3083 	 */
3084 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3085 	    NULL, MATCH_IRE_GW, ipst);
3086 	/*
3087 	 * Check that
3088 	 *	the redirect was not from ourselves
3089 	 *	the new gateway and the old gateway are directly reachable
3090 	 */
3091 	if (!prev_ire ||
3092 	    !ire ||
3093 	    ire->ire_type == IRE_LOCAL) {
3094 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3095 		freemsg(mp);
3096 		if (ire != NULL)
3097 			ire_refrele(ire);
3098 		if (prev_ire != NULL)
3099 			ire_refrele(prev_ire);
3100 		return;
3101 	}
3102 
3103 	/*
3104 	 * Should we use the old ULP info to create the new gateway?  From
3105 	 * a user's perspective, we should inherit the info so that it
3106 	 * is a "smooth" transition.  If we do not do that, then new
3107 	 * connections going thru the new gateway will have no route metrics,
3108 	 * which is counter-intuitive to user.  From a network point of
3109 	 * view, this may or may not make sense even though the new gateway
3110 	 * is still directly connected to us so the route metrics should not
3111 	 * change much.
3112 	 *
3113 	 * But if the old ire_uinfo is not initialized, we do another
3114 	 * recursive lookup on the dest using the new gateway.  There may
3115 	 * be a route to that.  If so, use it to initialize the redirect
3116 	 * route.
3117 	 */
3118 	if (prev_ire->ire_uinfo.iulp_set) {
3119 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3120 	} else {
3121 		ire_t *tmp_ire;
3122 		ire_t *sire;
3123 
3124 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3125 		    ALL_ZONES, 0, NULL,
3126 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3127 		    ipst);
3128 		if (sire != NULL) {
3129 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3130 			/*
3131 			 * If sire != NULL, ire_ftable_lookup() should not
3132 			 * return a NULL value.
3133 			 */
3134 			ASSERT(tmp_ire != NULL);
3135 			ire_refrele(tmp_ire);
3136 			ire_refrele(sire);
3137 		} else if (tmp_ire != NULL) {
3138 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3139 			    sizeof (iulp_t));
3140 			ire_refrele(tmp_ire);
3141 		}
3142 	}
3143 	if (prev_ire->ire_type == IRE_CACHE)
3144 		ire_delete(prev_ire);
3145 	ire_refrele(prev_ire);
3146 	/*
3147 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3148 	 * require TOS routing
3149 	 */
3150 	switch (icmph->icmph_code) {
3151 	case 0:
3152 	case 1:
3153 		/* TODO: TOS specificity for cases 2 and 3 */
3154 	case 2:
3155 	case 3:
3156 		break;
3157 	default:
3158 		freemsg(mp);
3159 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3160 		ire_refrele(ire);
3161 		return;
3162 	}
3163 	/*
3164 	 * Create a Route Association.  This will allow us to remember that
3165 	 * someone we believe told us to use the particular gateway.
3166 	 */
3167 	save_ire = ire;
3168 	ire = ire_create(
3169 	    (uchar_t *)&dst,			/* dest addr */
3170 	    (uchar_t *)&ip_g_all_ones,		/* mask */
3171 	    (uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3172 	    (uchar_t *)&gateway,		/* gateway addr */
3173 	    &save_ire->ire_max_frag,		/* max frag */
3174 	    NULL,				/* no src nce */
3175 	    NULL,				/* no rfq */
3176 	    NULL,				/* no stq */
3177 	    IRE_HOST,
3178 	    NULL,				/* ipif */
3179 	    0,					/* cmask */
3180 	    0,					/* phandle */
3181 	    0,					/* ihandle */
3182 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3183 	    &ulp_info,
3184 	    NULL,				/* tsol_gc_t */
3185 	    NULL,				/* gcgrp */
3186 	    ipst);
3187 
3188 	if (ire == NULL) {
3189 		freemsg(mp);
3190 		ire_refrele(save_ire);
3191 		return;
3192 	}
3193 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3194 	ire_refrele(save_ire);
3195 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3196 
3197 	if (error == 0) {
3198 		ire_refrele(ire);		/* Held in ire_add_v4 */
3199 		/* tell routing sockets that we received a redirect */
3200 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3201 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3202 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3203 	}
3204 
3205 	/*
3206 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3207 	 * This together with the added IRE has the effect of
3208 	 * modifying an existing redirect.
3209 	 */
3210 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3211 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3212 	if (prev_ire != NULL) {
3213 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3214 			ire_delete(prev_ire);
3215 		ire_refrele(prev_ire);
3216 	}
3217 
3218 	freemsg(mp);
3219 }
3220 
3221 /*
3222  * Generate an ICMP parameter problem message.
3223  */
3224 static void
3225 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3226 	ip_stack_t *ipst)
3227 {
3228 	icmph_t	icmph;
3229 	boolean_t mctl_present;
3230 	mblk_t *first_mp;
3231 
3232 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3233 
3234 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3235 		if (mctl_present)
3236 			freeb(first_mp);
3237 		return;
3238 	}
3239 
3240 	bzero(&icmph, sizeof (icmph_t));
3241 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3242 	icmph.icmph_pp_ptr = ptr;
3243 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3244 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3245 	    ipst);
3246 }
3247 
3248 /*
3249  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3250  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3251  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3252  * an icmp error packet can be sent.
3253  * Assigns an appropriate source address to the packet. If ipha_dst is
3254  * one of our addresses use it for source. Otherwise pick a source based
3255  * on a route lookup back to ipha_src.
3256  * Note that ipha_src must be set here since the
3257  * packet is likely to arrive on an ill queue in ip_wput() which will
3258  * not set a source address.
3259  */
3260 static void
3261 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3262     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3263 {
3264 	ipaddr_t dst;
3265 	icmph_t	*icmph;
3266 	ipha_t	*ipha;
3267 	uint_t	len_needed;
3268 	size_t	msg_len;
3269 	mblk_t	*mp1;
3270 	ipaddr_t src;
3271 	ire_t	*ire;
3272 	mblk_t *ipsec_mp;
3273 	ipsec_out_t	*io = NULL;
3274 
3275 	if (mctl_present) {
3276 		/*
3277 		 * If it is :
3278 		 *
3279 		 * 1) a IPSEC_OUT, then this is caused by outbound
3280 		 *    datagram originating on this host. IPsec processing
3281 		 *    may or may not have been done. Refer to comments above
3282 		 *    icmp_inbound_error_fanout for details.
3283 		 *
3284 		 * 2) a IPSEC_IN if we are generating a icmp_message
3285 		 *    for an incoming datagram destined for us i.e called
3286 		 *    from ip_fanout_send_icmp.
3287 		 */
3288 		ipsec_info_t *in;
3289 		ipsec_mp = mp;
3290 		mp = ipsec_mp->b_cont;
3291 
3292 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3293 		ipha = (ipha_t *)mp->b_rptr;
3294 
3295 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3296 		    in->ipsec_info_type == IPSEC_IN);
3297 
3298 		if (in->ipsec_info_type == IPSEC_IN) {
3299 			/*
3300 			 * Convert the IPSEC_IN to IPSEC_OUT.
3301 			 */
3302 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3303 				BUMP_MIB(&ipst->ips_ip_mib,
3304 				    ipIfStatsOutDiscards);
3305 				return;
3306 			}
3307 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3308 		} else {
3309 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3310 			io = (ipsec_out_t *)in;
3311 			/*
3312 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3313 			 * ire lookup.
3314 			 */
3315 			io->ipsec_out_proc_begin = B_FALSE;
3316 		}
3317 		ASSERT(zoneid == io->ipsec_out_zoneid);
3318 		ASSERT(zoneid != ALL_ZONES);
3319 	} else {
3320 		/*
3321 		 * This is in clear. The icmp message we are building
3322 		 * here should go out in clear.
3323 		 *
3324 		 * Pardon the convolution of it all, but it's easier to
3325 		 * allocate a "use cleartext" IPSEC_IN message and convert
3326 		 * it than it is to allocate a new one.
3327 		 */
3328 		ipsec_in_t *ii;
3329 		ASSERT(DB_TYPE(mp) == M_DATA);
3330 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3331 		if (ipsec_mp == NULL) {
3332 			freemsg(mp);
3333 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3334 			return;
3335 		}
3336 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3337 
3338 		/* This is not a secure packet */
3339 		ii->ipsec_in_secure = B_FALSE;
3340 		/*
3341 		 * For trusted extensions using a shared IP address we can
3342 		 * send using any zoneid.
3343 		 */
3344 		if (zoneid == ALL_ZONES)
3345 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3346 		else
3347 			ii->ipsec_in_zoneid = zoneid;
3348 		ipsec_mp->b_cont = mp;
3349 		ipha = (ipha_t *)mp->b_rptr;
3350 		/*
3351 		 * Convert the IPSEC_IN to IPSEC_OUT.
3352 		 */
3353 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3354 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3355 			return;
3356 		}
3357 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3358 	}
3359 
3360 	/* Remember our eventual destination */
3361 	dst = ipha->ipha_src;
3362 
3363 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3364 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3365 	if (ire != NULL &&
3366 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3367 		src = ipha->ipha_dst;
3368 	} else {
3369 		if (ire != NULL)
3370 			ire_refrele(ire);
3371 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3372 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3373 		    ipst);
3374 		if (ire == NULL) {
3375 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3376 			freemsg(ipsec_mp);
3377 			return;
3378 		}
3379 		src = ire->ire_src_addr;
3380 	}
3381 
3382 	if (ire != NULL)
3383 		ire_refrele(ire);
3384 
3385 	/*
3386 	 * Check if we can send back more then 8 bytes in addition to
3387 	 * the IP header.  We try to send 64 bytes of data and the internal
3388 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3389 	 */
3390 	len_needed = IPH_HDR_LENGTH(ipha);
3391 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3392 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3393 
3394 		if (!pullupmsg(mp, -1)) {
3395 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3396 			freemsg(ipsec_mp);
3397 			return;
3398 		}
3399 		ipha = (ipha_t *)mp->b_rptr;
3400 
3401 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3402 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3403 			    len_needed));
3404 		} else {
3405 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3406 
3407 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3408 			len_needed += ip_hdr_length_v6(mp, ip6h);
3409 		}
3410 	}
3411 	len_needed += ipst->ips_ip_icmp_return;
3412 	msg_len = msgdsize(mp);
3413 	if (msg_len > len_needed) {
3414 		(void) adjmsg(mp, len_needed - msg_len);
3415 		msg_len = len_needed;
3416 	}
3417 	mp1 = allocb_tmpl(sizeof (icmp_ipha) + len, mp);
3418 	if (mp1 == NULL) {
3419 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3420 		freemsg(ipsec_mp);
3421 		return;
3422 	}
3423 	mp1->b_cont = mp;
3424 	mp = mp1;
3425 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3426 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3427 	    io->ipsec_out_type == IPSEC_OUT);
3428 	ipsec_mp->b_cont = mp;
3429 
3430 	/*
3431 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3432 	 * node generates be accepted in peace by all on-host destinations.
3433 	 * If we do NOT assume that all on-host destinations trust
3434 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3435 	 * (Look for ipsec_out_icmp_loopback).
3436 	 */
3437 	io->ipsec_out_icmp_loopback = B_TRUE;
3438 
3439 	ipha = (ipha_t *)mp->b_rptr;
3440 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3441 	*ipha = icmp_ipha;
3442 	ipha->ipha_src = src;
3443 	ipha->ipha_dst = dst;
3444 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3445 	msg_len += sizeof (icmp_ipha) + len;
3446 	if (msg_len > IP_MAXPACKET) {
3447 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3448 		msg_len = IP_MAXPACKET;
3449 	}
3450 	ipha->ipha_length = htons((uint16_t)msg_len);
3451 	icmph = (icmph_t *)&ipha[1];
3452 	bcopy(stuff, icmph, len);
3453 	icmph->icmph_checksum = 0;
3454 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3455 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3456 	put(q, ipsec_mp);
3457 }
3458 
3459 /*
3460  * Determine if an ICMP error packet can be sent given the rate limit.
3461  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3462  * in milliseconds) and a burst size. Burst size number of packets can
3463  * be sent arbitrarely closely spaced.
3464  * The state is tracked using two variables to implement an approximate
3465  * token bucket filter:
3466  *	icmp_pkt_err_last - lbolt value when the last burst started
3467  *	icmp_pkt_err_sent - number of packets sent in current burst
3468  */
3469 boolean_t
3470 icmp_err_rate_limit(ip_stack_t *ipst)
3471 {
3472 	clock_t now = TICK_TO_MSEC(lbolt);
3473 	uint_t refilled; /* Number of packets refilled in tbf since last */
3474 	/* Guard against changes by loading into local variable */
3475 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3476 
3477 	if (err_interval == 0)
3478 		return (B_FALSE);
3479 
3480 	if (ipst->ips_icmp_pkt_err_last > now) {
3481 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3482 		ipst->ips_icmp_pkt_err_last = 0;
3483 		ipst->ips_icmp_pkt_err_sent = 0;
3484 	}
3485 	/*
3486 	 * If we are in a burst update the token bucket filter.
3487 	 * Update the "last" time to be close to "now" but make sure
3488 	 * we don't loose precision.
3489 	 */
3490 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3491 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3492 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3493 			ipst->ips_icmp_pkt_err_sent = 0;
3494 		} else {
3495 			ipst->ips_icmp_pkt_err_sent -= refilled;
3496 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3497 		}
3498 	}
3499 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3500 		/* Start of new burst */
3501 		ipst->ips_icmp_pkt_err_last = now;
3502 	}
3503 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3504 		ipst->ips_icmp_pkt_err_sent++;
3505 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3506 		    ipst->ips_icmp_pkt_err_sent));
3507 		return (B_FALSE);
3508 	}
3509 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3510 	return (B_TRUE);
3511 }
3512 
3513 /*
3514  * Check if it is ok to send an IPv4 ICMP error packet in
3515  * response to the IPv4 packet in mp.
3516  * Free the message and return null if no
3517  * ICMP error packet should be sent.
3518  */
3519 static mblk_t *
3520 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3521 {
3522 	icmph_t	*icmph;
3523 	ipha_t	*ipha;
3524 	uint_t	len_needed;
3525 	ire_t	*src_ire;
3526 	ire_t	*dst_ire;
3527 
3528 	if (!mp)
3529 		return (NULL);
3530 	ipha = (ipha_t *)mp->b_rptr;
3531 	if (ip_csum_hdr(ipha)) {
3532 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3533 		freemsg(mp);
3534 		return (NULL);
3535 	}
3536 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3537 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3538 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3539 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3540 	if (src_ire != NULL || dst_ire != NULL ||
3541 	    CLASSD(ipha->ipha_dst) ||
3542 	    CLASSD(ipha->ipha_src) ||
3543 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3544 		/* Note: only errors to the fragment with offset 0 */
3545 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3546 		freemsg(mp);
3547 		if (src_ire != NULL)
3548 			ire_refrele(src_ire);
3549 		if (dst_ire != NULL)
3550 			ire_refrele(dst_ire);
3551 		return (NULL);
3552 	}
3553 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3554 		/*
3555 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3556 		 * errors in response to any ICMP errors.
3557 		 */
3558 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3559 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3560 			if (!pullupmsg(mp, len_needed)) {
3561 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3562 				freemsg(mp);
3563 				return (NULL);
3564 			}
3565 			ipha = (ipha_t *)mp->b_rptr;
3566 		}
3567 		icmph = (icmph_t *)
3568 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3569 		switch (icmph->icmph_type) {
3570 		case ICMP_DEST_UNREACHABLE:
3571 		case ICMP_SOURCE_QUENCH:
3572 		case ICMP_TIME_EXCEEDED:
3573 		case ICMP_PARAM_PROBLEM:
3574 		case ICMP_REDIRECT:
3575 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3576 			freemsg(mp);
3577 			return (NULL);
3578 		default:
3579 			break;
3580 		}
3581 	}
3582 	/*
3583 	 * If this is a labeled system, then check to see if we're allowed to
3584 	 * send a response to this particular sender.  If not, then just drop.
3585 	 */
3586 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3587 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3588 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3589 		freemsg(mp);
3590 		return (NULL);
3591 	}
3592 	if (icmp_err_rate_limit(ipst)) {
3593 		/*
3594 		 * Only send ICMP error packets every so often.
3595 		 * This should be done on a per port/source basis,
3596 		 * but for now this will suffice.
3597 		 */
3598 		freemsg(mp);
3599 		return (NULL);
3600 	}
3601 	return (mp);
3602 }
3603 
3604 /*
3605  * Generate an ICMP redirect message.
3606  */
3607 static void
3608 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3609 {
3610 	icmph_t	icmph;
3611 
3612 	/*
3613 	 * We are called from ip_rput where we could
3614 	 * not have attached an IPSEC_IN.
3615 	 */
3616 	ASSERT(mp->b_datap->db_type == M_DATA);
3617 
3618 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3619 		return;
3620 	}
3621 
3622 	bzero(&icmph, sizeof (icmph_t));
3623 	icmph.icmph_type = ICMP_REDIRECT;
3624 	icmph.icmph_code = 1;
3625 	icmph.icmph_rd_gateway = gateway;
3626 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3627 	/* Redirects sent by router, and router is global zone */
3628 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3629 }
3630 
3631 /*
3632  * Generate an ICMP time exceeded message.
3633  */
3634 void
3635 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3636     ip_stack_t *ipst)
3637 {
3638 	icmph_t	icmph;
3639 	boolean_t mctl_present;
3640 	mblk_t *first_mp;
3641 
3642 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3643 
3644 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3645 		if (mctl_present)
3646 			freeb(first_mp);
3647 		return;
3648 	}
3649 
3650 	bzero(&icmph, sizeof (icmph_t));
3651 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3652 	icmph.icmph_code = code;
3653 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3654 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3655 	    ipst);
3656 }
3657 
3658 /*
3659  * Generate an ICMP unreachable message.
3660  */
3661 void
3662 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3663     ip_stack_t *ipst)
3664 {
3665 	icmph_t	icmph;
3666 	mblk_t *first_mp;
3667 	boolean_t mctl_present;
3668 
3669 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3670 
3671 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3672 		if (mctl_present)
3673 			freeb(first_mp);
3674 		return;
3675 	}
3676 
3677 	bzero(&icmph, sizeof (icmph_t));
3678 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3679 	icmph.icmph_code = code;
3680 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3681 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3682 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3683 	    zoneid, ipst);
3684 }
3685 
3686 /*
3687  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3688  * duplicate.  As long as someone else holds the address, the interface will
3689  * stay down.  When that conflict goes away, the interface is brought back up.
3690  * This is done so that accidental shutdowns of addresses aren't made
3691  * permanent.  Your server will recover from a failure.
3692  *
3693  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3694  * user space process (dhcpagent).
3695  *
3696  * Recovery completes if ARP reports that the address is now ours (via
3697  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3698  *
3699  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3700  */
3701 static void
3702 ipif_dup_recovery(void *arg)
3703 {
3704 	ipif_t *ipif = arg;
3705 	ill_t *ill = ipif->ipif_ill;
3706 	mblk_t *arp_add_mp;
3707 	mblk_t *arp_del_mp;
3708 	area_t *area;
3709 	ip_stack_t *ipst = ill->ill_ipst;
3710 
3711 	ipif->ipif_recovery_id = 0;
3712 
3713 	/*
3714 	 * No lock needed for moving or condemned check, as this is just an
3715 	 * optimization.
3716 	 */
3717 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3718 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3719 	    (ipif->ipif_state_flags & (IPIF_MOVING | IPIF_CONDEMNED))) {
3720 		/* No reason to try to bring this address back. */
3721 		return;
3722 	}
3723 
3724 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3725 		goto alloc_fail;
3726 
3727 	if (ipif->ipif_arp_del_mp == NULL) {
3728 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3729 			goto alloc_fail;
3730 		ipif->ipif_arp_del_mp = arp_del_mp;
3731 	}
3732 
3733 	/* Setting the 'unverified' flag restarts DAD */
3734 	area = (area_t *)arp_add_mp->b_rptr;
3735 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3736 	    ACE_F_UNVERIFIED;
3737 	putnext(ill->ill_rq, arp_add_mp);
3738 	return;
3739 
3740 alloc_fail:
3741 	/*
3742 	 * On allocation failure, just restart the timer.  Note that the ipif
3743 	 * is down here, so no other thread could be trying to start a recovery
3744 	 * timer.  The ill_lock protects the condemned flag and the recovery
3745 	 * timer ID.
3746 	 */
3747 	freemsg(arp_add_mp);
3748 	mutex_enter(&ill->ill_lock);
3749 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3750 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3751 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3752 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3753 	}
3754 	mutex_exit(&ill->ill_lock);
3755 }
3756 
3757 /*
3758  * This is for exclusive changes due to ARP.  Either tear down an interface due
3759  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3760  */
3761 /* ARGSUSED */
3762 static void
3763 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3764 {
3765 	ill_t	*ill = rq->q_ptr;
3766 	arh_t *arh;
3767 	ipaddr_t src;
3768 	ipif_t	*ipif;
3769 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3770 	char hbuf[MAC_STR_LEN];
3771 	char sbuf[INET_ADDRSTRLEN];
3772 	const char *failtype;
3773 	boolean_t bring_up;
3774 	ip_stack_t *ipst = ill->ill_ipst;
3775 
3776 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3777 	case AR_CN_READY:
3778 		failtype = NULL;
3779 		bring_up = B_TRUE;
3780 		break;
3781 	case AR_CN_FAILED:
3782 		failtype = "in use";
3783 		bring_up = B_FALSE;
3784 		break;
3785 	default:
3786 		failtype = "claimed";
3787 		bring_up = B_FALSE;
3788 		break;
3789 	}
3790 
3791 	arh = (arh_t *)mp->b_cont->b_rptr;
3792 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3793 
3794 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3795 	    sizeof (hbuf));
3796 	(void) ip_dot_addr(src, sbuf);
3797 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3798 
3799 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3800 		    ipif->ipif_lcl_addr != src) {
3801 			continue;
3802 		}
3803 
3804 		/*
3805 		 * If we failed on a recovery probe, then restart the timer to
3806 		 * try again later.
3807 		 */
3808 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3809 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3810 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3811 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3812 		    ipst->ips_ip_dup_recovery > 0 &&
3813 		    ipif->ipif_recovery_id == 0) {
3814 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3815 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3816 			continue;
3817 		}
3818 
3819 		/*
3820 		 * If what we're trying to do has already been done, then do
3821 		 * nothing.
3822 		 */
3823 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3824 			continue;
3825 
3826 		ipif_get_name(ipif, ibuf, sizeof (ibuf));
3827 
3828 		if (failtype == NULL) {
3829 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3830 			    ibuf);
3831 		} else {
3832 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3833 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3834 		}
3835 
3836 		if (bring_up) {
3837 			ASSERT(ill->ill_dl_up);
3838 			/*
3839 			 * Free up the ARP delete message so we can allocate
3840 			 * a fresh one through the normal path.
3841 			 */
3842 			freemsg(ipif->ipif_arp_del_mp);
3843 			ipif->ipif_arp_del_mp = NULL;
3844 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3845 			    EINPROGRESS) {
3846 				ipif->ipif_addr_ready = 1;
3847 				(void) ipif_up_done(ipif);
3848 			}
3849 			continue;
3850 		}
3851 
3852 		mutex_enter(&ill->ill_lock);
3853 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3854 		ipif->ipif_flags |= IPIF_DUPLICATE;
3855 		ill->ill_ipif_dup_count++;
3856 		mutex_exit(&ill->ill_lock);
3857 		/*
3858 		 * Already exclusive on the ill; no need to handle deferred
3859 		 * processing here.
3860 		 */
3861 		(void) ipif_down(ipif, NULL, NULL);
3862 		ipif_down_tail(ipif);
3863 		mutex_enter(&ill->ill_lock);
3864 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3865 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3866 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3867 		    ipst->ips_ip_dup_recovery > 0) {
3868 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3869 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3870 		}
3871 		mutex_exit(&ill->ill_lock);
3872 	}
3873 	freemsg(mp);
3874 }
3875 
3876 /* ARGSUSED */
3877 static void
3878 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3879 {
3880 	ill_t	*ill = rq->q_ptr;
3881 	arh_t *arh;
3882 	ipaddr_t src;
3883 	ipif_t	*ipif;
3884 
3885 	arh = (arh_t *)mp->b_cont->b_rptr;
3886 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3887 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3888 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3889 			(void) ipif_resolver_up(ipif, Res_act_defend);
3890 	}
3891 	freemsg(mp);
3892 }
3893 
3894 /*
3895  * News from ARP.  ARP sends notification of interesting events down
3896  * to its clients using M_CTL messages with the interesting ARP packet
3897  * attached via b_cont.
3898  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3899  * queue as opposed to ARP sending the message to all the clients, i.e. all
3900  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3901  * table if a cache IRE is found to delete all the entries for the address in
3902  * the packet.
3903  */
3904 static void
3905 ip_arp_news(queue_t *q, mblk_t *mp)
3906 {
3907 	arcn_t		*arcn;
3908 	arh_t		*arh;
3909 	ire_t		*ire = NULL;
3910 	char		hbuf[MAC_STR_LEN];
3911 	char		sbuf[INET_ADDRSTRLEN];
3912 	ipaddr_t	src;
3913 	in6_addr_t	v6src;
3914 	boolean_t	isv6 = B_FALSE;
3915 	ipif_t		*ipif;
3916 	ill_t		*ill;
3917 	ip_stack_t	*ipst;
3918 
3919 	if (CONN_Q(q)) {
3920 		conn_t *connp = Q_TO_CONN(q);
3921 
3922 		ipst = connp->conn_netstack->netstack_ip;
3923 	} else {
3924 		ill_t *ill = (ill_t *)q->q_ptr;
3925 
3926 		ipst = ill->ill_ipst;
3927 	}
3928 
3929 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3930 		if (q->q_next) {
3931 			putnext(q, mp);
3932 		} else
3933 			freemsg(mp);
3934 		return;
3935 	}
3936 	arh = (arh_t *)mp->b_cont->b_rptr;
3937 	/* Is it one we are interested in? */
3938 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3939 		isv6 = B_TRUE;
3940 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3941 		    IPV6_ADDR_LEN);
3942 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3943 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3944 		    IP_ADDR_LEN);
3945 	} else {
3946 		freemsg(mp);
3947 		return;
3948 	}
3949 
3950 	ill = q->q_ptr;
3951 
3952 	arcn = (arcn_t *)mp->b_rptr;
3953 	switch (arcn->arcn_code) {
3954 	case AR_CN_BOGON:
3955 		/*
3956 		 * Someone is sending ARP packets with a source protocol
3957 		 * address that we have published and for which we believe our
3958 		 * entry is authoritative and (when ill_arp_extend is set)
3959 		 * verified to be unique on the network.
3960 		 *
3961 		 * The ARP module internally handles the cases where the sender
3962 		 * is just probing (for DAD) and where the hardware address of
3963 		 * a non-authoritative entry has changed.  Thus, these are the
3964 		 * real conflicts, and we have to do resolution.
3965 		 *
3966 		 * We back away quickly from the address if it's from DHCP or
3967 		 * otherwise temporary and hasn't been used recently (or at
3968 		 * all).  We'd like to include "deprecated" addresses here as
3969 		 * well (as there's no real reason to defend something we're
3970 		 * discarding), but IPMP "reuses" this flag to mean something
3971 		 * other than the standard meaning.
3972 		 *
3973 		 * If the ARP module above is not extended (meaning that it
3974 		 * doesn't know how to defend the address), then we just log
3975 		 * the problem as we always did and continue on.  It's not
3976 		 * right, but there's little else we can do, and those old ATM
3977 		 * users are going away anyway.
3978 		 */
3979 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
3980 		    hbuf, sizeof (hbuf));
3981 		(void) ip_dot_addr(src, sbuf);
3982 		if (isv6) {
3983 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
3984 			    ipst);
3985 		} else {
3986 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
3987 		}
3988 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
3989 			uint32_t now;
3990 			uint32_t maxage;
3991 			clock_t lused;
3992 			uint_t maxdefense;
3993 			uint_t defs;
3994 
3995 			/*
3996 			 * First, figure out if this address hasn't been used
3997 			 * in a while.  If it hasn't, then it's a better
3998 			 * candidate for abandoning.
3999 			 */
4000 			ipif = ire->ire_ipif;
4001 			ASSERT(ipif != NULL);
4002 			now = gethrestime_sec();
4003 			maxage = now - ire->ire_create_time;
4004 			if (maxage > ipst->ips_ip_max_temp_idle)
4005 				maxage = ipst->ips_ip_max_temp_idle;
4006 			lused = drv_hztousec(ddi_get_lbolt() -
4007 			    ire->ire_last_used_time) / MICROSEC + 1;
4008 			if (lused >= maxage && (ipif->ipif_flags &
4009 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4010 				maxdefense = ipst->ips_ip_max_temp_defend;
4011 			else
4012 				maxdefense = ipst->ips_ip_max_defend;
4013 
4014 			/*
4015 			 * Now figure out how many times we've defended
4016 			 * ourselves.  Ignore defenses that happened long in
4017 			 * the past.
4018 			 */
4019 			mutex_enter(&ire->ire_lock);
4020 			if ((defs = ire->ire_defense_count) > 0 &&
4021 			    now - ire->ire_defense_time >
4022 			    ipst->ips_ip_defend_interval) {
4023 				ire->ire_defense_count = defs = 0;
4024 			}
4025 			ire->ire_defense_count++;
4026 			ire->ire_defense_time = now;
4027 			mutex_exit(&ire->ire_lock);
4028 			ill_refhold(ill);
4029 			ire_refrele(ire);
4030 
4031 			/*
4032 			 * If we've defended ourselves too many times already,
4033 			 * then give up and tear down the interface(s) using
4034 			 * this address.  Otherwise, defend by sending out a
4035 			 * gratuitous ARP.
4036 			 */
4037 			if (defs >= maxdefense && ill->ill_arp_extend) {
4038 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4039 				    B_FALSE);
4040 			} else {
4041 				cmn_err(CE_WARN,
4042 				    "node %s is using our IP address %s on %s",
4043 				    hbuf, sbuf, ill->ill_name);
4044 				/*
4045 				 * If this is an old (ATM) ARP module, then
4046 				 * don't try to defend the address.  Remain
4047 				 * compatible with the old behavior.  Defend
4048 				 * only with new ARP.
4049 				 */
4050 				if (ill->ill_arp_extend) {
4051 					qwriter_ip(ill, q, mp, ip_arp_defend,
4052 					    NEW_OP, B_FALSE);
4053 				} else {
4054 					ill_refrele(ill);
4055 				}
4056 			}
4057 			return;
4058 		}
4059 		cmn_err(CE_WARN,
4060 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4061 		    hbuf, sbuf, ill->ill_name);
4062 		if (ire != NULL)
4063 			ire_refrele(ire);
4064 		break;
4065 	case AR_CN_ANNOUNCE:
4066 		if (isv6) {
4067 			/*
4068 			 * For XRESOLV interfaces.
4069 			 * Delete the IRE cache entry and NCE for this
4070 			 * v6 address
4071 			 */
4072 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4073 			/*
4074 			 * If v6src is a non-zero, it's a router address
4075 			 * as below. Do the same sort of thing to clean
4076 			 * out off-net IRE_CACHE entries that go through
4077 			 * the router.
4078 			 */
4079 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4080 				ire_walk_v6(ire_delete_cache_gw_v6,
4081 				    (char *)&v6src, ALL_ZONES, ipst);
4082 			}
4083 		} else {
4084 			nce_hw_map_t hwm;
4085 
4086 			/*
4087 			 * ARP gives us a copy of any packet where it thinks
4088 			 * the address has changed, so that we can update our
4089 			 * caches.  We're responsible for caching known answers
4090 			 * in the current design.  We check whether the
4091 			 * hardware address really has changed in all of our
4092 			 * entries that have cached this mapping, and if so, we
4093 			 * blow them away.  This way we will immediately pick
4094 			 * up the rare case of a host changing hardware
4095 			 * address.
4096 			 */
4097 			if (src == 0)
4098 				break;
4099 			hwm.hwm_addr = src;
4100 			hwm.hwm_hwlen = arh->arh_hlen;
4101 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4102 			NDP_HW_CHANGE_INCR(ipst->ips_ndp4);
4103 			ndp_walk_common(ipst->ips_ndp4, NULL,
4104 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4105 			NDP_HW_CHANGE_DECR(ipst->ips_ndp4);
4106 		}
4107 		break;
4108 	case AR_CN_READY:
4109 		/* No external v6 resolver has a contract to use this */
4110 		if (isv6)
4111 			break;
4112 		/* If the link is down, we'll retry this later */
4113 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4114 			break;
4115 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4116 		    NULL, NULL, ipst);
4117 		if (ipif != NULL) {
4118 			/*
4119 			 * If this is a duplicate recovery, then we now need to
4120 			 * go exclusive to bring this thing back up.
4121 			 */
4122 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4123 			    IPIF_DUPLICATE) {
4124 				ipif_refrele(ipif);
4125 				ill_refhold(ill);
4126 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4127 				    B_FALSE);
4128 				return;
4129 			}
4130 			/*
4131 			 * If this is the first notice that this address is
4132 			 * ready, then let the user know now.
4133 			 */
4134 			if ((ipif->ipif_flags & IPIF_UP) &&
4135 			    !ipif->ipif_addr_ready) {
4136 				ipif_mask_reply(ipif);
4137 				ip_rts_ifmsg(ipif);
4138 				ip_rts_newaddrmsg(RTM_ADD, 0, ipif);
4139 				sctp_update_ipif(ipif, SCTP_IPIF_UP);
4140 			}
4141 			ipif->ipif_addr_ready = 1;
4142 			ipif_refrele(ipif);
4143 		}
4144 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp), ipst);
4145 		if (ire != NULL) {
4146 			ire->ire_defense_count = 0;
4147 			ire_refrele(ire);
4148 		}
4149 		break;
4150 	case AR_CN_FAILED:
4151 		/* No external v6 resolver has a contract to use this */
4152 		if (isv6)
4153 			break;
4154 		ill_refhold(ill);
4155 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, B_FALSE);
4156 		return;
4157 	}
4158 	freemsg(mp);
4159 }
4160 
4161 /*
4162  * Create a mblk suitable for carrying the interface index and/or source link
4163  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4164  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4165  * application.
4166  */
4167 mblk_t *
4168 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4169     ip_stack_t *ipst)
4170 {
4171 	mblk_t		*mp;
4172 	ip_pktinfo_t	*pinfo;
4173 	ipha_t *ipha;
4174 	struct ether_header *pether;
4175 
4176 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4177 	if (mp == NULL) {
4178 		ip1dbg(("ip_add_info: allocation failure.\n"));
4179 		return (data_mp);
4180 	}
4181 
4182 	ipha	= (ipha_t *)data_mp->b_rptr;
4183 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4184 	bzero(pinfo, sizeof (ip_pktinfo_t));
4185 	pinfo->ip_pkt_flags = (uchar_t)flags;
4186 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4187 
4188 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4189 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4190 	if (flags & IPF_RECVADDR) {
4191 		ipif_t	*ipif;
4192 		ire_t	*ire;
4193 
4194 		/*
4195 		 * Only valid for V4
4196 		 */
4197 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4198 		    (IPV4_VERSION << 4));
4199 
4200 		ipif = ipif_get_next_ipif(NULL, ill);
4201 		if (ipif != NULL) {
4202 			/*
4203 			 * Since a decision has already been made to deliver the
4204 			 * packet, there is no need to test for SECATTR and
4205 			 * ZONEONLY.
4206 			 * When a multicast packet is transmitted
4207 			 * a cache entry is created for the multicast address.
4208 			 * When delivering a copy of the packet or when new
4209 			 * packets are received we do not want to match on the
4210 			 * cached entry so explicitly match on
4211 			 * IRE_LOCAL and IRE_LOOPBACK
4212 			 */
4213 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4214 			    IRE_LOCAL | IRE_LOOPBACK,
4215 			    ipif, zoneid, NULL,
4216 			    MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP, ipst);
4217 			if (ire == NULL) {
4218 				/*
4219 				 * packet must have come on a different
4220 				 * interface.
4221 				 * Since a decision has already been made to
4222 				 * deliver the packet, there is no need to test
4223 				 * for SECATTR and ZONEONLY.
4224 				 * Only match on local and broadcast ire's.
4225 				 * See detailed comment above.
4226 				 */
4227 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4228 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4229 				    NULL, MATCH_IRE_TYPE, ipst);
4230 			}
4231 
4232 			if (ire == NULL) {
4233 				/*
4234 				 * This is either a multicast packet or
4235 				 * the address has been removed since
4236 				 * the packet was received.
4237 				 * Return INADDR_ANY so that normal source
4238 				 * selection occurs for the response.
4239 				 */
4240 
4241 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4242 			} else {
4243 				pinfo->ip_pkt_match_addr.s_addr =
4244 				    ire->ire_src_addr;
4245 				ire_refrele(ire);
4246 			}
4247 			ipif_refrele(ipif);
4248 		} else {
4249 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4250 		}
4251 	}
4252 
4253 	pether = (struct ether_header *)((char *)ipha
4254 	    - sizeof (struct ether_header));
4255 	/*
4256 	 * Make sure the interface is an ethernet type, since this option
4257 	 * is currently supported only on this type of interface. Also make
4258 	 * sure we are pointing correctly above db_base.
4259 	 */
4260 
4261 	if ((flags & IPF_RECVSLLA) &&
4262 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4263 	    (ill->ill_type == IFT_ETHER) &&
4264 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4265 
4266 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4267 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4268 		    (uchar_t *)pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4269 	} else {
4270 		/*
4271 		 * Clear the bit. Indicate to upper layer that IP is not
4272 		 * sending this ancillary info.
4273 		 */
4274 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4275 	}
4276 
4277 	mp->b_datap->db_type = M_CTL;
4278 	mp->b_wptr += sizeof (ip_pktinfo_t);
4279 	mp->b_cont = data_mp;
4280 
4281 	return (mp);
4282 }
4283 
4284 /*
4285  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4286  * part of the bind request.
4287  */
4288 
4289 boolean_t
4290 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4291 {
4292 	ipsec_in_t *ii;
4293 
4294 	ASSERT(policy_mp != NULL);
4295 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4296 
4297 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4298 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4299 
4300 	connp->conn_policy = ii->ipsec_in_policy;
4301 	ii->ipsec_in_policy = NULL;
4302 
4303 	if (ii->ipsec_in_action != NULL) {
4304 		if (connp->conn_latch == NULL) {
4305 			connp->conn_latch = iplatch_create();
4306 			if (connp->conn_latch == NULL)
4307 				return (B_FALSE);
4308 		}
4309 		ipsec_latch_inbound(connp->conn_latch, ii);
4310 	}
4311 	return (B_TRUE);
4312 }
4313 
4314 /*
4315  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4316  * and to arrange for power-fanout assist.  The ULP is identified by
4317  * adding a single byte at the end of the original bind message.
4318  * A ULP other than UDP or TCP that wishes to be recognized passes
4319  * down a bind with a zero length address.
4320  *
4321  * The binding works as follows:
4322  * - A zero byte address means just bind to the protocol.
4323  * - A four byte address is treated as a request to validate
4324  *   that the address is a valid local address, appropriate for
4325  *   an application to bind to. This does not affect any fanout
4326  *   information in IP.
4327  * - A sizeof sin_t byte address is used to bind to only the local address
4328  *   and port.
4329  * - A sizeof ipa_conn_t byte address contains complete fanout information
4330  *   consisting of local and remote addresses and ports.  In
4331  *   this case, the addresses are both validated as appropriate
4332  *   for this operation, and, if so, the information is retained
4333  *   for use in the inbound fanout.
4334  *
4335  * The ULP (except in the zero-length bind) can append an
4336  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4337  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4338  * a copy of the source or destination IRE (source for local bind;
4339  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4340  * policy information contained should be copied on to the conn.
4341  *
4342  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4343  */
4344 mblk_t *
4345 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4346 {
4347 	ssize_t		len;
4348 	struct T_bind_req	*tbr;
4349 	sin_t		*sin;
4350 	ipa_conn_t	*ac;
4351 	uchar_t		*ucp;
4352 	mblk_t		*mp1;
4353 	boolean_t	ire_requested;
4354 	boolean_t	ipsec_policy_set = B_FALSE;
4355 	int		error = 0;
4356 	int		protocol;
4357 	ipa_conn_x_t	*acx;
4358 
4359 	ASSERT(!connp->conn_af_isv6);
4360 	connp->conn_pkt_isv6 = B_FALSE;
4361 
4362 	len = MBLKL(mp);
4363 	if (len < (sizeof (*tbr) + 1)) {
4364 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4365 		    "ip_bind: bogus msg, len %ld", len);
4366 		/* XXX: Need to return something better */
4367 		goto bad_addr;
4368 	}
4369 	/* Back up and extract the protocol identifier. */
4370 	mp->b_wptr--;
4371 	protocol = *mp->b_wptr & 0xFF;
4372 	tbr = (struct T_bind_req *)mp->b_rptr;
4373 	/* Reset the message type in preparation for shipping it back. */
4374 	DB_TYPE(mp) = M_PCPROTO;
4375 
4376 	connp->conn_ulp = (uint8_t)protocol;
4377 
4378 	/*
4379 	 * Check for a zero length address.  This is from a protocol that
4380 	 * wants to register to receive all packets of its type.
4381 	 */
4382 	if (tbr->ADDR_length == 0) {
4383 		/*
4384 		 * These protocols are now intercepted in ip_bind_v6().
4385 		 * Reject protocol-level binds here for now.
4386 		 *
4387 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4388 		 * so that the protocol type cannot be SCTP.
4389 		 */
4390 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4391 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4392 			goto bad_addr;
4393 		}
4394 
4395 		/*
4396 		 *
4397 		 * The udp module never sends down a zero-length address,
4398 		 * and allowing this on a labeled system will break MLP
4399 		 * functionality.
4400 		 */
4401 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4402 			goto bad_addr;
4403 
4404 		if (connp->conn_mac_exempt)
4405 			goto bad_addr;
4406 
4407 		/* No hash here really.  The table is big enough. */
4408 		connp->conn_srcv6 = ipv6_all_zeros;
4409 
4410 		ipcl_proto_insert(connp, protocol);
4411 
4412 		tbr->PRIM_type = T_BIND_ACK;
4413 		return (mp);
4414 	}
4415 
4416 	/* Extract the address pointer from the message. */
4417 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4418 	    tbr->ADDR_length);
4419 	if (ucp == NULL) {
4420 		ip1dbg(("ip_bind: no address\n"));
4421 		goto bad_addr;
4422 	}
4423 	if (!OK_32PTR(ucp)) {
4424 		ip1dbg(("ip_bind: unaligned address\n"));
4425 		goto bad_addr;
4426 	}
4427 	/*
4428 	 * Check for trailing mps.
4429 	 */
4430 
4431 	mp1 = mp->b_cont;
4432 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4433 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4434 
4435 	switch (tbr->ADDR_length) {
4436 	default:
4437 		ip1dbg(("ip_bind: bad address length %d\n",
4438 		    (int)tbr->ADDR_length));
4439 		goto bad_addr;
4440 
4441 	case IP_ADDR_LEN:
4442 		/* Verification of local address only */
4443 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4444 		    ire_requested, ipsec_policy_set, B_FALSE);
4445 		break;
4446 
4447 	case sizeof (sin_t):
4448 		sin = (sin_t *)ucp;
4449 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4450 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4451 		break;
4452 
4453 	case sizeof (ipa_conn_t):
4454 		ac = (ipa_conn_t *)ucp;
4455 		/* For raw socket, the local port is not set. */
4456 		if (ac->ac_lport == 0)
4457 			ac->ac_lport = connp->conn_lport;
4458 		/* Always verify destination reachability. */
4459 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4460 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4461 		    ipsec_policy_set, B_TRUE, B_TRUE);
4462 		break;
4463 
4464 	case sizeof (ipa_conn_x_t):
4465 		acx = (ipa_conn_x_t *)ucp;
4466 		/*
4467 		 * Whether or not to verify destination reachability depends
4468 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4469 		 */
4470 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4471 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4472 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4473 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4474 		break;
4475 	}
4476 	if (error == EINPROGRESS)
4477 		return (NULL);
4478 	else if (error != 0)
4479 		goto bad_addr;
4480 	/*
4481 	 * Pass the IPsec headers size in ire_ipsec_overhead.
4482 	 * We can't do this in ip_bind_insert_ire because the policy
4483 	 * may not have been inherited at that point in time and hence
4484 	 * conn_out_enforce_policy may not be set.
4485 	 */
4486 	mp1 = mp->b_cont;
4487 	if (ire_requested && connp->conn_out_enforce_policy &&
4488 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4489 		ire_t *ire = (ire_t *)mp1->b_rptr;
4490 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4491 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4492 	}
4493 
4494 	/* Send it home. */
4495 	mp->b_datap->db_type = M_PCPROTO;
4496 	tbr->PRIM_type = T_BIND_ACK;
4497 	return (mp);
4498 
4499 bad_addr:
4500 	/*
4501 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4502 	 * a unix errno.
4503 	 */
4504 	if (error > 0)
4505 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4506 	else
4507 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4508 	return (mp);
4509 }
4510 
4511 /*
4512  * Here address is verified to be a valid local address.
4513  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4514  * address is also considered a valid local address.
4515  * In the case of a broadcast/multicast address, however, the
4516  * upper protocol is expected to reset the src address
4517  * to 0 if it sees a IRE_BROADCAST type returned so that
4518  * no packets are emitted with broadcast/multicast address as
4519  * source address (that violates hosts requirements RFC1122)
4520  * The addresses valid for bind are:
4521  *	(1) - INADDR_ANY (0)
4522  *	(2) - IP address of an UP interface
4523  *	(3) - IP address of a DOWN interface
4524  *	(4) - valid local IP broadcast addresses. In this case
4525  *	the conn will only receive packets destined to
4526  *	the specified broadcast address.
4527  *	(5) - a multicast address. In this case
4528  *	the conn will only receive packets destined to
4529  *	the specified multicast address. Note: the
4530  *	application still has to issue an
4531  *	IP_ADD_MEMBERSHIP socket option.
4532  *
4533  * On error, return -1 for TBADADDR otherwise pass the
4534  * errno with TSYSERR reply.
4535  *
4536  * In all the above cases, the bound address must be valid in the current zone.
4537  * When the address is loopback, multicast or broadcast, there might be many
4538  * matching IREs so bind has to look up based on the zone.
4539  *
4540  * Note: lport is in network byte order.
4541  */
4542 int
4543 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4544     boolean_t ire_requested, boolean_t ipsec_policy_set,
4545     boolean_t fanout_insert)
4546 {
4547 	int		error = 0;
4548 	ire_t		*src_ire;
4549 	mblk_t		*policy_mp;
4550 	ipif_t		*ipif;
4551 	zoneid_t	zoneid;
4552 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4553 
4554 	if (ipsec_policy_set) {
4555 		policy_mp = mp->b_cont;
4556 	}
4557 
4558 	/*
4559 	 * If it was previously connected, conn_fully_bound would have
4560 	 * been set.
4561 	 */
4562 	connp->conn_fully_bound = B_FALSE;
4563 
4564 	src_ire = NULL;
4565 	ipif = NULL;
4566 
4567 	zoneid = IPCL_ZONEID(connp);
4568 
4569 	if (src_addr) {
4570 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4571 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4572 		/*
4573 		 * If an address other than 0.0.0.0 is requested,
4574 		 * we verify that it is a valid address for bind
4575 		 * Note: Following code is in if-else-if form for
4576 		 * readability compared to a condition check.
4577 		 */
4578 		/* LINTED - statement has no consequent */
4579 		if (IRE_IS_LOCAL(src_ire)) {
4580 			/*
4581 			 * (2) Bind to address of local UP interface
4582 			 */
4583 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4584 			/*
4585 			 * (4) Bind to broadcast address
4586 			 * Note: permitted only from transports that
4587 			 * request IRE
4588 			 */
4589 			if (!ire_requested)
4590 				error = EADDRNOTAVAIL;
4591 		} else {
4592 			/*
4593 			 * (3) Bind to address of local DOWN interface
4594 			 * (ipif_lookup_addr() looks up all interfaces
4595 			 * but we do not get here for UP interfaces
4596 			 * - case (2) above)
4597 			 * We put the protocol byte back into the mblk
4598 			 * since we may come back via ip_wput_nondata()
4599 			 * later with this mblk if ipif_lookup_addr chooses
4600 			 * to defer processing.
4601 			 */
4602 			*mp->b_wptr++ = (char)connp->conn_ulp;
4603 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4604 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4605 			    &error, ipst)) != NULL) {
4606 				ipif_refrele(ipif);
4607 			} else if (error == EINPROGRESS) {
4608 				if (src_ire != NULL)
4609 					ire_refrele(src_ire);
4610 				return (EINPROGRESS);
4611 			} else if (CLASSD(src_addr)) {
4612 				error = 0;
4613 				if (src_ire != NULL)
4614 					ire_refrele(src_ire);
4615 				/*
4616 				 * (5) bind to multicast address.
4617 				 * Fake out the IRE returned to upper
4618 				 * layer to be a broadcast IRE.
4619 				 */
4620 				src_ire = ire_ctable_lookup(
4621 				    INADDR_BROADCAST, INADDR_ANY,
4622 				    IRE_BROADCAST, NULL, zoneid, NULL,
4623 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4624 				    ipst);
4625 				if (src_ire == NULL || !ire_requested)
4626 					error = EADDRNOTAVAIL;
4627 			} else {
4628 				/*
4629 				 * Not a valid address for bind
4630 				 */
4631 				error = EADDRNOTAVAIL;
4632 			}
4633 			/*
4634 			 * Just to keep it consistent with the processing in
4635 			 * ip_bind_v4()
4636 			 */
4637 			mp->b_wptr--;
4638 		}
4639 		if (error) {
4640 			/* Red Alert!  Attempting to be a bogon! */
4641 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4642 			    ntohl(src_addr)));
4643 			goto bad_addr;
4644 		}
4645 	}
4646 
4647 	/*
4648 	 * Allow setting new policies. For example, disconnects come
4649 	 * down as ipa_t bind. As we would have set conn_policy_cached
4650 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4651 	 * can change after the disconnect.
4652 	 */
4653 	connp->conn_policy_cached = B_FALSE;
4654 
4655 	/*
4656 	 * If not fanout_insert this was just an address verification
4657 	 */
4658 	if (fanout_insert) {
4659 		/*
4660 		 * The addresses have been verified. Time to insert in
4661 		 * the correct fanout list.
4662 		 */
4663 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4664 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4665 		connp->conn_lport = lport;
4666 		connp->conn_fport = 0;
4667 		/*
4668 		 * Do we need to add a check to reject Multicast packets
4669 		 */
4670 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4671 	}
4672 
4673 	if (error == 0) {
4674 		if (ire_requested) {
4675 			if (!ip_bind_insert_ire(mp, src_ire, NULL, ipst)) {
4676 				error = -1;
4677 				/* Falls through to bad_addr */
4678 			}
4679 		} else if (ipsec_policy_set) {
4680 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4681 				error = -1;
4682 				/* Falls through to bad_addr */
4683 			}
4684 		}
4685 	}
4686 bad_addr:
4687 	if (error != 0) {
4688 		if (connp->conn_anon_port) {
4689 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4690 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4691 			    B_FALSE);
4692 		}
4693 		connp->conn_mlp_type = mlptSingle;
4694 	}
4695 	if (src_ire != NULL)
4696 		IRE_REFRELE(src_ire);
4697 	if (ipsec_policy_set) {
4698 		ASSERT(policy_mp == mp->b_cont);
4699 		ASSERT(policy_mp != NULL);
4700 		freeb(policy_mp);
4701 		/*
4702 		 * As of now assume that nothing else accompanies
4703 		 * IPSEC_POLICY_SET.
4704 		 */
4705 		mp->b_cont = NULL;
4706 	}
4707 	return (error);
4708 }
4709 
4710 /*
4711  * Verify that both the source and destination addresses
4712  * are valid.  If verify_dst is false, then the destination address may be
4713  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4714  * destination reachability, while tunnels do not.
4715  * Note that we allow connect to broadcast and multicast
4716  * addresses when ire_requested is set. Thus the ULP
4717  * has to check for IRE_BROADCAST and multicast.
4718  *
4719  * Returns zero if ok.
4720  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4721  * (for use with TSYSERR reply).
4722  *
4723  * Note: lport and fport are in network byte order.
4724  */
4725 int
4726 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4727     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4728     boolean_t ire_requested, boolean_t ipsec_policy_set,
4729     boolean_t fanout_insert, boolean_t verify_dst)
4730 {
4731 	ire_t		*src_ire;
4732 	ire_t		*dst_ire;
4733 	int		error = 0;
4734 	int 		protocol;
4735 	mblk_t		*policy_mp;
4736 	ire_t		*sire = NULL;
4737 	ire_t		*md_dst_ire = NULL;
4738 	ire_t		*lso_dst_ire = NULL;
4739 	ill_t		*ill = NULL;
4740 	zoneid_t	zoneid;
4741 	ipaddr_t	src_addr = *src_addrp;
4742 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4743 
4744 	src_ire = dst_ire = NULL;
4745 	protocol = *mp->b_wptr & 0xFF;
4746 
4747 	/*
4748 	 * If we never got a disconnect before, clear it now.
4749 	 */
4750 	connp->conn_fully_bound = B_FALSE;
4751 
4752 	if (ipsec_policy_set) {
4753 		policy_mp = mp->b_cont;
4754 	}
4755 
4756 	zoneid = IPCL_ZONEID(connp);
4757 
4758 	if (CLASSD(dst_addr)) {
4759 		/* Pick up an IRE_BROADCAST */
4760 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4761 		    NULL, zoneid, MBLK_GETLABEL(mp),
4762 		    (MATCH_IRE_RECURSIVE |
4763 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4764 		    MATCH_IRE_SECATTR), ipst);
4765 	} else {
4766 		/*
4767 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4768 		 * and onlink ipif is not found set ENETUNREACH error.
4769 		 */
4770 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4771 			ipif_t *ipif;
4772 
4773 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4774 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4775 			if (ipif == NULL) {
4776 				error = ENETUNREACH;
4777 				goto bad_addr;
4778 			}
4779 			ipif_refrele(ipif);
4780 		}
4781 
4782 		if (connp->conn_nexthop_set) {
4783 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4784 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4785 			    MATCH_IRE_SECATTR, ipst);
4786 		} else {
4787 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4788 			    &sire, zoneid, MBLK_GETLABEL(mp),
4789 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4790 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4791 			    MATCH_IRE_SECATTR), ipst);
4792 		}
4793 	}
4794 	/*
4795 	 * dst_ire can't be a broadcast when not ire_requested.
4796 	 * We also prevent ire's with src address INADDR_ANY to
4797 	 * be used, which are created temporarily for
4798 	 * sending out packets from endpoints that have
4799 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4800 	 * reachable.  If verify_dst is false, the destination needn't be
4801 	 * reachable.
4802 	 *
4803 	 * If we match on a reject or black hole, then we've got a
4804 	 * local failure.  May as well fail out the connect() attempt,
4805 	 * since it's never going to succeed.
4806 	 */
4807 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4808 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4809 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4810 		/*
4811 		 * If we're verifying destination reachability, we always want
4812 		 * to complain here.
4813 		 *
4814 		 * If we're not verifying destination reachability but the
4815 		 * destination has a route, we still want to fail on the
4816 		 * temporary address and broadcast address tests.
4817 		 */
4818 		if (verify_dst || (dst_ire != NULL)) {
4819 			if (ip_debug > 2) {
4820 				pr_addr_dbg("ip_bind_connected: bad connected "
4821 				    "dst %s\n", AF_INET, &dst_addr);
4822 			}
4823 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4824 				error = ENETUNREACH;
4825 			else
4826 				error = EHOSTUNREACH;
4827 			goto bad_addr;
4828 		}
4829 	}
4830 
4831 	/*
4832 	 * We now know that routing will allow us to reach the destination.
4833 	 * Check whether Trusted Solaris policy allows communication with this
4834 	 * host, and pretend that the destination is unreachable if not.
4835 	 *
4836 	 * This is never a problem for TCP, since that transport is known to
4837 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4838 	 * handling.  If the remote is unreachable, it will be detected at that
4839 	 * point, so there's no reason to check it here.
4840 	 *
4841 	 * Note that for sendto (and other datagram-oriented friends), this
4842 	 * check is done as part of the data path label computation instead.
4843 	 * The check here is just to make non-TCP connect() report the right
4844 	 * error.
4845 	 */
4846 	if (dst_ire != NULL && is_system_labeled() &&
4847 	    !IPCL_IS_TCP(connp) &&
4848 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4849 	    connp->conn_mac_exempt, ipst) != 0) {
4850 		error = EHOSTUNREACH;
4851 		if (ip_debug > 2) {
4852 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4853 			    AF_INET, &dst_addr);
4854 		}
4855 		goto bad_addr;
4856 	}
4857 
4858 	/*
4859 	 * If the app does a connect(), it means that it will most likely
4860 	 * send more than 1 packet to the destination.  It makes sense
4861 	 * to clear the temporary flag.
4862 	 */
4863 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4864 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4865 		irb_t *irb = dst_ire->ire_bucket;
4866 
4867 		rw_enter(&irb->irb_lock, RW_WRITER);
4868 		/*
4869 		 * We need to recheck for IRE_MARK_TEMPORARY after acquiring
4870 		 * the lock to guarantee irb_tmp_ire_cnt.
4871 		 */
4872 		if (dst_ire->ire_marks & IRE_MARK_TEMPORARY) {
4873 			dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4874 			irb->irb_tmp_ire_cnt--;
4875 		}
4876 		rw_exit(&irb->irb_lock);
4877 	}
4878 
4879 	/*
4880 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4881 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4882 	 * eligibility tests for passive connects are handled separately
4883 	 * through tcp_adapt_ire().  We do this before the source address
4884 	 * selection, because dst_ire may change after a call to
4885 	 * ipif_select_source().  This is a best-effort check, as the
4886 	 * packet for this connection may not actually go through
4887 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4888 	 * calling ip_newroute().  This is why we further check on the
4889 	 * IRE during LSO/Multidata packet transmission in
4890 	 * tcp_lsosend()/tcp_multisend().
4891 	 */
4892 	if (!ipsec_policy_set && dst_ire != NULL &&
4893 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4894 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4895 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4896 			lso_dst_ire = dst_ire;
4897 			IRE_REFHOLD(lso_dst_ire);
4898 		} else if (ipst->ips_ip_multidata_outbound &&
4899 		    ILL_MDT_CAPABLE(ill)) {
4900 			md_dst_ire = dst_ire;
4901 			IRE_REFHOLD(md_dst_ire);
4902 		}
4903 	}
4904 
4905 	if (dst_ire != NULL &&
4906 	    dst_ire->ire_type == IRE_LOCAL &&
4907 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4908 		/*
4909 		 * If the IRE belongs to a different zone, look for a matching
4910 		 * route in the forwarding table and use the source address from
4911 		 * that route.
4912 		 */
4913 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4914 		    zoneid, 0, NULL,
4915 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4916 		    MATCH_IRE_RJ_BHOLE, ipst);
4917 		if (src_ire == NULL) {
4918 			error = EHOSTUNREACH;
4919 			goto bad_addr;
4920 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4921 			if (!(src_ire->ire_type & IRE_HOST))
4922 				error = ENETUNREACH;
4923 			else
4924 				error = EHOSTUNREACH;
4925 			goto bad_addr;
4926 		}
4927 		if (src_addr == INADDR_ANY)
4928 			src_addr = src_ire->ire_src_addr;
4929 		ire_refrele(src_ire);
4930 		src_ire = NULL;
4931 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4932 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4933 			src_addr = sire->ire_src_addr;
4934 			ire_refrele(dst_ire);
4935 			dst_ire = sire;
4936 			sire = NULL;
4937 		} else {
4938 			/*
4939 			 * Pick a source address so that a proper inbound
4940 			 * load spreading would happen.
4941 			 */
4942 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4943 			ipif_t *src_ipif = NULL;
4944 			ire_t *ipif_ire;
4945 
4946 			/*
4947 			 * Supply a local source address such that inbound
4948 			 * load spreading happens.
4949 			 *
4950 			 * Determine the best source address on this ill for
4951 			 * the destination.
4952 			 *
4953 			 * 1) For broadcast, we should return a broadcast ire
4954 			 *    found above so that upper layers know that the
4955 			 *    destination address is a broadcast address.
4956 			 *
4957 			 * 2) If this is part of a group, select a better
4958 			 *    source address so that better inbound load
4959 			 *    balancing happens. Do the same if the ipif
4960 			 *    is DEPRECATED.
4961 			 *
4962 			 * 3) If the outgoing interface is part of a usesrc
4963 			 *    group, then try selecting a source address from
4964 			 *    the usesrc ILL.
4965 			 */
4966 			if ((dst_ire->ire_zoneid != zoneid &&
4967 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4968 			    (!(dst_ire->ire_flags & RTF_SETSRC)) &&
4969 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4970 			    ((dst_ill->ill_group != NULL) ||
4971 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4972 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4973 				/*
4974 				 * If the destination is reachable via a
4975 				 * given gateway, the selected source address
4976 				 * should be in the same subnet as the gateway.
4977 				 * Otherwise, the destination is not reachable.
4978 				 *
4979 				 * If there are no interfaces on the same subnet
4980 				 * as the destination, ipif_select_source gives
4981 				 * first non-deprecated interface which might be
4982 				 * on a different subnet than the gateway.
4983 				 * This is not desirable. Hence pass the dst_ire
4984 				 * source address to ipif_select_source.
4985 				 * It is sure that the destination is reachable
4986 				 * with the dst_ire source address subnet.
4987 				 * So passing dst_ire source address to
4988 				 * ipif_select_source will make sure that the
4989 				 * selected source will be on the same subnet
4990 				 * as dst_ire source address.
4991 				 */
4992 				ipaddr_t saddr =
4993 				    dst_ire->ire_ipif->ipif_src_addr;
4994 				src_ipif = ipif_select_source(dst_ill,
4995 				    saddr, zoneid);
4996 				if (src_ipif != NULL) {
4997 					if (IS_VNI(src_ipif->ipif_ill)) {
4998 						/*
4999 						 * For VNI there is no
5000 						 * interface route
5001 						 */
5002 						src_addr =
5003 						    src_ipif->ipif_src_addr;
5004 					} else {
5005 						ipif_ire =
5006 						    ipif_to_ire(src_ipif);
5007 						if (ipif_ire != NULL) {
5008 							IRE_REFRELE(dst_ire);
5009 							dst_ire = ipif_ire;
5010 						}
5011 						src_addr =
5012 						    dst_ire->ire_src_addr;
5013 					}
5014 					ipif_refrele(src_ipif);
5015 				} else {
5016 					src_addr = dst_ire->ire_src_addr;
5017 				}
5018 			} else {
5019 				src_addr = dst_ire->ire_src_addr;
5020 			}
5021 		}
5022 	}
5023 
5024 	/*
5025 	 * We do ire_route_lookup() here (and not
5026 	 * interface lookup as we assert that
5027 	 * src_addr should only come from an
5028 	 * UP interface for hard binding.
5029 	 */
5030 	ASSERT(src_ire == NULL);
5031 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5032 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5033 	/* src_ire must be a local|loopback */
5034 	if (!IRE_IS_LOCAL(src_ire)) {
5035 		if (ip_debug > 2) {
5036 			pr_addr_dbg("ip_bind_connected: bad connected "
5037 			    "src %s\n", AF_INET, &src_addr);
5038 		}
5039 		error = EADDRNOTAVAIL;
5040 		goto bad_addr;
5041 	}
5042 
5043 	/*
5044 	 * If the source address is a loopback address, the
5045 	 * destination had best be local or multicast.
5046 	 * The transports that can't handle multicast will reject
5047 	 * those addresses.
5048 	 */
5049 	if (src_ire->ire_type == IRE_LOOPBACK &&
5050 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5051 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5052 		error = -1;
5053 		goto bad_addr;
5054 	}
5055 
5056 	/*
5057 	 * Allow setting new policies. For example, disconnects come
5058 	 * down as ipa_t bind. As we would have set conn_policy_cached
5059 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5060 	 * can change after the disconnect.
5061 	 */
5062 	connp->conn_policy_cached = B_FALSE;
5063 
5064 	/*
5065 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5066 	 * can handle their passed-in conn's.
5067 	 */
5068 
5069 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5070 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5071 	connp->conn_lport = lport;
5072 	connp->conn_fport = fport;
5073 	*src_addrp = src_addr;
5074 
5075 	ASSERT(!(ipsec_policy_set && ire_requested));
5076 	if (ire_requested) {
5077 		iulp_t *ulp_info = NULL;
5078 
5079 		/*
5080 		 * Note that sire will not be NULL if this is an off-link
5081 		 * connection and there is not cache for that dest yet.
5082 		 *
5083 		 * XXX Because of an existing bug, if there are multiple
5084 		 * default routes, the IRE returned now may not be the actual
5085 		 * default route used (default routes are chosen in a
5086 		 * round robin fashion).  So if the metrics for different
5087 		 * default routes are different, we may return the wrong
5088 		 * metrics.  This will not be a problem if the existing
5089 		 * bug is fixed.
5090 		 */
5091 		if (sire != NULL) {
5092 			ulp_info = &(sire->ire_uinfo);
5093 		}
5094 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info, ipst)) {
5095 			error = -1;
5096 			goto bad_addr;
5097 		}
5098 	} else if (ipsec_policy_set) {
5099 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5100 			error = -1;
5101 			goto bad_addr;
5102 		}
5103 	}
5104 
5105 	/*
5106 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5107 	 * we'll cache that.  If we don't, we'll inherit global policy.
5108 	 *
5109 	 * We can't insert until the conn reflects the policy. Note that
5110 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5111 	 * connections where we don't have a policy. This is to prevent
5112 	 * global policy lookups in the inbound path.
5113 	 *
5114 	 * If we insert before we set conn_policy_cached,
5115 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5116 	 * because global policy cound be non-empty. We normally call
5117 	 * ipsec_check_policy() for conn_policy_cached connections only if
5118 	 * ipc_in_enforce_policy is set. But in this case,
5119 	 * conn_policy_cached can get set anytime since we made the
5120 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5121 	 * called, which will make the above assumption false.  Thus, we
5122 	 * need to insert after we set conn_policy_cached.
5123 	 */
5124 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5125 		goto bad_addr;
5126 
5127 	if (fanout_insert) {
5128 		/*
5129 		 * The addresses have been verified. Time to insert in
5130 		 * the correct fanout list.
5131 		 */
5132 		error = ipcl_conn_insert(connp, protocol, src_addr,
5133 		    dst_addr, connp->conn_ports);
5134 	}
5135 
5136 	if (error == 0) {
5137 		connp->conn_fully_bound = B_TRUE;
5138 		/*
5139 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5140 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5141 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5142 		 * ip_xxinfo_return(), which performs further checks
5143 		 * against them and upon success, returns the LSO/MDT info
5144 		 * mblk which we will attach to the bind acknowledgment.
5145 		 */
5146 		if (lso_dst_ire != NULL) {
5147 			mblk_t *lsoinfo_mp;
5148 
5149 			ASSERT(ill->ill_lso_capab != NULL);
5150 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5151 			    ill->ill_name, ill->ill_lso_capab)) != NULL)
5152 				linkb(mp, lsoinfo_mp);
5153 		} else if (md_dst_ire != NULL) {
5154 			mblk_t *mdinfo_mp;
5155 
5156 			ASSERT(ill->ill_mdt_capab != NULL);
5157 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5158 			    ill->ill_name, ill->ill_mdt_capab)) != NULL)
5159 				linkb(mp, mdinfo_mp);
5160 		}
5161 	}
5162 bad_addr:
5163 	if (ipsec_policy_set) {
5164 		ASSERT(policy_mp == mp->b_cont);
5165 		ASSERT(policy_mp != NULL);
5166 		freeb(policy_mp);
5167 		/*
5168 		 * As of now assume that nothing else accompanies
5169 		 * IPSEC_POLICY_SET.
5170 		 */
5171 		mp->b_cont = NULL;
5172 	}
5173 	if (src_ire != NULL)
5174 		IRE_REFRELE(src_ire);
5175 	if (dst_ire != NULL)
5176 		IRE_REFRELE(dst_ire);
5177 	if (sire != NULL)
5178 		IRE_REFRELE(sire);
5179 	if (md_dst_ire != NULL)
5180 		IRE_REFRELE(md_dst_ire);
5181 	if (lso_dst_ire != NULL)
5182 		IRE_REFRELE(lso_dst_ire);
5183 	return (error);
5184 }
5185 
5186 /*
5187  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5188  * Prefers dst_ire over src_ire.
5189  */
5190 static boolean_t
5191 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5192 {
5193 	mblk_t	*mp1;
5194 	ire_t *ret_ire = NULL;
5195 
5196 	mp1 = mp->b_cont;
5197 	ASSERT(mp1 != NULL);
5198 
5199 	if (ire != NULL) {
5200 		/*
5201 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5202 		 * appended mblk. Its <upper protocol>'s
5203 		 * job to make sure there is room.
5204 		 */
5205 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5206 			return (0);
5207 
5208 		mp1->b_datap->db_type = IRE_DB_TYPE;
5209 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5210 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5211 		ret_ire = (ire_t *)mp1->b_rptr;
5212 		/*
5213 		 * Pass the latest setting of the ip_path_mtu_discovery and
5214 		 * copy the ulp info if any.
5215 		 */
5216 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5217 		    IPH_DF : 0;
5218 		if (ulp_info != NULL) {
5219 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5220 			    sizeof (iulp_t));
5221 		}
5222 		ret_ire->ire_mp = mp1;
5223 	} else {
5224 		/*
5225 		 * No IRE was found. Remove IRE mblk.
5226 		 */
5227 		mp->b_cont = mp1->b_cont;
5228 		freeb(mp1);
5229 	}
5230 
5231 	return (1);
5232 }
5233 
5234 /*
5235  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5236  * the final piece where we don't.  Return a pointer to the first mblk in the
5237  * result, and update the pointer to the next mblk to chew on.  If anything
5238  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5239  * NULL pointer.
5240  */
5241 mblk_t *
5242 ip_carve_mp(mblk_t **mpp, ssize_t len)
5243 {
5244 	mblk_t	*mp0;
5245 	mblk_t	*mp1;
5246 	mblk_t	*mp2;
5247 
5248 	if (!len || !mpp || !(mp0 = *mpp))
5249 		return (NULL);
5250 	/* If we aren't going to consume the first mblk, we need a dup. */
5251 	if (mp0->b_wptr - mp0->b_rptr > len) {
5252 		mp1 = dupb(mp0);
5253 		if (mp1) {
5254 			/* Partition the data between the two mblks. */
5255 			mp1->b_wptr = mp1->b_rptr + len;
5256 			mp0->b_rptr = mp1->b_wptr;
5257 			/*
5258 			 * after adjustments if mblk not consumed is now
5259 			 * unaligned, try to align it. If this fails free
5260 			 * all messages and let upper layer recover.
5261 			 */
5262 			if (!OK_32PTR(mp0->b_rptr)) {
5263 				if (!pullupmsg(mp0, -1)) {
5264 					freemsg(mp0);
5265 					freemsg(mp1);
5266 					*mpp = NULL;
5267 					return (NULL);
5268 				}
5269 			}
5270 		}
5271 		return (mp1);
5272 	}
5273 	/* Eat through as many mblks as we need to get len bytes. */
5274 	len -= mp0->b_wptr - mp0->b_rptr;
5275 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5276 		if (mp2->b_wptr - mp2->b_rptr > len) {
5277 			/*
5278 			 * We won't consume the entire last mblk.  Like
5279 			 * above, dup and partition it.
5280 			 */
5281 			mp1->b_cont = dupb(mp2);
5282 			mp1 = mp1->b_cont;
5283 			if (!mp1) {
5284 				/*
5285 				 * Trouble.  Rather than go to a lot of
5286 				 * trouble to clean up, we free the messages.
5287 				 * This won't be any worse than losing it on
5288 				 * the wire.
5289 				 */
5290 				freemsg(mp0);
5291 				freemsg(mp2);
5292 				*mpp = NULL;
5293 				return (NULL);
5294 			}
5295 			mp1->b_wptr = mp1->b_rptr + len;
5296 			mp2->b_rptr = mp1->b_wptr;
5297 			/*
5298 			 * after adjustments if mblk not consumed is now
5299 			 * unaligned, try to align it. If this fails free
5300 			 * all messages and let upper layer recover.
5301 			 */
5302 			if (!OK_32PTR(mp2->b_rptr)) {
5303 				if (!pullupmsg(mp2, -1)) {
5304 					freemsg(mp0);
5305 					freemsg(mp2);
5306 					*mpp = NULL;
5307 					return (NULL);
5308 				}
5309 			}
5310 			*mpp = mp2;
5311 			return (mp0);
5312 		}
5313 		/* Decrement len by the amount we just got. */
5314 		len -= mp2->b_wptr - mp2->b_rptr;
5315 	}
5316 	/*
5317 	 * len should be reduced to zero now.  If not our caller has
5318 	 * screwed up.
5319 	 */
5320 	if (len) {
5321 		/* Shouldn't happen! */
5322 		freemsg(mp0);
5323 		*mpp = NULL;
5324 		return (NULL);
5325 	}
5326 	/*
5327 	 * We consumed up to exactly the end of an mblk.  Detach the part
5328 	 * we are returning from the rest of the chain.
5329 	 */
5330 	mp1->b_cont = NULL;
5331 	*mpp = mp2;
5332 	return (mp0);
5333 }
5334 
5335 /* The ill stream is being unplumbed. Called from ip_close */
5336 int
5337 ip_modclose(ill_t *ill)
5338 {
5339 	boolean_t success;
5340 	ipsq_t	*ipsq;
5341 	ipif_t	*ipif;
5342 	queue_t	*q = ill->ill_rq;
5343 	ip_stack_t	*ipst = ill->ill_ipst;
5344 	clock_t timeout;
5345 
5346 	/*
5347 	 * Wait for the ACKs of all deferred control messages to be processed.
5348 	 * In particular, we wait for a potential capability reset initiated
5349 	 * in ip_sioctl_plink() to complete before proceeding.
5350 	 *
5351 	 * Note: we wait for at most ip_modclose_ackwait_ms (by default 3000 ms)
5352 	 * in case the driver never replies.
5353 	 */
5354 	timeout = lbolt + MSEC_TO_TICK(ip_modclose_ackwait_ms);
5355 	mutex_enter(&ill->ill_lock);
5356 	while (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
5357 		if (cv_timedwait(&ill->ill_cv, &ill->ill_lock, timeout) < 0) {
5358 			/* Timeout */
5359 			break;
5360 		}
5361 	}
5362 	mutex_exit(&ill->ill_lock);
5363 
5364 	/*
5365 	 * Forcibly enter the ipsq after some delay. This is to take
5366 	 * care of the case when some ioctl does not complete because
5367 	 * we sent a control message to the driver and it did not
5368 	 * send us a reply. We want to be able to at least unplumb
5369 	 * and replumb rather than force the user to reboot the system.
5370 	 */
5371 	success = ipsq_enter(ill, B_FALSE);
5372 
5373 	/*
5374 	 * Open/close/push/pop is guaranteed to be single threaded
5375 	 * per stream by STREAMS. FS guarantees that all references
5376 	 * from top are gone before close is called. So there can't
5377 	 * be another close thread that has set CONDEMNED on this ill.
5378 	 * and cause ipsq_enter to return failure.
5379 	 */
5380 	ASSERT(success);
5381 	ipsq = ill->ill_phyint->phyint_ipsq;
5382 
5383 	/*
5384 	 * Mark it condemned. No new reference will be made to this ill.
5385 	 * Lookup functions will return an error. Threads that try to
5386 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5387 	 * that the refcnt will drop down to zero.
5388 	 */
5389 	mutex_enter(&ill->ill_lock);
5390 	ill->ill_state_flags |= ILL_CONDEMNED;
5391 	for (ipif = ill->ill_ipif; ipif != NULL;
5392 	    ipif = ipif->ipif_next) {
5393 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5394 	}
5395 	/*
5396 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5397 	 * returns  error if ILL_CONDEMNED is set
5398 	 */
5399 	cv_broadcast(&ill->ill_cv);
5400 	mutex_exit(&ill->ill_lock);
5401 
5402 	/*
5403 	 * Send all the deferred DLPI messages downstream which came in
5404 	 * during the small window right before ipsq_enter(). We do this
5405 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5406 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5407 	 */
5408 	ill_dlpi_send_deferred(ill);
5409 
5410 	/*
5411 	 * Shut down fragmentation reassembly.
5412 	 * ill_frag_timer won't start a timer again.
5413 	 * Now cancel any existing timer
5414 	 */
5415 	(void) untimeout(ill->ill_frag_timer_id);
5416 	(void) ill_frag_timeout(ill, 0);
5417 
5418 	/*
5419 	 * If MOVE was in progress, clear the
5420 	 * move_in_progress fields also.
5421 	 */
5422 	if (ill->ill_move_in_progress) {
5423 		ILL_CLEAR_MOVE(ill);
5424 	}
5425 
5426 	/*
5427 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5428 	 * this ill. Then wait for the refcnts to drop to zero.
5429 	 * ill_is_freeable checks whether the ill is really quiescent.
5430 	 * Then make sure that threads that are waiting to enter the
5431 	 * ipsq have seen the error returned by ipsq_enter and have
5432 	 * gone away. Then we call ill_delete_tail which does the
5433 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5434 	 */
5435 	ill_delete(ill);
5436 	mutex_enter(&ill->ill_lock);
5437 	while (!ill_is_freeable(ill))
5438 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5439 	while (ill->ill_waiters)
5440 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5441 
5442 	mutex_exit(&ill->ill_lock);
5443 
5444 	/*
5445 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5446 	 * it held until the end of the function since the cleanup
5447 	 * below needs to be able to use the ip_stack_t.
5448 	 */
5449 	netstack_hold(ipst->ips_netstack);
5450 
5451 	/* qprocsoff is called in ill_delete_tail */
5452 	ill_delete_tail(ill);
5453 	ASSERT(ill->ill_ipst == NULL);
5454 
5455 	/*
5456 	 * Walk through all upper (conn) streams and qenable
5457 	 * those that have queued data.
5458 	 * close synchronization needs this to
5459 	 * be done to ensure that all upper layers blocked
5460 	 * due to flow control to the closing device
5461 	 * get unblocked.
5462 	 */
5463 	ip1dbg(("ip_wsrv: walking\n"));
5464 	conn_walk_drain(ipst);
5465 
5466 	mutex_enter(&ipst->ips_ip_mi_lock);
5467 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5468 	mutex_exit(&ipst->ips_ip_mi_lock);
5469 
5470 	/*
5471 	 * credp could be null if the open didn't succeed and ip_modopen
5472 	 * itself calls ip_close.
5473 	 */
5474 	if (ill->ill_credp != NULL)
5475 		crfree(ill->ill_credp);
5476 
5477 	mutex_enter(&ill->ill_lock);
5478 	ill_nic_info_dispatch(ill);
5479 	mutex_exit(&ill->ill_lock);
5480 
5481 	/*
5482 	 * Now we are done with the module close pieces that
5483 	 * need the netstack_t.
5484 	 */
5485 	netstack_rele(ipst->ips_netstack);
5486 
5487 	mi_close_free((IDP)ill);
5488 	q->q_ptr = WR(q)->q_ptr = NULL;
5489 
5490 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5491 
5492 	return (0);
5493 }
5494 
5495 /*
5496  * This is called as part of close() for IP, UDP, ICMP, and RTS
5497  * in order to quiesce the conn.
5498  */
5499 void
5500 ip_quiesce_conn(conn_t *connp)
5501 {
5502 	boolean_t	drain_cleanup_reqd = B_FALSE;
5503 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5504 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5505 	ip_stack_t	*ipst;
5506 
5507 	ASSERT(!IPCL_IS_TCP(connp));
5508 	ipst = connp->conn_netstack->netstack_ip;
5509 
5510 	/*
5511 	 * Mark the conn as closing, and this conn must not be
5512 	 * inserted in future into any list. Eg. conn_drain_insert(),
5513 	 * won't insert this conn into the conn_drain_list.
5514 	 * Similarly ill_pending_mp_add() will not add any mp to
5515 	 * the pending mp list, after this conn has started closing.
5516 	 *
5517 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5518 	 * cannot get set henceforth.
5519 	 */
5520 	mutex_enter(&connp->conn_lock);
5521 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5522 	connp->conn_state_flags |= CONN_CLOSING;
5523 	if (connp->conn_idl != NULL)
5524 		drain_cleanup_reqd = B_TRUE;
5525 	if (connp->conn_oper_pending_ill != NULL)
5526 		conn_ioctl_cleanup_reqd = B_TRUE;
5527 	if (connp->conn_dhcpinit_ill != NULL) {
5528 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
5529 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
5530 		connp->conn_dhcpinit_ill = NULL;
5531 	}
5532 	if (connp->conn_ilg_inuse != 0)
5533 		ilg_cleanup_reqd = B_TRUE;
5534 	mutex_exit(&connp->conn_lock);
5535 
5536 	if (conn_ioctl_cleanup_reqd)
5537 		conn_ioctl_cleanup(connp);
5538 
5539 	if (is_system_labeled() && connp->conn_anon_port) {
5540 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5541 		    connp->conn_mlp_type, connp->conn_ulp,
5542 		    ntohs(connp->conn_lport), B_FALSE);
5543 		connp->conn_anon_port = 0;
5544 	}
5545 	connp->conn_mlp_type = mlptSingle;
5546 
5547 	/*
5548 	 * Remove this conn from any fanout list it is on.
5549 	 * and then wait for any threads currently operating
5550 	 * on this endpoint to finish
5551 	 */
5552 	ipcl_hash_remove(connp);
5553 
5554 	/*
5555 	 * Remove this conn from the drain list, and do
5556 	 * any other cleanup that may be required.
5557 	 * (Only non-tcp streams may have a non-null conn_idl.
5558 	 * TCP streams are never flow controlled, and
5559 	 * conn_idl will be null)
5560 	 */
5561 	if (drain_cleanup_reqd)
5562 		conn_drain_tail(connp, B_TRUE);
5563 
5564 	if (connp == ipst->ips_ip_g_mrouter)
5565 		(void) ip_mrouter_done(NULL, ipst);
5566 
5567 	if (ilg_cleanup_reqd)
5568 		ilg_delete_all(connp);
5569 
5570 	conn_delete_ire(connp, NULL);
5571 
5572 	/*
5573 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5574 	 * callers from write side can't be there now because close
5575 	 * is in progress. The only other caller is ipcl_walk
5576 	 * which checks for the condemned flag.
5577 	 */
5578 	mutex_enter(&connp->conn_lock);
5579 	connp->conn_state_flags |= CONN_CONDEMNED;
5580 	while (connp->conn_ref != 1)
5581 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5582 	connp->conn_state_flags |= CONN_QUIESCED;
5583 	mutex_exit(&connp->conn_lock);
5584 }
5585 
5586 /* ARGSUSED */
5587 int
5588 ip_close(queue_t *q, int flags)
5589 {
5590 	conn_t		*connp;
5591 
5592 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5593 
5594 	/*
5595 	 * Call the appropriate delete routine depending on whether this is
5596 	 * a module or device.
5597 	 */
5598 	if (WR(q)->q_next != NULL) {
5599 		/* This is a module close */
5600 		return (ip_modclose((ill_t *)q->q_ptr));
5601 	}
5602 
5603 	connp = q->q_ptr;
5604 	ip_quiesce_conn(connp);
5605 
5606 	qprocsoff(q);
5607 
5608 	/*
5609 	 * Now we are truly single threaded on this stream, and can
5610 	 * delete the things hanging off the connp, and finally the connp.
5611 	 * We removed this connp from the fanout list, it cannot be
5612 	 * accessed thru the fanouts, and we already waited for the
5613 	 * conn_ref to drop to 0. We are already in close, so
5614 	 * there cannot be any other thread from the top. qprocsoff
5615 	 * has completed, and service has completed or won't run in
5616 	 * future.
5617 	 */
5618 	ASSERT(connp->conn_ref == 1);
5619 
5620 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
5621 
5622 	connp->conn_ref--;
5623 	ipcl_conn_destroy(connp);
5624 
5625 	q->q_ptr = WR(q)->q_ptr = NULL;
5626 	return (0);
5627 }
5628 
5629 /*
5630  * Wapper around putnext() so that ip_rts_request can merely use
5631  * conn_recv.
5632  */
5633 /*ARGSUSED2*/
5634 static void
5635 ip_conn_input(void *arg1, mblk_t *mp, void *arg2)
5636 {
5637 	conn_t *connp = (conn_t *)arg1;
5638 
5639 	putnext(connp->conn_rq, mp);
5640 }
5641 
5642 /* Return the IP checksum for the IP header at "iph". */
5643 uint16_t
5644 ip_csum_hdr(ipha_t *ipha)
5645 {
5646 	uint16_t	*uph;
5647 	uint32_t	sum;
5648 	int		opt_len;
5649 
5650 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5651 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5652 	uph = (uint16_t *)ipha;
5653 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5654 	    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5655 	if (opt_len > 0) {
5656 		do {
5657 			sum += uph[10];
5658 			sum += uph[11];
5659 			uph += 2;
5660 		} while (--opt_len);
5661 	}
5662 	sum = (sum & 0xFFFF) + (sum >> 16);
5663 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5664 	if (sum == 0xffff)
5665 		sum = 0;
5666 	return ((uint16_t)sum);
5667 }
5668 
5669 /*
5670  * Called when the module is about to be unloaded
5671  */
5672 void
5673 ip_ddi_destroy(void)
5674 {
5675 	tnet_fini();
5676 
5677 	icmp_ddi_destroy();
5678 	rts_ddi_destroy();
5679 	udp_ddi_destroy();
5680 	sctp_ddi_g_destroy();
5681 	tcp_ddi_g_destroy();
5682 	ipsec_policy_g_destroy();
5683 	ipcl_g_destroy();
5684 	ip_net_g_destroy();
5685 	ip_ire_g_fini();
5686 	inet_minor_destroy(ip_minor_arena_sa);
5687 #if defined(_LP64)
5688 	inet_minor_destroy(ip_minor_arena_la);
5689 #endif
5690 
5691 #ifdef DEBUG
5692 	list_destroy(&ip_thread_list);
5693 	rw_destroy(&ip_thread_rwlock);
5694 	tsd_destroy(&ip_thread_data);
5695 #endif
5696 
5697 	netstack_unregister(NS_IP);
5698 }
5699 
5700 /*
5701  * First step in cleanup.
5702  */
5703 /* ARGSUSED */
5704 static void
5705 ip_stack_shutdown(netstackid_t stackid, void *arg)
5706 {
5707 	ip_stack_t *ipst = (ip_stack_t *)arg;
5708 
5709 #ifdef NS_DEBUG
5710 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5711 #endif
5712 
5713 	/* Get rid of loopback interfaces and their IREs */
5714 	ip_loopback_cleanup(ipst);
5715 }
5716 
5717 /*
5718  * Free the IP stack instance.
5719  */
5720 static void
5721 ip_stack_fini(netstackid_t stackid, void *arg)
5722 {
5723 	ip_stack_t *ipst = (ip_stack_t *)arg;
5724 	int ret;
5725 
5726 #ifdef NS_DEBUG
5727 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5728 #endif
5729 	ipv4_hook_destroy(ipst);
5730 	ipv6_hook_destroy(ipst);
5731 	ip_net_destroy(ipst);
5732 
5733 	rw_destroy(&ipst->ips_srcid_lock);
5734 
5735 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5736 	ipst->ips_ip_mibkp = NULL;
5737 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5738 	ipst->ips_icmp_mibkp = NULL;
5739 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5740 	ipst->ips_ip_kstat = NULL;
5741 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5742 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5743 	ipst->ips_ip6_kstat = NULL;
5744 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5745 
5746 	nd_free(&ipst->ips_ip_g_nd);
5747 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5748 	ipst->ips_param_arr = NULL;
5749 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5750 	ipst->ips_ndp_arr = NULL;
5751 
5752 	ip_mrouter_stack_destroy(ipst);
5753 
5754 	mutex_destroy(&ipst->ips_ip_mi_lock);
5755 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5756 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5757 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5758 
5759 	ret = untimeout(ipst->ips_igmp_timeout_id);
5760 	if (ret == -1) {
5761 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5762 	} else {
5763 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5764 		ipst->ips_igmp_timeout_id = 0;
5765 	}
5766 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5767 	if (ret == -1) {
5768 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5769 	} else {
5770 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5771 		ipst->ips_igmp_slowtimeout_id = 0;
5772 	}
5773 	ret = untimeout(ipst->ips_mld_timeout_id);
5774 	if (ret == -1) {
5775 		ASSERT(ipst->ips_mld_timeout_id == 0);
5776 	} else {
5777 		ASSERT(ipst->ips_mld_timeout_id != 0);
5778 		ipst->ips_mld_timeout_id = 0;
5779 	}
5780 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5781 	if (ret == -1) {
5782 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5783 	} else {
5784 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5785 		ipst->ips_mld_slowtimeout_id = 0;
5786 	}
5787 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5788 	if (ret == -1) {
5789 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5790 	} else {
5791 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5792 		ipst->ips_ip_ire_expire_id = 0;
5793 	}
5794 
5795 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5796 	mutex_destroy(&ipst->ips_mld_timer_lock);
5797 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5798 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5799 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5800 	rw_destroy(&ipst->ips_ill_g_lock);
5801 
5802 	ip_ire_fini(ipst);
5803 	ip6_asp_free(ipst);
5804 	conn_drain_fini(ipst);
5805 	ipcl_destroy(ipst);
5806 
5807 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5808 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5809 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5810 	ipst->ips_ndp4 = NULL;
5811 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5812 	ipst->ips_ndp6 = NULL;
5813 
5814 	if (ipst->ips_loopback_ksp != NULL) {
5815 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5816 		ipst->ips_loopback_ksp = NULL;
5817 	}
5818 
5819 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5820 	ipst->ips_phyint_g_list = NULL;
5821 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5822 	ipst->ips_ill_g_heads = NULL;
5823 
5824 	kmem_free(ipst, sizeof (*ipst));
5825 }
5826 
5827 /*
5828  * This function is called from the TSD destructor, and is used to debug
5829  * reference count issues in IP. See block comment in <inet/ip_if.h> for
5830  * details.
5831  */
5832 static void
5833 ip_thread_exit(void *phash)
5834 {
5835 	th_hash_t *thh = phash;
5836 
5837 	rw_enter(&ip_thread_rwlock, RW_WRITER);
5838 	list_remove(&ip_thread_list, thh);
5839 	rw_exit(&ip_thread_rwlock);
5840 	mod_hash_destroy_hash(thh->thh_hash);
5841 	kmem_free(thh, sizeof (*thh));
5842 }
5843 
5844 /*
5845  * Called when the IP kernel module is loaded into the kernel
5846  */
5847 void
5848 ip_ddi_init(void)
5849 {
5850 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5851 
5852 	/*
5853 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5854 	 * initial devices: ip, ip6, tcp, tcp6.
5855 	 */
5856 	/*
5857 	 * If this is a 64-bit kernel, then create two separate arenas -
5858 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
5859 	 * other for socket apps in the range 2^^18 through 2^^32-1.
5860 	 */
5861 	ip_minor_arena_la = NULL;
5862 	ip_minor_arena_sa = NULL;
5863 #if defined(_LP64)
5864 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5865 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
5866 		cmn_err(CE_PANIC,
5867 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5868 	}
5869 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
5870 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
5871 		cmn_err(CE_PANIC,
5872 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
5873 	}
5874 #else
5875 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5876 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
5877 		cmn_err(CE_PANIC,
5878 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5879 	}
5880 #endif
5881 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5882 
5883 	ipcl_g_init();
5884 	ip_ire_g_init();
5885 	ip_net_g_init();
5886 
5887 #ifdef DEBUG
5888 	tsd_create(&ip_thread_data, ip_thread_exit);
5889 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
5890 	list_create(&ip_thread_list, sizeof (th_hash_t),
5891 	    offsetof(th_hash_t, thh_link));
5892 #endif
5893 
5894 	/*
5895 	 * We want to be informed each time a stack is created or
5896 	 * destroyed in the kernel, so we can maintain the
5897 	 * set of udp_stack_t's.
5898 	 */
5899 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5900 	    ip_stack_fini);
5901 
5902 	ipsec_policy_g_init();
5903 	tcp_ddi_g_init();
5904 	sctp_ddi_g_init();
5905 
5906 	tnet_init();
5907 
5908 	udp_ddi_init();
5909 	rts_ddi_init();
5910 	icmp_ddi_init();
5911 }
5912 
5913 /*
5914  * Initialize the IP stack instance.
5915  */
5916 static void *
5917 ip_stack_init(netstackid_t stackid, netstack_t *ns)
5918 {
5919 	ip_stack_t	*ipst;
5920 	ipparam_t	*pa;
5921 	ipndp_t		*na;
5922 
5923 #ifdef NS_DEBUG
5924 	printf("ip_stack_init(stack %d)\n", stackid);
5925 #endif
5926 
5927 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
5928 	ipst->ips_netstack = ns;
5929 
5930 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
5931 	    KM_SLEEP);
5932 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
5933 	    KM_SLEEP);
5934 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5935 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5936 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5937 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5938 
5939 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5940 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5941 	ipst->ips_igmp_deferred_next = INFINITY;
5942 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5943 	ipst->ips_mld_deferred_next = INFINITY;
5944 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5945 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5946 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5947 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5948 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
5949 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5950 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5951 
5952 	ipcl_init(ipst);
5953 	ip_ire_init(ipst);
5954 	ip6_asp_init(ipst);
5955 	ipif_init(ipst);
5956 	conn_drain_init(ipst);
5957 	ip_mrouter_stack_init(ipst);
5958 
5959 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
5960 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
5961 
5962 	ipst->ips_ip_multirt_log_interval = 1000;
5963 
5964 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
5965 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
5966 	ipst->ips_ill_index = 1;
5967 
5968 	ipst->ips_saved_ip_g_forward = -1;
5969 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
5970 
5971 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
5972 	ipst->ips_param_arr = pa;
5973 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
5974 
5975 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
5976 	ipst->ips_ndp_arr = na;
5977 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5978 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
5979 	    (caddr_t)&ipst->ips_ip_g_forward;
5980 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
5981 	    (caddr_t)&ipst->ips_ipv6_forward;
5982 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
5983 	    "ip_cgtp_filter") == 0);
5984 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
5985 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
5986 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_name,
5987 	    "ipmp_hook_emulation") == 0);
5988 	ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_data =
5989 	    (caddr_t)&ipst->ips_ipmp_hook_emulation;
5990 
5991 	(void) ip_param_register(&ipst->ips_ip_g_nd,
5992 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
5993 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
5994 
5995 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
5996 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
5997 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
5998 	ipst->ips_ip6_kstat =
5999 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6000 
6001 	ipst->ips_ipmp_enable_failback = B_TRUE;
6002 
6003 	ipst->ips_ip_src_id = 1;
6004 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6005 
6006 	ip_net_init(ipst, ns);
6007 	ipv4_hook_init(ipst);
6008 	ipv6_hook_init(ipst);
6009 
6010 	return (ipst);
6011 }
6012 
6013 /*
6014  * Allocate and initialize a DLPI template of the specified length.  (May be
6015  * called as writer.)
6016  */
6017 mblk_t *
6018 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6019 {
6020 	mblk_t	*mp;
6021 
6022 	mp = allocb(len, BPRI_MED);
6023 	if (!mp)
6024 		return (NULL);
6025 
6026 	/*
6027 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6028 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6029 	 * that other DLPI are M_PROTO.
6030 	 */
6031 	if (prim == DL_INFO_REQ) {
6032 		mp->b_datap->db_type = M_PCPROTO;
6033 	} else {
6034 		mp->b_datap->db_type = M_PROTO;
6035 	}
6036 
6037 	mp->b_wptr = mp->b_rptr + len;
6038 	bzero(mp->b_rptr, len);
6039 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6040 	return (mp);
6041 }
6042 
6043 /*
6044  * Debug formatting routine.  Returns a character string representation of the
6045  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6046  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6047  *
6048  * Once the ndd table-printing interfaces are removed, this can be changed to
6049  * standard dotted-decimal form.
6050  */
6051 char *
6052 ip_dot_addr(ipaddr_t addr, char *buf)
6053 {
6054 	uint8_t *ap = (uint8_t *)&addr;
6055 
6056 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6057 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6058 	return (buf);
6059 }
6060 
6061 /*
6062  * Write the given MAC address as a printable string in the usual colon-
6063  * separated format.
6064  */
6065 const char *
6066 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6067 {
6068 	char *bp;
6069 
6070 	if (alen == 0 || buflen < 4)
6071 		return ("?");
6072 	bp = buf;
6073 	for (;;) {
6074 		/*
6075 		 * If there are more MAC address bytes available, but we won't
6076 		 * have any room to print them, then add "..." to the string
6077 		 * instead.  See below for the 'magic number' explanation.
6078 		 */
6079 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6080 			(void) strcpy(bp, "...");
6081 			break;
6082 		}
6083 		(void) sprintf(bp, "%02x", *addr++);
6084 		bp += 2;
6085 		if (--alen == 0)
6086 			break;
6087 		*bp++ = ':';
6088 		buflen -= 3;
6089 		/*
6090 		 * At this point, based on the first 'if' statement above,
6091 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6092 		 * buflen >= 4.  The first case leaves room for the final "xx"
6093 		 * number and trailing NUL byte.  The second leaves room for at
6094 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6095 		 * that statement.
6096 		 */
6097 	}
6098 	return (buf);
6099 }
6100 
6101 /*
6102  * Send an ICMP error after patching up the packet appropriately.  Returns
6103  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6104  */
6105 static boolean_t
6106 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6107     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6108     zoneid_t zoneid, ip_stack_t *ipst)
6109 {
6110 	ipha_t *ipha;
6111 	mblk_t *first_mp;
6112 	boolean_t secure;
6113 	unsigned char db_type;
6114 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6115 
6116 	first_mp = mp;
6117 	if (mctl_present) {
6118 		mp = mp->b_cont;
6119 		secure = ipsec_in_is_secure(first_mp);
6120 		ASSERT(mp != NULL);
6121 	} else {
6122 		/*
6123 		 * If this is an ICMP error being reported - which goes
6124 		 * up as M_CTLs, we need to convert them to M_DATA till
6125 		 * we finish checking with global policy because
6126 		 * ipsec_check_global_policy() assumes M_DATA as clear
6127 		 * and M_CTL as secure.
6128 		 */
6129 		db_type = DB_TYPE(mp);
6130 		DB_TYPE(mp) = M_DATA;
6131 		secure = B_FALSE;
6132 	}
6133 	/*
6134 	 * We are generating an icmp error for some inbound packet.
6135 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6136 	 * Before we generate an error, check with global policy
6137 	 * to see whether this is allowed to enter the system. As
6138 	 * there is no "conn", we are checking with global policy.
6139 	 */
6140 	ipha = (ipha_t *)mp->b_rptr;
6141 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6142 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6143 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6144 		if (first_mp == NULL)
6145 			return (B_FALSE);
6146 	}
6147 
6148 	if (!mctl_present)
6149 		DB_TYPE(mp) = db_type;
6150 
6151 	if (flags & IP_FF_SEND_ICMP) {
6152 		if (flags & IP_FF_HDR_COMPLETE) {
6153 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6154 				freemsg(first_mp);
6155 				return (B_TRUE);
6156 			}
6157 		}
6158 		if (flags & IP_FF_CKSUM) {
6159 			/*
6160 			 * Have to correct checksum since
6161 			 * the packet might have been
6162 			 * fragmented and the reassembly code in ip_rput
6163 			 * does not restore the IP checksum.
6164 			 */
6165 			ipha->ipha_hdr_checksum = 0;
6166 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6167 		}
6168 		switch (icmp_type) {
6169 		case ICMP_DEST_UNREACHABLE:
6170 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6171 			    ipst);
6172 			break;
6173 		default:
6174 			freemsg(first_mp);
6175 			break;
6176 		}
6177 	} else {
6178 		freemsg(first_mp);
6179 		return (B_FALSE);
6180 	}
6181 
6182 	return (B_TRUE);
6183 }
6184 
6185 /*
6186  * Used to send an ICMP error message when a packet is received for
6187  * a protocol that is not supported. The mblk passed as argument
6188  * is consumed by this function.
6189  */
6190 void
6191 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6192     ip_stack_t *ipst)
6193 {
6194 	mblk_t *mp;
6195 	ipha_t *ipha;
6196 	ill_t *ill;
6197 	ipsec_in_t *ii;
6198 
6199 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6200 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6201 
6202 	mp = ipsec_mp->b_cont;
6203 	ipsec_mp->b_cont = NULL;
6204 	ipha = (ipha_t *)mp->b_rptr;
6205 	/* Get ill from index in ipsec_in_t. */
6206 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6207 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6208 	    ipst);
6209 	if (ill != NULL) {
6210 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6211 			if (ip_fanout_send_icmp(q, mp, flags,
6212 			    ICMP_DEST_UNREACHABLE,
6213 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6214 				BUMP_MIB(ill->ill_ip_mib,
6215 				    ipIfStatsInUnknownProtos);
6216 			}
6217 		} else {
6218 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6219 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6220 			    0, B_FALSE, zoneid, ipst)) {
6221 				BUMP_MIB(ill->ill_ip_mib,
6222 				    ipIfStatsInUnknownProtos);
6223 			}
6224 		}
6225 		ill_refrele(ill);
6226 	} else { /* re-link for the freemsg() below. */
6227 		ipsec_mp->b_cont = mp;
6228 	}
6229 
6230 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6231 	freemsg(ipsec_mp);
6232 }
6233 
6234 /*
6235  * See if the inbound datagram has had IPsec processing applied to it.
6236  */
6237 boolean_t
6238 ipsec_in_is_secure(mblk_t *ipsec_mp)
6239 {
6240 	ipsec_in_t *ii;
6241 
6242 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6243 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6244 
6245 	if (ii->ipsec_in_loopback) {
6246 		return (ii->ipsec_in_secure);
6247 	} else {
6248 		return (ii->ipsec_in_ah_sa != NULL ||
6249 		    ii->ipsec_in_esp_sa != NULL ||
6250 		    ii->ipsec_in_decaps);
6251 	}
6252 }
6253 
6254 /*
6255  * Handle protocols with which IP is less intimate.  There
6256  * can be more than one stream bound to a particular
6257  * protocol.  When this is the case, normally each one gets a copy
6258  * of any incoming packets.
6259  *
6260  * IPsec NOTE :
6261  *
6262  * Don't allow a secure packet going up a non-secure connection.
6263  * We don't allow this because
6264  *
6265  * 1) Reply might go out in clear which will be dropped at
6266  *    the sending side.
6267  * 2) If the reply goes out in clear it will give the
6268  *    adversary enough information for getting the key in
6269  *    most of the cases.
6270  *
6271  * Moreover getting a secure packet when we expect clear
6272  * implies that SA's were added without checking for
6273  * policy on both ends. This should not happen once ISAKMP
6274  * is used to negotiate SAs as SAs will be added only after
6275  * verifying the policy.
6276  *
6277  * NOTE : If the packet was tunneled and not multicast we only send
6278  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6279  * back to delivering packets to AF_INET6 raw sockets.
6280  *
6281  * IPQoS Notes:
6282  * Once we have determined the client, invoke IPPF processing.
6283  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6284  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6285  * ip_policy will be false.
6286  *
6287  * Zones notes:
6288  * Currently only applications in the global zone can create raw sockets for
6289  * protocols other than ICMP. So unlike the broadcast / multicast case of
6290  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6291  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6292  */
6293 static void
6294 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6295     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6296     zoneid_t zoneid)
6297 {
6298 	queue_t	*rq;
6299 	mblk_t	*mp1, *first_mp1;
6300 	uint_t	protocol = ipha->ipha_protocol;
6301 	ipaddr_t dst;
6302 	boolean_t one_only;
6303 	mblk_t *first_mp = mp;
6304 	boolean_t secure;
6305 	uint32_t ill_index;
6306 	conn_t	*connp, *first_connp, *next_connp;
6307 	connf_t	*connfp;
6308 	boolean_t shared_addr;
6309 	mib2_ipIfStatsEntry_t *mibptr;
6310 	ip_stack_t *ipst = recv_ill->ill_ipst;
6311 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6312 
6313 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6314 	if (mctl_present) {
6315 		mp = first_mp->b_cont;
6316 		secure = ipsec_in_is_secure(first_mp);
6317 		ASSERT(mp != NULL);
6318 	} else {
6319 		secure = B_FALSE;
6320 	}
6321 	dst = ipha->ipha_dst;
6322 	/*
6323 	 * If the packet was tunneled and not multicast we only send to it
6324 	 * the first match.
6325 	 */
6326 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6327 	    !CLASSD(dst));
6328 
6329 	shared_addr = (zoneid == ALL_ZONES);
6330 	if (shared_addr) {
6331 		/*
6332 		 * We don't allow multilevel ports for raw IP, so no need to
6333 		 * check for that here.
6334 		 */
6335 		zoneid = tsol_packet_to_zoneid(mp);
6336 	}
6337 
6338 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6339 	mutex_enter(&connfp->connf_lock);
6340 	connp = connfp->connf_head;
6341 	for (connp = connfp->connf_head; connp != NULL;
6342 	    connp = connp->conn_next) {
6343 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6344 		    zoneid) &&
6345 		    (!is_system_labeled() ||
6346 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6347 		    connp))) {
6348 			break;
6349 		}
6350 	}
6351 
6352 	if (connp == NULL || connp->conn_upq == NULL) {
6353 		/*
6354 		 * No one bound to these addresses.  Is
6355 		 * there a client that wants all
6356 		 * unclaimed datagrams?
6357 		 */
6358 		mutex_exit(&connfp->connf_lock);
6359 		/*
6360 		 * Check for IPPROTO_ENCAP...
6361 		 */
6362 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6363 			/*
6364 			 * If an IPsec mblk is here on a multicast
6365 			 * tunnel (using ip_mroute stuff), check policy here,
6366 			 * THEN ship off to ip_mroute_decap().
6367 			 *
6368 			 * BTW,  If I match a configured IP-in-IP
6369 			 * tunnel, this path will not be reached, and
6370 			 * ip_mroute_decap will never be called.
6371 			 */
6372 			first_mp = ipsec_check_global_policy(first_mp, connp,
6373 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6374 			if (first_mp != NULL) {
6375 				if (mctl_present)
6376 					freeb(first_mp);
6377 				ip_mroute_decap(q, mp, ill);
6378 			} /* Else we already freed everything! */
6379 		} else {
6380 			/*
6381 			 * Otherwise send an ICMP protocol unreachable.
6382 			 */
6383 			if (ip_fanout_send_icmp(q, first_mp, flags,
6384 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6385 			    mctl_present, zoneid, ipst)) {
6386 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6387 			}
6388 		}
6389 		return;
6390 	}
6391 	CONN_INC_REF(connp);
6392 	first_connp = connp;
6393 
6394 	/*
6395 	 * Only send message to one tunnel driver by immediately
6396 	 * terminating the loop.
6397 	 */
6398 	connp = one_only ? NULL : connp->conn_next;
6399 
6400 	for (;;) {
6401 		while (connp != NULL) {
6402 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6403 			    flags, zoneid) &&
6404 			    (!is_system_labeled() ||
6405 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6406 			    shared_addr, connp)))
6407 				break;
6408 			connp = connp->conn_next;
6409 		}
6410 
6411 		/*
6412 		 * Copy the packet.
6413 		 */
6414 		if (connp == NULL || connp->conn_upq == NULL ||
6415 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6416 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6417 			/*
6418 			 * No more interested clients or memory
6419 			 * allocation failed
6420 			 */
6421 			connp = first_connp;
6422 			break;
6423 		}
6424 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6425 		CONN_INC_REF(connp);
6426 		mutex_exit(&connfp->connf_lock);
6427 		rq = connp->conn_rq;
6428 		if (!canputnext(rq)) {
6429 			if (flags & IP_FF_RAWIP) {
6430 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6431 			} else {
6432 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6433 			}
6434 
6435 			freemsg(first_mp1);
6436 		} else {
6437 			/*
6438 			 * Don't enforce here if we're an actual tunnel -
6439 			 * let "tun" do it instead.
6440 			 */
6441 			if (!IPCL_IS_IPTUN(connp) &&
6442 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6443 			    secure)) {
6444 				first_mp1 = ipsec_check_inbound_policy
6445 				    (first_mp1, connp, ipha, NULL,
6446 				    mctl_present);
6447 			}
6448 			if (first_mp1 != NULL) {
6449 				int in_flags = 0;
6450 				/*
6451 				 * ip_fanout_proto also gets called from
6452 				 * icmp_inbound_error_fanout, in which case
6453 				 * the msg type is M_CTL.  Don't add info
6454 				 * in this case for the time being. In future
6455 				 * when there is a need for knowing the
6456 				 * inbound iface index for ICMP error msgs,
6457 				 * then this can be changed.
6458 				 */
6459 				if (connp->conn_recvif)
6460 					in_flags = IPF_RECVIF;
6461 				/*
6462 				 * The ULP may support IP_RECVPKTINFO for both
6463 				 * IP v4 and v6 so pass the appropriate argument
6464 				 * based on conn IP version.
6465 				 */
6466 				if (connp->conn_ip_recvpktinfo) {
6467 					if (connp->conn_af_isv6) {
6468 						/*
6469 						 * V6 only needs index
6470 						 */
6471 						in_flags |= IPF_RECVIF;
6472 					} else {
6473 						/*
6474 						 * V4 needs index +
6475 						 * matching address.
6476 						 */
6477 						in_flags |= IPF_RECVADDR;
6478 					}
6479 				}
6480 				if ((in_flags != 0) &&
6481 				    (mp->b_datap->db_type != M_CTL)) {
6482 					/*
6483 					 * the actual data will be
6484 					 * contained in b_cont upon
6485 					 * successful return of the
6486 					 * following call else
6487 					 * original mblk is returned
6488 					 */
6489 					ASSERT(recv_ill != NULL);
6490 					mp1 = ip_add_info(mp1, recv_ill,
6491 					    in_flags, IPCL_ZONEID(connp), ipst);
6492 				}
6493 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6494 				if (mctl_present)
6495 					freeb(first_mp1);
6496 				(connp->conn_recv)(connp, mp1, NULL);
6497 			}
6498 		}
6499 		mutex_enter(&connfp->connf_lock);
6500 		/* Follow the next pointer before releasing the conn. */
6501 		next_connp = connp->conn_next;
6502 		CONN_DEC_REF(connp);
6503 		connp = next_connp;
6504 	}
6505 
6506 	/* Last one.  Send it upstream. */
6507 	mutex_exit(&connfp->connf_lock);
6508 
6509 	/*
6510 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6511 	 * will be set to false.
6512 	 */
6513 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6514 		ill_index = ill->ill_phyint->phyint_ifindex;
6515 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6516 		if (mp == NULL) {
6517 			CONN_DEC_REF(connp);
6518 			if (mctl_present) {
6519 				freeb(first_mp);
6520 			}
6521 			return;
6522 		}
6523 	}
6524 
6525 	rq = connp->conn_rq;
6526 	if (!canputnext(rq)) {
6527 		if (flags & IP_FF_RAWIP) {
6528 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6529 		} else {
6530 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6531 		}
6532 
6533 		freemsg(first_mp);
6534 	} else {
6535 		if (IPCL_IS_IPTUN(connp)) {
6536 			/*
6537 			 * Tunneled packet.  We enforce policy in the tunnel
6538 			 * module itself.
6539 			 *
6540 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6541 			 * a policy check.
6542 			 * FIXME to use conn_recv for tun later.
6543 			 */
6544 			putnext(rq, first_mp);
6545 			CONN_DEC_REF(connp);
6546 			return;
6547 		}
6548 
6549 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6550 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6551 			    ipha, NULL, mctl_present);
6552 		}
6553 
6554 		if (first_mp != NULL) {
6555 			int in_flags = 0;
6556 
6557 			/*
6558 			 * ip_fanout_proto also gets called
6559 			 * from icmp_inbound_error_fanout, in
6560 			 * which case the msg type is M_CTL.
6561 			 * Don't add info in this case for time
6562 			 * being. In future when there is a
6563 			 * need for knowing the inbound iface
6564 			 * index for ICMP error msgs, then this
6565 			 * can be changed
6566 			 */
6567 			if (connp->conn_recvif)
6568 				in_flags = IPF_RECVIF;
6569 			if (connp->conn_ip_recvpktinfo) {
6570 				if (connp->conn_af_isv6) {
6571 					/*
6572 					 * V6 only needs index
6573 					 */
6574 					in_flags |= IPF_RECVIF;
6575 				} else {
6576 					/*
6577 					 * V4 needs index +
6578 					 * matching address.
6579 					 */
6580 					in_flags |= IPF_RECVADDR;
6581 				}
6582 			}
6583 			if ((in_flags != 0) &&
6584 			    (mp->b_datap->db_type != M_CTL)) {
6585 
6586 				/*
6587 				 * the actual data will be contained in
6588 				 * b_cont upon successful return
6589 				 * of the following call else original
6590 				 * mblk is returned
6591 				 */
6592 				ASSERT(recv_ill != NULL);
6593 				mp = ip_add_info(mp, recv_ill,
6594 				    in_flags, IPCL_ZONEID(connp), ipst);
6595 			}
6596 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6597 			(connp->conn_recv)(connp, mp, NULL);
6598 			if (mctl_present)
6599 				freeb(first_mp);
6600 		}
6601 	}
6602 	CONN_DEC_REF(connp);
6603 }
6604 
6605 /*
6606  * Fanout for TCP packets
6607  * The caller puts <fport, lport> in the ports parameter.
6608  *
6609  * IPQoS Notes
6610  * Before sending it to the client, invoke IPPF processing.
6611  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6612  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6613  * ip_policy is false.
6614  */
6615 static void
6616 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6617     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6618 {
6619 	mblk_t  *first_mp;
6620 	boolean_t secure;
6621 	uint32_t ill_index;
6622 	int	ip_hdr_len;
6623 	tcph_t	*tcph;
6624 	boolean_t syn_present = B_FALSE;
6625 	conn_t	*connp;
6626 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6627 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6628 
6629 	ASSERT(recv_ill != NULL);
6630 
6631 	first_mp = mp;
6632 	if (mctl_present) {
6633 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6634 		mp = first_mp->b_cont;
6635 		secure = ipsec_in_is_secure(first_mp);
6636 		ASSERT(mp != NULL);
6637 	} else {
6638 		secure = B_FALSE;
6639 	}
6640 
6641 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6642 
6643 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6644 	    zoneid, ipst)) == NULL) {
6645 		/*
6646 		 * No connected connection or listener. Send a
6647 		 * TH_RST via tcp_xmit_listeners_reset.
6648 		 */
6649 
6650 		/* Initiate IPPf processing, if needed. */
6651 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6652 			uint32_t ill_index;
6653 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6654 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6655 			if (first_mp == NULL)
6656 				return;
6657 		}
6658 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6659 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6660 		    zoneid));
6661 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6662 		    ipst->ips_netstack->netstack_tcp, NULL);
6663 		return;
6664 	}
6665 
6666 	/*
6667 	 * Allocate the SYN for the TCP connection here itself
6668 	 */
6669 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6670 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6671 		if (IPCL_IS_TCP(connp)) {
6672 			squeue_t *sqp;
6673 
6674 			/*
6675 			 * For fused tcp loopback, assign the eager's
6676 			 * squeue to be that of the active connect's.
6677 			 * Note that we don't check for IP_FF_LOOPBACK
6678 			 * here since this routine gets called only
6679 			 * for loopback (unlike the IPv6 counterpart).
6680 			 */
6681 			ASSERT(Q_TO_CONN(q) != NULL);
6682 			if (do_tcp_fusion &&
6683 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6684 			    !secure &&
6685 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6686 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6687 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6688 				sqp = Q_TO_CONN(q)->conn_sqp;
6689 			} else {
6690 				sqp = IP_SQUEUE_GET(lbolt);
6691 			}
6692 
6693 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6694 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6695 			syn_present = B_TRUE;
6696 		}
6697 	}
6698 
6699 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6700 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6701 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6702 		if ((flags & TH_RST) || (flags & TH_URG)) {
6703 			CONN_DEC_REF(connp);
6704 			freemsg(first_mp);
6705 			return;
6706 		}
6707 		if (flags & TH_ACK) {
6708 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6709 			    ipst->ips_netstack->netstack_tcp, connp);
6710 			CONN_DEC_REF(connp);
6711 			return;
6712 		}
6713 
6714 		CONN_DEC_REF(connp);
6715 		freemsg(first_mp);
6716 		return;
6717 	}
6718 
6719 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6720 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6721 		    NULL, mctl_present);
6722 		if (first_mp == NULL) {
6723 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6724 			CONN_DEC_REF(connp);
6725 			return;
6726 		}
6727 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6728 			ASSERT(syn_present);
6729 			if (mctl_present) {
6730 				ASSERT(first_mp != mp);
6731 				first_mp->b_datap->db_struioflag |=
6732 				    STRUIO_POLICY;
6733 			} else {
6734 				ASSERT(first_mp == mp);
6735 				mp->b_datap->db_struioflag &=
6736 				    ~STRUIO_EAGER;
6737 				mp->b_datap->db_struioflag |=
6738 				    STRUIO_POLICY;
6739 			}
6740 		} else {
6741 			/*
6742 			 * Discard first_mp early since we're dealing with a
6743 			 * fully-connected conn_t and tcp doesn't do policy in
6744 			 * this case.
6745 			 */
6746 			if (mctl_present) {
6747 				freeb(first_mp);
6748 				mctl_present = B_FALSE;
6749 			}
6750 			first_mp = mp;
6751 		}
6752 	}
6753 
6754 	/*
6755 	 * Initiate policy processing here if needed. If we get here from
6756 	 * icmp_inbound_error_fanout, ip_policy is false.
6757 	 */
6758 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6759 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6760 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6761 		if (mp == NULL) {
6762 			CONN_DEC_REF(connp);
6763 			if (mctl_present)
6764 				freeb(first_mp);
6765 			return;
6766 		} else if (mctl_present) {
6767 			ASSERT(first_mp != mp);
6768 			first_mp->b_cont = mp;
6769 		} else {
6770 			first_mp = mp;
6771 		}
6772 	}
6773 
6774 
6775 
6776 	/* Handle socket options. */
6777 	if (!syn_present &&
6778 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6779 		/* Add header */
6780 		ASSERT(recv_ill != NULL);
6781 		/*
6782 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6783 		 * IPF_RECVIF.
6784 		 */
6785 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6786 		    ipst);
6787 		if (mp == NULL) {
6788 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6789 			CONN_DEC_REF(connp);
6790 			if (mctl_present)
6791 				freeb(first_mp);
6792 			return;
6793 		} else if (mctl_present) {
6794 			/*
6795 			 * ip_add_info might return a new mp.
6796 			 */
6797 			ASSERT(first_mp != mp);
6798 			first_mp->b_cont = mp;
6799 		} else {
6800 			first_mp = mp;
6801 		}
6802 	}
6803 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6804 	if (IPCL_IS_TCP(connp)) {
6805 		/* do not drain, certain use cases can blow the stack */
6806 		squeue_enter_nodrain(connp->conn_sqp, first_mp,
6807 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6808 	} else {
6809 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
6810 		(connp->conn_recv)(connp, first_mp, NULL);
6811 		CONN_DEC_REF(connp);
6812 	}
6813 }
6814 
6815 /*
6816  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
6817  * pass it along to ESP if the SPI is non-zero.  Returns TRUE if the mblk
6818  * is not consumed.
6819  *
6820  * One of four things can happen, all of which affect the passed-in mblk:
6821  *
6822  * 1.) ICMP messages that go through here just get returned TRUE.
6823  *
6824  * 2.) The packet is stock UDP and gets its zero-SPI stripped.  Return TRUE.
6825  *
6826  * 3.) The packet is ESP-in-UDP, gets transformed into an equivalent
6827  *     ESP packet, and is passed along to ESP for consumption.  Return FALSE.
6828  *
6829  * 4.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
6830  */
6831 static boolean_t
6832 zero_spi_check(queue_t *q, mblk_t *mp, ire_t *ire, ill_t *recv_ill,
6833     ipsec_stack_t *ipss)
6834 {
6835 	int shift, plen, iph_len;
6836 	ipha_t *ipha;
6837 	udpha_t *udpha;
6838 	uint32_t *spi;
6839 	uint8_t *orptr;
6840 	boolean_t udp_pkt, free_ire;
6841 
6842 	if (DB_TYPE(mp) == M_CTL) {
6843 		/*
6844 		 * ICMP message with UDP inside.  Don't bother stripping, just
6845 		 * send it up.
6846 		 *
6847 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
6848 		 * to ignore errors set by ICMP anyway ('cause they might be
6849 		 * forged), but that's the app's decision, not ours.
6850 		 */
6851 
6852 		/* Bunch of reality checks for DEBUG kernels... */
6853 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
6854 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
6855 
6856 		return (B_TRUE);
6857 	}
6858 
6859 	ipha = (ipha_t *)mp->b_rptr;
6860 	iph_len = IPH_HDR_LENGTH(ipha);
6861 	plen = ntohs(ipha->ipha_length);
6862 
6863 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
6864 		/*
6865 		 * Most likely a keepalive for the benefit of an intervening
6866 		 * NAT.  These aren't for us, per se, so drop it.
6867 		 *
6868 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
6869 		 * byte packets (keepalives are 1-byte), but we'll drop them
6870 		 * also.
6871 		 */
6872 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6873 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
6874 		return (B_FALSE);
6875 	}
6876 
6877 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
6878 		/* might as well pull it all up - it might be ESP. */
6879 		if (!pullupmsg(mp, -1)) {
6880 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6881 			    DROPPER(ipss, ipds_esp_nomem),
6882 			    &ipss->ipsec_dropper);
6883 			return (B_FALSE);
6884 		}
6885 
6886 		ipha = (ipha_t *)mp->b_rptr;
6887 	}
6888 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
6889 	if (*spi == 0) {
6890 		/* UDP packet - remove 0-spi. */
6891 		shift = sizeof (uint32_t);
6892 	} else {
6893 		/* ESP-in-UDP packet - reduce to ESP. */
6894 		ipha->ipha_protocol = IPPROTO_ESP;
6895 		shift = sizeof (udpha_t);
6896 	}
6897 
6898 	/* Fix IP header */
6899 	ipha->ipha_length = htons(plen - shift);
6900 	ipha->ipha_hdr_checksum = 0;
6901 
6902 	orptr = mp->b_rptr;
6903 	mp->b_rptr += shift;
6904 
6905 	if (*spi == 0) {
6906 		ASSERT((uint8_t *)ipha == orptr);
6907 		udpha = (udpha_t *)(orptr + iph_len);
6908 		udpha->uha_length = htons(plen - shift - iph_len);
6909 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
6910 		udp_pkt = B_TRUE;
6911 	} else {
6912 		udp_pkt = B_FALSE;
6913 	}
6914 	ovbcopy(orptr, orptr + shift, iph_len);
6915 	if (!udp_pkt) /* Punt up for ESP processing. */ {
6916 		ipha = (ipha_t *)(orptr + shift);
6917 
6918 		free_ire = (ire == NULL);
6919 		if (free_ire) {
6920 			/* Re-acquire ire. */
6921 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
6922 			    ipss->ipsec_netstack->netstack_ip);
6923 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
6924 				if (ire != NULL)
6925 					ire_refrele(ire);
6926 				/*
6927 				 * Do a regular freemsg(), as this is an IP
6928 				 * error (no local route) not an IPsec one.
6929 				 */
6930 				freemsg(mp);
6931 			}
6932 		}
6933 
6934 		ip_proto_input(q, mp, ipha, ire, recv_ill, B_TRUE);
6935 		if (free_ire)
6936 			ire_refrele(ire);
6937 	}
6938 
6939 	return (udp_pkt);
6940 }
6941 
6942 /*
6943  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6944  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6945  * Caller is responsible for dropping references to the conn, and freeing
6946  * first_mp.
6947  *
6948  * IPQoS Notes
6949  * Before sending it to the client, invoke IPPF processing. Policy processing
6950  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6951  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6952  * ip_wput_local, ip_policy is false.
6953  */
6954 static void
6955 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
6956     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
6957     boolean_t ip_policy)
6958 {
6959 	boolean_t	mctl_present = (first_mp != NULL);
6960 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
6961 	uint32_t	ill_index;
6962 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6963 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6964 
6965 	ASSERT(ill != NULL);
6966 
6967 	if (mctl_present)
6968 		first_mp->b_cont = mp;
6969 	else
6970 		first_mp = mp;
6971 
6972 	if (CONN_UDP_FLOWCTLD(connp)) {
6973 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
6974 		freemsg(first_mp);
6975 		return;
6976 	}
6977 
6978 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6979 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6980 		    NULL, mctl_present);
6981 		if (first_mp == NULL) {
6982 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
6983 			return;	/* Freed by ipsec_check_inbound_policy(). */
6984 		}
6985 	}
6986 	if (mctl_present)
6987 		freeb(first_mp);
6988 
6989 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
6990 	if (connp->conn_udp->udp_nat_t_endpoint) {
6991 		if (mctl_present) {
6992 			/* mctl_present *shouldn't* happen. */
6993 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
6994 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
6995 			    &ipss->ipsec_dropper);
6996 			return;
6997 		}
6998 
6999 		if (!zero_spi_check(ill->ill_rq, mp, NULL, recv_ill, ipss))
7000 			return;
7001 	}
7002 
7003 	/* Handle options. */
7004 	if (connp->conn_recvif)
7005 		in_flags = IPF_RECVIF;
7006 	/*
7007 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7008 	 * passed to ip_add_info is based on IP version of connp.
7009 	 */
7010 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7011 		if (connp->conn_af_isv6) {
7012 			/*
7013 			 * V6 only needs index
7014 			 */
7015 			in_flags |= IPF_RECVIF;
7016 		} else {
7017 			/*
7018 			 * V4 needs index + matching address.
7019 			 */
7020 			in_flags |= IPF_RECVADDR;
7021 		}
7022 	}
7023 
7024 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7025 		in_flags |= IPF_RECVSLLA;
7026 
7027 	/*
7028 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7029 	 * freed if the packet is dropped. The caller will do so.
7030 	 */
7031 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7032 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7033 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7034 		if (mp == NULL) {
7035 			return;
7036 		}
7037 	}
7038 	if ((in_flags != 0) &&
7039 	    (mp->b_datap->db_type != M_CTL)) {
7040 		/*
7041 		 * The actual data will be contained in b_cont
7042 		 * upon successful return of the following call
7043 		 * else original mblk is returned
7044 		 */
7045 		ASSERT(recv_ill != NULL);
7046 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7047 		    ipst);
7048 	}
7049 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7050 	/* Send it upstream */
7051 	(connp->conn_recv)(connp, mp, NULL);
7052 }
7053 
7054 /*
7055  * Fanout for UDP packets.
7056  * The caller puts <fport, lport> in the ports parameter.
7057  *
7058  * If SO_REUSEADDR is set all multicast and broadcast packets
7059  * will be delivered to all streams bound to the same port.
7060  *
7061  * Zones notes:
7062  * Multicast and broadcast packets will be distributed to streams in all zones.
7063  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7064  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7065  * packets. To maintain this behavior with multiple zones, the conns are grouped
7066  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7067  * each zone. If unset, all the following conns in the same zone are skipped.
7068  */
7069 static void
7070 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7071     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7072     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7073 {
7074 	uint32_t	dstport, srcport;
7075 	ipaddr_t	dst;
7076 	mblk_t		*first_mp;
7077 	boolean_t	secure;
7078 	in6_addr_t	v6src;
7079 	conn_t		*connp;
7080 	connf_t		*connfp;
7081 	conn_t		*first_connp;
7082 	conn_t		*next_connp;
7083 	mblk_t		*mp1, *first_mp1;
7084 	ipaddr_t	src;
7085 	zoneid_t	last_zoneid;
7086 	boolean_t	reuseaddr;
7087 	boolean_t	shared_addr;
7088 	boolean_t	unlabeled;
7089 	ip_stack_t	*ipst;
7090 
7091 	ASSERT(recv_ill != NULL);
7092 	ipst = recv_ill->ill_ipst;
7093 
7094 	first_mp = mp;
7095 	if (mctl_present) {
7096 		mp = first_mp->b_cont;
7097 		first_mp->b_cont = NULL;
7098 		secure = ipsec_in_is_secure(first_mp);
7099 		ASSERT(mp != NULL);
7100 	} else {
7101 		first_mp = NULL;
7102 		secure = B_FALSE;
7103 	}
7104 
7105 	/* Extract ports in net byte order */
7106 	dstport = htons(ntohl(ports) & 0xFFFF);
7107 	srcport = htons(ntohl(ports) >> 16);
7108 	dst = ipha->ipha_dst;
7109 	src = ipha->ipha_src;
7110 
7111 	unlabeled = B_FALSE;
7112 	if (is_system_labeled())
7113 		/* Cred cannot be null on IPv4 */
7114 		unlabeled = (crgetlabel(DB_CRED(mp))->tsl_flags &
7115 		    TSLF_UNLABELED) != 0;
7116 	shared_addr = (zoneid == ALL_ZONES);
7117 	if (shared_addr) {
7118 		/*
7119 		 * No need to handle exclusive-stack zones since ALL_ZONES
7120 		 * only applies to the shared stack.
7121 		 */
7122 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7123 		/*
7124 		 * If no shared MLP is found, tsol_mlp_findzone returns
7125 		 * ALL_ZONES.  In that case, we assume it's SLP, and
7126 		 * search for the zone based on the packet label.
7127 		 *
7128 		 * If there is such a zone, we prefer to find a
7129 		 * connection in it.  Otherwise, we look for a
7130 		 * MAC-exempt connection in any zone whose label
7131 		 * dominates the default label on the packet.
7132 		 */
7133 		if (zoneid == ALL_ZONES)
7134 			zoneid = tsol_packet_to_zoneid(mp);
7135 		else
7136 			unlabeled = B_FALSE;
7137 	}
7138 
7139 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7140 	mutex_enter(&connfp->connf_lock);
7141 	connp = connfp->connf_head;
7142 	if (!broadcast && !CLASSD(dst)) {
7143 		/*
7144 		 * Not broadcast or multicast. Send to the one (first)
7145 		 * client we find. No need to check conn_wantpacket()
7146 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7147 		 * IPv4 unicast packets.
7148 		 */
7149 		while ((connp != NULL) &&
7150 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7151 		    (!IPCL_ZONE_MATCH(connp, zoneid) &&
7152 		    !(unlabeled && connp->conn_mac_exempt)))) {
7153 			/*
7154 			 * We keep searching since the conn did not match,
7155 			 * or its zone did not match and it is not either
7156 			 * an allzones conn or a mac exempt conn (if the
7157 			 * sender is unlabeled.)
7158 			 */
7159 			connp = connp->conn_next;
7160 		}
7161 
7162 		if (connp == NULL || connp->conn_upq == NULL)
7163 			goto notfound;
7164 
7165 		if (is_system_labeled() &&
7166 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7167 		    connp))
7168 			goto notfound;
7169 
7170 		CONN_INC_REF(connp);
7171 		mutex_exit(&connfp->connf_lock);
7172 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7173 		    flags, recv_ill, ip_policy);
7174 		IP_STAT(ipst, ip_udp_fannorm);
7175 		CONN_DEC_REF(connp);
7176 		return;
7177 	}
7178 
7179 	/*
7180 	 * Broadcast and multicast case
7181 	 *
7182 	 * Need to check conn_wantpacket().
7183 	 * If SO_REUSEADDR has been set on the first we send the
7184 	 * packet to all clients that have joined the group and
7185 	 * match the port.
7186 	 */
7187 
7188 	while (connp != NULL) {
7189 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7190 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7191 		    (!is_system_labeled() ||
7192 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7193 		    connp)))
7194 			break;
7195 		connp = connp->conn_next;
7196 	}
7197 
7198 	if (connp == NULL || connp->conn_upq == NULL)
7199 		goto notfound;
7200 
7201 	first_connp = connp;
7202 	/*
7203 	 * When SO_REUSEADDR is not set, send the packet only to the first
7204 	 * matching connection in its zone by keeping track of the zoneid.
7205 	 */
7206 	reuseaddr = first_connp->conn_reuseaddr;
7207 	last_zoneid = first_connp->conn_zoneid;
7208 
7209 	CONN_INC_REF(connp);
7210 	connp = connp->conn_next;
7211 	for (;;) {
7212 		while (connp != NULL) {
7213 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7214 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7215 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7216 			    (!is_system_labeled() ||
7217 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7218 			    shared_addr, connp)))
7219 				break;
7220 			connp = connp->conn_next;
7221 		}
7222 		/*
7223 		 * Just copy the data part alone. The mctl part is
7224 		 * needed just for verifying policy and it is never
7225 		 * sent up.
7226 		 */
7227 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7228 		    ((mp1 = copymsg(mp)) == NULL))) {
7229 			/*
7230 			 * No more interested clients or memory
7231 			 * allocation failed
7232 			 */
7233 			connp = first_connp;
7234 			break;
7235 		}
7236 		if (connp->conn_zoneid != last_zoneid) {
7237 			/*
7238 			 * Update the zoneid so that the packet isn't sent to
7239 			 * any more conns in the same zone unless SO_REUSEADDR
7240 			 * is set.
7241 			 */
7242 			reuseaddr = connp->conn_reuseaddr;
7243 			last_zoneid = connp->conn_zoneid;
7244 		}
7245 		if (first_mp != NULL) {
7246 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7247 			    ipsec_info_type == IPSEC_IN);
7248 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7249 			    ipst->ips_netstack);
7250 			if (first_mp1 == NULL) {
7251 				freemsg(mp1);
7252 				connp = first_connp;
7253 				break;
7254 			}
7255 		} else {
7256 			first_mp1 = NULL;
7257 		}
7258 		CONN_INC_REF(connp);
7259 		mutex_exit(&connfp->connf_lock);
7260 		/*
7261 		 * IPQoS notes: We don't send the packet for policy
7262 		 * processing here, will do it for the last one (below).
7263 		 * i.e. we do it per-packet now, but if we do policy
7264 		 * processing per-conn, then we would need to do it
7265 		 * here too.
7266 		 */
7267 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7268 		    ipha, flags, recv_ill, B_FALSE);
7269 		mutex_enter(&connfp->connf_lock);
7270 		/* Follow the next pointer before releasing the conn. */
7271 		next_connp = connp->conn_next;
7272 		IP_STAT(ipst, ip_udp_fanmb);
7273 		CONN_DEC_REF(connp);
7274 		connp = next_connp;
7275 	}
7276 
7277 	/* Last one.  Send it upstream. */
7278 	mutex_exit(&connfp->connf_lock);
7279 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7280 	    recv_ill, ip_policy);
7281 	IP_STAT(ipst, ip_udp_fanmb);
7282 	CONN_DEC_REF(connp);
7283 	return;
7284 
7285 notfound:
7286 
7287 	mutex_exit(&connfp->connf_lock);
7288 	IP_STAT(ipst, ip_udp_fanothers);
7289 	/*
7290 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7291 	 * have already been matched above, since they live in the IPv4
7292 	 * fanout tables. This implies we only need to
7293 	 * check for IPv6 in6addr_any endpoints here.
7294 	 * Thus we compare using ipv6_all_zeros instead of the destination
7295 	 * address, except for the multicast group membership lookup which
7296 	 * uses the IPv4 destination.
7297 	 */
7298 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7299 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7300 	mutex_enter(&connfp->connf_lock);
7301 	connp = connfp->connf_head;
7302 	if (!broadcast && !CLASSD(dst)) {
7303 		while (connp != NULL) {
7304 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7305 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7306 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7307 			    !connp->conn_ipv6_v6only)
7308 				break;
7309 			connp = connp->conn_next;
7310 		}
7311 
7312 		if (connp != NULL && is_system_labeled() &&
7313 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7314 		    connp))
7315 			connp = NULL;
7316 
7317 		if (connp == NULL || connp->conn_upq == NULL) {
7318 			/*
7319 			 * No one bound to this port.  Is
7320 			 * there a client that wants all
7321 			 * unclaimed datagrams?
7322 			 */
7323 			mutex_exit(&connfp->connf_lock);
7324 
7325 			if (mctl_present)
7326 				first_mp->b_cont = mp;
7327 			else
7328 				first_mp = mp;
7329 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7330 			    connf_head != NULL) {
7331 				ip_fanout_proto(q, first_mp, ill, ipha,
7332 				    flags | IP_FF_RAWIP, mctl_present,
7333 				    ip_policy, recv_ill, zoneid);
7334 			} else {
7335 				if (ip_fanout_send_icmp(q, first_mp, flags,
7336 				    ICMP_DEST_UNREACHABLE,
7337 				    ICMP_PORT_UNREACHABLE,
7338 				    mctl_present, zoneid, ipst)) {
7339 					BUMP_MIB(ill->ill_ip_mib,
7340 					    udpIfStatsNoPorts);
7341 				}
7342 			}
7343 			return;
7344 		}
7345 
7346 		CONN_INC_REF(connp);
7347 		mutex_exit(&connfp->connf_lock);
7348 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7349 		    flags, recv_ill, ip_policy);
7350 		CONN_DEC_REF(connp);
7351 		return;
7352 	}
7353 	/*
7354 	 * IPv4 multicast packet being delivered to an AF_INET6
7355 	 * in6addr_any endpoint.
7356 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7357 	 * and not conn_wantpacket_v6() since any multicast membership is
7358 	 * for an IPv4-mapped multicast address.
7359 	 * The packet is sent to all clients in all zones that have joined the
7360 	 * group and match the port.
7361 	 */
7362 	while (connp != NULL) {
7363 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7364 		    srcport, v6src) &&
7365 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7366 		    (!is_system_labeled() ||
7367 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7368 		    connp)))
7369 			break;
7370 		connp = connp->conn_next;
7371 	}
7372 
7373 	if (connp == NULL || connp->conn_upq == NULL) {
7374 		/*
7375 		 * No one bound to this port.  Is
7376 		 * there a client that wants all
7377 		 * unclaimed datagrams?
7378 		 */
7379 		mutex_exit(&connfp->connf_lock);
7380 
7381 		if (mctl_present)
7382 			first_mp->b_cont = mp;
7383 		else
7384 			first_mp = mp;
7385 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7386 		    NULL) {
7387 			ip_fanout_proto(q, first_mp, ill, ipha,
7388 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7389 			    recv_ill, zoneid);
7390 		} else {
7391 			/*
7392 			 * We used to attempt to send an icmp error here, but
7393 			 * since this is known to be a multicast packet
7394 			 * and we don't send icmp errors in response to
7395 			 * multicast, just drop the packet and give up sooner.
7396 			 */
7397 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7398 			freemsg(first_mp);
7399 		}
7400 		return;
7401 	}
7402 
7403 	first_connp = connp;
7404 
7405 	CONN_INC_REF(connp);
7406 	connp = connp->conn_next;
7407 	for (;;) {
7408 		while (connp != NULL) {
7409 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7410 			    ipv6_all_zeros, srcport, v6src) &&
7411 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7412 			    (!is_system_labeled() ||
7413 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7414 			    shared_addr, connp)))
7415 				break;
7416 			connp = connp->conn_next;
7417 		}
7418 		/*
7419 		 * Just copy the data part alone. The mctl part is
7420 		 * needed just for verifying policy and it is never
7421 		 * sent up.
7422 		 */
7423 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7424 		    ((mp1 = copymsg(mp)) == NULL))) {
7425 			/*
7426 			 * No more intested clients or memory
7427 			 * allocation failed
7428 			 */
7429 			connp = first_connp;
7430 			break;
7431 		}
7432 		if (first_mp != NULL) {
7433 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7434 			    ipsec_info_type == IPSEC_IN);
7435 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7436 			    ipst->ips_netstack);
7437 			if (first_mp1 == NULL) {
7438 				freemsg(mp1);
7439 				connp = first_connp;
7440 				break;
7441 			}
7442 		} else {
7443 			first_mp1 = NULL;
7444 		}
7445 		CONN_INC_REF(connp);
7446 		mutex_exit(&connfp->connf_lock);
7447 		/*
7448 		 * IPQoS notes: We don't send the packet for policy
7449 		 * processing here, will do it for the last one (below).
7450 		 * i.e. we do it per-packet now, but if we do policy
7451 		 * processing per-conn, then we would need to do it
7452 		 * here too.
7453 		 */
7454 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7455 		    ipha, flags, recv_ill, B_FALSE);
7456 		mutex_enter(&connfp->connf_lock);
7457 		/* Follow the next pointer before releasing the conn. */
7458 		next_connp = connp->conn_next;
7459 		CONN_DEC_REF(connp);
7460 		connp = next_connp;
7461 	}
7462 
7463 	/* Last one.  Send it upstream. */
7464 	mutex_exit(&connfp->connf_lock);
7465 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7466 	    recv_ill, ip_policy);
7467 	CONN_DEC_REF(connp);
7468 }
7469 
7470 /*
7471  * Complete the ip_wput header so that it
7472  * is possible to generate ICMP
7473  * errors.
7474  */
7475 int
7476 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7477 {
7478 	ire_t *ire;
7479 
7480 	if (ipha->ipha_src == INADDR_ANY) {
7481 		ire = ire_lookup_local(zoneid, ipst);
7482 		if (ire == NULL) {
7483 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7484 			return (1);
7485 		}
7486 		ipha->ipha_src = ire->ire_addr;
7487 		ire_refrele(ire);
7488 	}
7489 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7490 	ipha->ipha_hdr_checksum = 0;
7491 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7492 	return (0);
7493 }
7494 
7495 /*
7496  * Nobody should be sending
7497  * packets up this stream
7498  */
7499 static void
7500 ip_lrput(queue_t *q, mblk_t *mp)
7501 {
7502 	mblk_t *mp1;
7503 
7504 	switch (mp->b_datap->db_type) {
7505 	case M_FLUSH:
7506 		/* Turn around */
7507 		if (*mp->b_rptr & FLUSHW) {
7508 			*mp->b_rptr &= ~FLUSHR;
7509 			qreply(q, mp);
7510 			return;
7511 		}
7512 		break;
7513 	}
7514 	/* Could receive messages that passed through ar_rput */
7515 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7516 		mp1->b_prev = mp1->b_next = NULL;
7517 	freemsg(mp);
7518 }
7519 
7520 /* Nobody should be sending packets down this stream */
7521 /* ARGSUSED */
7522 void
7523 ip_lwput(queue_t *q, mblk_t *mp)
7524 {
7525 	freemsg(mp);
7526 }
7527 
7528 /*
7529  * Move the first hop in any source route to ipha_dst and remove that part of
7530  * the source route.  Called by other protocols.  Errors in option formatting
7531  * are ignored - will be handled by ip_wput_options Return the final
7532  * destination (either ipha_dst or the last entry in a source route.)
7533  */
7534 ipaddr_t
7535 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7536 {
7537 	ipoptp_t	opts;
7538 	uchar_t		*opt;
7539 	uint8_t		optval;
7540 	uint8_t		optlen;
7541 	ipaddr_t	dst;
7542 	int		i;
7543 	ire_t		*ire;
7544 	ip_stack_t	*ipst = ns->netstack_ip;
7545 
7546 	ip2dbg(("ip_massage_options\n"));
7547 	dst = ipha->ipha_dst;
7548 	for (optval = ipoptp_first(&opts, ipha);
7549 	    optval != IPOPT_EOL;
7550 	    optval = ipoptp_next(&opts)) {
7551 		opt = opts.ipoptp_cur;
7552 		switch (optval) {
7553 			uint8_t off;
7554 		case IPOPT_SSRR:
7555 		case IPOPT_LSRR:
7556 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7557 				ip1dbg(("ip_massage_options: bad src route\n"));
7558 				break;
7559 			}
7560 			optlen = opts.ipoptp_len;
7561 			off = opt[IPOPT_OFFSET];
7562 			off--;
7563 		redo_srr:
7564 			if (optlen < IP_ADDR_LEN ||
7565 			    off > optlen - IP_ADDR_LEN) {
7566 				/* End of source route */
7567 				ip1dbg(("ip_massage_options: end of SR\n"));
7568 				break;
7569 			}
7570 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7571 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7572 			    ntohl(dst)));
7573 			/*
7574 			 * Check if our address is present more than
7575 			 * once as consecutive hops in source route.
7576 			 * XXX verify per-interface ip_forwarding
7577 			 * for source route?
7578 			 */
7579 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7580 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7581 			if (ire != NULL) {
7582 				ire_refrele(ire);
7583 				off += IP_ADDR_LEN;
7584 				goto redo_srr;
7585 			}
7586 			if (dst == htonl(INADDR_LOOPBACK)) {
7587 				ip1dbg(("ip_massage_options: loopback addr in "
7588 				    "source route!\n"));
7589 				break;
7590 			}
7591 			/*
7592 			 * Update ipha_dst to be the first hop and remove the
7593 			 * first hop from the source route (by overwriting
7594 			 * part of the option with NOP options).
7595 			 */
7596 			ipha->ipha_dst = dst;
7597 			/* Put the last entry in dst */
7598 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7599 			    3;
7600 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7601 
7602 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7603 			    ntohl(dst)));
7604 			/* Move down and overwrite */
7605 			opt[IP_ADDR_LEN] = opt[0];
7606 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7607 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7608 			for (i = 0; i < IP_ADDR_LEN; i++)
7609 				opt[i] = IPOPT_NOP;
7610 			break;
7611 		}
7612 	}
7613 	return (dst);
7614 }
7615 
7616 /*
7617  * Return the network mask
7618  * associated with the specified address.
7619  */
7620 ipaddr_t
7621 ip_net_mask(ipaddr_t addr)
7622 {
7623 	uchar_t	*up = (uchar_t *)&addr;
7624 	ipaddr_t mask = 0;
7625 	uchar_t	*maskp = (uchar_t *)&mask;
7626 
7627 #if defined(__i386) || defined(__amd64)
7628 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7629 #endif
7630 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7631 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7632 #endif
7633 	if (CLASSD(addr)) {
7634 		maskp[0] = 0xF0;
7635 		return (mask);
7636 	}
7637 
7638 	/* We assume Class E default netmask to be 32 */
7639 	if (CLASSE(addr))
7640 		return (0xffffffffU);
7641 
7642 	if (addr == 0)
7643 		return (0);
7644 	maskp[0] = 0xFF;
7645 	if ((up[0] & 0x80) == 0)
7646 		return (mask);
7647 
7648 	maskp[1] = 0xFF;
7649 	if ((up[0] & 0xC0) == 0x80)
7650 		return (mask);
7651 
7652 	maskp[2] = 0xFF;
7653 	if ((up[0] & 0xE0) == 0xC0)
7654 		return (mask);
7655 
7656 	/* Otherwise return no mask */
7657 	return ((ipaddr_t)0);
7658 }
7659 
7660 /*
7661  * Select an ill for the packet by considering load spreading across
7662  * a different ill in the group if dst_ill is part of some group.
7663  */
7664 ill_t *
7665 ip_newroute_get_dst_ill(ill_t *dst_ill)
7666 {
7667 	ill_t *ill;
7668 
7669 	/*
7670 	 * We schedule irrespective of whether the source address is
7671 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7672 	 */
7673 	ill = illgrp_scheduler(dst_ill);
7674 	if (ill == NULL)
7675 		return (NULL);
7676 
7677 	/*
7678 	 * For groups with names ip_sioctl_groupname ensures that all
7679 	 * ills are of same type. For groups without names, ifgrp_insert
7680 	 * ensures this.
7681 	 */
7682 	ASSERT(dst_ill->ill_type == ill->ill_type);
7683 
7684 	return (ill);
7685 }
7686 
7687 /*
7688  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7689  */
7690 ill_t *
7691 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6,
7692     ip_stack_t *ipst)
7693 {
7694 	ill_t *ret_ill;
7695 
7696 	ASSERT(ifindex != 0);
7697 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7698 	    ipst);
7699 	if (ret_ill == NULL ||
7700 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7701 		if (isv6) {
7702 			if (ill != NULL) {
7703 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7704 			} else {
7705 				BUMP_MIB(&ipst->ips_ip6_mib,
7706 				    ipIfStatsOutDiscards);
7707 			}
7708 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7709 			    "bad ifindex %d.\n", ifindex));
7710 		} else {
7711 			if (ill != NULL) {
7712 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7713 			} else {
7714 				BUMP_MIB(&ipst->ips_ip_mib,
7715 				    ipIfStatsOutDiscards);
7716 			}
7717 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7718 			    "bad ifindex %d.\n", ifindex));
7719 		}
7720 		if (ret_ill != NULL)
7721 			ill_refrele(ret_ill);
7722 		freemsg(first_mp);
7723 		return (NULL);
7724 	}
7725 
7726 	return (ret_ill);
7727 }
7728 
7729 /*
7730  * IPv4 -
7731  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7732  * out a packet to a destination address for which we do not have specific
7733  * (or sufficient) routing information.
7734  *
7735  * NOTE : These are the scopes of some of the variables that point at IRE,
7736  *	  which needs to be followed while making any future modifications
7737  *	  to avoid memory leaks.
7738  *
7739  *	- ire and sire are the entries looked up initially by
7740  *	  ire_ftable_lookup.
7741  *	- ipif_ire is used to hold the interface ire associated with
7742  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7743  *	  it before branching out to error paths.
7744  *	- save_ire is initialized before ire_create, so that ire returned
7745  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7746  *	  before breaking out of the switch.
7747  *
7748  *	Thus on failures, we have to REFRELE only ire and sire, if they
7749  *	are not NULL.
7750  */
7751 void
7752 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7753     zoneid_t zoneid, ip_stack_t *ipst)
7754 {
7755 	areq_t	*areq;
7756 	ipaddr_t gw = 0;
7757 	ire_t	*ire = NULL;
7758 	mblk_t	*res_mp;
7759 	ipaddr_t *addrp;
7760 	ipaddr_t nexthop_addr;
7761 	ipif_t  *src_ipif = NULL;
7762 	ill_t	*dst_ill = NULL;
7763 	ipha_t  *ipha;
7764 	ire_t	*sire = NULL;
7765 	mblk_t	*first_mp;
7766 	ire_t	*save_ire;
7767 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7768 	ushort_t ire_marks = 0;
7769 	boolean_t mctl_present;
7770 	ipsec_out_t *io;
7771 	mblk_t	*saved_mp;
7772 	ire_t	*first_sire = NULL;
7773 	mblk_t	*copy_mp = NULL;
7774 	mblk_t	*xmit_mp = NULL;
7775 	ipaddr_t save_dst;
7776 	uint32_t multirt_flags =
7777 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7778 	boolean_t multirt_is_resolvable;
7779 	boolean_t multirt_resolve_next;
7780 	boolean_t unspec_src;
7781 	boolean_t do_attach_ill = B_FALSE;
7782 	boolean_t ip_nexthop = B_FALSE;
7783 	tsol_ire_gw_secattr_t *attrp = NULL;
7784 	tsol_gcgrp_t *gcgrp = NULL;
7785 	tsol_gcgrp_addr_t ga;
7786 
7787 	if (ip_debug > 2) {
7788 		/* ip1dbg */
7789 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7790 	}
7791 
7792 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7793 	if (mctl_present) {
7794 		io = (ipsec_out_t *)first_mp->b_rptr;
7795 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7796 		ASSERT(zoneid == io->ipsec_out_zoneid);
7797 		ASSERT(zoneid != ALL_ZONES);
7798 	}
7799 
7800 	ipha = (ipha_t *)mp->b_rptr;
7801 
7802 	/* All multicast lookups come through ip_newroute_ipif() */
7803 	if (CLASSD(dst)) {
7804 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7805 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7806 		freemsg(first_mp);
7807 		return;
7808 	}
7809 
7810 	if (mctl_present && io->ipsec_out_attach_if) {
7811 		/* ip_grab_attach_ill returns a held ill */
7812 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7813 		    io->ipsec_out_ill_index, B_FALSE, ipst);
7814 
7815 		/* Failure case frees things for us. */
7816 		if (attach_ill == NULL)
7817 			return;
7818 
7819 		/*
7820 		 * Check if we need an ire that will not be
7821 		 * looked up by anybody else i.e. HIDDEN.
7822 		 */
7823 		if (ill_is_probeonly(attach_ill))
7824 			ire_marks = IRE_MARK_HIDDEN;
7825 	}
7826 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7827 		ip_nexthop = B_TRUE;
7828 		nexthop_addr = io->ipsec_out_nexthop_addr;
7829 	}
7830 	/*
7831 	 * If this IRE is created for forwarding or it is not for
7832 	 * traffic for congestion controlled protocols, mark it as temporary.
7833 	 */
7834 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7835 		ire_marks |= IRE_MARK_TEMPORARY;
7836 
7837 	/*
7838 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7839 	 * chain until it gets the most specific information available.
7840 	 * For example, we know that there is no IRE_CACHE for this dest,
7841 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7842 	 * ire_ftable_lookup will look up the gateway, etc.
7843 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7844 	 * to the destination, of equal netmask length in the forward table,
7845 	 * will be recursively explored. If no information is available
7846 	 * for the final gateway of that route, we force the returned ire
7847 	 * to be equal to sire using MATCH_IRE_PARENT.
7848 	 * At least, in this case we have a starting point (in the buckets)
7849 	 * to look for other routes to the destination in the forward table.
7850 	 * This is actually used only for multirouting, where a list
7851 	 * of routes has to be processed in sequence.
7852 	 *
7853 	 * In the process of coming up with the most specific information,
7854 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7855 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7856 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7857 	 * Two caveats when handling incomplete ire's in ip_newroute:
7858 	 * - we should be careful when accessing its ire_nce (specifically
7859 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7860 	 * - not all legacy code path callers are prepared to handle
7861 	 *   incomplete ire's, so we should not create/add incomplete
7862 	 *   ire_cache entries here. (See discussion about temporary solution
7863 	 *   further below).
7864 	 *
7865 	 * In order to minimize packet dropping, and to preserve existing
7866 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7867 	 * gateway, and instead use the IF_RESOLVER ire to send out
7868 	 * another request to ARP (this is achieved by passing the
7869 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7870 	 * arp response comes back in ip_wput_nondata, we will create
7871 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7872 	 *
7873 	 * Note that this is a temporary solution; the correct solution is
7874 	 * to create an incomplete  per-dst ire_cache entry, and send the
7875 	 * packet out when the gw's nce is resolved. In order to achieve this,
7876 	 * all packet processing must have been completed prior to calling
7877 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7878 	 * to be modified to accomodate this solution.
7879 	 */
7880 	if (ip_nexthop) {
7881 		/*
7882 		 * The first time we come here, we look for an IRE_INTERFACE
7883 		 * entry for the specified nexthop, set the dst to be the
7884 		 * nexthop address and create an IRE_CACHE entry for the
7885 		 * nexthop. The next time around, we are able to find an
7886 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7887 		 * nexthop address and create an IRE_CACHE entry for the
7888 		 * destination address via the specified nexthop.
7889 		 */
7890 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7891 		    MBLK_GETLABEL(mp), ipst);
7892 		if (ire != NULL) {
7893 			gw = nexthop_addr;
7894 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7895 		} else {
7896 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7897 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7898 			    MBLK_GETLABEL(mp),
7899 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
7900 			    ipst);
7901 			if (ire != NULL) {
7902 				dst = nexthop_addr;
7903 			}
7904 		}
7905 	} else if (attach_ill == NULL) {
7906 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7907 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
7908 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7909 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7910 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
7911 		    ipst);
7912 	} else {
7913 		/*
7914 		 * attach_ill is set only for communicating with
7915 		 * on-link hosts. So, don't look for DEFAULT.
7916 		 */
7917 		ipif_t	*attach_ipif;
7918 
7919 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
7920 		if (attach_ipif == NULL) {
7921 			ill_refrele(attach_ill);
7922 			goto icmp_err_ret;
7923 		}
7924 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
7925 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
7926 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
7927 		    MATCH_IRE_SECATTR, ipst);
7928 		ipif_refrele(attach_ipif);
7929 	}
7930 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7931 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7932 
7933 	/*
7934 	 * This loop is run only once in most cases.
7935 	 * We loop to resolve further routes only when the destination
7936 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7937 	 */
7938 	do {
7939 		/* Clear the previous iteration's values */
7940 		if (src_ipif != NULL) {
7941 			ipif_refrele(src_ipif);
7942 			src_ipif = NULL;
7943 		}
7944 		if (dst_ill != NULL) {
7945 			ill_refrele(dst_ill);
7946 			dst_ill = NULL;
7947 		}
7948 
7949 		multirt_resolve_next = B_FALSE;
7950 		/*
7951 		 * We check if packets have to be multirouted.
7952 		 * In this case, given the current <ire, sire> couple,
7953 		 * we look for the next suitable <ire, sire>.
7954 		 * This check is done in ire_multirt_lookup(),
7955 		 * which applies various criteria to find the next route
7956 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7957 		 * unchanged if it detects it has not been tried yet.
7958 		 */
7959 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7960 			ip3dbg(("ip_newroute: starting next_resolution "
7961 			    "with first_mp %p, tag %d\n",
7962 			    (void *)first_mp,
7963 			    MULTIRT_DEBUG_TAGGED(first_mp)));
7964 
7965 			ASSERT(sire != NULL);
7966 			multirt_is_resolvable =
7967 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
7968 			    MBLK_GETLABEL(mp), ipst);
7969 
7970 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
7971 			    "ire %p, sire %p\n",
7972 			    multirt_is_resolvable,
7973 			    (void *)ire, (void *)sire));
7974 
7975 			if (!multirt_is_resolvable) {
7976 				/*
7977 				 * No more multirt route to resolve; give up
7978 				 * (all routes resolved or no more
7979 				 * resolvable routes).
7980 				 */
7981 				if (ire != NULL) {
7982 					ire_refrele(ire);
7983 					ire = NULL;
7984 				}
7985 			} else {
7986 				ASSERT(sire != NULL);
7987 				ASSERT(ire != NULL);
7988 				/*
7989 				 * We simply use first_sire as a flag that
7990 				 * indicates if a resolvable multirt route
7991 				 * has already been found.
7992 				 * If it is not the case, we may have to send
7993 				 * an ICMP error to report that the
7994 				 * destination is unreachable.
7995 				 * We do not IRE_REFHOLD first_sire.
7996 				 */
7997 				if (first_sire == NULL) {
7998 					first_sire = sire;
7999 				}
8000 			}
8001 		}
8002 		if (ire == NULL) {
8003 			if (ip_debug > 3) {
8004 				/* ip2dbg */
8005 				pr_addr_dbg("ip_newroute: "
8006 				    "can't resolve %s\n", AF_INET, &dst);
8007 			}
8008 			ip3dbg(("ip_newroute: "
8009 			    "ire %p, sire %p, first_sire %p\n",
8010 			    (void *)ire, (void *)sire, (void *)first_sire));
8011 
8012 			if (sire != NULL) {
8013 				ire_refrele(sire);
8014 				sire = NULL;
8015 			}
8016 
8017 			if (first_sire != NULL) {
8018 				/*
8019 				 * At least one multirt route has been found
8020 				 * in the same call to ip_newroute();
8021 				 * there is no need to report an ICMP error.
8022 				 * first_sire was not IRE_REFHOLDed.
8023 				 */
8024 				MULTIRT_DEBUG_UNTAG(first_mp);
8025 				freemsg(first_mp);
8026 				return;
8027 			}
8028 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8029 			    RTA_DST, ipst);
8030 			if (attach_ill != NULL)
8031 				ill_refrele(attach_ill);
8032 			goto icmp_err_ret;
8033 		}
8034 
8035 		/*
8036 		 * Verify that the returned IRE does not have either
8037 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8038 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8039 		 */
8040 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8041 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8042 			if (attach_ill != NULL)
8043 				ill_refrele(attach_ill);
8044 			goto icmp_err_ret;
8045 		}
8046 		/*
8047 		 * Increment the ire_ob_pkt_count field for ire if it is an
8048 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8049 		 * increment the same for the parent IRE, sire, if it is some
8050 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8051 		 */
8052 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8053 			UPDATE_OB_PKT_COUNT(ire);
8054 			ire->ire_last_used_time = lbolt;
8055 		}
8056 
8057 		if (sire != NULL) {
8058 			gw = sire->ire_gateway_addr;
8059 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8060 			    IRE_INTERFACE)) == 0);
8061 			UPDATE_OB_PKT_COUNT(sire);
8062 			sire->ire_last_used_time = lbolt;
8063 		}
8064 		/*
8065 		 * We have a route to reach the destination.
8066 		 *
8067 		 * 1) If the interface is part of ill group, try to get a new
8068 		 *    ill taking load spreading into account.
8069 		 *
8070 		 * 2) After selecting the ill, get a source address that
8071 		 *    might create good inbound load spreading.
8072 		 *    ipif_select_source does this for us.
8073 		 *
8074 		 * If the application specified the ill (ifindex), we still
8075 		 * load spread. Only if the packets needs to go out
8076 		 * specifically on a given ill e.g. binding to
8077 		 * IPIF_NOFAILOVER address, then we don't try to use a
8078 		 * different ill for load spreading.
8079 		 */
8080 		if (attach_ill == NULL) {
8081 			/*
8082 			 * Don't perform outbound load spreading in the
8083 			 * case of an RTF_MULTIRT route, as we actually
8084 			 * typically want to replicate outgoing packets
8085 			 * through particular interfaces.
8086 			 */
8087 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8088 				dst_ill = ire->ire_ipif->ipif_ill;
8089 				/* for uniformity */
8090 				ill_refhold(dst_ill);
8091 			} else {
8092 				/*
8093 				 * If we are here trying to create an IRE_CACHE
8094 				 * for an offlink destination and have the
8095 				 * IRE_CACHE for the next hop and the latter is
8096 				 * using virtual IP source address selection i.e
8097 				 * it's ire->ire_ipif is pointing to a virtual
8098 				 * network interface (vni) then
8099 				 * ip_newroute_get_dst_ll() will return the vni
8100 				 * interface as the dst_ill. Since the vni is
8101 				 * virtual i.e not associated with any physical
8102 				 * interface, it cannot be the dst_ill, hence
8103 				 * in such a case call ip_newroute_get_dst_ll()
8104 				 * with the stq_ill instead of the ire_ipif ILL.
8105 				 * The function returns a refheld ill.
8106 				 */
8107 				if ((ire->ire_type == IRE_CACHE) &&
8108 				    IS_VNI(ire->ire_ipif->ipif_ill))
8109 					dst_ill = ip_newroute_get_dst_ill(
8110 					    ire->ire_stq->q_ptr);
8111 				else
8112 					dst_ill = ip_newroute_get_dst_ill(
8113 					    ire->ire_ipif->ipif_ill);
8114 			}
8115 			if (dst_ill == NULL) {
8116 				if (ip_debug > 2) {
8117 					pr_addr_dbg("ip_newroute: "
8118 					    "no dst ill for dst"
8119 					    " %s\n", AF_INET, &dst);
8120 				}
8121 				goto icmp_err_ret;
8122 			}
8123 		} else {
8124 			dst_ill = ire->ire_ipif->ipif_ill;
8125 			/* for uniformity */
8126 			ill_refhold(dst_ill);
8127 			/*
8128 			 * We should have found a route matching ill as we
8129 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
8130 			 * Rather than asserting, when there is a mismatch,
8131 			 * we just drop the packet.
8132 			 */
8133 			if (dst_ill != attach_ill) {
8134 				ip0dbg(("ip_newroute: Packet dropped as "
8135 				    "IPIF_NOFAILOVER ill is %s, "
8136 				    "ire->ire_ipif->ipif_ill is %s\n",
8137 				    attach_ill->ill_name,
8138 				    dst_ill->ill_name));
8139 				ill_refrele(attach_ill);
8140 				goto icmp_err_ret;
8141 			}
8142 		}
8143 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
8144 		if (attach_ill != NULL) {
8145 			ill_refrele(attach_ill);
8146 			attach_ill = NULL;
8147 			do_attach_ill = B_TRUE;
8148 		}
8149 		ASSERT(dst_ill != NULL);
8150 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8151 
8152 		/*
8153 		 * Pick the best source address from dst_ill.
8154 		 *
8155 		 * 1) If it is part of a multipathing group, we would
8156 		 *    like to spread the inbound packets across different
8157 		 *    interfaces. ipif_select_source picks a random source
8158 		 *    across the different ills in the group.
8159 		 *
8160 		 * 2) If it is not part of a multipathing group, we try
8161 		 *    to pick the source address from the destination
8162 		 *    route. Clustering assumes that when we have multiple
8163 		 *    prefixes hosted on an interface, the prefix of the
8164 		 *    source address matches the prefix of the destination
8165 		 *    route. We do this only if the address is not
8166 		 *    DEPRECATED.
8167 		 *
8168 		 * 3) If the conn is in a different zone than the ire, we
8169 		 *    need to pick a source address from the right zone.
8170 		 *
8171 		 * NOTE : If we hit case (1) above, the prefix of the source
8172 		 *	  address picked may not match the prefix of the
8173 		 *	  destination routes prefix as ipif_select_source
8174 		 *	  does not look at "dst" while picking a source
8175 		 *	  address.
8176 		 *	  If we want the same behavior as (2), we will need
8177 		 *	  to change the behavior of ipif_select_source.
8178 		 */
8179 		ASSERT(src_ipif == NULL);
8180 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8181 			/*
8182 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8183 			 * Check that the ipif matching the requested source
8184 			 * address still exists.
8185 			 */
8186 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8187 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8188 		}
8189 
8190 		unspec_src = (connp != NULL && connp->conn_unspec_src);
8191 
8192 		if (src_ipif == NULL &&
8193 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
8194 			ire_marks |= IRE_MARK_USESRC_CHECK;
8195 			if ((dst_ill->ill_group != NULL) ||
8196 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8197 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8198 			    ire->ire_zoneid != ALL_ZONES) ||
8199 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8200 				/*
8201 				 * If the destination is reachable via a
8202 				 * given gateway, the selected source address
8203 				 * should be in the same subnet as the gateway.
8204 				 * Otherwise, the destination is not reachable.
8205 				 *
8206 				 * If there are no interfaces on the same subnet
8207 				 * as the destination, ipif_select_source gives
8208 				 * first non-deprecated interface which might be
8209 				 * on a different subnet than the gateway.
8210 				 * This is not desirable. Hence pass the dst_ire
8211 				 * source address to ipif_select_source.
8212 				 * It is sure that the destination is reachable
8213 				 * with the dst_ire source address subnet.
8214 				 * So passing dst_ire source address to
8215 				 * ipif_select_source will make sure that the
8216 				 * selected source will be on the same subnet
8217 				 * as dst_ire source address.
8218 				 */
8219 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8220 				src_ipif = ipif_select_source(dst_ill, saddr,
8221 				    zoneid);
8222 				if (src_ipif == NULL) {
8223 					if (ip_debug > 2) {
8224 						pr_addr_dbg("ip_newroute: "
8225 						    "no src for dst %s ",
8226 						    AF_INET, &dst);
8227 						printf("through interface %s\n",
8228 						    dst_ill->ill_name);
8229 					}
8230 					goto icmp_err_ret;
8231 				}
8232 			} else {
8233 				src_ipif = ire->ire_ipif;
8234 				ASSERT(src_ipif != NULL);
8235 				/* hold src_ipif for uniformity */
8236 				ipif_refhold(src_ipif);
8237 			}
8238 		}
8239 
8240 		/*
8241 		 * Assign a source address while we have the conn.
8242 		 * We can't have ip_wput_ire pick a source address when the
8243 		 * packet returns from arp since we need to look at
8244 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8245 		 * going through arp.
8246 		 *
8247 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8248 		 *	  it uses ip6i to store this information.
8249 		 */
8250 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
8251 			ipha->ipha_src = src_ipif->ipif_src_addr;
8252 
8253 		if (ip_debug > 3) {
8254 			/* ip2dbg */
8255 			pr_addr_dbg("ip_newroute: first hop %s\n",
8256 			    AF_INET, &gw);
8257 		}
8258 		ip2dbg(("\tire type %s (%d)\n",
8259 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8260 
8261 		/*
8262 		 * The TTL of multirouted packets is bounded by the
8263 		 * ip_multirt_ttl ndd variable.
8264 		 */
8265 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8266 			/* Force TTL of multirouted packets */
8267 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8268 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8269 				ip2dbg(("ip_newroute: forcing multirt TTL "
8270 				    "to %d (was %d), dst 0x%08x\n",
8271 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8272 				    ntohl(sire->ire_addr)));
8273 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8274 			}
8275 		}
8276 		/*
8277 		 * At this point in ip_newroute(), ire is either the
8278 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8279 		 * destination or an IRE_INTERFACE type that should be used
8280 		 * to resolve an on-subnet destination or an on-subnet
8281 		 * next-hop gateway.
8282 		 *
8283 		 * In the IRE_CACHE case, we have the following :
8284 		 *
8285 		 * 1) src_ipif - used for getting a source address.
8286 		 *
8287 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8288 		 *    means packets using this IRE_CACHE will go out on
8289 		 *    dst_ill.
8290 		 *
8291 		 * 3) The IRE sire will point to the prefix that is the
8292 		 *    longest  matching route for the destination. These
8293 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8294 		 *
8295 		 *    The newly created IRE_CACHE entry for the off-subnet
8296 		 *    destination is tied to both the prefix route and the
8297 		 *    interface route used to resolve the next-hop gateway
8298 		 *    via the ire_phandle and ire_ihandle fields,
8299 		 *    respectively.
8300 		 *
8301 		 * In the IRE_INTERFACE case, we have the following :
8302 		 *
8303 		 * 1) src_ipif - used for getting a source address.
8304 		 *
8305 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8306 		 *    means packets using the IRE_CACHE that we will build
8307 		 *    here will go out on dst_ill.
8308 		 *
8309 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8310 		 *    to be created will only be tied to the IRE_INTERFACE
8311 		 *    that was derived from the ire_ihandle field.
8312 		 *
8313 		 *    If sire is non-NULL, it means the destination is
8314 		 *    off-link and we will first create the IRE_CACHE for the
8315 		 *    gateway. Next time through ip_newroute, we will create
8316 		 *    the IRE_CACHE for the final destination as described
8317 		 *    above.
8318 		 *
8319 		 * In both cases, after the current resolution has been
8320 		 * completed (or possibly initialised, in the IRE_INTERFACE
8321 		 * case), the loop may be re-entered to attempt the resolution
8322 		 * of another RTF_MULTIRT route.
8323 		 *
8324 		 * When an IRE_CACHE entry for the off-subnet destination is
8325 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8326 		 * for further processing in emission loops.
8327 		 */
8328 		save_ire = ire;
8329 		switch (ire->ire_type) {
8330 		case IRE_CACHE: {
8331 			ire_t	*ipif_ire;
8332 
8333 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8334 			if (gw == 0)
8335 				gw = ire->ire_gateway_addr;
8336 			/*
8337 			 * We need 3 ire's to create a new cache ire for an
8338 			 * off-link destination from the cache ire of the
8339 			 * gateway.
8340 			 *
8341 			 *	1. The prefix ire 'sire' (Note that this does
8342 			 *	   not apply to the conn_nexthop_set case)
8343 			 *	2. The cache ire of the gateway 'ire'
8344 			 *	3. The interface ire 'ipif_ire'
8345 			 *
8346 			 * We have (1) and (2). We lookup (3) below.
8347 			 *
8348 			 * If there is no interface route to the gateway,
8349 			 * it is a race condition, where we found the cache
8350 			 * but the interface route has been deleted.
8351 			 */
8352 			if (ip_nexthop) {
8353 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8354 			} else {
8355 				ipif_ire =
8356 				    ire_ihandle_lookup_offlink(ire, sire);
8357 			}
8358 			if (ipif_ire == NULL) {
8359 				ip1dbg(("ip_newroute: "
8360 				    "ire_ihandle_lookup_offlink failed\n"));
8361 				goto icmp_err_ret;
8362 			}
8363 
8364 			/*
8365 			 * Check cached gateway IRE for any security
8366 			 * attributes; if found, associate the gateway
8367 			 * credentials group to the destination IRE.
8368 			 */
8369 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8370 				mutex_enter(&attrp->igsa_lock);
8371 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8372 					GCGRP_REFHOLD(gcgrp);
8373 				mutex_exit(&attrp->igsa_lock);
8374 			}
8375 
8376 			/*
8377 			 * XXX For the source of the resolver mp,
8378 			 * we are using the same DL_UNITDATA_REQ
8379 			 * (from save_ire->ire_nce->nce_res_mp)
8380 			 * though the save_ire is not pointing at the same ill.
8381 			 * This is incorrect. We need to send it up to the
8382 			 * resolver to get the right res_mp. For ethernets
8383 			 * this may be okay (ill_type == DL_ETHER).
8384 			 */
8385 
8386 			ire = ire_create(
8387 			    (uchar_t *)&dst,		/* dest address */
8388 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8389 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8390 			    (uchar_t *)&gw,		/* gateway address */
8391 			    &save_ire->ire_max_frag,
8392 			    save_ire->ire_nce,		/* src nce */
8393 			    dst_ill->ill_rq,		/* recv-from queue */
8394 			    dst_ill->ill_wq,		/* send-to queue */
8395 			    IRE_CACHE,			/* IRE type */
8396 			    src_ipif,
8397 			    (sire != NULL) ?
8398 			    sire->ire_mask : 0, 	/* Parent mask */
8399 			    (sire != NULL) ?
8400 			    sire->ire_phandle : 0,	/* Parent handle */
8401 			    ipif_ire->ire_ihandle,	/* Interface handle */
8402 			    (sire != NULL) ? (sire->ire_flags &
8403 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8404 			    (sire != NULL) ?
8405 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8406 			    NULL,
8407 			    gcgrp,
8408 			    ipst);
8409 
8410 			if (ire == NULL) {
8411 				if (gcgrp != NULL) {
8412 					GCGRP_REFRELE(gcgrp);
8413 					gcgrp = NULL;
8414 				}
8415 				ire_refrele(ipif_ire);
8416 				ire_refrele(save_ire);
8417 				break;
8418 			}
8419 
8420 			/* reference now held by IRE */
8421 			gcgrp = NULL;
8422 
8423 			ire->ire_marks |= ire_marks;
8424 
8425 			/*
8426 			 * Prevent sire and ipif_ire from getting deleted.
8427 			 * The newly created ire is tied to both of them via
8428 			 * the phandle and ihandle respectively.
8429 			 */
8430 			if (sire != NULL) {
8431 				IRB_REFHOLD(sire->ire_bucket);
8432 				/* Has it been removed already ? */
8433 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8434 					IRB_REFRELE(sire->ire_bucket);
8435 					ire_refrele(ipif_ire);
8436 					ire_refrele(save_ire);
8437 					break;
8438 				}
8439 			}
8440 
8441 			IRB_REFHOLD(ipif_ire->ire_bucket);
8442 			/* Has it been removed already ? */
8443 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8444 				IRB_REFRELE(ipif_ire->ire_bucket);
8445 				if (sire != NULL)
8446 					IRB_REFRELE(sire->ire_bucket);
8447 				ire_refrele(ipif_ire);
8448 				ire_refrele(save_ire);
8449 				break;
8450 			}
8451 
8452 			xmit_mp = first_mp;
8453 			/*
8454 			 * In the case of multirouting, a copy
8455 			 * of the packet is done before its sending.
8456 			 * The copy is used to attempt another
8457 			 * route resolution, in a next loop.
8458 			 */
8459 			if (ire->ire_flags & RTF_MULTIRT) {
8460 				copy_mp = copymsg(first_mp);
8461 				if (copy_mp != NULL) {
8462 					xmit_mp = copy_mp;
8463 					MULTIRT_DEBUG_TAG(first_mp);
8464 				}
8465 			}
8466 			ire_add_then_send(q, ire, xmit_mp);
8467 			ire_refrele(save_ire);
8468 
8469 			/* Assert that sire is not deleted yet. */
8470 			if (sire != NULL) {
8471 				ASSERT(sire->ire_ptpn != NULL);
8472 				IRB_REFRELE(sire->ire_bucket);
8473 			}
8474 
8475 			/* Assert that ipif_ire is not deleted yet. */
8476 			ASSERT(ipif_ire->ire_ptpn != NULL);
8477 			IRB_REFRELE(ipif_ire->ire_bucket);
8478 			ire_refrele(ipif_ire);
8479 
8480 			/*
8481 			 * If copy_mp is not NULL, multirouting was
8482 			 * requested. We loop to initiate a next
8483 			 * route resolution attempt, starting from sire.
8484 			 */
8485 			if (copy_mp != NULL) {
8486 				/*
8487 				 * Search for the next unresolved
8488 				 * multirt route.
8489 				 */
8490 				copy_mp = NULL;
8491 				ipif_ire = NULL;
8492 				ire = NULL;
8493 				multirt_resolve_next = B_TRUE;
8494 				continue;
8495 			}
8496 			if (sire != NULL)
8497 				ire_refrele(sire);
8498 			ipif_refrele(src_ipif);
8499 			ill_refrele(dst_ill);
8500 			return;
8501 		}
8502 		case IRE_IF_NORESOLVER: {
8503 
8504 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8505 			    dst_ill->ill_resolver_mp == NULL) {
8506 				ip1dbg(("ip_newroute: dst_ill %p "
8507 				    "for IRE_IF_NORESOLVER ire %p has "
8508 				    "no ill_resolver_mp\n",
8509 				    (void *)dst_ill, (void *)ire));
8510 				break;
8511 			}
8512 
8513 			/*
8514 			 * TSol note: We are creating the ire cache for the
8515 			 * destination 'dst'. If 'dst' is offlink, going
8516 			 * through the first hop 'gw', the security attributes
8517 			 * of 'dst' must be set to point to the gateway
8518 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8519 			 * is possible that 'dst' is a potential gateway that is
8520 			 * referenced by some route that has some security
8521 			 * attributes. Thus in the former case, we need to do a
8522 			 * gcgrp_lookup of 'gw' while in the latter case we
8523 			 * need to do gcgrp_lookup of 'dst' itself.
8524 			 */
8525 			ga.ga_af = AF_INET;
8526 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8527 			    &ga.ga_addr);
8528 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8529 
8530 			ire = ire_create(
8531 			    (uchar_t *)&dst,		/* dest address */
8532 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8533 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8534 			    (uchar_t *)&gw,		/* gateway address */
8535 			    &save_ire->ire_max_frag,
8536 			    NULL,			/* no src nce */
8537 			    dst_ill->ill_rq,		/* recv-from queue */
8538 			    dst_ill->ill_wq,		/* send-to queue */
8539 			    IRE_CACHE,
8540 			    src_ipif,
8541 			    save_ire->ire_mask,		/* Parent mask */
8542 			    (sire != NULL) ?		/* Parent handle */
8543 			    sire->ire_phandle : 0,
8544 			    save_ire->ire_ihandle,	/* Interface handle */
8545 			    (sire != NULL) ? sire->ire_flags &
8546 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8547 			    &(save_ire->ire_uinfo),
8548 			    NULL,
8549 			    gcgrp,
8550 			    ipst);
8551 
8552 			if (ire == NULL) {
8553 				if (gcgrp != NULL) {
8554 					GCGRP_REFRELE(gcgrp);
8555 					gcgrp = NULL;
8556 				}
8557 				ire_refrele(save_ire);
8558 				break;
8559 			}
8560 
8561 			/* reference now held by IRE */
8562 			gcgrp = NULL;
8563 
8564 			ire->ire_marks |= ire_marks;
8565 
8566 			/* Prevent save_ire from getting deleted */
8567 			IRB_REFHOLD(save_ire->ire_bucket);
8568 			/* Has it been removed already ? */
8569 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8570 				IRB_REFRELE(save_ire->ire_bucket);
8571 				ire_refrele(save_ire);
8572 				break;
8573 			}
8574 
8575 			/*
8576 			 * In the case of multirouting, a copy
8577 			 * of the packet is made before it is sent.
8578 			 * The copy is used in the next
8579 			 * loop to attempt another resolution.
8580 			 */
8581 			xmit_mp = first_mp;
8582 			if ((sire != NULL) &&
8583 			    (sire->ire_flags & RTF_MULTIRT)) {
8584 				copy_mp = copymsg(first_mp);
8585 				if (copy_mp != NULL) {
8586 					xmit_mp = copy_mp;
8587 					MULTIRT_DEBUG_TAG(first_mp);
8588 				}
8589 			}
8590 			ire_add_then_send(q, ire, xmit_mp);
8591 
8592 			/* Assert that it is not deleted yet. */
8593 			ASSERT(save_ire->ire_ptpn != NULL);
8594 			IRB_REFRELE(save_ire->ire_bucket);
8595 			ire_refrele(save_ire);
8596 
8597 			if (copy_mp != NULL) {
8598 				/*
8599 				 * If we found a (no)resolver, we ignore any
8600 				 * trailing top priority IRE_CACHE in further
8601 				 * loops. This ensures that we do not omit any
8602 				 * (no)resolver.
8603 				 * This IRE_CACHE, if any, will be processed
8604 				 * by another thread entering ip_newroute().
8605 				 * IRE_CACHE entries, if any, will be processed
8606 				 * by another thread entering ip_newroute(),
8607 				 * (upon resolver response, for instance).
8608 				 * This aims to force parallel multirt
8609 				 * resolutions as soon as a packet must be sent.
8610 				 * In the best case, after the tx of only one
8611 				 * packet, all reachable routes are resolved.
8612 				 * Otherwise, the resolution of all RTF_MULTIRT
8613 				 * routes would require several emissions.
8614 				 */
8615 				multirt_flags &= ~MULTIRT_CACHEGW;
8616 
8617 				/*
8618 				 * Search for the next unresolved multirt
8619 				 * route.
8620 				 */
8621 				copy_mp = NULL;
8622 				save_ire = NULL;
8623 				ire = NULL;
8624 				multirt_resolve_next = B_TRUE;
8625 				continue;
8626 			}
8627 
8628 			/*
8629 			 * Don't need sire anymore
8630 			 */
8631 			if (sire != NULL)
8632 				ire_refrele(sire);
8633 
8634 			ipif_refrele(src_ipif);
8635 			ill_refrele(dst_ill);
8636 			return;
8637 		}
8638 		case IRE_IF_RESOLVER:
8639 			/*
8640 			 * We can't build an IRE_CACHE yet, but at least we
8641 			 * found a resolver that can help.
8642 			 */
8643 			res_mp = dst_ill->ill_resolver_mp;
8644 			if (!OK_RESOLVER_MP(res_mp))
8645 				break;
8646 
8647 			/*
8648 			 * To be at this point in the code with a non-zero gw
8649 			 * means that dst is reachable through a gateway that
8650 			 * we have never resolved.  By changing dst to the gw
8651 			 * addr we resolve the gateway first.
8652 			 * When ire_add_then_send() tries to put the IP dg
8653 			 * to dst, it will reenter ip_newroute() at which
8654 			 * time we will find the IRE_CACHE for the gw and
8655 			 * create another IRE_CACHE in case IRE_CACHE above.
8656 			 */
8657 			if (gw != INADDR_ANY) {
8658 				/*
8659 				 * The source ipif that was determined above was
8660 				 * relative to the destination address, not the
8661 				 * gateway's. If src_ipif was not taken out of
8662 				 * the IRE_IF_RESOLVER entry, we'll need to call
8663 				 * ipif_select_source() again.
8664 				 */
8665 				if (src_ipif != ire->ire_ipif) {
8666 					ipif_refrele(src_ipif);
8667 					src_ipif = ipif_select_source(dst_ill,
8668 					    gw, zoneid);
8669 					if (src_ipif == NULL) {
8670 						if (ip_debug > 2) {
8671 							pr_addr_dbg(
8672 							    "ip_newroute: no "
8673 							    "src for gw %s ",
8674 							    AF_INET, &gw);
8675 							printf("through "
8676 							    "interface %s\n",
8677 							    dst_ill->ill_name);
8678 						}
8679 						goto icmp_err_ret;
8680 					}
8681 				}
8682 				save_dst = dst;
8683 				dst = gw;
8684 				gw = INADDR_ANY;
8685 			}
8686 
8687 			/*
8688 			 * We obtain a partial IRE_CACHE which we will pass
8689 			 * along with the resolver query.  When the response
8690 			 * comes back it will be there ready for us to add.
8691 			 * The ire_max_frag is atomically set under the
8692 			 * irebucket lock in ire_add_v[46].
8693 			 */
8694 
8695 			ire = ire_create_mp(
8696 			    (uchar_t *)&dst,		/* dest address */
8697 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8698 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8699 			    (uchar_t *)&gw,		/* gateway address */
8700 			    NULL,			/* ire_max_frag */
8701 			    NULL,			/* no src nce */
8702 			    dst_ill->ill_rq,		/* recv-from queue */
8703 			    dst_ill->ill_wq,		/* send-to queue */
8704 			    IRE_CACHE,
8705 			    src_ipif,			/* Interface ipif */
8706 			    save_ire->ire_mask,		/* Parent mask */
8707 			    0,
8708 			    save_ire->ire_ihandle,	/* Interface handle */
8709 			    0,				/* flags if any */
8710 			    &(save_ire->ire_uinfo),
8711 			    NULL,
8712 			    NULL,
8713 			    ipst);
8714 
8715 			if (ire == NULL) {
8716 				ire_refrele(save_ire);
8717 				break;
8718 			}
8719 
8720 			if ((sire != NULL) &&
8721 			    (sire->ire_flags & RTF_MULTIRT)) {
8722 				copy_mp = copymsg(first_mp);
8723 				if (copy_mp != NULL)
8724 					MULTIRT_DEBUG_TAG(copy_mp);
8725 			}
8726 
8727 			ire->ire_marks |= ire_marks;
8728 
8729 			/*
8730 			 * Construct message chain for the resolver
8731 			 * of the form:
8732 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8733 			 * Packet could contain a IPSEC_OUT mp.
8734 			 *
8735 			 * NOTE : ire will be added later when the response
8736 			 * comes back from ARP. If the response does not
8737 			 * come back, ARP frees the packet. For this reason,
8738 			 * we can't REFHOLD the bucket of save_ire to prevent
8739 			 * deletions. We may not be able to REFRELE the bucket
8740 			 * if the response never comes back. Thus, before
8741 			 * adding the ire, ire_add_v4 will make sure that the
8742 			 * interface route does not get deleted. This is the
8743 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8744 			 * where we can always prevent deletions because of
8745 			 * the synchronous nature of adding IRES i.e
8746 			 * ire_add_then_send is called after creating the IRE.
8747 			 */
8748 			ASSERT(ire->ire_mp != NULL);
8749 			ire->ire_mp->b_cont = first_mp;
8750 			/* Have saved_mp handy, for cleanup if canput fails */
8751 			saved_mp = mp;
8752 			mp = copyb(res_mp);
8753 			if (mp == NULL) {
8754 				/* Prepare for cleanup */
8755 				mp = saved_mp; /* pkt */
8756 				ire_delete(ire); /* ire_mp */
8757 				ire = NULL;
8758 				ire_refrele(save_ire);
8759 				if (copy_mp != NULL) {
8760 					MULTIRT_DEBUG_UNTAG(copy_mp);
8761 					freemsg(copy_mp);
8762 					copy_mp = NULL;
8763 				}
8764 				break;
8765 			}
8766 			linkb(mp, ire->ire_mp);
8767 
8768 			/*
8769 			 * Fill in the source and dest addrs for the resolver.
8770 			 * NOTE: this depends on memory layouts imposed by
8771 			 * ill_init().
8772 			 */
8773 			areq = (areq_t *)mp->b_rptr;
8774 			addrp = (ipaddr_t *)((char *)areq +
8775 			    areq->areq_sender_addr_offset);
8776 			if (do_attach_ill) {
8777 				/*
8778 				 * This is bind to no failover case.
8779 				 * arp packet also must go out on attach_ill.
8780 				 */
8781 				ASSERT(ipha->ipha_src != NULL);
8782 				*addrp = ipha->ipha_src;
8783 			} else {
8784 				*addrp = save_ire->ire_src_addr;
8785 			}
8786 
8787 			ire_refrele(save_ire);
8788 			addrp = (ipaddr_t *)((char *)areq +
8789 			    areq->areq_target_addr_offset);
8790 			*addrp = dst;
8791 			/* Up to the resolver. */
8792 			if (canputnext(dst_ill->ill_rq) &&
8793 			    !(dst_ill->ill_arp_closing)) {
8794 				putnext(dst_ill->ill_rq, mp);
8795 				ire = NULL;
8796 				if (copy_mp != NULL) {
8797 					/*
8798 					 * If we found a resolver, we ignore
8799 					 * any trailing top priority IRE_CACHE
8800 					 * in the further loops. This ensures
8801 					 * that we do not omit any resolver.
8802 					 * IRE_CACHE entries, if any, will be
8803 					 * processed next time we enter
8804 					 * ip_newroute().
8805 					 */
8806 					multirt_flags &= ~MULTIRT_CACHEGW;
8807 					/*
8808 					 * Search for the next unresolved
8809 					 * multirt route.
8810 					 */
8811 					first_mp = copy_mp;
8812 					copy_mp = NULL;
8813 					/* Prepare the next resolution loop. */
8814 					mp = first_mp;
8815 					EXTRACT_PKT_MP(mp, first_mp,
8816 					    mctl_present);
8817 					if (mctl_present)
8818 						io = (ipsec_out_t *)
8819 						    first_mp->b_rptr;
8820 					ipha = (ipha_t *)mp->b_rptr;
8821 
8822 					ASSERT(sire != NULL);
8823 
8824 					dst = save_dst;
8825 					multirt_resolve_next = B_TRUE;
8826 					continue;
8827 				}
8828 
8829 				if (sire != NULL)
8830 					ire_refrele(sire);
8831 
8832 				/*
8833 				 * The response will come back in ip_wput
8834 				 * with db_type IRE_DB_TYPE.
8835 				 */
8836 				ipif_refrele(src_ipif);
8837 				ill_refrele(dst_ill);
8838 				return;
8839 			} else {
8840 				/* Prepare for cleanup */
8841 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8842 				    mp);
8843 				mp->b_cont = NULL;
8844 				freeb(mp); /* areq */
8845 				/*
8846 				 * this is an ire that is not added to the
8847 				 * cache. ire_freemblk will handle the release
8848 				 * of any resources associated with the ire.
8849 				 */
8850 				ire_delete(ire); /* ire_mp */
8851 				mp = saved_mp; /* pkt */
8852 				ire = NULL;
8853 				if (copy_mp != NULL) {
8854 					MULTIRT_DEBUG_UNTAG(copy_mp);
8855 					freemsg(copy_mp);
8856 					copy_mp = NULL;
8857 				}
8858 				break;
8859 			}
8860 		default:
8861 			break;
8862 		}
8863 	} while (multirt_resolve_next);
8864 
8865 	ip1dbg(("ip_newroute: dropped\n"));
8866 	/* Did this packet originate externally? */
8867 	if (mp->b_prev) {
8868 		mp->b_next = NULL;
8869 		mp->b_prev = NULL;
8870 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8871 	} else {
8872 		if (dst_ill != NULL) {
8873 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8874 		} else {
8875 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8876 		}
8877 	}
8878 	ASSERT(copy_mp == NULL);
8879 	MULTIRT_DEBUG_UNTAG(first_mp);
8880 	freemsg(first_mp);
8881 	if (ire != NULL)
8882 		ire_refrele(ire);
8883 	if (sire != NULL)
8884 		ire_refrele(sire);
8885 	if (src_ipif != NULL)
8886 		ipif_refrele(src_ipif);
8887 	if (dst_ill != NULL)
8888 		ill_refrele(dst_ill);
8889 	return;
8890 
8891 icmp_err_ret:
8892 	ip1dbg(("ip_newroute: no route\n"));
8893 	if (src_ipif != NULL)
8894 		ipif_refrele(src_ipif);
8895 	if (dst_ill != NULL)
8896 		ill_refrele(dst_ill);
8897 	if (sire != NULL)
8898 		ire_refrele(sire);
8899 	/* Did this packet originate externally? */
8900 	if (mp->b_prev) {
8901 		mp->b_next = NULL;
8902 		mp->b_prev = NULL;
8903 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8904 		q = WR(q);
8905 	} else {
8906 		/*
8907 		 * There is no outgoing ill, so just increment the
8908 		 * system MIB.
8909 		 */
8910 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
8911 		/*
8912 		 * Since ip_wput() isn't close to finished, we fill
8913 		 * in enough of the header for credible error reporting.
8914 		 */
8915 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
8916 			/* Failed */
8917 			MULTIRT_DEBUG_UNTAG(first_mp);
8918 			freemsg(first_mp);
8919 			if (ire != NULL)
8920 				ire_refrele(ire);
8921 			return;
8922 		}
8923 	}
8924 
8925 	/*
8926 	 * At this point we will have ire only if RTF_BLACKHOLE
8927 	 * or RTF_REJECT flags are set on the IRE. It will not
8928 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8929 	 */
8930 	if (ire != NULL) {
8931 		if (ire->ire_flags & RTF_BLACKHOLE) {
8932 			ire_refrele(ire);
8933 			MULTIRT_DEBUG_UNTAG(first_mp);
8934 			freemsg(first_mp);
8935 			return;
8936 		}
8937 		ire_refrele(ire);
8938 	}
8939 	if (ip_source_routed(ipha, ipst)) {
8940 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8941 		    zoneid, ipst);
8942 		return;
8943 	}
8944 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
8945 }
8946 
8947 ip_opt_info_t zero_info;
8948 
8949 /*
8950  * IPv4 -
8951  * ip_newroute_ipif is called by ip_wput_multicast and
8952  * ip_rput_forward_multicast whenever we need to send
8953  * out a packet to a destination address for which we do not have specific
8954  * routing information. It is used when the packet will be sent out
8955  * on a specific interface. It is also called by ip_wput() when IP_BOUND_IF
8956  * socket option is set or icmp error message wants to go out on a particular
8957  * interface for a unicast packet.
8958  *
8959  * In most cases, the destination address is resolved thanks to the ipif
8960  * intrinsic resolver. However, there are some cases where the call to
8961  * ip_newroute_ipif must take into account the potential presence of
8962  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8963  * that uses the interface. This is specified through flags,
8964  * which can be a combination of:
8965  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8966  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
8967  *   and flags. Additionally, the packet source address has to be set to
8968  *   the specified address. The caller is thus expected to set this flag
8969  *   if the packet has no specific source address yet.
8970  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
8971  *   flag, the resulting ire will inherit the flag. All unresolved routes
8972  *   to the destination must be explored in the same call to
8973  *   ip_newroute_ipif().
8974  */
8975 static void
8976 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
8977     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
8978 {
8979 	areq_t	*areq;
8980 	ire_t	*ire = NULL;
8981 	mblk_t	*res_mp;
8982 	ipaddr_t *addrp;
8983 	mblk_t *first_mp;
8984 	ire_t	*save_ire = NULL;
8985 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
8986 	ipif_t	*src_ipif = NULL;
8987 	ushort_t ire_marks = 0;
8988 	ill_t	*dst_ill = NULL;
8989 	boolean_t mctl_present;
8990 	ipsec_out_t *io;
8991 	ipha_t *ipha;
8992 	int	ihandle = 0;
8993 	mblk_t	*saved_mp;
8994 	ire_t   *fire = NULL;
8995 	mblk_t  *copy_mp = NULL;
8996 	boolean_t multirt_resolve_next;
8997 	boolean_t unspec_src;
8998 	ipaddr_t ipha_dst;
8999 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
9000 
9001 	/*
9002 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9003 	 * here for uniformity
9004 	 */
9005 	ipif_refhold(ipif);
9006 
9007 	/*
9008 	 * This loop is run only once in most cases.
9009 	 * We loop to resolve further routes only when the destination
9010 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9011 	 */
9012 	do {
9013 		if (dst_ill != NULL) {
9014 			ill_refrele(dst_ill);
9015 			dst_ill = NULL;
9016 		}
9017 		if (src_ipif != NULL) {
9018 			ipif_refrele(src_ipif);
9019 			src_ipif = NULL;
9020 		}
9021 		multirt_resolve_next = B_FALSE;
9022 
9023 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9024 		    ipif->ipif_ill->ill_name));
9025 
9026 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
9027 		if (mctl_present)
9028 			io = (ipsec_out_t *)first_mp->b_rptr;
9029 
9030 		ipha = (ipha_t *)mp->b_rptr;
9031 
9032 		/*
9033 		 * Save the packet destination address, we may need it after
9034 		 * the packet has been consumed.
9035 		 */
9036 		ipha_dst = ipha->ipha_dst;
9037 
9038 		/*
9039 		 * If the interface is a pt-pt interface we look for an
9040 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9041 		 * local_address and the pt-pt destination address. Otherwise
9042 		 * we just match the local address.
9043 		 * NOTE: dst could be different than ipha->ipha_dst in case
9044 		 * of sending igmp multicast packets over a point-to-point
9045 		 * connection.
9046 		 * Thus we must be careful enough to check ipha_dst to be a
9047 		 * multicast address, otherwise it will take xmit_if path for
9048 		 * multicast packets resulting into kernel stack overflow by
9049 		 * repeated calls to ip_newroute_ipif from ire_send().
9050 		 */
9051 		if (CLASSD(ipha_dst) &&
9052 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9053 			goto err_ret;
9054 		}
9055 
9056 		/*
9057 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9058 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9059 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9060 		 * propagate its flags to the new ire.
9061 		 */
9062 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9063 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9064 			ip2dbg(("ip_newroute_ipif: "
9065 			    "ipif_lookup_multi_ire("
9066 			    "ipif %p, dst %08x) = fire %p\n",
9067 			    (void *)ipif, ntohl(dst), (void *)fire));
9068 		}
9069 
9070 		if (mctl_present && io->ipsec_out_attach_if) {
9071 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
9072 			    io->ipsec_out_ill_index, B_FALSE, ipst);
9073 
9074 			/* Failure case frees things for us. */
9075 			if (attach_ill == NULL) {
9076 				ipif_refrele(ipif);
9077 				if (fire != NULL)
9078 					ire_refrele(fire);
9079 				return;
9080 			}
9081 
9082 			/*
9083 			 * Check if we need an ire that will not be
9084 			 * looked up by anybody else i.e. HIDDEN.
9085 			 */
9086 			if (ill_is_probeonly(attach_ill)) {
9087 				ire_marks = IRE_MARK_HIDDEN;
9088 			}
9089 			/*
9090 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
9091 			 * case.
9092 			 */
9093 			dst_ill = ipif->ipif_ill;
9094 			/* attach_ill has been refheld by ip_grab_attach_ill */
9095 			ASSERT(dst_ill == attach_ill);
9096 		} else {
9097 			/*
9098 			 * If the interface belongs to an interface group,
9099 			 * make sure the next possible interface in the group
9100 			 * is used.  This encourages load spreading among
9101 			 * peers in an interface group.
9102 			 * Note: load spreading is disabled for RTF_MULTIRT
9103 			 * routes.
9104 			 */
9105 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9106 			    (fire->ire_flags & RTF_MULTIRT)) {
9107 				/*
9108 				 * Don't perform outbound load spreading
9109 				 * in the case of an RTF_MULTIRT issued route,
9110 				 * we actually typically want to replicate
9111 				 * outgoing packets through particular
9112 				 * interfaces.
9113 				 */
9114 				dst_ill = ipif->ipif_ill;
9115 				ill_refhold(dst_ill);
9116 			} else {
9117 				dst_ill = ip_newroute_get_dst_ill(
9118 				    ipif->ipif_ill);
9119 			}
9120 			if (dst_ill == NULL) {
9121 				if (ip_debug > 2) {
9122 					pr_addr_dbg("ip_newroute_ipif: "
9123 					    "no dst ill for dst %s\n",
9124 					    AF_INET, &dst);
9125 				}
9126 				goto err_ret;
9127 			}
9128 		}
9129 
9130 		/*
9131 		 * Pick a source address preferring non-deprecated ones.
9132 		 * Unlike ip_newroute, we don't do any source address
9133 		 * selection here since for multicast it really does not help
9134 		 * in inbound load spreading as in the unicast case.
9135 		 */
9136 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9137 		    (fire->ire_flags & RTF_SETSRC)) {
9138 			/*
9139 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9140 			 * on that interface. This ire has RTF_SETSRC flag, so
9141 			 * the source address of the packet must be changed.
9142 			 * Check that the ipif matching the requested source
9143 			 * address still exists.
9144 			 */
9145 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9146 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9147 		}
9148 
9149 		unspec_src = (connp != NULL && connp->conn_unspec_src);
9150 
9151 		if (((!ipif->ipif_isv6 && ipif->ipif_lcl_addr == INADDR_ANY) ||
9152 		    (ipif->ipif_flags & (IPIF_DEPRECATED|IPIF_UP)) != IPIF_UP ||
9153 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9154 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9155 		    (src_ipif == NULL) &&
9156 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
9157 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9158 			if (src_ipif == NULL) {
9159 				if (ip_debug > 2) {
9160 					/* ip1dbg */
9161 					pr_addr_dbg("ip_newroute_ipif: "
9162 					    "no src for dst %s",
9163 					    AF_INET, &dst);
9164 				}
9165 				ip1dbg((" through interface %s\n",
9166 				    dst_ill->ill_name));
9167 				goto err_ret;
9168 			}
9169 			ipif_refrele(ipif);
9170 			ipif = src_ipif;
9171 			ipif_refhold(ipif);
9172 		}
9173 		if (src_ipif == NULL) {
9174 			src_ipif = ipif;
9175 			ipif_refhold(src_ipif);
9176 		}
9177 
9178 		/*
9179 		 * Assign a source address while we have the conn.
9180 		 * We can't have ip_wput_ire pick a source address when the
9181 		 * packet returns from arp since conn_unspec_src might be set
9182 		 * and we lose the conn when going through arp.
9183 		 */
9184 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
9185 			ipha->ipha_src = src_ipif->ipif_src_addr;
9186 
9187 		/*
9188 		 * In the case of IP_BOUND_IF and IP_PKTINFO, it is possible
9189 		 * that the outgoing interface does not have an interface ire.
9190 		 */
9191 		if (CLASSD(ipha_dst) && (connp == NULL ||
9192 		    connp->conn_outgoing_ill == NULL) &&
9193 		    infop->ip_opt_ill_index == 0) {
9194 			/* ipif_to_ire returns an held ire */
9195 			ire = ipif_to_ire(ipif);
9196 			if (ire == NULL)
9197 				goto err_ret;
9198 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9199 				goto err_ret;
9200 			/*
9201 			 * ihandle is needed when the ire is added to
9202 			 * cache table.
9203 			 */
9204 			save_ire = ire;
9205 			ihandle = save_ire->ire_ihandle;
9206 
9207 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9208 			    "flags %04x\n",
9209 			    (void *)ire, (void *)ipif, flags));
9210 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9211 			    (fire->ire_flags & RTF_MULTIRT)) {
9212 				/*
9213 				 * As requested by flags, an IRE_OFFSUBNET was
9214 				 * looked up on that interface. This ire has
9215 				 * RTF_MULTIRT flag, so the resolution loop will
9216 				 * be re-entered to resolve additional routes on
9217 				 * other interfaces. For that purpose, a copy of
9218 				 * the packet is performed at this point.
9219 				 */
9220 				fire->ire_last_used_time = lbolt;
9221 				copy_mp = copymsg(first_mp);
9222 				if (copy_mp) {
9223 					MULTIRT_DEBUG_TAG(copy_mp);
9224 				}
9225 			}
9226 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9227 			    (fire->ire_flags & RTF_SETSRC)) {
9228 				/*
9229 				 * As requested by flags, an IRE_OFFSUBET was
9230 				 * looked up on that interface. This ire has
9231 				 * RTF_SETSRC flag, so the source address of the
9232 				 * packet must be changed.
9233 				 */
9234 				ipha->ipha_src = fire->ire_src_addr;
9235 			}
9236 		} else {
9237 			ASSERT((connp == NULL) ||
9238 			    (connp->conn_outgoing_ill != NULL) ||
9239 			    (connp->conn_dontroute) ||
9240 			    infop->ip_opt_ill_index != 0);
9241 			/*
9242 			 * The only ways we can come here are:
9243 			 * 1) IP_BOUND_IF socket option is set
9244 			 * 2) SO_DONTROUTE socket option is set
9245 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9246 			 * In all cases, the new ire will not be added
9247 			 * into cache table.
9248 			 */
9249 			ire_marks |= IRE_MARK_NOADD;
9250 		}
9251 
9252 		switch (ipif->ipif_net_type) {
9253 		case IRE_IF_NORESOLVER: {
9254 			/* We have what we need to build an IRE_CACHE. */
9255 
9256 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9257 			    (dst_ill->ill_resolver_mp == NULL)) {
9258 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9259 				    "for IRE_IF_NORESOLVER ire %p has "
9260 				    "no ill_resolver_mp\n",
9261 				    (void *)dst_ill, (void *)ire));
9262 				break;
9263 			}
9264 
9265 			/*
9266 			 * The new ire inherits the IRE_OFFSUBNET flags
9267 			 * and source address, if this was requested.
9268 			 */
9269 			ire = ire_create(
9270 			    (uchar_t *)&dst,		/* dest address */
9271 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9272 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9273 			    NULL,			/* gateway address */
9274 			    &ipif->ipif_mtu,
9275 			    NULL,			/* no src nce */
9276 			    dst_ill->ill_rq,		/* recv-from queue */
9277 			    dst_ill->ill_wq,		/* send-to queue */
9278 			    IRE_CACHE,
9279 			    src_ipif,
9280 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9281 			    (fire != NULL) ?		/* Parent handle */
9282 			    fire->ire_phandle : 0,
9283 			    ihandle,			/* Interface handle */
9284 			    (fire != NULL) ?
9285 			    (fire->ire_flags &
9286 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9287 			    (save_ire == NULL ? &ire_uinfo_null :
9288 			    &save_ire->ire_uinfo),
9289 			    NULL,
9290 			    NULL,
9291 			    ipst);
9292 
9293 			if (ire == NULL) {
9294 				if (save_ire != NULL)
9295 					ire_refrele(save_ire);
9296 				break;
9297 			}
9298 
9299 			ire->ire_marks |= ire_marks;
9300 
9301 			/*
9302 			 * If IRE_MARK_NOADD is set then we need to convert
9303 			 * the max_fragp to a useable value now. This is
9304 			 * normally done in ire_add_v[46]. We also need to
9305 			 * associate the ire with an nce (normally would be
9306 			 * done in ip_wput_nondata()).
9307 			 *
9308 			 * Note that IRE_MARK_NOADD packets created here
9309 			 * do not have a non-null ire_mp pointer. The null
9310 			 * value of ire_bucket indicates that they were
9311 			 * never added.
9312 			 */
9313 			if (ire->ire_marks & IRE_MARK_NOADD) {
9314 				uint_t  max_frag;
9315 
9316 				max_frag = *ire->ire_max_fragp;
9317 				ire->ire_max_fragp = NULL;
9318 				ire->ire_max_frag = max_frag;
9319 
9320 				if ((ire->ire_nce = ndp_lookup_v4(
9321 				    ire_to_ill(ire),
9322 				    (ire->ire_gateway_addr != INADDR_ANY ?
9323 				    &ire->ire_gateway_addr : &ire->ire_addr),
9324 				    B_FALSE)) == NULL) {
9325 					if (save_ire != NULL)
9326 						ire_refrele(save_ire);
9327 					break;
9328 				}
9329 				ASSERT(ire->ire_nce->nce_state ==
9330 				    ND_REACHABLE);
9331 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9332 			}
9333 
9334 			/* Prevent save_ire from getting deleted */
9335 			if (save_ire != NULL) {
9336 				IRB_REFHOLD(save_ire->ire_bucket);
9337 				/* Has it been removed already ? */
9338 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9339 					IRB_REFRELE(save_ire->ire_bucket);
9340 					ire_refrele(save_ire);
9341 					break;
9342 				}
9343 			}
9344 
9345 			ire_add_then_send(q, ire, first_mp);
9346 
9347 			/* Assert that save_ire is not deleted yet. */
9348 			if (save_ire != NULL) {
9349 				ASSERT(save_ire->ire_ptpn != NULL);
9350 				IRB_REFRELE(save_ire->ire_bucket);
9351 				ire_refrele(save_ire);
9352 				save_ire = NULL;
9353 			}
9354 			if (fire != NULL) {
9355 				ire_refrele(fire);
9356 				fire = NULL;
9357 			}
9358 
9359 			/*
9360 			 * the resolution loop is re-entered if this
9361 			 * was requested through flags and if we
9362 			 * actually are in a multirouting case.
9363 			 */
9364 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9365 				boolean_t need_resolve =
9366 				    ire_multirt_need_resolve(ipha_dst,
9367 				    MBLK_GETLABEL(copy_mp), ipst);
9368 				if (!need_resolve) {
9369 					MULTIRT_DEBUG_UNTAG(copy_mp);
9370 					freemsg(copy_mp);
9371 					copy_mp = NULL;
9372 				} else {
9373 					/*
9374 					 * ipif_lookup_group() calls
9375 					 * ire_lookup_multi() that uses
9376 					 * ire_ftable_lookup() to find
9377 					 * an IRE_INTERFACE for the group.
9378 					 * In the multirt case,
9379 					 * ire_lookup_multi() then invokes
9380 					 * ire_multirt_lookup() to find
9381 					 * the next resolvable ire.
9382 					 * As a result, we obtain an new
9383 					 * interface, derived from the
9384 					 * next ire.
9385 					 */
9386 					ipif_refrele(ipif);
9387 					ipif = ipif_lookup_group(ipha_dst,
9388 					    zoneid, ipst);
9389 					ip2dbg(("ip_newroute_ipif: "
9390 					    "multirt dst %08x, ipif %p\n",
9391 					    htonl(dst), (void *)ipif));
9392 					if (ipif != NULL) {
9393 						mp = copy_mp;
9394 						copy_mp = NULL;
9395 						multirt_resolve_next = B_TRUE;
9396 						continue;
9397 					} else {
9398 						freemsg(copy_mp);
9399 					}
9400 				}
9401 			}
9402 			if (ipif != NULL)
9403 				ipif_refrele(ipif);
9404 			ill_refrele(dst_ill);
9405 			ipif_refrele(src_ipif);
9406 			return;
9407 		}
9408 		case IRE_IF_RESOLVER:
9409 			/*
9410 			 * We can't build an IRE_CACHE yet, but at least
9411 			 * we found a resolver that can help.
9412 			 */
9413 			res_mp = dst_ill->ill_resolver_mp;
9414 			if (!OK_RESOLVER_MP(res_mp))
9415 				break;
9416 
9417 			/*
9418 			 * We obtain a partial IRE_CACHE which we will pass
9419 			 * along with the resolver query.  When the response
9420 			 * comes back it will be there ready for us to add.
9421 			 * The new ire inherits the IRE_OFFSUBNET flags
9422 			 * and source address, if this was requested.
9423 			 * The ire_max_frag is atomically set under the
9424 			 * irebucket lock in ire_add_v[46]. Only in the
9425 			 * case of IRE_MARK_NOADD, we set it here itself.
9426 			 */
9427 			ire = ire_create_mp(
9428 			    (uchar_t *)&dst,		/* dest address */
9429 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9430 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9431 			    NULL,			/* gateway address */
9432 			    (ire_marks & IRE_MARK_NOADD) ?
9433 			    ipif->ipif_mtu : 0,		/* max_frag */
9434 			    NULL,			/* no src nce */
9435 			    dst_ill->ill_rq,		/* recv-from queue */
9436 			    dst_ill->ill_wq,		/* send-to queue */
9437 			    IRE_CACHE,
9438 			    src_ipif,
9439 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9440 			    (fire != NULL) ?		/* Parent handle */
9441 			    fire->ire_phandle : 0,
9442 			    ihandle,			/* Interface handle */
9443 			    (fire != NULL) ?		/* flags if any */
9444 			    (fire->ire_flags &
9445 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9446 			    (save_ire == NULL ? &ire_uinfo_null :
9447 			    &save_ire->ire_uinfo),
9448 			    NULL,
9449 			    NULL,
9450 			    ipst);
9451 
9452 			if (save_ire != NULL) {
9453 				ire_refrele(save_ire);
9454 				save_ire = NULL;
9455 			}
9456 			if (ire == NULL)
9457 				break;
9458 
9459 			ire->ire_marks |= ire_marks;
9460 			/*
9461 			 * Construct message chain for the resolver of the
9462 			 * form:
9463 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9464 			 *
9465 			 * NOTE : ire will be added later when the response
9466 			 * comes back from ARP. If the response does not
9467 			 * come back, ARP frees the packet. For this reason,
9468 			 * we can't REFHOLD the bucket of save_ire to prevent
9469 			 * deletions. We may not be able to REFRELE the
9470 			 * bucket if the response never comes back.
9471 			 * Thus, before adding the ire, ire_add_v4 will make
9472 			 * sure that the interface route does not get deleted.
9473 			 * This is the only case unlike ip_newroute_v6,
9474 			 * ip_newroute_ipif_v6 where we can always prevent
9475 			 * deletions because ire_add_then_send is called after
9476 			 * creating the IRE.
9477 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9478 			 * does not add this IRE into the IRE CACHE.
9479 			 */
9480 			ASSERT(ire->ire_mp != NULL);
9481 			ire->ire_mp->b_cont = first_mp;
9482 			/* Have saved_mp handy, for cleanup if canput fails */
9483 			saved_mp = mp;
9484 			mp = copyb(res_mp);
9485 			if (mp == NULL) {
9486 				/* Prepare for cleanup */
9487 				mp = saved_mp; /* pkt */
9488 				ire_delete(ire); /* ire_mp */
9489 				ire = NULL;
9490 				if (copy_mp != NULL) {
9491 					MULTIRT_DEBUG_UNTAG(copy_mp);
9492 					freemsg(copy_mp);
9493 					copy_mp = NULL;
9494 				}
9495 				break;
9496 			}
9497 			linkb(mp, ire->ire_mp);
9498 
9499 			/*
9500 			 * Fill in the source and dest addrs for the resolver.
9501 			 * NOTE: this depends on memory layouts imposed by
9502 			 * ill_init().
9503 			 */
9504 			areq = (areq_t *)mp->b_rptr;
9505 			addrp = (ipaddr_t *)((char *)areq +
9506 			    areq->areq_sender_addr_offset);
9507 			*addrp = ire->ire_src_addr;
9508 			addrp = (ipaddr_t *)((char *)areq +
9509 			    areq->areq_target_addr_offset);
9510 			*addrp = dst;
9511 			/* Up to the resolver. */
9512 			if (canputnext(dst_ill->ill_rq) &&
9513 			    !(dst_ill->ill_arp_closing)) {
9514 				putnext(dst_ill->ill_rq, mp);
9515 				/*
9516 				 * The response will come back in ip_wput
9517 				 * with db_type IRE_DB_TYPE.
9518 				 */
9519 			} else {
9520 				mp->b_cont = NULL;
9521 				freeb(mp); /* areq */
9522 				ire_delete(ire); /* ire_mp */
9523 				saved_mp->b_next = NULL;
9524 				saved_mp->b_prev = NULL;
9525 				freemsg(first_mp); /* pkt */
9526 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9527 			}
9528 
9529 			if (fire != NULL) {
9530 				ire_refrele(fire);
9531 				fire = NULL;
9532 			}
9533 
9534 
9535 			/*
9536 			 * The resolution loop is re-entered if this was
9537 			 * requested through flags and we actually are
9538 			 * in a multirouting case.
9539 			 */
9540 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9541 				boolean_t need_resolve =
9542 				    ire_multirt_need_resolve(ipha_dst,
9543 				    MBLK_GETLABEL(copy_mp), ipst);
9544 				if (!need_resolve) {
9545 					MULTIRT_DEBUG_UNTAG(copy_mp);
9546 					freemsg(copy_mp);
9547 					copy_mp = NULL;
9548 				} else {
9549 					/*
9550 					 * ipif_lookup_group() calls
9551 					 * ire_lookup_multi() that uses
9552 					 * ire_ftable_lookup() to find
9553 					 * an IRE_INTERFACE for the group.
9554 					 * In the multirt case,
9555 					 * ire_lookup_multi() then invokes
9556 					 * ire_multirt_lookup() to find
9557 					 * the next resolvable ire.
9558 					 * As a result, we obtain an new
9559 					 * interface, derived from the
9560 					 * next ire.
9561 					 */
9562 					ipif_refrele(ipif);
9563 					ipif = ipif_lookup_group(ipha_dst,
9564 					    zoneid, ipst);
9565 					if (ipif != NULL) {
9566 						mp = copy_mp;
9567 						copy_mp = NULL;
9568 						multirt_resolve_next = B_TRUE;
9569 						continue;
9570 					} else {
9571 						freemsg(copy_mp);
9572 					}
9573 				}
9574 			}
9575 			if (ipif != NULL)
9576 				ipif_refrele(ipif);
9577 			ill_refrele(dst_ill);
9578 			ipif_refrele(src_ipif);
9579 			return;
9580 		default:
9581 			break;
9582 		}
9583 	} while (multirt_resolve_next);
9584 
9585 err_ret:
9586 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9587 	if (fire != NULL)
9588 		ire_refrele(fire);
9589 	ipif_refrele(ipif);
9590 	/* Did this packet originate externally? */
9591 	if (dst_ill != NULL)
9592 		ill_refrele(dst_ill);
9593 	if (src_ipif != NULL)
9594 		ipif_refrele(src_ipif);
9595 	if (mp->b_prev || mp->b_next) {
9596 		mp->b_next = NULL;
9597 		mp->b_prev = NULL;
9598 	} else {
9599 		/*
9600 		 * Since ip_wput() isn't close to finished, we fill
9601 		 * in enough of the header for credible error reporting.
9602 		 */
9603 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9604 			/* Failed */
9605 			freemsg(first_mp);
9606 			if (ire != NULL)
9607 				ire_refrele(ire);
9608 			return;
9609 		}
9610 	}
9611 	/*
9612 	 * At this point we will have ire only if RTF_BLACKHOLE
9613 	 * or RTF_REJECT flags are set on the IRE. It will not
9614 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9615 	 */
9616 	if (ire != NULL) {
9617 		if (ire->ire_flags & RTF_BLACKHOLE) {
9618 			ire_refrele(ire);
9619 			freemsg(first_mp);
9620 			return;
9621 		}
9622 		ire_refrele(ire);
9623 	}
9624 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9625 }
9626 
9627 /* Name/Value Table Lookup Routine */
9628 char *
9629 ip_nv_lookup(nv_t *nv, int value)
9630 {
9631 	if (!nv)
9632 		return (NULL);
9633 	for (; nv->nv_name; nv++) {
9634 		if (nv->nv_value == value)
9635 			return (nv->nv_name);
9636 	}
9637 	return ("unknown");
9638 }
9639 
9640 /*
9641  * This is a module open, i.e. this is a control stream for access
9642  * to a DLPI device.  We allocate an ill_t as the instance data in
9643  * this case.
9644  */
9645 int
9646 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9647 {
9648 	ill_t	*ill;
9649 	int	err;
9650 	zoneid_t zoneid;
9651 	netstack_t *ns;
9652 	ip_stack_t *ipst;
9653 
9654 	/*
9655 	 * Prevent unprivileged processes from pushing IP so that
9656 	 * they can't send raw IP.
9657 	 */
9658 	if (secpolicy_net_rawaccess(credp) != 0)
9659 		return (EPERM);
9660 
9661 	ns = netstack_find_by_cred(credp);
9662 	ASSERT(ns != NULL);
9663 	ipst = ns->netstack_ip;
9664 	ASSERT(ipst != NULL);
9665 
9666 	/*
9667 	 * For exclusive stacks we set the zoneid to zero
9668 	 * to make IP operate as if in the global zone.
9669 	 */
9670 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9671 		zoneid = GLOBAL_ZONEID;
9672 	else
9673 		zoneid = crgetzoneid(credp);
9674 
9675 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9676 	q->q_ptr = WR(q)->q_ptr = ill;
9677 	ill->ill_ipst = ipst;
9678 	ill->ill_zoneid = zoneid;
9679 
9680 	/*
9681 	 * ill_init initializes the ill fields and then sends down
9682 	 * down a DL_INFO_REQ after calling qprocson.
9683 	 */
9684 	err = ill_init(q, ill);
9685 	if (err != 0) {
9686 		mi_free(ill);
9687 		netstack_rele(ipst->ips_netstack);
9688 		q->q_ptr = NULL;
9689 		WR(q)->q_ptr = NULL;
9690 		return (err);
9691 	}
9692 
9693 	/* ill_init initializes the ipsq marking this thread as writer */
9694 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9695 	/* Wait for the DL_INFO_ACK */
9696 	mutex_enter(&ill->ill_lock);
9697 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9698 		/*
9699 		 * Return value of 0 indicates a pending signal.
9700 		 */
9701 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9702 		if (err == 0) {
9703 			mutex_exit(&ill->ill_lock);
9704 			(void) ip_close(q, 0);
9705 			return (EINTR);
9706 		}
9707 	}
9708 	mutex_exit(&ill->ill_lock);
9709 
9710 	/*
9711 	 * ip_rput_other could have set an error  in ill_error on
9712 	 * receipt of M_ERROR.
9713 	 */
9714 
9715 	err = ill->ill_error;
9716 	if (err != 0) {
9717 		(void) ip_close(q, 0);
9718 		return (err);
9719 	}
9720 
9721 	ill->ill_credp = credp;
9722 	crhold(credp);
9723 
9724 	mutex_enter(&ipst->ips_ip_mi_lock);
9725 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9726 	    credp);
9727 	mutex_exit(&ipst->ips_ip_mi_lock);
9728 	if (err) {
9729 		(void) ip_close(q, 0);
9730 		return (err);
9731 	}
9732 	return (0);
9733 }
9734 
9735 /* For /dev/ip aka AF_INET open */
9736 int
9737 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9738 {
9739 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
9740 }
9741 
9742 /* For /dev/ip6 aka AF_INET6 open */
9743 int
9744 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9745 {
9746 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
9747 }
9748 
9749 /* IP open routine. */
9750 int
9751 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9752     boolean_t isv6)
9753 {
9754 	conn_t 		*connp;
9755 	major_t		maj;
9756 	zoneid_t	zoneid;
9757 	netstack_t	*ns;
9758 	ip_stack_t	*ipst;
9759 
9760 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9761 
9762 	/* Allow reopen. */
9763 	if (q->q_ptr != NULL)
9764 		return (0);
9765 
9766 	if (sflag & MODOPEN) {
9767 		/* This is a module open */
9768 		return (ip_modopen(q, devp, flag, sflag, credp));
9769 	}
9770 
9771 	ns = netstack_find_by_cred(credp);
9772 	ASSERT(ns != NULL);
9773 	ipst = ns->netstack_ip;
9774 	ASSERT(ipst != NULL);
9775 
9776 	/*
9777 	 * For exclusive stacks we set the zoneid to zero
9778 	 * to make IP operate as if in the global zone.
9779 	 */
9780 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9781 		zoneid = GLOBAL_ZONEID;
9782 	else
9783 		zoneid = crgetzoneid(credp);
9784 
9785 	/*
9786 	 * We are opening as a device. This is an IP client stream, and we
9787 	 * allocate an conn_t as the instance data.
9788 	 */
9789 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9790 
9791 	/*
9792 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9793 	 * done by netstack_find_by_cred()
9794 	 */
9795 	netstack_rele(ipst->ips_netstack);
9796 
9797 	connp->conn_zoneid = zoneid;
9798 
9799 	connp->conn_upq = q;
9800 	q->q_ptr = WR(q)->q_ptr = connp;
9801 
9802 	if (flag & SO_SOCKSTR)
9803 		connp->conn_flags |= IPCL_SOCKET;
9804 
9805 	/* Minor tells us which /dev entry was opened */
9806 	if (isv6) {
9807 		connp->conn_flags |= IPCL_ISV6;
9808 		connp->conn_af_isv6 = B_TRUE;
9809 		ip_setpktversion(connp, isv6, B_FALSE, ipst);
9810 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9811 	} else {
9812 		connp->conn_af_isv6 = B_FALSE;
9813 		connp->conn_pkt_isv6 = B_FALSE;
9814 	}
9815 
9816 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9817 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9818 		connp->conn_minor_arena = ip_minor_arena_la;
9819 	} else {
9820 		/*
9821 		 * Either minor numbers in the large arena were exhausted
9822 		 * or a non socket application is doing the open.
9823 		 * Try to allocate from the small arena.
9824 		 */
9825 		if ((connp->conn_dev =
9826 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9827 			/* CONN_DEC_REF takes care of netstack_rele() */
9828 			q->q_ptr = WR(q)->q_ptr = NULL;
9829 			CONN_DEC_REF(connp);
9830 			return (EBUSY);
9831 		}
9832 		connp->conn_minor_arena = ip_minor_arena_sa;
9833 	}
9834 
9835 	maj = getemajor(*devp);
9836 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9837 
9838 	/*
9839 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9840 	 */
9841 	connp->conn_cred = credp;
9842 
9843 	/*
9844 	 * Handle IP_RTS_REQUEST and other ioctls which use conn_recv
9845 	 */
9846 	connp->conn_recv = ip_conn_input;
9847 
9848 	crhold(connp->conn_cred);
9849 
9850 	/*
9851 	 * If the caller has the process-wide flag set, then default to MAC
9852 	 * exempt mode.  This allows read-down to unlabeled hosts.
9853 	 */
9854 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9855 		connp->conn_mac_exempt = B_TRUE;
9856 
9857 	connp->conn_rq = q;
9858 	connp->conn_wq = WR(q);
9859 
9860 	/* Non-zero default values */
9861 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9862 
9863 	/*
9864 	 * Make the conn globally visible to walkers
9865 	 */
9866 	ASSERT(connp->conn_ref == 1);
9867 	mutex_enter(&connp->conn_lock);
9868 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9869 	mutex_exit(&connp->conn_lock);
9870 
9871 	qprocson(q);
9872 
9873 	return (0);
9874 }
9875 
9876 /*
9877  * Change the output format (IPv4 vs. IPv6) for a conn_t.
9878  * Note that there is no race since either ip_output function works - it
9879  * is just an optimization to enter the best ip_output routine directly.
9880  */
9881 void
9882 ip_setpktversion(conn_t *connp, boolean_t isv6, boolean_t bump_mib,
9883     ip_stack_t *ipst)
9884 {
9885 	if (isv6)  {
9886 		if (bump_mib) {
9887 			BUMP_MIB(&ipst->ips_ip6_mib,
9888 			    ipIfStatsOutSwitchIPVersion);
9889 		}
9890 		connp->conn_send = ip_output_v6;
9891 		connp->conn_pkt_isv6 = B_TRUE;
9892 	} else {
9893 		if (bump_mib) {
9894 			BUMP_MIB(&ipst->ips_ip_mib,
9895 			    ipIfStatsOutSwitchIPVersion);
9896 		}
9897 		connp->conn_send = ip_output;
9898 		connp->conn_pkt_isv6 = B_FALSE;
9899 	}
9900 
9901 }
9902 
9903 /*
9904  * See if IPsec needs loading because of the options in mp.
9905  */
9906 static boolean_t
9907 ipsec_opt_present(mblk_t *mp)
9908 {
9909 	uint8_t *optcp, *next_optcp, *opt_endcp;
9910 	struct opthdr *opt;
9911 	struct T_opthdr *topt;
9912 	int opthdr_len;
9913 	t_uscalar_t optname, optlevel;
9914 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9915 	ipsec_req_t *ipsr;
9916 
9917 	/*
9918 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9919 	 * return TRUE.
9920 	 */
9921 
9922 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9923 	opt_endcp = optcp + tor->OPT_length;
9924 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9925 		opthdr_len = sizeof (struct T_opthdr);
9926 	} else {		/* O_OPTMGMT_REQ */
9927 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9928 		opthdr_len = sizeof (struct opthdr);
9929 	}
9930 	for (; optcp < opt_endcp; optcp = next_optcp) {
9931 		if (optcp + opthdr_len > opt_endcp)
9932 			return (B_FALSE);	/* Not enough option header. */
9933 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9934 			topt = (struct T_opthdr *)optcp;
9935 			optlevel = topt->level;
9936 			optname = topt->name;
9937 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9938 		} else {
9939 			opt = (struct opthdr *)optcp;
9940 			optlevel = opt->level;
9941 			optname = opt->name;
9942 			next_optcp = optcp + opthdr_len +
9943 			    _TPI_ALIGN_OPT(opt->len);
9944 		}
9945 		if ((next_optcp < optcp) || /* wraparound pointer space */
9946 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9947 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9948 			return (B_FALSE); /* bad option buffer */
9949 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9950 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9951 			/*
9952 			 * Check to see if it's an all-bypass or all-zeroes
9953 			 * IPsec request.  Don't bother loading IPsec if
9954 			 * the socket doesn't want to use it.  (A good example
9955 			 * is a bypass request.)
9956 			 *
9957 			 * Basically, if any of the non-NEVER bits are set,
9958 			 * load IPsec.
9959 			 */
9960 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9961 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9962 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9963 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9964 			    != 0)
9965 				return (B_TRUE);
9966 		}
9967 	}
9968 	return (B_FALSE);
9969 }
9970 
9971 /*
9972  * If conn is is waiting for ipsec to finish loading, kick it.
9973  */
9974 /* ARGSUSED */
9975 static void
9976 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9977 {
9978 	t_scalar_t	optreq_prim;
9979 	mblk_t		*mp;
9980 	cred_t		*cr;
9981 	int		err = 0;
9982 
9983 	/*
9984 	 * This function is called, after ipsec loading is complete.
9985 	 * Since IP checks exclusively and atomically (i.e it prevents
9986 	 * ipsec load from completing until ip_optcom_req completes)
9987 	 * whether ipsec load is complete, there cannot be a race with IP
9988 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
9989 	 */
9990 	mutex_enter(&connp->conn_lock);
9991 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
9992 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
9993 		mp = connp->conn_ipsec_opt_mp;
9994 		connp->conn_ipsec_opt_mp = NULL;
9995 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
9996 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
9997 		mutex_exit(&connp->conn_lock);
9998 
9999 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
10000 
10001 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
10002 		if (optreq_prim == T_OPTMGMT_REQ) {
10003 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10004 			    &ip_opt_obj, B_FALSE);
10005 		} else {
10006 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10007 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10008 			    &ip_opt_obj, B_FALSE);
10009 		}
10010 		if (err != EINPROGRESS)
10011 			CONN_OPER_PENDING_DONE(connp);
10012 		return;
10013 	}
10014 	mutex_exit(&connp->conn_lock);
10015 }
10016 
10017 /*
10018  * Called from the ipsec_loader thread, outside any perimeter, to tell
10019  * ip qenable any of the queues waiting for the ipsec loader to
10020  * complete.
10021  */
10022 void
10023 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10024 {
10025 	netstack_t *ns = ipss->ipsec_netstack;
10026 
10027 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10028 }
10029 
10030 /*
10031  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10032  * determines the grp on which it has to become exclusive, queues the mp
10033  * and sq draining restarts the optmgmt
10034  */
10035 static boolean_t
10036 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10037 {
10038 	conn_t *connp = Q_TO_CONN(q);
10039 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10040 
10041 	/*
10042 	 * Take IPsec requests and treat them special.
10043 	 */
10044 	if (ipsec_opt_present(mp)) {
10045 		/* First check if IPsec is loaded. */
10046 		mutex_enter(&ipss->ipsec_loader_lock);
10047 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10048 			mutex_exit(&ipss->ipsec_loader_lock);
10049 			return (B_FALSE);
10050 		}
10051 		mutex_enter(&connp->conn_lock);
10052 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10053 
10054 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10055 		connp->conn_ipsec_opt_mp = mp;
10056 		mutex_exit(&connp->conn_lock);
10057 		mutex_exit(&ipss->ipsec_loader_lock);
10058 
10059 		ipsec_loader_loadnow(ipss);
10060 		return (B_TRUE);
10061 	}
10062 	return (B_FALSE);
10063 }
10064 
10065 /*
10066  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10067  * all of them are copied to the conn_t. If the req is "zero", the policy is
10068  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10069  * fields.
10070  * We keep only the latest setting of the policy and thus policy setting
10071  * is not incremental/cumulative.
10072  *
10073  * Requests to set policies with multiple alternative actions will
10074  * go through a different API.
10075  */
10076 int
10077 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10078 {
10079 	uint_t ah_req = 0;
10080 	uint_t esp_req = 0;
10081 	uint_t se_req = 0;
10082 	ipsec_selkey_t sel;
10083 	ipsec_act_t *actp = NULL;
10084 	uint_t nact;
10085 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10086 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10087 	ipsec_policy_root_t *pr;
10088 	ipsec_policy_head_t *ph;
10089 	int fam;
10090 	boolean_t is_pol_reset;
10091 	int error = 0;
10092 	netstack_t	*ns = connp->conn_netstack;
10093 	ip_stack_t	*ipst = ns->netstack_ip;
10094 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10095 
10096 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10097 
10098 	/*
10099 	 * The IP_SEC_OPT option does not allow variable length parameters,
10100 	 * hence a request cannot be NULL.
10101 	 */
10102 	if (req == NULL)
10103 		return (EINVAL);
10104 
10105 	ah_req = req->ipsr_ah_req;
10106 	esp_req = req->ipsr_esp_req;
10107 	se_req = req->ipsr_self_encap_req;
10108 
10109 	/* Don't allow setting self-encap without one or more of AH/ESP. */
10110 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
10111 		return (EINVAL);
10112 
10113 	/*
10114 	 * Are we dealing with a request to reset the policy (i.e.
10115 	 * zero requests).
10116 	 */
10117 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10118 	    (esp_req & REQ_MASK) == 0 &&
10119 	    (se_req & REQ_MASK) == 0);
10120 
10121 	if (!is_pol_reset) {
10122 		/*
10123 		 * If we couldn't load IPsec, fail with "protocol
10124 		 * not supported".
10125 		 * IPsec may not have been loaded for a request with zero
10126 		 * policies, so we don't fail in this case.
10127 		 */
10128 		mutex_enter(&ipss->ipsec_loader_lock);
10129 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10130 			mutex_exit(&ipss->ipsec_loader_lock);
10131 			return (EPROTONOSUPPORT);
10132 		}
10133 		mutex_exit(&ipss->ipsec_loader_lock);
10134 
10135 		/*
10136 		 * Test for valid requests. Invalid algorithms
10137 		 * need to be tested by IPsec code because new
10138 		 * algorithms can be added dynamically.
10139 		 */
10140 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10141 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10142 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10143 			return (EINVAL);
10144 		}
10145 
10146 		/*
10147 		 * Only privileged users can issue these
10148 		 * requests.
10149 		 */
10150 		if (((ah_req & IPSEC_PREF_NEVER) ||
10151 		    (esp_req & IPSEC_PREF_NEVER) ||
10152 		    (se_req & IPSEC_PREF_NEVER)) &&
10153 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10154 			return (EPERM);
10155 		}
10156 
10157 		/*
10158 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10159 		 * are mutually exclusive.
10160 		 */
10161 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10162 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10163 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10164 			/* Both of them are set */
10165 			return (EINVAL);
10166 		}
10167 	}
10168 
10169 	mutex_enter(&connp->conn_lock);
10170 
10171 	/*
10172 	 * If we have already cached policies in ip_bind_connected*(), don't
10173 	 * let them change now. We cache policies for connections
10174 	 * whose src,dst [addr, port] is known.
10175 	 */
10176 	if (connp->conn_policy_cached) {
10177 		mutex_exit(&connp->conn_lock);
10178 		return (EINVAL);
10179 	}
10180 
10181 	/*
10182 	 * We have a zero policies, reset the connection policy if already
10183 	 * set. This will cause the connection to inherit the
10184 	 * global policy, if any.
10185 	 */
10186 	if (is_pol_reset) {
10187 		if (connp->conn_policy != NULL) {
10188 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10189 			connp->conn_policy = NULL;
10190 		}
10191 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10192 		connp->conn_in_enforce_policy = B_FALSE;
10193 		connp->conn_out_enforce_policy = B_FALSE;
10194 		mutex_exit(&connp->conn_lock);
10195 		return (0);
10196 	}
10197 
10198 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10199 	    ipst->ips_netstack);
10200 	if (ph == NULL)
10201 		goto enomem;
10202 
10203 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10204 	if (actp == NULL)
10205 		goto enomem;
10206 
10207 	/*
10208 	 * Always allocate IPv4 policy entries, since they can also
10209 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10210 	 */
10211 	bzero(&sel, sizeof (sel));
10212 	sel.ipsl_valid = IPSL_IPV4;
10213 
10214 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10215 	    ipst->ips_netstack);
10216 	if (pin4 == NULL)
10217 		goto enomem;
10218 
10219 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10220 	    ipst->ips_netstack);
10221 	if (pout4 == NULL)
10222 		goto enomem;
10223 
10224 	if (connp->conn_af_isv6) {
10225 		/*
10226 		 * We're looking at a v6 socket, also allocate the
10227 		 * v6-specific entries...
10228 		 */
10229 		sel.ipsl_valid = IPSL_IPV6;
10230 		pin6 = ipsec_policy_create(&sel, actp, nact,
10231 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10232 		if (pin6 == NULL)
10233 			goto enomem;
10234 
10235 		pout6 = ipsec_policy_create(&sel, actp, nact,
10236 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10237 		if (pout6 == NULL)
10238 			goto enomem;
10239 
10240 		/*
10241 		 * .. and file them away in the right place.
10242 		 */
10243 		fam = IPSEC_AF_V6;
10244 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10245 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10246 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10247 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10248 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10249 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10250 	}
10251 
10252 	ipsec_actvec_free(actp, nact);
10253 
10254 	/*
10255 	 * File the v4 policies.
10256 	 */
10257 	fam = IPSEC_AF_V4;
10258 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10259 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10260 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10261 
10262 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10263 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10264 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10265 
10266 	/*
10267 	 * If the requests need security, set enforce_policy.
10268 	 * If the requests are IPSEC_PREF_NEVER, one should
10269 	 * still set conn_out_enforce_policy so that an ipsec_out
10270 	 * gets attached in ip_wput. This is needed so that
10271 	 * for connections that we don't cache policy in ip_bind,
10272 	 * if global policy matches in ip_wput_attach_policy, we
10273 	 * don't wrongly inherit global policy. Similarly, we need
10274 	 * to set conn_in_enforce_policy also so that we don't verify
10275 	 * policy wrongly.
10276 	 */
10277 	if ((ah_req & REQ_MASK) != 0 ||
10278 	    (esp_req & REQ_MASK) != 0 ||
10279 	    (se_req & REQ_MASK) != 0) {
10280 		connp->conn_in_enforce_policy = B_TRUE;
10281 		connp->conn_out_enforce_policy = B_TRUE;
10282 		connp->conn_flags |= IPCL_CHECK_POLICY;
10283 	}
10284 
10285 	mutex_exit(&connp->conn_lock);
10286 	return (error);
10287 #undef REQ_MASK
10288 
10289 	/*
10290 	 * Common memory-allocation-failure exit path.
10291 	 */
10292 enomem:
10293 	mutex_exit(&connp->conn_lock);
10294 	if (actp != NULL)
10295 		ipsec_actvec_free(actp, nact);
10296 	if (pin4 != NULL)
10297 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10298 	if (pout4 != NULL)
10299 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10300 	if (pin6 != NULL)
10301 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10302 	if (pout6 != NULL)
10303 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10304 	return (ENOMEM);
10305 }
10306 
10307 /*
10308  * Only for options that pass in an IP addr. Currently only V4 options
10309  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10310  * So this function assumes level is IPPROTO_IP
10311  */
10312 int
10313 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10314     mblk_t *first_mp)
10315 {
10316 	ipif_t *ipif = NULL;
10317 	int error;
10318 	ill_t *ill;
10319 	int zoneid;
10320 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10321 
10322 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10323 
10324 	if (addr != INADDR_ANY || checkonly) {
10325 		ASSERT(connp != NULL);
10326 		zoneid = IPCL_ZONEID(connp);
10327 		if (option == IP_NEXTHOP) {
10328 			ipif = ipif_lookup_onlink_addr(addr,
10329 			    connp->conn_zoneid, ipst);
10330 		} else {
10331 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10332 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10333 			    &error, ipst);
10334 		}
10335 		if (ipif == NULL) {
10336 			if (error == EINPROGRESS)
10337 				return (error);
10338 			else if ((option == IP_MULTICAST_IF) ||
10339 			    (option == IP_NEXTHOP))
10340 				return (EHOSTUNREACH);
10341 			else
10342 				return (EINVAL);
10343 		} else if (checkonly) {
10344 			if (option == IP_MULTICAST_IF) {
10345 				ill = ipif->ipif_ill;
10346 				/* not supported by the virtual network iface */
10347 				if (IS_VNI(ill)) {
10348 					ipif_refrele(ipif);
10349 					return (EINVAL);
10350 				}
10351 			}
10352 			ipif_refrele(ipif);
10353 			return (0);
10354 		}
10355 		ill = ipif->ipif_ill;
10356 		mutex_enter(&connp->conn_lock);
10357 		mutex_enter(&ill->ill_lock);
10358 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10359 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10360 			mutex_exit(&ill->ill_lock);
10361 			mutex_exit(&connp->conn_lock);
10362 			ipif_refrele(ipif);
10363 			return (option == IP_MULTICAST_IF ?
10364 			    EHOSTUNREACH : EINVAL);
10365 		}
10366 	} else {
10367 		mutex_enter(&connp->conn_lock);
10368 	}
10369 
10370 	/* None of the options below are supported on the VNI */
10371 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10372 		mutex_exit(&ill->ill_lock);
10373 		mutex_exit(&connp->conn_lock);
10374 		ipif_refrele(ipif);
10375 		return (EINVAL);
10376 	}
10377 
10378 	switch (option) {
10379 	case IP_DONTFAILOVER_IF:
10380 		/*
10381 		 * This option is used by in.mpathd to ensure
10382 		 * that IPMP probe packets only go out on the
10383 		 * test interfaces. in.mpathd sets this option
10384 		 * on the non-failover interfaces.
10385 		 * For backward compatibility, this option
10386 		 * implicitly sets IP_MULTICAST_IF, as used
10387 		 * be done in bind(), so that ip_wput gets
10388 		 * this ipif to send mcast packets.
10389 		 */
10390 		if (ipif != NULL) {
10391 			ASSERT(addr != INADDR_ANY);
10392 			connp->conn_nofailover_ill = ipif->ipif_ill;
10393 			connp->conn_multicast_ipif = ipif;
10394 		} else {
10395 			ASSERT(addr == INADDR_ANY);
10396 			connp->conn_nofailover_ill = NULL;
10397 			connp->conn_multicast_ipif = NULL;
10398 		}
10399 		break;
10400 
10401 	case IP_MULTICAST_IF:
10402 		connp->conn_multicast_ipif = ipif;
10403 		break;
10404 	case IP_NEXTHOP:
10405 		connp->conn_nexthop_v4 = addr;
10406 		connp->conn_nexthop_set = B_TRUE;
10407 		break;
10408 	}
10409 
10410 	if (ipif != NULL) {
10411 		mutex_exit(&ill->ill_lock);
10412 		mutex_exit(&connp->conn_lock);
10413 		ipif_refrele(ipif);
10414 		return (0);
10415 	}
10416 	mutex_exit(&connp->conn_lock);
10417 	/* We succeded in cleared the option */
10418 	return (0);
10419 }
10420 
10421 /*
10422  * For options that pass in an ifindex specifying the ill. V6 options always
10423  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10424  */
10425 int
10426 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10427     int level, int option, mblk_t *first_mp)
10428 {
10429 	ill_t *ill = NULL;
10430 	int error = 0;
10431 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10432 
10433 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10434 	if (ifindex != 0) {
10435 		ASSERT(connp != NULL);
10436 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10437 		    first_mp, ip_restart_optmgmt, &error, ipst);
10438 		if (ill != NULL) {
10439 			if (checkonly) {
10440 				/* not supported by the virtual network iface */
10441 				if (IS_VNI(ill)) {
10442 					ill_refrele(ill);
10443 					return (EINVAL);
10444 				}
10445 				ill_refrele(ill);
10446 				return (0);
10447 			}
10448 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10449 			    0, NULL)) {
10450 				ill_refrele(ill);
10451 				ill = NULL;
10452 				mutex_enter(&connp->conn_lock);
10453 				goto setit;
10454 			}
10455 			mutex_enter(&connp->conn_lock);
10456 			mutex_enter(&ill->ill_lock);
10457 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10458 				mutex_exit(&ill->ill_lock);
10459 				mutex_exit(&connp->conn_lock);
10460 				ill_refrele(ill);
10461 				ill = NULL;
10462 				mutex_enter(&connp->conn_lock);
10463 			}
10464 			goto setit;
10465 		} else if (error == EINPROGRESS) {
10466 			return (error);
10467 		} else {
10468 			error = 0;
10469 		}
10470 	}
10471 	mutex_enter(&connp->conn_lock);
10472 setit:
10473 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10474 
10475 	/*
10476 	 * The options below assume that the ILL (if any) transmits and/or
10477 	 * receives traffic. Neither of which is true for the virtual network
10478 	 * interface, so fail setting these on a VNI.
10479 	 */
10480 	if (IS_VNI(ill)) {
10481 		ASSERT(ill != NULL);
10482 		mutex_exit(&ill->ill_lock);
10483 		mutex_exit(&connp->conn_lock);
10484 		ill_refrele(ill);
10485 		return (EINVAL);
10486 	}
10487 
10488 	if (level == IPPROTO_IP) {
10489 		switch (option) {
10490 		case IP_BOUND_IF:
10491 			connp->conn_incoming_ill = ill;
10492 			connp->conn_outgoing_ill = ill;
10493 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10494 			    0 : ifindex;
10495 			break;
10496 
10497 		case IP_MULTICAST_IF:
10498 			/*
10499 			 * This option is an internal special. The socket
10500 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10501 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10502 			 * specifies an ifindex and we try first on V6 ill's.
10503 			 * If we don't find one, we they try using on v4 ill's
10504 			 * intenally and we come here.
10505 			 */
10506 			if (!checkonly && ill != NULL) {
10507 				ipif_t	*ipif;
10508 				ipif = ill->ill_ipif;
10509 
10510 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10511 					mutex_exit(&ill->ill_lock);
10512 					mutex_exit(&connp->conn_lock);
10513 					ill_refrele(ill);
10514 					ill = NULL;
10515 					mutex_enter(&connp->conn_lock);
10516 				} else {
10517 					connp->conn_multicast_ipif = ipif;
10518 				}
10519 			}
10520 			break;
10521 
10522 		case IP_DHCPINIT_IF:
10523 			if (connp->conn_dhcpinit_ill != NULL) {
10524 				/*
10525 				 * We've locked the conn so conn_cleanup_ill()
10526 				 * cannot clear conn_dhcpinit_ill -- so it's
10527 				 * safe to access the ill.
10528 				 */
10529 				ill_t *oill = connp->conn_dhcpinit_ill;
10530 
10531 				ASSERT(oill->ill_dhcpinit != 0);
10532 				atomic_dec_32(&oill->ill_dhcpinit);
10533 				connp->conn_dhcpinit_ill = NULL;
10534 			}
10535 
10536 			if (ill != NULL) {
10537 				connp->conn_dhcpinit_ill = ill;
10538 				atomic_inc_32(&ill->ill_dhcpinit);
10539 			}
10540 			break;
10541 		}
10542 	} else {
10543 		switch (option) {
10544 		case IPV6_BOUND_IF:
10545 			connp->conn_incoming_ill = ill;
10546 			connp->conn_outgoing_ill = ill;
10547 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10548 			    0 : ifindex;
10549 			break;
10550 
10551 		case IPV6_BOUND_PIF:
10552 			/*
10553 			 * Limit all transmit to this ill.
10554 			 * Unlike IPV6_BOUND_IF, using this option
10555 			 * prevents load spreading and failover from
10556 			 * happening when the interface is part of the
10557 			 * group. That's why we don't need to remember
10558 			 * the ifindex in orig_bound_ifindex as in
10559 			 * IPV6_BOUND_IF.
10560 			 */
10561 			connp->conn_outgoing_pill = ill;
10562 			break;
10563 
10564 		case IPV6_DONTFAILOVER_IF:
10565 			/*
10566 			 * This option is used by in.mpathd to ensure
10567 			 * that IPMP probe packets only go out on the
10568 			 * test interfaces. in.mpathd sets this option
10569 			 * on the non-failover interfaces.
10570 			 */
10571 			connp->conn_nofailover_ill = ill;
10572 			/*
10573 			 * For backward compatibility, this option
10574 			 * implicitly sets ip_multicast_ill as used in
10575 			 * IPV6_MULTICAST_IF so that ip_wput gets
10576 			 * this ill to send mcast packets.
10577 			 */
10578 			connp->conn_multicast_ill = ill;
10579 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10580 			    0 : ifindex;
10581 			break;
10582 
10583 		case IPV6_MULTICAST_IF:
10584 			/*
10585 			 * Set conn_multicast_ill to be the IPv6 ill.
10586 			 * Set conn_multicast_ipif to be an IPv4 ipif
10587 			 * for ifindex to make IPv4 mapped addresses
10588 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10589 			 * Even if no IPv6 ill exists for the ifindex
10590 			 * we need to check for an IPv4 ifindex in order
10591 			 * for this to work with mapped addresses. In that
10592 			 * case only set conn_multicast_ipif.
10593 			 */
10594 			if (!checkonly) {
10595 				if (ifindex == 0) {
10596 					connp->conn_multicast_ill = NULL;
10597 					connp->conn_orig_multicast_ifindex = 0;
10598 					connp->conn_multicast_ipif = NULL;
10599 				} else if (ill != NULL) {
10600 					connp->conn_multicast_ill = ill;
10601 					connp->conn_orig_multicast_ifindex =
10602 					    ifindex;
10603 				}
10604 			}
10605 			break;
10606 		}
10607 	}
10608 
10609 	if (ill != NULL) {
10610 		mutex_exit(&ill->ill_lock);
10611 		mutex_exit(&connp->conn_lock);
10612 		ill_refrele(ill);
10613 		return (0);
10614 	}
10615 	mutex_exit(&connp->conn_lock);
10616 	/*
10617 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10618 	 * locate the ill and could not set the option (ifindex != 0)
10619 	 */
10620 	return (ifindex == 0 ? 0 : EINVAL);
10621 }
10622 
10623 /* This routine sets socket options. */
10624 /* ARGSUSED */
10625 int
10626 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10627     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10628     void *dummy, cred_t *cr, mblk_t *first_mp)
10629 {
10630 	int		*i1 = (int *)invalp;
10631 	conn_t		*connp = Q_TO_CONN(q);
10632 	int		error = 0;
10633 	boolean_t	checkonly;
10634 	ire_t		*ire;
10635 	boolean_t	found;
10636 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10637 
10638 	switch (optset_context) {
10639 
10640 	case SETFN_OPTCOM_CHECKONLY:
10641 		checkonly = B_TRUE;
10642 		/*
10643 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10644 		 * inlen != 0 implies value supplied and
10645 		 * 	we have to "pretend" to set it.
10646 		 * inlen == 0 implies that there is no
10647 		 * 	value part in T_CHECK request and just validation
10648 		 * done elsewhere should be enough, we just return here.
10649 		 */
10650 		if (inlen == 0) {
10651 			*outlenp = 0;
10652 			return (0);
10653 		}
10654 		break;
10655 	case SETFN_OPTCOM_NEGOTIATE:
10656 	case SETFN_UD_NEGOTIATE:
10657 	case SETFN_CONN_NEGOTIATE:
10658 		checkonly = B_FALSE;
10659 		break;
10660 	default:
10661 		/*
10662 		 * We should never get here
10663 		 */
10664 		*outlenp = 0;
10665 		return (EINVAL);
10666 	}
10667 
10668 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10669 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10670 
10671 	/*
10672 	 * For fixed length options, no sanity check
10673 	 * of passed in length is done. It is assumed *_optcom_req()
10674 	 * routines do the right thing.
10675 	 */
10676 
10677 	switch (level) {
10678 	case SOL_SOCKET:
10679 		/*
10680 		 * conn_lock protects the bitfields, and is used to
10681 		 * set the fields atomically.
10682 		 */
10683 		switch (name) {
10684 		case SO_BROADCAST:
10685 			if (!checkonly) {
10686 				/* TODO: use value someplace? */
10687 				mutex_enter(&connp->conn_lock);
10688 				connp->conn_broadcast = *i1 ? 1 : 0;
10689 				mutex_exit(&connp->conn_lock);
10690 			}
10691 			break;	/* goto sizeof (int) option return */
10692 		case SO_USELOOPBACK:
10693 			if (!checkonly) {
10694 				/* TODO: use value someplace? */
10695 				mutex_enter(&connp->conn_lock);
10696 				connp->conn_loopback = *i1 ? 1 : 0;
10697 				mutex_exit(&connp->conn_lock);
10698 			}
10699 			break;	/* goto sizeof (int) option return */
10700 		case SO_DONTROUTE:
10701 			if (!checkonly) {
10702 				mutex_enter(&connp->conn_lock);
10703 				connp->conn_dontroute = *i1 ? 1 : 0;
10704 				mutex_exit(&connp->conn_lock);
10705 			}
10706 			break;	/* goto sizeof (int) option return */
10707 		case SO_REUSEADDR:
10708 			if (!checkonly) {
10709 				mutex_enter(&connp->conn_lock);
10710 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10711 				mutex_exit(&connp->conn_lock);
10712 			}
10713 			break;	/* goto sizeof (int) option return */
10714 		case SO_PROTOTYPE:
10715 			if (!checkonly) {
10716 				mutex_enter(&connp->conn_lock);
10717 				connp->conn_proto = *i1;
10718 				mutex_exit(&connp->conn_lock);
10719 			}
10720 			break;	/* goto sizeof (int) option return */
10721 		case SO_ALLZONES:
10722 			if (!checkonly) {
10723 				mutex_enter(&connp->conn_lock);
10724 				if (IPCL_IS_BOUND(connp)) {
10725 					mutex_exit(&connp->conn_lock);
10726 					return (EINVAL);
10727 				}
10728 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10729 				mutex_exit(&connp->conn_lock);
10730 			}
10731 			break;	/* goto sizeof (int) option return */
10732 		case SO_ANON_MLP:
10733 			if (!checkonly) {
10734 				mutex_enter(&connp->conn_lock);
10735 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10736 				mutex_exit(&connp->conn_lock);
10737 			}
10738 			break;	/* goto sizeof (int) option return */
10739 		case SO_MAC_EXEMPT:
10740 			if (secpolicy_net_mac_aware(cr) != 0 ||
10741 			    IPCL_IS_BOUND(connp))
10742 				return (EACCES);
10743 			if (!checkonly) {
10744 				mutex_enter(&connp->conn_lock);
10745 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10746 				mutex_exit(&connp->conn_lock);
10747 			}
10748 			break;	/* goto sizeof (int) option return */
10749 		default:
10750 			/*
10751 			 * "soft" error (negative)
10752 			 * option not handled at this level
10753 			 * Note: Do not modify *outlenp
10754 			 */
10755 			return (-EINVAL);
10756 		}
10757 		break;
10758 	case IPPROTO_IP:
10759 		switch (name) {
10760 		case IP_NEXTHOP:
10761 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10762 				return (EPERM);
10763 			/* FALLTHRU */
10764 		case IP_MULTICAST_IF:
10765 		case IP_DONTFAILOVER_IF: {
10766 			ipaddr_t addr = *i1;
10767 
10768 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10769 			    first_mp);
10770 			if (error != 0)
10771 				return (error);
10772 			break;	/* goto sizeof (int) option return */
10773 		}
10774 
10775 		case IP_MULTICAST_TTL:
10776 			/* Recorded in transport above IP */
10777 			*outvalp = *invalp;
10778 			*outlenp = sizeof (uchar_t);
10779 			return (0);
10780 		case IP_MULTICAST_LOOP:
10781 			if (!checkonly) {
10782 				mutex_enter(&connp->conn_lock);
10783 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10784 				mutex_exit(&connp->conn_lock);
10785 			}
10786 			*outvalp = *invalp;
10787 			*outlenp = sizeof (uchar_t);
10788 			return (0);
10789 		case IP_ADD_MEMBERSHIP:
10790 		case MCAST_JOIN_GROUP:
10791 		case IP_DROP_MEMBERSHIP:
10792 		case MCAST_LEAVE_GROUP: {
10793 			struct ip_mreq *mreqp;
10794 			struct group_req *greqp;
10795 			ire_t *ire;
10796 			boolean_t done = B_FALSE;
10797 			ipaddr_t group, ifaddr;
10798 			struct sockaddr_in *sin;
10799 			uint32_t *ifindexp;
10800 			boolean_t mcast_opt = B_TRUE;
10801 			mcast_record_t fmode;
10802 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10803 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10804 
10805 			switch (name) {
10806 			case IP_ADD_MEMBERSHIP:
10807 				mcast_opt = B_FALSE;
10808 				/* FALLTHRU */
10809 			case MCAST_JOIN_GROUP:
10810 				fmode = MODE_IS_EXCLUDE;
10811 				optfn = ip_opt_add_group;
10812 				break;
10813 
10814 			case IP_DROP_MEMBERSHIP:
10815 				mcast_opt = B_FALSE;
10816 				/* FALLTHRU */
10817 			case MCAST_LEAVE_GROUP:
10818 				fmode = MODE_IS_INCLUDE;
10819 				optfn = ip_opt_delete_group;
10820 				break;
10821 			}
10822 
10823 			if (mcast_opt) {
10824 				greqp = (struct group_req *)i1;
10825 				sin = (struct sockaddr_in *)&greqp->gr_group;
10826 				if (sin->sin_family != AF_INET) {
10827 					*outlenp = 0;
10828 					return (ENOPROTOOPT);
10829 				}
10830 				group = (ipaddr_t)sin->sin_addr.s_addr;
10831 				ifaddr = INADDR_ANY;
10832 				ifindexp = &greqp->gr_interface;
10833 			} else {
10834 				mreqp = (struct ip_mreq *)i1;
10835 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10836 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10837 				ifindexp = NULL;
10838 			}
10839 
10840 			/*
10841 			 * In the multirouting case, we need to replicate
10842 			 * the request on all interfaces that will take part
10843 			 * in replication.  We do so because multirouting is
10844 			 * reflective, thus we will probably receive multi-
10845 			 * casts on those interfaces.
10846 			 * The ip_multirt_apply_membership() succeeds if the
10847 			 * operation succeeds on at least one interface.
10848 			 */
10849 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10850 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10851 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10852 			if (ire != NULL) {
10853 				if (ire->ire_flags & RTF_MULTIRT) {
10854 					error = ip_multirt_apply_membership(
10855 					    optfn, ire, connp, checkonly, group,
10856 					    fmode, INADDR_ANY, first_mp);
10857 					done = B_TRUE;
10858 				}
10859 				ire_refrele(ire);
10860 			}
10861 			if (!done) {
10862 				error = optfn(connp, checkonly, group, ifaddr,
10863 				    ifindexp, fmode, INADDR_ANY, first_mp);
10864 			}
10865 			if (error) {
10866 				/*
10867 				 * EINPROGRESS is a soft error, needs retry
10868 				 * so don't make *outlenp zero.
10869 				 */
10870 				if (error != EINPROGRESS)
10871 					*outlenp = 0;
10872 				return (error);
10873 			}
10874 			/* OK return - copy input buffer into output buffer */
10875 			if (invalp != outvalp) {
10876 				/* don't trust bcopy for identical src/dst */
10877 				bcopy(invalp, outvalp, inlen);
10878 			}
10879 			*outlenp = inlen;
10880 			return (0);
10881 		}
10882 		case IP_BLOCK_SOURCE:
10883 		case IP_UNBLOCK_SOURCE:
10884 		case IP_ADD_SOURCE_MEMBERSHIP:
10885 		case IP_DROP_SOURCE_MEMBERSHIP:
10886 		case MCAST_BLOCK_SOURCE:
10887 		case MCAST_UNBLOCK_SOURCE:
10888 		case MCAST_JOIN_SOURCE_GROUP:
10889 		case MCAST_LEAVE_SOURCE_GROUP: {
10890 			struct ip_mreq_source *imreqp;
10891 			struct group_source_req *gsreqp;
10892 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10893 			uint32_t ifindex = 0;
10894 			mcast_record_t fmode;
10895 			struct sockaddr_in *sin;
10896 			ire_t *ire;
10897 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10898 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10899 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10900 
10901 			switch (name) {
10902 			case IP_BLOCK_SOURCE:
10903 				mcast_opt = B_FALSE;
10904 				/* FALLTHRU */
10905 			case MCAST_BLOCK_SOURCE:
10906 				fmode = MODE_IS_EXCLUDE;
10907 				optfn = ip_opt_add_group;
10908 				break;
10909 
10910 			case IP_UNBLOCK_SOURCE:
10911 				mcast_opt = B_FALSE;
10912 				/* FALLTHRU */
10913 			case MCAST_UNBLOCK_SOURCE:
10914 				fmode = MODE_IS_EXCLUDE;
10915 				optfn = ip_opt_delete_group;
10916 				break;
10917 
10918 			case IP_ADD_SOURCE_MEMBERSHIP:
10919 				mcast_opt = B_FALSE;
10920 				/* FALLTHRU */
10921 			case MCAST_JOIN_SOURCE_GROUP:
10922 				fmode = MODE_IS_INCLUDE;
10923 				optfn = ip_opt_add_group;
10924 				break;
10925 
10926 			case IP_DROP_SOURCE_MEMBERSHIP:
10927 				mcast_opt = B_FALSE;
10928 				/* FALLTHRU */
10929 			case MCAST_LEAVE_SOURCE_GROUP:
10930 				fmode = MODE_IS_INCLUDE;
10931 				optfn = ip_opt_delete_group;
10932 				break;
10933 			}
10934 
10935 			if (mcast_opt) {
10936 				gsreqp = (struct group_source_req *)i1;
10937 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10938 					*outlenp = 0;
10939 					return (ENOPROTOOPT);
10940 				}
10941 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10942 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10943 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10944 				src = (ipaddr_t)sin->sin_addr.s_addr;
10945 				ifindex = gsreqp->gsr_interface;
10946 			} else {
10947 				imreqp = (struct ip_mreq_source *)i1;
10948 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10949 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10950 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10951 			}
10952 
10953 			/*
10954 			 * In the multirouting case, we need to replicate
10955 			 * the request as noted in the mcast cases above.
10956 			 */
10957 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10958 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10959 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10960 			if (ire != NULL) {
10961 				if (ire->ire_flags & RTF_MULTIRT) {
10962 					error = ip_multirt_apply_membership(
10963 					    optfn, ire, connp, checkonly, grp,
10964 					    fmode, src, first_mp);
10965 					done = B_TRUE;
10966 				}
10967 				ire_refrele(ire);
10968 			}
10969 			if (!done) {
10970 				error = optfn(connp, checkonly, grp, ifaddr,
10971 				    &ifindex, fmode, src, first_mp);
10972 			}
10973 			if (error != 0) {
10974 				/*
10975 				 * EINPROGRESS is a soft error, needs retry
10976 				 * so don't make *outlenp zero.
10977 				 */
10978 				if (error != EINPROGRESS)
10979 					*outlenp = 0;
10980 				return (error);
10981 			}
10982 			/* OK return - copy input buffer into output buffer */
10983 			if (invalp != outvalp) {
10984 				bcopy(invalp, outvalp, inlen);
10985 			}
10986 			*outlenp = inlen;
10987 			return (0);
10988 		}
10989 		case IP_SEC_OPT:
10990 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10991 			if (error != 0) {
10992 				*outlenp = 0;
10993 				return (error);
10994 			}
10995 			break;
10996 		case IP_HDRINCL:
10997 		case IP_OPTIONS:
10998 		case T_IP_OPTIONS:
10999 		case IP_TOS:
11000 		case T_IP_TOS:
11001 		case IP_TTL:
11002 		case IP_RECVDSTADDR:
11003 		case IP_RECVOPTS:
11004 			/* OK return - copy input buffer into output buffer */
11005 			if (invalp != outvalp) {
11006 				/* don't trust bcopy for identical src/dst */
11007 				bcopy(invalp, outvalp, inlen);
11008 			}
11009 			*outlenp = inlen;
11010 			return (0);
11011 		case IP_RECVIF:
11012 			/* Retrieve the inbound interface index */
11013 			if (!checkonly) {
11014 				mutex_enter(&connp->conn_lock);
11015 				connp->conn_recvif = *i1 ? 1 : 0;
11016 				mutex_exit(&connp->conn_lock);
11017 			}
11018 			break;	/* goto sizeof (int) option return */
11019 		case IP_RECVPKTINFO:
11020 			if (!checkonly) {
11021 				mutex_enter(&connp->conn_lock);
11022 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11023 				mutex_exit(&connp->conn_lock);
11024 			}
11025 			break;	/* goto sizeof (int) option return */
11026 		case IP_RECVSLLA:
11027 			/* Retrieve the source link layer address */
11028 			if (!checkonly) {
11029 				mutex_enter(&connp->conn_lock);
11030 				connp->conn_recvslla = *i1 ? 1 : 0;
11031 				mutex_exit(&connp->conn_lock);
11032 			}
11033 			break;	/* goto sizeof (int) option return */
11034 		case MRT_INIT:
11035 		case MRT_DONE:
11036 		case MRT_ADD_VIF:
11037 		case MRT_DEL_VIF:
11038 		case MRT_ADD_MFC:
11039 		case MRT_DEL_MFC:
11040 		case MRT_ASSERT:
11041 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11042 				*outlenp = 0;
11043 				return (error);
11044 			}
11045 			error = ip_mrouter_set((int)name, q, checkonly,
11046 			    (uchar_t *)invalp, inlen, first_mp);
11047 			if (error) {
11048 				*outlenp = 0;
11049 				return (error);
11050 			}
11051 			/* OK return - copy input buffer into output buffer */
11052 			if (invalp != outvalp) {
11053 				/* don't trust bcopy for identical src/dst */
11054 				bcopy(invalp, outvalp, inlen);
11055 			}
11056 			*outlenp = inlen;
11057 			return (0);
11058 		case IP_BOUND_IF:
11059 		case IP_DHCPINIT_IF:
11060 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11061 			    level, name, first_mp);
11062 			if (error != 0)
11063 				return (error);
11064 			break; 		/* goto sizeof (int) option return */
11065 
11066 		case IP_UNSPEC_SRC:
11067 			/* Allow sending with a zero source address */
11068 			if (!checkonly) {
11069 				mutex_enter(&connp->conn_lock);
11070 				connp->conn_unspec_src = *i1 ? 1 : 0;
11071 				mutex_exit(&connp->conn_lock);
11072 			}
11073 			break;	/* goto sizeof (int) option return */
11074 		default:
11075 			/*
11076 			 * "soft" error (negative)
11077 			 * option not handled at this level
11078 			 * Note: Do not modify *outlenp
11079 			 */
11080 			return (-EINVAL);
11081 		}
11082 		break;
11083 	case IPPROTO_IPV6:
11084 		switch (name) {
11085 		case IPV6_BOUND_IF:
11086 		case IPV6_BOUND_PIF:
11087 		case IPV6_DONTFAILOVER_IF:
11088 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11089 			    level, name, first_mp);
11090 			if (error != 0)
11091 				return (error);
11092 			break; 		/* goto sizeof (int) option return */
11093 
11094 		case IPV6_MULTICAST_IF:
11095 			/*
11096 			 * The only possible errors are EINPROGRESS and
11097 			 * EINVAL. EINPROGRESS will be restarted and is not
11098 			 * a hard error. We call this option on both V4 and V6
11099 			 * If both return EINVAL, then this call returns
11100 			 * EINVAL. If at least one of them succeeds we
11101 			 * return success.
11102 			 */
11103 			found = B_FALSE;
11104 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11105 			    level, name, first_mp);
11106 			if (error == EINPROGRESS)
11107 				return (error);
11108 			if (error == 0)
11109 				found = B_TRUE;
11110 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11111 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11112 			if (error == 0)
11113 				found = B_TRUE;
11114 			if (!found)
11115 				return (error);
11116 			break; 		/* goto sizeof (int) option return */
11117 
11118 		case IPV6_MULTICAST_HOPS:
11119 			/* Recorded in transport above IP */
11120 			break;	/* goto sizeof (int) option return */
11121 		case IPV6_MULTICAST_LOOP:
11122 			if (!checkonly) {
11123 				mutex_enter(&connp->conn_lock);
11124 				connp->conn_multicast_loop = *i1;
11125 				mutex_exit(&connp->conn_lock);
11126 			}
11127 			break;	/* goto sizeof (int) option return */
11128 		case IPV6_JOIN_GROUP:
11129 		case MCAST_JOIN_GROUP:
11130 		case IPV6_LEAVE_GROUP:
11131 		case MCAST_LEAVE_GROUP: {
11132 			struct ipv6_mreq *ip_mreqp;
11133 			struct group_req *greqp;
11134 			ire_t *ire;
11135 			boolean_t done = B_FALSE;
11136 			in6_addr_t groupv6;
11137 			uint32_t ifindex;
11138 			boolean_t mcast_opt = B_TRUE;
11139 			mcast_record_t fmode;
11140 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11141 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11142 
11143 			switch (name) {
11144 			case IPV6_JOIN_GROUP:
11145 				mcast_opt = B_FALSE;
11146 				/* FALLTHRU */
11147 			case MCAST_JOIN_GROUP:
11148 				fmode = MODE_IS_EXCLUDE;
11149 				optfn = ip_opt_add_group_v6;
11150 				break;
11151 
11152 			case IPV6_LEAVE_GROUP:
11153 				mcast_opt = B_FALSE;
11154 				/* FALLTHRU */
11155 			case MCAST_LEAVE_GROUP:
11156 				fmode = MODE_IS_INCLUDE;
11157 				optfn = ip_opt_delete_group_v6;
11158 				break;
11159 			}
11160 
11161 			if (mcast_opt) {
11162 				struct sockaddr_in *sin;
11163 				struct sockaddr_in6 *sin6;
11164 				greqp = (struct group_req *)i1;
11165 				if (greqp->gr_group.ss_family == AF_INET) {
11166 					sin = (struct sockaddr_in *)
11167 					    &(greqp->gr_group);
11168 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11169 					    &groupv6);
11170 				} else {
11171 					sin6 = (struct sockaddr_in6 *)
11172 					    &(greqp->gr_group);
11173 					groupv6 = sin6->sin6_addr;
11174 				}
11175 				ifindex = greqp->gr_interface;
11176 			} else {
11177 				ip_mreqp = (struct ipv6_mreq *)i1;
11178 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11179 				ifindex = ip_mreqp->ipv6mr_interface;
11180 			}
11181 			/*
11182 			 * In the multirouting case, we need to replicate
11183 			 * the request on all interfaces that will take part
11184 			 * in replication.  We do so because multirouting is
11185 			 * reflective, thus we will probably receive multi-
11186 			 * casts on those interfaces.
11187 			 * The ip_multirt_apply_membership_v6() succeeds if
11188 			 * the operation succeeds on at least one interface.
11189 			 */
11190 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11191 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11192 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11193 			if (ire != NULL) {
11194 				if (ire->ire_flags & RTF_MULTIRT) {
11195 					error = ip_multirt_apply_membership_v6(
11196 					    optfn, ire, connp, checkonly,
11197 					    &groupv6, fmode, &ipv6_all_zeros,
11198 					    first_mp);
11199 					done = B_TRUE;
11200 				}
11201 				ire_refrele(ire);
11202 			}
11203 			if (!done) {
11204 				error = optfn(connp, checkonly, &groupv6,
11205 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11206 			}
11207 			if (error) {
11208 				/*
11209 				 * EINPROGRESS is a soft error, needs retry
11210 				 * so don't make *outlenp zero.
11211 				 */
11212 				if (error != EINPROGRESS)
11213 					*outlenp = 0;
11214 				return (error);
11215 			}
11216 			/* OK return - copy input buffer into output buffer */
11217 			if (invalp != outvalp) {
11218 				/* don't trust bcopy for identical src/dst */
11219 				bcopy(invalp, outvalp, inlen);
11220 			}
11221 			*outlenp = inlen;
11222 			return (0);
11223 		}
11224 		case MCAST_BLOCK_SOURCE:
11225 		case MCAST_UNBLOCK_SOURCE:
11226 		case MCAST_JOIN_SOURCE_GROUP:
11227 		case MCAST_LEAVE_SOURCE_GROUP: {
11228 			struct group_source_req *gsreqp;
11229 			in6_addr_t v6grp, v6src;
11230 			uint32_t ifindex;
11231 			mcast_record_t fmode;
11232 			ire_t *ire;
11233 			boolean_t done = B_FALSE;
11234 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11235 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11236 
11237 			switch (name) {
11238 			case MCAST_BLOCK_SOURCE:
11239 				fmode = MODE_IS_EXCLUDE;
11240 				optfn = ip_opt_add_group_v6;
11241 				break;
11242 			case MCAST_UNBLOCK_SOURCE:
11243 				fmode = MODE_IS_EXCLUDE;
11244 				optfn = ip_opt_delete_group_v6;
11245 				break;
11246 			case MCAST_JOIN_SOURCE_GROUP:
11247 				fmode = MODE_IS_INCLUDE;
11248 				optfn = ip_opt_add_group_v6;
11249 				break;
11250 			case MCAST_LEAVE_SOURCE_GROUP:
11251 				fmode = MODE_IS_INCLUDE;
11252 				optfn = ip_opt_delete_group_v6;
11253 				break;
11254 			}
11255 
11256 			gsreqp = (struct group_source_req *)i1;
11257 			ifindex = gsreqp->gsr_interface;
11258 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11259 				struct sockaddr_in *s;
11260 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11261 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11262 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11263 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11264 			} else {
11265 				struct sockaddr_in6 *s6;
11266 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11267 				v6grp = s6->sin6_addr;
11268 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11269 				v6src = s6->sin6_addr;
11270 			}
11271 
11272 			/*
11273 			 * In the multirouting case, we need to replicate
11274 			 * the request as noted in the mcast cases above.
11275 			 */
11276 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11277 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11278 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11279 			if (ire != NULL) {
11280 				if (ire->ire_flags & RTF_MULTIRT) {
11281 					error = ip_multirt_apply_membership_v6(
11282 					    optfn, ire, connp, checkonly,
11283 					    &v6grp, fmode, &v6src, first_mp);
11284 					done = B_TRUE;
11285 				}
11286 				ire_refrele(ire);
11287 			}
11288 			if (!done) {
11289 				error = optfn(connp, checkonly, &v6grp,
11290 				    ifindex, fmode, &v6src, first_mp);
11291 			}
11292 			if (error != 0) {
11293 				/*
11294 				 * EINPROGRESS is a soft error, needs retry
11295 				 * so don't make *outlenp zero.
11296 				 */
11297 				if (error != EINPROGRESS)
11298 					*outlenp = 0;
11299 				return (error);
11300 			}
11301 			/* OK return - copy input buffer into output buffer */
11302 			if (invalp != outvalp) {
11303 				bcopy(invalp, outvalp, inlen);
11304 			}
11305 			*outlenp = inlen;
11306 			return (0);
11307 		}
11308 		case IPV6_UNICAST_HOPS:
11309 			/* Recorded in transport above IP */
11310 			break;	/* goto sizeof (int) option return */
11311 		case IPV6_UNSPEC_SRC:
11312 			/* Allow sending with a zero source address */
11313 			if (!checkonly) {
11314 				mutex_enter(&connp->conn_lock);
11315 				connp->conn_unspec_src = *i1 ? 1 : 0;
11316 				mutex_exit(&connp->conn_lock);
11317 			}
11318 			break;	/* goto sizeof (int) option return */
11319 		case IPV6_RECVPKTINFO:
11320 			if (!checkonly) {
11321 				mutex_enter(&connp->conn_lock);
11322 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11323 				mutex_exit(&connp->conn_lock);
11324 			}
11325 			break;	/* goto sizeof (int) option return */
11326 		case IPV6_RECVTCLASS:
11327 			if (!checkonly) {
11328 				if (*i1 < 0 || *i1 > 1) {
11329 					return (EINVAL);
11330 				}
11331 				mutex_enter(&connp->conn_lock);
11332 				connp->conn_ipv6_recvtclass = *i1;
11333 				mutex_exit(&connp->conn_lock);
11334 			}
11335 			break;
11336 		case IPV6_RECVPATHMTU:
11337 			if (!checkonly) {
11338 				if (*i1 < 0 || *i1 > 1) {
11339 					return (EINVAL);
11340 				}
11341 				mutex_enter(&connp->conn_lock);
11342 				connp->conn_ipv6_recvpathmtu = *i1;
11343 				mutex_exit(&connp->conn_lock);
11344 			}
11345 			break;
11346 		case IPV6_RECVHOPLIMIT:
11347 			if (!checkonly) {
11348 				mutex_enter(&connp->conn_lock);
11349 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11350 				mutex_exit(&connp->conn_lock);
11351 			}
11352 			break;	/* goto sizeof (int) option return */
11353 		case IPV6_RECVHOPOPTS:
11354 			if (!checkonly) {
11355 				mutex_enter(&connp->conn_lock);
11356 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11357 				mutex_exit(&connp->conn_lock);
11358 			}
11359 			break;	/* goto sizeof (int) option return */
11360 		case IPV6_RECVDSTOPTS:
11361 			if (!checkonly) {
11362 				mutex_enter(&connp->conn_lock);
11363 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11364 				mutex_exit(&connp->conn_lock);
11365 			}
11366 			break;	/* goto sizeof (int) option return */
11367 		case IPV6_RECVRTHDR:
11368 			if (!checkonly) {
11369 				mutex_enter(&connp->conn_lock);
11370 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11371 				mutex_exit(&connp->conn_lock);
11372 			}
11373 			break;	/* goto sizeof (int) option return */
11374 		case IPV6_RECVRTHDRDSTOPTS:
11375 			if (!checkonly) {
11376 				mutex_enter(&connp->conn_lock);
11377 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11378 				mutex_exit(&connp->conn_lock);
11379 			}
11380 			break;	/* goto sizeof (int) option return */
11381 		case IPV6_PKTINFO:
11382 			if (inlen == 0)
11383 				return (-EINVAL);	/* clearing option */
11384 			error = ip6_set_pktinfo(cr, connp,
11385 			    (struct in6_pktinfo *)invalp, first_mp);
11386 			if (error != 0)
11387 				*outlenp = 0;
11388 			else
11389 				*outlenp = inlen;
11390 			return (error);
11391 		case IPV6_NEXTHOP: {
11392 			struct sockaddr_in6 *sin6;
11393 
11394 			/* Verify that the nexthop is reachable */
11395 			if (inlen == 0)
11396 				return (-EINVAL);	/* clearing option */
11397 
11398 			sin6 = (struct sockaddr_in6 *)invalp;
11399 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11400 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11401 			    NULL, MATCH_IRE_DEFAULT, ipst);
11402 
11403 			if (ire == NULL) {
11404 				*outlenp = 0;
11405 				return (EHOSTUNREACH);
11406 			}
11407 			ire_refrele(ire);
11408 			return (-EINVAL);
11409 		}
11410 		case IPV6_SEC_OPT:
11411 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11412 			if (error != 0) {
11413 				*outlenp = 0;
11414 				return (error);
11415 			}
11416 			break;
11417 		case IPV6_SRC_PREFERENCES: {
11418 			/*
11419 			 * This is implemented strictly in the ip module
11420 			 * (here and in tcp_opt_*() to accomodate tcp
11421 			 * sockets).  Modules above ip pass this option
11422 			 * down here since ip is the only one that needs to
11423 			 * be aware of source address preferences.
11424 			 *
11425 			 * This socket option only affects connected
11426 			 * sockets that haven't already bound to a specific
11427 			 * IPv6 address.  In other words, sockets that
11428 			 * don't call bind() with an address other than the
11429 			 * unspecified address and that call connect().
11430 			 * ip_bind_connected_v6() passes these preferences
11431 			 * to the ipif_select_source_v6() function.
11432 			 */
11433 			if (inlen != sizeof (uint32_t))
11434 				return (EINVAL);
11435 			error = ip6_set_src_preferences(connp,
11436 			    *(uint32_t *)invalp);
11437 			if (error != 0) {
11438 				*outlenp = 0;
11439 				return (error);
11440 			} else {
11441 				*outlenp = sizeof (uint32_t);
11442 			}
11443 			break;
11444 		}
11445 		case IPV6_V6ONLY:
11446 			if (*i1 < 0 || *i1 > 1) {
11447 				return (EINVAL);
11448 			}
11449 			mutex_enter(&connp->conn_lock);
11450 			connp->conn_ipv6_v6only = *i1;
11451 			mutex_exit(&connp->conn_lock);
11452 			break;
11453 		default:
11454 			return (-EINVAL);
11455 		}
11456 		break;
11457 	default:
11458 		/*
11459 		 * "soft" error (negative)
11460 		 * option not handled at this level
11461 		 * Note: Do not modify *outlenp
11462 		 */
11463 		return (-EINVAL);
11464 	}
11465 	/*
11466 	 * Common case of return from an option that is sizeof (int)
11467 	 */
11468 	*(int *)outvalp = *i1;
11469 	*outlenp = sizeof (int);
11470 	return (0);
11471 }
11472 
11473 /*
11474  * This routine gets default values of certain options whose default
11475  * values are maintained by protocol specific code
11476  */
11477 /* ARGSUSED */
11478 int
11479 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11480 {
11481 	int *i1 = (int *)ptr;
11482 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11483 
11484 	switch (level) {
11485 	case IPPROTO_IP:
11486 		switch (name) {
11487 		case IP_MULTICAST_TTL:
11488 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11489 			return (sizeof (uchar_t));
11490 		case IP_MULTICAST_LOOP:
11491 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11492 			return (sizeof (uchar_t));
11493 		default:
11494 			return (-1);
11495 		}
11496 	case IPPROTO_IPV6:
11497 		switch (name) {
11498 		case IPV6_UNICAST_HOPS:
11499 			*i1 = ipst->ips_ipv6_def_hops;
11500 			return (sizeof (int));
11501 		case IPV6_MULTICAST_HOPS:
11502 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11503 			return (sizeof (int));
11504 		case IPV6_MULTICAST_LOOP:
11505 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11506 			return (sizeof (int));
11507 		case IPV6_V6ONLY:
11508 			*i1 = 1;
11509 			return (sizeof (int));
11510 		default:
11511 			return (-1);
11512 		}
11513 	default:
11514 		return (-1);
11515 	}
11516 	/* NOTREACHED */
11517 }
11518 
11519 /*
11520  * Given a destination address and a pointer to where to put the information
11521  * this routine fills in the mtuinfo.
11522  */
11523 int
11524 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11525     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11526 {
11527 	ire_t *ire;
11528 	ip_stack_t	*ipst = ns->netstack_ip;
11529 
11530 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11531 		return (-1);
11532 
11533 	bzero(mtuinfo, sizeof (*mtuinfo));
11534 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11535 	mtuinfo->ip6m_addr.sin6_port = port;
11536 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11537 
11538 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11539 	if (ire != NULL) {
11540 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11541 		ire_refrele(ire);
11542 	} else {
11543 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11544 	}
11545 	return (sizeof (struct ip6_mtuinfo));
11546 }
11547 
11548 /*
11549  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11550  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11551  * isn't.  This doesn't matter as the error checking is done properly for the
11552  * other MRT options coming in through ip_opt_set.
11553  */
11554 int
11555 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11556 {
11557 	conn_t		*connp = Q_TO_CONN(q);
11558 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11559 
11560 	switch (level) {
11561 	case IPPROTO_IP:
11562 		switch (name) {
11563 		case MRT_VERSION:
11564 		case MRT_ASSERT:
11565 			(void) ip_mrouter_get(name, q, ptr);
11566 			return (sizeof (int));
11567 		case IP_SEC_OPT:
11568 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11569 		case IP_NEXTHOP:
11570 			if (connp->conn_nexthop_set) {
11571 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11572 				return (sizeof (ipaddr_t));
11573 			} else
11574 				return (0);
11575 		case IP_RECVPKTINFO:
11576 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11577 			return (sizeof (int));
11578 		default:
11579 			break;
11580 		}
11581 		break;
11582 	case IPPROTO_IPV6:
11583 		switch (name) {
11584 		case IPV6_SEC_OPT:
11585 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11586 		case IPV6_SRC_PREFERENCES: {
11587 			return (ip6_get_src_preferences(connp,
11588 			    (uint32_t *)ptr));
11589 		}
11590 		case IPV6_V6ONLY:
11591 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11592 			return (sizeof (int));
11593 		case IPV6_PATHMTU:
11594 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11595 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11596 		default:
11597 			break;
11598 		}
11599 		break;
11600 	default:
11601 		break;
11602 	}
11603 	return (-1);
11604 }
11605 
11606 /* Named Dispatch routine to get a current value out of our parameter table. */
11607 /* ARGSUSED */
11608 static int
11609 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11610 {
11611 	ipparam_t *ippa = (ipparam_t *)cp;
11612 
11613 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11614 	return (0);
11615 }
11616 
11617 /* ARGSUSED */
11618 static int
11619 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11620 {
11621 
11622 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11623 	return (0);
11624 }
11625 
11626 /*
11627  * Set ip{,6}_forwarding values.  This means walking through all of the
11628  * ill's and toggling their forwarding values.
11629  */
11630 /* ARGSUSED */
11631 static int
11632 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11633 {
11634 	long new_value;
11635 	int *forwarding_value = (int *)cp;
11636 	ill_t *ill;
11637 	boolean_t isv6;
11638 	ill_walk_context_t ctx;
11639 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11640 
11641 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11642 
11643 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11644 	    new_value < 0 || new_value > 1) {
11645 		return (EINVAL);
11646 	}
11647 
11648 	*forwarding_value = new_value;
11649 
11650 	/*
11651 	 * Regardless of the current value of ip_forwarding, set all per-ill
11652 	 * values of ip_forwarding to the value being set.
11653 	 *
11654 	 * Bring all the ill's up to date with the new global value.
11655 	 */
11656 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11657 
11658 	if (isv6)
11659 		ill = ILL_START_WALK_V6(&ctx, ipst);
11660 	else
11661 		ill = ILL_START_WALK_V4(&ctx, ipst);
11662 
11663 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11664 		(void) ill_forward_set(ill, new_value != 0);
11665 
11666 	rw_exit(&ipst->ips_ill_g_lock);
11667 	return (0);
11668 }
11669 
11670 /*
11671  * Walk through the param array specified registering each element with the
11672  * Named Dispatch handler. This is called only during init. So it is ok
11673  * not to acquire any locks
11674  */
11675 static boolean_t
11676 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11677     ipndp_t *ipnd, size_t ipnd_cnt)
11678 {
11679 	for (; ippa_cnt-- > 0; ippa++) {
11680 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11681 			if (!nd_load(ndp, ippa->ip_param_name,
11682 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11683 				nd_free(ndp);
11684 				return (B_FALSE);
11685 			}
11686 		}
11687 	}
11688 
11689 	for (; ipnd_cnt-- > 0; ipnd++) {
11690 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11691 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11692 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11693 			    ipnd->ip_ndp_data)) {
11694 				nd_free(ndp);
11695 				return (B_FALSE);
11696 			}
11697 		}
11698 	}
11699 
11700 	return (B_TRUE);
11701 }
11702 
11703 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11704 /* ARGSUSED */
11705 static int
11706 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11707 {
11708 	long		new_value;
11709 	ipparam_t	*ippa = (ipparam_t *)cp;
11710 
11711 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11712 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11713 		return (EINVAL);
11714 	}
11715 	ippa->ip_param_value = new_value;
11716 	return (0);
11717 }
11718 
11719 /*
11720  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11721  * When an ipf is passed here for the first time, if
11722  * we already have in-order fragments on the queue, we convert from the fast-
11723  * path reassembly scheme to the hard-case scheme.  From then on, additional
11724  * fragments are reassembled here.  We keep track of the start and end offsets
11725  * of each piece, and the number of holes in the chain.  When the hole count
11726  * goes to zero, we are done!
11727  *
11728  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11729  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11730  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11731  * after the call to ip_reassemble().
11732  */
11733 int
11734 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11735     size_t msg_len)
11736 {
11737 	uint_t	end;
11738 	mblk_t	*next_mp;
11739 	mblk_t	*mp1;
11740 	uint_t	offset;
11741 	boolean_t incr_dups = B_TRUE;
11742 	boolean_t offset_zero_seen = B_FALSE;
11743 	boolean_t pkt_boundary_checked = B_FALSE;
11744 
11745 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11746 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11747 
11748 	/* Add in byte count */
11749 	ipf->ipf_count += msg_len;
11750 	if (ipf->ipf_end) {
11751 		/*
11752 		 * We were part way through in-order reassembly, but now there
11753 		 * is a hole.  We walk through messages already queued, and
11754 		 * mark them for hard case reassembly.  We know that up till
11755 		 * now they were in order starting from offset zero.
11756 		 */
11757 		offset = 0;
11758 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11759 			IP_REASS_SET_START(mp1, offset);
11760 			if (offset == 0) {
11761 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11762 				offset = -ipf->ipf_nf_hdr_len;
11763 			}
11764 			offset += mp1->b_wptr - mp1->b_rptr;
11765 			IP_REASS_SET_END(mp1, offset);
11766 		}
11767 		/* One hole at the end. */
11768 		ipf->ipf_hole_cnt = 1;
11769 		/* Brand it as a hard case, forever. */
11770 		ipf->ipf_end = 0;
11771 	}
11772 	/* Walk through all the new pieces. */
11773 	do {
11774 		end = start + (mp->b_wptr - mp->b_rptr);
11775 		/*
11776 		 * If start is 0, decrease 'end' only for the first mblk of
11777 		 * the fragment. Otherwise 'end' can get wrong value in the
11778 		 * second pass of the loop if first mblk is exactly the
11779 		 * size of ipf_nf_hdr_len.
11780 		 */
11781 		if (start == 0 && !offset_zero_seen) {
11782 			/* First segment */
11783 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11784 			end -= ipf->ipf_nf_hdr_len;
11785 			offset_zero_seen = B_TRUE;
11786 		}
11787 		next_mp = mp->b_cont;
11788 		/*
11789 		 * We are checking to see if there is any interesing data
11790 		 * to process.  If there isn't and the mblk isn't the
11791 		 * one which carries the unfragmentable header then we
11792 		 * drop it.  It's possible to have just the unfragmentable
11793 		 * header come through without any data.  That needs to be
11794 		 * saved.
11795 		 *
11796 		 * If the assert at the top of this function holds then the
11797 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11798 		 * is infrequently traveled enough that the test is left in
11799 		 * to protect against future code changes which break that
11800 		 * invariant.
11801 		 */
11802 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11803 			/* Empty.  Blast it. */
11804 			IP_REASS_SET_START(mp, 0);
11805 			IP_REASS_SET_END(mp, 0);
11806 			/*
11807 			 * If the ipf points to the mblk we are about to free,
11808 			 * update ipf to point to the next mblk (or NULL
11809 			 * if none).
11810 			 */
11811 			if (ipf->ipf_mp->b_cont == mp)
11812 				ipf->ipf_mp->b_cont = next_mp;
11813 			freeb(mp);
11814 			continue;
11815 		}
11816 		mp->b_cont = NULL;
11817 		IP_REASS_SET_START(mp, start);
11818 		IP_REASS_SET_END(mp, end);
11819 		if (!ipf->ipf_tail_mp) {
11820 			ipf->ipf_tail_mp = mp;
11821 			ipf->ipf_mp->b_cont = mp;
11822 			if (start == 0 || !more) {
11823 				ipf->ipf_hole_cnt = 1;
11824 				/*
11825 				 * if the first fragment comes in more than one
11826 				 * mblk, this loop will be executed for each
11827 				 * mblk. Need to adjust hole count so exiting
11828 				 * this routine will leave hole count at 1.
11829 				 */
11830 				if (next_mp)
11831 					ipf->ipf_hole_cnt++;
11832 			} else
11833 				ipf->ipf_hole_cnt = 2;
11834 			continue;
11835 		} else if (ipf->ipf_last_frag_seen && !more &&
11836 		    !pkt_boundary_checked) {
11837 			/*
11838 			 * We check datagram boundary only if this fragment
11839 			 * claims to be the last fragment and we have seen a
11840 			 * last fragment in the past too. We do this only
11841 			 * once for a given fragment.
11842 			 *
11843 			 * start cannot be 0 here as fragments with start=0
11844 			 * and MF=0 gets handled as a complete packet. These
11845 			 * fragments should not reach here.
11846 			 */
11847 
11848 			if (start + msgdsize(mp) !=
11849 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11850 				/*
11851 				 * We have two fragments both of which claim
11852 				 * to be the last fragment but gives conflicting
11853 				 * information about the whole datagram size.
11854 				 * Something fishy is going on. Drop the
11855 				 * fragment and free up the reassembly list.
11856 				 */
11857 				return (IP_REASS_FAILED);
11858 			}
11859 
11860 			/*
11861 			 * We shouldn't come to this code block again for this
11862 			 * particular fragment.
11863 			 */
11864 			pkt_boundary_checked = B_TRUE;
11865 		}
11866 
11867 		/* New stuff at or beyond tail? */
11868 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11869 		if (start >= offset) {
11870 			if (ipf->ipf_last_frag_seen) {
11871 				/* current fragment is beyond last fragment */
11872 				return (IP_REASS_FAILED);
11873 			}
11874 			/* Link it on end. */
11875 			ipf->ipf_tail_mp->b_cont = mp;
11876 			ipf->ipf_tail_mp = mp;
11877 			if (more) {
11878 				if (start != offset)
11879 					ipf->ipf_hole_cnt++;
11880 			} else if (start == offset && next_mp == NULL)
11881 					ipf->ipf_hole_cnt--;
11882 			continue;
11883 		}
11884 		mp1 = ipf->ipf_mp->b_cont;
11885 		offset = IP_REASS_START(mp1);
11886 		/* New stuff at the front? */
11887 		if (start < offset) {
11888 			if (start == 0) {
11889 				if (end >= offset) {
11890 					/* Nailed the hole at the begining. */
11891 					ipf->ipf_hole_cnt--;
11892 				}
11893 			} else if (end < offset) {
11894 				/*
11895 				 * A hole, stuff, and a hole where there used
11896 				 * to be just a hole.
11897 				 */
11898 				ipf->ipf_hole_cnt++;
11899 			}
11900 			mp->b_cont = mp1;
11901 			/* Check for overlap. */
11902 			while (end > offset) {
11903 				if (end < IP_REASS_END(mp1)) {
11904 					mp->b_wptr -= end - offset;
11905 					IP_REASS_SET_END(mp, offset);
11906 					BUMP_MIB(ill->ill_ip_mib,
11907 					    ipIfStatsReasmPartDups);
11908 					break;
11909 				}
11910 				/* Did we cover another hole? */
11911 				if ((mp1->b_cont &&
11912 				    IP_REASS_END(mp1) !=
11913 				    IP_REASS_START(mp1->b_cont) &&
11914 				    end >= IP_REASS_START(mp1->b_cont)) ||
11915 				    (!ipf->ipf_last_frag_seen && !more)) {
11916 					ipf->ipf_hole_cnt--;
11917 				}
11918 				/* Clip out mp1. */
11919 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11920 					/*
11921 					 * After clipping out mp1, this guy
11922 					 * is now hanging off the end.
11923 					 */
11924 					ipf->ipf_tail_mp = mp;
11925 				}
11926 				IP_REASS_SET_START(mp1, 0);
11927 				IP_REASS_SET_END(mp1, 0);
11928 				/* Subtract byte count */
11929 				ipf->ipf_count -= mp1->b_datap->db_lim -
11930 				    mp1->b_datap->db_base;
11931 				freeb(mp1);
11932 				BUMP_MIB(ill->ill_ip_mib,
11933 				    ipIfStatsReasmPartDups);
11934 				mp1 = mp->b_cont;
11935 				if (!mp1)
11936 					break;
11937 				offset = IP_REASS_START(mp1);
11938 			}
11939 			ipf->ipf_mp->b_cont = mp;
11940 			continue;
11941 		}
11942 		/*
11943 		 * The new piece starts somewhere between the start of the head
11944 		 * and before the end of the tail.
11945 		 */
11946 		for (; mp1; mp1 = mp1->b_cont) {
11947 			offset = IP_REASS_END(mp1);
11948 			if (start < offset) {
11949 				if (end <= offset) {
11950 					/* Nothing new. */
11951 					IP_REASS_SET_START(mp, 0);
11952 					IP_REASS_SET_END(mp, 0);
11953 					/* Subtract byte count */
11954 					ipf->ipf_count -= mp->b_datap->db_lim -
11955 					    mp->b_datap->db_base;
11956 					if (incr_dups) {
11957 						ipf->ipf_num_dups++;
11958 						incr_dups = B_FALSE;
11959 					}
11960 					freeb(mp);
11961 					BUMP_MIB(ill->ill_ip_mib,
11962 					    ipIfStatsReasmDuplicates);
11963 					break;
11964 				}
11965 				/*
11966 				 * Trim redundant stuff off beginning of new
11967 				 * piece.
11968 				 */
11969 				IP_REASS_SET_START(mp, offset);
11970 				mp->b_rptr += offset - start;
11971 				BUMP_MIB(ill->ill_ip_mib,
11972 				    ipIfStatsReasmPartDups);
11973 				start = offset;
11974 				if (!mp1->b_cont) {
11975 					/*
11976 					 * After trimming, this guy is now
11977 					 * hanging off the end.
11978 					 */
11979 					mp1->b_cont = mp;
11980 					ipf->ipf_tail_mp = mp;
11981 					if (!more) {
11982 						ipf->ipf_hole_cnt--;
11983 					}
11984 					break;
11985 				}
11986 			}
11987 			if (start >= IP_REASS_START(mp1->b_cont))
11988 				continue;
11989 			/* Fill a hole */
11990 			if (start > offset)
11991 				ipf->ipf_hole_cnt++;
11992 			mp->b_cont = mp1->b_cont;
11993 			mp1->b_cont = mp;
11994 			mp1 = mp->b_cont;
11995 			offset = IP_REASS_START(mp1);
11996 			if (end >= offset) {
11997 				ipf->ipf_hole_cnt--;
11998 				/* Check for overlap. */
11999 				while (end > offset) {
12000 					if (end < IP_REASS_END(mp1)) {
12001 						mp->b_wptr -= end - offset;
12002 						IP_REASS_SET_END(mp, offset);
12003 						/*
12004 						 * TODO we might bump
12005 						 * this up twice if there is
12006 						 * overlap at both ends.
12007 						 */
12008 						BUMP_MIB(ill->ill_ip_mib,
12009 						    ipIfStatsReasmPartDups);
12010 						break;
12011 					}
12012 					/* Did we cover another hole? */
12013 					if ((mp1->b_cont &&
12014 					    IP_REASS_END(mp1)
12015 					    != IP_REASS_START(mp1->b_cont) &&
12016 					    end >=
12017 					    IP_REASS_START(mp1->b_cont)) ||
12018 					    (!ipf->ipf_last_frag_seen &&
12019 					    !more)) {
12020 						ipf->ipf_hole_cnt--;
12021 					}
12022 					/* Clip out mp1. */
12023 					if ((mp->b_cont = mp1->b_cont) ==
12024 					    NULL) {
12025 						/*
12026 						 * After clipping out mp1,
12027 						 * this guy is now hanging
12028 						 * off the end.
12029 						 */
12030 						ipf->ipf_tail_mp = mp;
12031 					}
12032 					IP_REASS_SET_START(mp1, 0);
12033 					IP_REASS_SET_END(mp1, 0);
12034 					/* Subtract byte count */
12035 					ipf->ipf_count -=
12036 					    mp1->b_datap->db_lim -
12037 					    mp1->b_datap->db_base;
12038 					freeb(mp1);
12039 					BUMP_MIB(ill->ill_ip_mib,
12040 					    ipIfStatsReasmPartDups);
12041 					mp1 = mp->b_cont;
12042 					if (!mp1)
12043 						break;
12044 					offset = IP_REASS_START(mp1);
12045 				}
12046 			}
12047 			break;
12048 		}
12049 	} while (start = end, mp = next_mp);
12050 
12051 	/* Fragment just processed could be the last one. Remember this fact */
12052 	if (!more)
12053 		ipf->ipf_last_frag_seen = B_TRUE;
12054 
12055 	/* Still got holes? */
12056 	if (ipf->ipf_hole_cnt)
12057 		return (IP_REASS_PARTIAL);
12058 	/* Clean up overloaded fields to avoid upstream disasters. */
12059 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12060 		IP_REASS_SET_START(mp1, 0);
12061 		IP_REASS_SET_END(mp1, 0);
12062 	}
12063 	return (IP_REASS_COMPLETE);
12064 }
12065 
12066 /*
12067  * ipsec processing for the fast path, used for input UDP Packets
12068  * Returns true if ready for passup to UDP.
12069  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
12070  * was an ESP-in-UDP packet, etc.).
12071  */
12072 static boolean_t
12073 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12074     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
12075 {
12076 	uint32_t	ill_index;
12077 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12078 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12079 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12080 	udp_t		*udp = connp->conn_udp;
12081 
12082 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12083 	/* The ill_index of the incoming ILL */
12084 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12085 
12086 	/* pass packet up to the transport */
12087 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12088 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12089 		    NULL, mctl_present);
12090 		if (*first_mpp == NULL) {
12091 			return (B_FALSE);
12092 		}
12093 	}
12094 
12095 	/* Initiate IPPF processing for fastpath UDP */
12096 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12097 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12098 		if (*mpp == NULL) {
12099 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12100 			    "deferred/dropped during IPPF processing\n"));
12101 			return (B_FALSE);
12102 		}
12103 	}
12104 	/*
12105 	 * Remove 0-spi if it's 0, or move everything behind
12106 	 * the UDP header over it and forward to ESP via
12107 	 * ip_proto_input().
12108 	 */
12109 	if (udp->udp_nat_t_endpoint) {
12110 		if (mctl_present) {
12111 			/* mctl_present *shouldn't* happen. */
12112 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
12113 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
12114 			    &ipss->ipsec_dropper);
12115 			*first_mpp = NULL;
12116 			return (B_FALSE);
12117 		}
12118 
12119 		/* "ill" is "recv_ill" in actuality. */
12120 		if (!zero_spi_check(q, *mpp, ire, ill, ipss))
12121 			return (B_FALSE);
12122 
12123 		/* Else continue like a normal UDP packet. */
12124 	}
12125 
12126 	/*
12127 	 * We make the checks as below since we are in the fast path
12128 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12129 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12130 	 */
12131 	if (connp->conn_recvif || connp->conn_recvslla ||
12132 	    connp->conn_ip_recvpktinfo) {
12133 		if (connp->conn_recvif) {
12134 			in_flags = IPF_RECVIF;
12135 		}
12136 		/*
12137 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12138 		 * so the flag passed to ip_add_info is based on IP version
12139 		 * of connp.
12140 		 */
12141 		if (connp->conn_ip_recvpktinfo) {
12142 			if (connp->conn_af_isv6) {
12143 				/*
12144 				 * V6 only needs index
12145 				 */
12146 				in_flags |= IPF_RECVIF;
12147 			} else {
12148 				/*
12149 				 * V4 needs index + matching address.
12150 				 */
12151 				in_flags |= IPF_RECVADDR;
12152 			}
12153 		}
12154 		if (connp->conn_recvslla) {
12155 			in_flags |= IPF_RECVSLLA;
12156 		}
12157 		/*
12158 		 * since in_flags are being set ill will be
12159 		 * referenced in ip_add_info, so it better not
12160 		 * be NULL.
12161 		 */
12162 		/*
12163 		 * the actual data will be contained in b_cont
12164 		 * upon successful return of the following call.
12165 		 * If the call fails then the original mblk is
12166 		 * returned.
12167 		 */
12168 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12169 		    ipst);
12170 	}
12171 
12172 	return (B_TRUE);
12173 }
12174 
12175 /*
12176  * Fragmentation reassembly.  Each ILL has a hash table for
12177  * queuing packets undergoing reassembly for all IPIFs
12178  * associated with the ILL.  The hash is based on the packet
12179  * IP ident field.  The ILL frag hash table was allocated
12180  * as a timer block at the time the ILL was created.  Whenever
12181  * there is anything on the reassembly queue, the timer will
12182  * be running.  Returns B_TRUE if successful else B_FALSE;
12183  * frees mp on failure.
12184  */
12185 static boolean_t
12186 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12187     uint32_t *cksum_val, uint16_t *cksum_flags)
12188 {
12189 	uint32_t	frag_offset_flags;
12190 	ill_t		*ill = (ill_t *)q->q_ptr;
12191 	mblk_t		*mp = *mpp;
12192 	mblk_t		*t_mp;
12193 	ipaddr_t	dst;
12194 	uint8_t		proto = ipha->ipha_protocol;
12195 	uint32_t	sum_val;
12196 	uint16_t	sum_flags;
12197 	ipf_t		*ipf;
12198 	ipf_t		**ipfp;
12199 	ipfb_t		*ipfb;
12200 	uint16_t	ident;
12201 	uint32_t	offset;
12202 	ipaddr_t	src;
12203 	uint_t		hdr_length;
12204 	uint32_t	end;
12205 	mblk_t		*mp1;
12206 	mblk_t		*tail_mp;
12207 	size_t		count;
12208 	size_t		msg_len;
12209 	uint8_t		ecn_info = 0;
12210 	uint32_t	packet_size;
12211 	boolean_t	pruned = B_FALSE;
12212 	ip_stack_t *ipst = ill->ill_ipst;
12213 
12214 	if (cksum_val != NULL)
12215 		*cksum_val = 0;
12216 	if (cksum_flags != NULL)
12217 		*cksum_flags = 0;
12218 
12219 	/*
12220 	 * Drop the fragmented as early as possible, if
12221 	 * we don't have resource(s) to re-assemble.
12222 	 */
12223 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12224 		freemsg(mp);
12225 		return (B_FALSE);
12226 	}
12227 
12228 	/* Check for fragmentation offset; return if there's none */
12229 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12230 	    (IPH_MF | IPH_OFFSET)) == 0)
12231 		return (B_TRUE);
12232 
12233 	/*
12234 	 * We utilize hardware computed checksum info only for UDP since
12235 	 * IP fragmentation is a normal occurence for the protocol.  In
12236 	 * addition, checksum offload support for IP fragments carrying
12237 	 * UDP payload is commonly implemented across network adapters.
12238 	 */
12239 	ASSERT(ill != NULL);
12240 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12241 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12242 		mblk_t *mp1 = mp->b_cont;
12243 		int32_t len;
12244 
12245 		/* Record checksum information from the packet */
12246 		sum_val = (uint32_t)DB_CKSUM16(mp);
12247 		sum_flags = DB_CKSUMFLAGS(mp);
12248 
12249 		/* IP payload offset from beginning of mblk */
12250 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12251 
12252 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12253 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12254 		    offset >= DB_CKSUMSTART(mp) &&
12255 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12256 			uint32_t adj;
12257 			/*
12258 			 * Partial checksum has been calculated by hardware
12259 			 * and attached to the packet; in addition, any
12260 			 * prepended extraneous data is even byte aligned.
12261 			 * If any such data exists, we adjust the checksum;
12262 			 * this would also handle any postpended data.
12263 			 */
12264 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12265 			    mp, mp1, len, adj);
12266 
12267 			/* One's complement subtract extraneous checksum */
12268 			if (adj >= sum_val)
12269 				sum_val = ~(adj - sum_val) & 0xFFFF;
12270 			else
12271 				sum_val -= adj;
12272 		}
12273 	} else {
12274 		sum_val = 0;
12275 		sum_flags = 0;
12276 	}
12277 
12278 	/* Clear hardware checksumming flag */
12279 	DB_CKSUMFLAGS(mp) = 0;
12280 
12281 	ident = ipha->ipha_ident;
12282 	offset = (frag_offset_flags << 3) & 0xFFFF;
12283 	src = ipha->ipha_src;
12284 	dst = ipha->ipha_dst;
12285 	hdr_length = IPH_HDR_LENGTH(ipha);
12286 	end = ntohs(ipha->ipha_length) - hdr_length;
12287 
12288 	/* If end == 0 then we have a packet with no data, so just free it */
12289 	if (end == 0) {
12290 		freemsg(mp);
12291 		return (B_FALSE);
12292 	}
12293 
12294 	/* Record the ECN field info. */
12295 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12296 	if (offset != 0) {
12297 		/*
12298 		 * If this isn't the first piece, strip the header, and
12299 		 * add the offset to the end value.
12300 		 */
12301 		mp->b_rptr += hdr_length;
12302 		end += offset;
12303 	}
12304 
12305 	msg_len = MBLKSIZE(mp);
12306 	tail_mp = mp;
12307 	while (tail_mp->b_cont != NULL) {
12308 		tail_mp = tail_mp->b_cont;
12309 		msg_len += MBLKSIZE(tail_mp);
12310 	}
12311 
12312 	/* If the reassembly list for this ILL will get too big, prune it */
12313 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12314 	    ipst->ips_ip_reass_queue_bytes) {
12315 		ill_frag_prune(ill,
12316 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12317 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12318 		pruned = B_TRUE;
12319 	}
12320 
12321 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12322 	mutex_enter(&ipfb->ipfb_lock);
12323 
12324 	ipfp = &ipfb->ipfb_ipf;
12325 	/* Try to find an existing fragment queue for this packet. */
12326 	for (;;) {
12327 		ipf = ipfp[0];
12328 		if (ipf != NULL) {
12329 			/*
12330 			 * It has to match on ident and src/dst address.
12331 			 */
12332 			if (ipf->ipf_ident == ident &&
12333 			    ipf->ipf_src == src &&
12334 			    ipf->ipf_dst == dst &&
12335 			    ipf->ipf_protocol == proto) {
12336 				/*
12337 				 * If we have received too many
12338 				 * duplicate fragments for this packet
12339 				 * free it.
12340 				 */
12341 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12342 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12343 					freemsg(mp);
12344 					mutex_exit(&ipfb->ipfb_lock);
12345 					return (B_FALSE);
12346 				}
12347 				/* Found it. */
12348 				break;
12349 			}
12350 			ipfp = &ipf->ipf_hash_next;
12351 			continue;
12352 		}
12353 
12354 		/*
12355 		 * If we pruned the list, do we want to store this new
12356 		 * fragment?. We apply an optimization here based on the
12357 		 * fact that most fragments will be received in order.
12358 		 * So if the offset of this incoming fragment is zero,
12359 		 * it is the first fragment of a new packet. We will
12360 		 * keep it.  Otherwise drop the fragment, as we have
12361 		 * probably pruned the packet already (since the
12362 		 * packet cannot be found).
12363 		 */
12364 		if (pruned && offset != 0) {
12365 			mutex_exit(&ipfb->ipfb_lock);
12366 			freemsg(mp);
12367 			return (B_FALSE);
12368 		}
12369 
12370 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12371 			/*
12372 			 * Too many fragmented packets in this hash
12373 			 * bucket. Free the oldest.
12374 			 */
12375 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12376 		}
12377 
12378 		/* New guy.  Allocate a frag message. */
12379 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12380 		if (mp1 == NULL) {
12381 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12382 			freemsg(mp);
12383 reass_done:
12384 			mutex_exit(&ipfb->ipfb_lock);
12385 			return (B_FALSE);
12386 		}
12387 
12388 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12389 		mp1->b_cont = mp;
12390 
12391 		/* Initialize the fragment header. */
12392 		ipf = (ipf_t *)mp1->b_rptr;
12393 		ipf->ipf_mp = mp1;
12394 		ipf->ipf_ptphn = ipfp;
12395 		ipfp[0] = ipf;
12396 		ipf->ipf_hash_next = NULL;
12397 		ipf->ipf_ident = ident;
12398 		ipf->ipf_protocol = proto;
12399 		ipf->ipf_src = src;
12400 		ipf->ipf_dst = dst;
12401 		ipf->ipf_nf_hdr_len = 0;
12402 		/* Record reassembly start time. */
12403 		ipf->ipf_timestamp = gethrestime_sec();
12404 		/* Record ipf generation and account for frag header */
12405 		ipf->ipf_gen = ill->ill_ipf_gen++;
12406 		ipf->ipf_count = MBLKSIZE(mp1);
12407 		ipf->ipf_last_frag_seen = B_FALSE;
12408 		ipf->ipf_ecn = ecn_info;
12409 		ipf->ipf_num_dups = 0;
12410 		ipfb->ipfb_frag_pkts++;
12411 		ipf->ipf_checksum = 0;
12412 		ipf->ipf_checksum_flags = 0;
12413 
12414 		/* Store checksum value in fragment header */
12415 		if (sum_flags != 0) {
12416 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12417 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12418 			ipf->ipf_checksum = sum_val;
12419 			ipf->ipf_checksum_flags = sum_flags;
12420 		}
12421 
12422 		/*
12423 		 * We handle reassembly two ways.  In the easy case,
12424 		 * where all the fragments show up in order, we do
12425 		 * minimal bookkeeping, and just clip new pieces on
12426 		 * the end.  If we ever see a hole, then we go off
12427 		 * to ip_reassemble which has to mark the pieces and
12428 		 * keep track of the number of holes, etc.  Obviously,
12429 		 * the point of having both mechanisms is so we can
12430 		 * handle the easy case as efficiently as possible.
12431 		 */
12432 		if (offset == 0) {
12433 			/* Easy case, in-order reassembly so far. */
12434 			ipf->ipf_count += msg_len;
12435 			ipf->ipf_tail_mp = tail_mp;
12436 			/*
12437 			 * Keep track of next expected offset in
12438 			 * ipf_end.
12439 			 */
12440 			ipf->ipf_end = end;
12441 			ipf->ipf_nf_hdr_len = hdr_length;
12442 		} else {
12443 			/* Hard case, hole at the beginning. */
12444 			ipf->ipf_tail_mp = NULL;
12445 			/*
12446 			 * ipf_end == 0 means that we have given up
12447 			 * on easy reassembly.
12448 			 */
12449 			ipf->ipf_end = 0;
12450 
12451 			/* Forget checksum offload from now on */
12452 			ipf->ipf_checksum_flags = 0;
12453 
12454 			/*
12455 			 * ipf_hole_cnt is set by ip_reassemble.
12456 			 * ipf_count is updated by ip_reassemble.
12457 			 * No need to check for return value here
12458 			 * as we don't expect reassembly to complete
12459 			 * or fail for the first fragment itself.
12460 			 */
12461 			(void) ip_reassemble(mp, ipf,
12462 			    (frag_offset_flags & IPH_OFFSET) << 3,
12463 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12464 		}
12465 		/* Update per ipfb and ill byte counts */
12466 		ipfb->ipfb_count += ipf->ipf_count;
12467 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12468 		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
12469 		/* If the frag timer wasn't already going, start it. */
12470 		mutex_enter(&ill->ill_lock);
12471 		ill_frag_timer_start(ill);
12472 		mutex_exit(&ill->ill_lock);
12473 		goto reass_done;
12474 	}
12475 
12476 	/*
12477 	 * If the packet's flag has changed (it could be coming up
12478 	 * from an interface different than the previous, therefore
12479 	 * possibly different checksum capability), then forget about
12480 	 * any stored checksum states.  Otherwise add the value to
12481 	 * the existing one stored in the fragment header.
12482 	 */
12483 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12484 		sum_val += ipf->ipf_checksum;
12485 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12486 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12487 		ipf->ipf_checksum = sum_val;
12488 	} else if (ipf->ipf_checksum_flags != 0) {
12489 		/* Forget checksum offload from now on */
12490 		ipf->ipf_checksum_flags = 0;
12491 	}
12492 
12493 	/*
12494 	 * We have a new piece of a datagram which is already being
12495 	 * reassembled.  Update the ECN info if all IP fragments
12496 	 * are ECN capable.  If there is one which is not, clear
12497 	 * all the info.  If there is at least one which has CE
12498 	 * code point, IP needs to report that up to transport.
12499 	 */
12500 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12501 		if (ecn_info == IPH_ECN_CE)
12502 			ipf->ipf_ecn = IPH_ECN_CE;
12503 	} else {
12504 		ipf->ipf_ecn = IPH_ECN_NECT;
12505 	}
12506 	if (offset && ipf->ipf_end == offset) {
12507 		/* The new fragment fits at the end */
12508 		ipf->ipf_tail_mp->b_cont = mp;
12509 		/* Update the byte count */
12510 		ipf->ipf_count += msg_len;
12511 		/* Update per ipfb and ill byte counts */
12512 		ipfb->ipfb_count += msg_len;
12513 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12514 		atomic_add_32(&ill->ill_frag_count, msg_len);
12515 		if (frag_offset_flags & IPH_MF) {
12516 			/* More to come. */
12517 			ipf->ipf_end = end;
12518 			ipf->ipf_tail_mp = tail_mp;
12519 			goto reass_done;
12520 		}
12521 	} else {
12522 		/* Go do the hard cases. */
12523 		int ret;
12524 
12525 		if (offset == 0)
12526 			ipf->ipf_nf_hdr_len = hdr_length;
12527 
12528 		/* Save current byte count */
12529 		count = ipf->ipf_count;
12530 		ret = ip_reassemble(mp, ipf,
12531 		    (frag_offset_flags & IPH_OFFSET) << 3,
12532 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12533 		/* Count of bytes added and subtracted (freeb()ed) */
12534 		count = ipf->ipf_count - count;
12535 		if (count) {
12536 			/* Update per ipfb and ill byte counts */
12537 			ipfb->ipfb_count += count;
12538 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12539 			atomic_add_32(&ill->ill_frag_count, count);
12540 		}
12541 		if (ret == IP_REASS_PARTIAL) {
12542 			goto reass_done;
12543 		} else if (ret == IP_REASS_FAILED) {
12544 			/* Reassembly failed. Free up all resources */
12545 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12546 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12547 				IP_REASS_SET_START(t_mp, 0);
12548 				IP_REASS_SET_END(t_mp, 0);
12549 			}
12550 			freemsg(mp);
12551 			goto reass_done;
12552 		}
12553 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12554 	}
12555 	/*
12556 	 * We have completed reassembly.  Unhook the frag header from
12557 	 * the reassembly list.
12558 	 *
12559 	 * Before we free the frag header, record the ECN info
12560 	 * to report back to the transport.
12561 	 */
12562 	ecn_info = ipf->ipf_ecn;
12563 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12564 	ipfp = ipf->ipf_ptphn;
12565 
12566 	/* We need to supply these to caller */
12567 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12568 		sum_val = ipf->ipf_checksum;
12569 	else
12570 		sum_val = 0;
12571 
12572 	mp1 = ipf->ipf_mp;
12573 	count = ipf->ipf_count;
12574 	ipf = ipf->ipf_hash_next;
12575 	if (ipf != NULL)
12576 		ipf->ipf_ptphn = ipfp;
12577 	ipfp[0] = ipf;
12578 	atomic_add_32(&ill->ill_frag_count, -count);
12579 	ASSERT(ipfb->ipfb_count >= count);
12580 	ipfb->ipfb_count -= count;
12581 	ipfb->ipfb_frag_pkts--;
12582 	mutex_exit(&ipfb->ipfb_lock);
12583 	/* Ditch the frag header. */
12584 	mp = mp1->b_cont;
12585 
12586 	freeb(mp1);
12587 
12588 	/* Restore original IP length in header. */
12589 	packet_size = (uint32_t)msgdsize(mp);
12590 	if (packet_size > IP_MAXPACKET) {
12591 		freemsg(mp);
12592 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12593 		return (B_FALSE);
12594 	}
12595 
12596 	if (DB_REF(mp) > 1) {
12597 		mblk_t *mp2 = copymsg(mp);
12598 
12599 		freemsg(mp);
12600 		if (mp2 == NULL) {
12601 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12602 			return (B_FALSE);
12603 		}
12604 		mp = mp2;
12605 	}
12606 	ipha = (ipha_t *)mp->b_rptr;
12607 
12608 	ipha->ipha_length = htons((uint16_t)packet_size);
12609 	/* We're now complete, zip the frag state */
12610 	ipha->ipha_fragment_offset_and_flags = 0;
12611 	/* Record the ECN info. */
12612 	ipha->ipha_type_of_service &= 0xFC;
12613 	ipha->ipha_type_of_service |= ecn_info;
12614 	*mpp = mp;
12615 
12616 	/* Reassembly is successful; return checksum information if needed */
12617 	if (cksum_val != NULL)
12618 		*cksum_val = sum_val;
12619 	if (cksum_flags != NULL)
12620 		*cksum_flags = sum_flags;
12621 
12622 	return (B_TRUE);
12623 }
12624 
12625 /*
12626  * Perform ip header check sum update local options.
12627  * return B_TRUE if all is well, else return B_FALSE and release
12628  * the mp. caller is responsible for decrementing ire ref cnt.
12629  */
12630 static boolean_t
12631 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12632     ip_stack_t *ipst)
12633 {
12634 	mblk_t		*first_mp;
12635 	boolean_t	mctl_present;
12636 	uint16_t	sum;
12637 
12638 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12639 	/*
12640 	 * Don't do the checksum if it has gone through AH/ESP
12641 	 * processing.
12642 	 */
12643 	if (!mctl_present) {
12644 		sum = ip_csum_hdr(ipha);
12645 		if (sum != 0) {
12646 			if (ill != NULL) {
12647 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12648 			} else {
12649 				BUMP_MIB(&ipst->ips_ip_mib,
12650 				    ipIfStatsInCksumErrs);
12651 			}
12652 			freemsg(first_mp);
12653 			return (B_FALSE);
12654 		}
12655 	}
12656 
12657 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12658 		if (mctl_present)
12659 			freeb(first_mp);
12660 		return (B_FALSE);
12661 	}
12662 
12663 	return (B_TRUE);
12664 }
12665 
12666 /*
12667  * All udp packet are delivered to the local host via this routine.
12668  */
12669 void
12670 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12671     ill_t *recv_ill)
12672 {
12673 	uint32_t	sum;
12674 	uint32_t	u1;
12675 	boolean_t	mctl_present;
12676 	conn_t		*connp;
12677 	mblk_t		*first_mp;
12678 	uint16_t	*up;
12679 	ill_t		*ill = (ill_t *)q->q_ptr;
12680 	uint16_t	reass_hck_flags = 0;
12681 	ip_stack_t	*ipst;
12682 
12683 	ASSERT(recv_ill != NULL);
12684 	ipst = recv_ill->ill_ipst;
12685 
12686 #define	rptr    ((uchar_t *)ipha)
12687 
12688 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12689 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12690 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12691 	ASSERT(ill != NULL);
12692 
12693 	/*
12694 	 * FAST PATH for udp packets
12695 	 */
12696 
12697 	/* u1 is # words of IP options */
12698 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12699 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12700 
12701 	/* IP options present */
12702 	if (u1 != 0)
12703 		goto ipoptions;
12704 
12705 	/* Check the IP header checksum.  */
12706 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12707 		/* Clear the IP header h/w cksum flag */
12708 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12709 	} else if (!mctl_present) {
12710 		/*
12711 		 * Don't verify header checksum if this packet is coming
12712 		 * back from AH/ESP as we already did it.
12713 		 */
12714 #define	uph	((uint16_t *)ipha)
12715 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12716 		    uph[6] + uph[7] + uph[8] + uph[9];
12717 #undef	uph
12718 		/* finish doing IP checksum */
12719 		sum = (sum & 0xFFFF) + (sum >> 16);
12720 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12721 		if (sum != 0 && sum != 0xFFFF) {
12722 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12723 			freemsg(first_mp);
12724 			return;
12725 		}
12726 	}
12727 
12728 	/*
12729 	 * Count for SNMP of inbound packets for ire.
12730 	 * if mctl is present this might be a secure packet and
12731 	 * has already been counted for in ip_proto_input().
12732 	 */
12733 	if (!mctl_present) {
12734 		UPDATE_IB_PKT_COUNT(ire);
12735 		ire->ire_last_used_time = lbolt;
12736 	}
12737 
12738 	/* packet part of fragmented IP packet? */
12739 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12740 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12741 		goto fragmented;
12742 	}
12743 
12744 	/* u1 = IP header length (20 bytes) */
12745 	u1 = IP_SIMPLE_HDR_LENGTH;
12746 
12747 	/* packet does not contain complete IP & UDP headers */
12748 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12749 		goto udppullup;
12750 
12751 	/* up points to UDP header */
12752 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12753 #define	iphs    ((uint16_t *)ipha)
12754 
12755 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12756 	if (up[3] != 0) {
12757 		mblk_t *mp1 = mp->b_cont;
12758 		boolean_t cksum_err;
12759 		uint16_t hck_flags = 0;
12760 
12761 		/* Pseudo-header checksum */
12762 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12763 		    iphs[9] + up[2];
12764 
12765 		/*
12766 		 * Revert to software checksum calculation if the interface
12767 		 * isn't capable of checksum offload or if IPsec is present.
12768 		 */
12769 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12770 			hck_flags = DB_CKSUMFLAGS(mp);
12771 
12772 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12773 			IP_STAT(ipst, ip_in_sw_cksum);
12774 
12775 		IP_CKSUM_RECV(hck_flags, u1,
12776 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12777 		    (int32_t)((uchar_t *)up - rptr),
12778 		    mp, mp1, cksum_err);
12779 
12780 		if (cksum_err) {
12781 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12782 			if (hck_flags & HCK_FULLCKSUM)
12783 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12784 			else if (hck_flags & HCK_PARTIALCKSUM)
12785 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12786 			else
12787 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12788 
12789 			freemsg(first_mp);
12790 			return;
12791 		}
12792 	}
12793 
12794 	/* Non-fragmented broadcast or multicast packet? */
12795 	if (ire->ire_type == IRE_BROADCAST)
12796 		goto udpslowpath;
12797 
12798 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12799 	    ire->ire_zoneid, ipst)) != NULL) {
12800 		ASSERT(connp->conn_upq != NULL);
12801 		IP_STAT(ipst, ip_udp_fast_path);
12802 
12803 		if (CONN_UDP_FLOWCTLD(connp)) {
12804 			freemsg(mp);
12805 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12806 		} else {
12807 			if (!mctl_present) {
12808 				BUMP_MIB(ill->ill_ip_mib,
12809 				    ipIfStatsHCInDelivers);
12810 			}
12811 			/*
12812 			 * mp and first_mp can change.
12813 			 */
12814 			if (ip_udp_check(q, connp, recv_ill,
12815 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12816 				/* Send it upstream */
12817 				(connp->conn_recv)(connp, mp, NULL);
12818 			}
12819 		}
12820 		/*
12821 		 * freeb() cannot deal with null mblk being passed
12822 		 * in and first_mp can be set to null in the call
12823 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12824 		 */
12825 		if (mctl_present && first_mp != NULL) {
12826 			freeb(first_mp);
12827 		}
12828 		CONN_DEC_REF(connp);
12829 		return;
12830 	}
12831 
12832 	/*
12833 	 * if we got here we know the packet is not fragmented and
12834 	 * has no options. The classifier could not find a conn_t and
12835 	 * most likely its an icmp packet so send it through slow path.
12836 	 */
12837 
12838 	goto udpslowpath;
12839 
12840 ipoptions:
12841 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12842 		goto slow_done;
12843 	}
12844 
12845 	UPDATE_IB_PKT_COUNT(ire);
12846 	ire->ire_last_used_time = lbolt;
12847 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12848 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12849 fragmented:
12850 		/*
12851 		 * "sum" and "reass_hck_flags" are non-zero if the
12852 		 * reassembled packet has a valid hardware computed
12853 		 * checksum information associated with it.
12854 		 */
12855 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12856 			goto slow_done;
12857 		/*
12858 		 * Make sure that first_mp points back to mp as
12859 		 * the mp we came in with could have changed in
12860 		 * ip_rput_fragment().
12861 		 */
12862 		ASSERT(!mctl_present);
12863 		ipha = (ipha_t *)mp->b_rptr;
12864 		first_mp = mp;
12865 	}
12866 
12867 	/* Now we have a complete datagram, destined for this machine. */
12868 	u1 = IPH_HDR_LENGTH(ipha);
12869 	/* Pull up the UDP header, if necessary. */
12870 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12871 udppullup:
12872 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12873 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12874 			freemsg(first_mp);
12875 			goto slow_done;
12876 		}
12877 		ipha = (ipha_t *)mp->b_rptr;
12878 	}
12879 
12880 	/*
12881 	 * Validate the checksum for the reassembled packet; for the
12882 	 * pullup case we calculate the payload checksum in software.
12883 	 */
12884 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12885 	if (up[3] != 0) {
12886 		boolean_t cksum_err;
12887 
12888 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12889 			IP_STAT(ipst, ip_in_sw_cksum);
12890 
12891 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12892 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12893 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12894 		    iphs[9] + up[2], sum, cksum_err);
12895 
12896 		if (cksum_err) {
12897 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12898 
12899 			if (reass_hck_flags & HCK_FULLCKSUM)
12900 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12901 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12902 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12903 			else
12904 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12905 
12906 			freemsg(first_mp);
12907 			goto slow_done;
12908 		}
12909 	}
12910 udpslowpath:
12911 
12912 	/* Clear hardware checksum flag to be safe */
12913 	DB_CKSUMFLAGS(mp) = 0;
12914 
12915 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12916 	    (ire->ire_type == IRE_BROADCAST),
12917 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12918 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12919 
12920 slow_done:
12921 	IP_STAT(ipst, ip_udp_slow_path);
12922 	return;
12923 
12924 #undef  iphs
12925 #undef  rptr
12926 }
12927 
12928 /* ARGSUSED */
12929 static mblk_t *
12930 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12931     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12932     ill_rx_ring_t *ill_ring)
12933 {
12934 	conn_t		*connp;
12935 	uint32_t	sum;
12936 	uint32_t	u1;
12937 	uint16_t	*up;
12938 	int		offset;
12939 	ssize_t		len;
12940 	mblk_t		*mp1;
12941 	boolean_t	syn_present = B_FALSE;
12942 	tcph_t		*tcph;
12943 	uint_t		ip_hdr_len;
12944 	ill_t		*ill = (ill_t *)q->q_ptr;
12945 	zoneid_t	zoneid = ire->ire_zoneid;
12946 	boolean_t	cksum_err;
12947 	uint16_t	hck_flags = 0;
12948 	ip_stack_t	*ipst = recv_ill->ill_ipst;
12949 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12950 
12951 #define	rptr	((uchar_t *)ipha)
12952 
12953 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12954 	ASSERT(ill != NULL);
12955 
12956 	/*
12957 	 * FAST PATH for tcp packets
12958 	 */
12959 
12960 	/* u1 is # words of IP options */
12961 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12962 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12963 
12964 	/* IP options present */
12965 	if (u1) {
12966 		goto ipoptions;
12967 	} else if (!mctl_present) {
12968 		/* Check the IP header checksum.  */
12969 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12970 			/* Clear the IP header h/w cksum flag */
12971 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12972 		} else if (!mctl_present) {
12973 			/*
12974 			 * Don't verify header checksum if this packet
12975 			 * is coming back from AH/ESP as we already did it.
12976 			 */
12977 #define	uph	((uint16_t *)ipha)
12978 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12979 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12980 #undef	uph
12981 			/* finish doing IP checksum */
12982 			sum = (sum & 0xFFFF) + (sum >> 16);
12983 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12984 			if (sum != 0 && sum != 0xFFFF) {
12985 				BUMP_MIB(ill->ill_ip_mib,
12986 				    ipIfStatsInCksumErrs);
12987 				goto error;
12988 			}
12989 		}
12990 	}
12991 
12992 	if (!mctl_present) {
12993 		UPDATE_IB_PKT_COUNT(ire);
12994 		ire->ire_last_used_time = lbolt;
12995 	}
12996 
12997 	/* packet part of fragmented IP packet? */
12998 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12999 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13000 		goto fragmented;
13001 	}
13002 
13003 	/* u1 = IP header length (20 bytes) */
13004 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
13005 
13006 	/* does packet contain IP+TCP headers? */
13007 	len = mp->b_wptr - rptr;
13008 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
13009 		IP_STAT(ipst, ip_tcppullup);
13010 		goto tcppullup;
13011 	}
13012 
13013 	/* TCP options present? */
13014 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
13015 
13016 	/*
13017 	 * If options need to be pulled up, then goto tcpoptions.
13018 	 * otherwise we are still in the fast path
13019 	 */
13020 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
13021 		IP_STAT(ipst, ip_tcpoptions);
13022 		goto tcpoptions;
13023 	}
13024 
13025 	/* multiple mblks of tcp data? */
13026 	if ((mp1 = mp->b_cont) != NULL) {
13027 		/* more then two? */
13028 		if (mp1->b_cont != NULL) {
13029 			IP_STAT(ipst, ip_multipkttcp);
13030 			goto multipkttcp;
13031 		}
13032 		len += mp1->b_wptr - mp1->b_rptr;
13033 	}
13034 
13035 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13036 
13037 	/* part of pseudo checksum */
13038 
13039 	/* TCP datagram length */
13040 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13041 
13042 #define	iphs    ((uint16_t *)ipha)
13043 
13044 #ifdef	_BIG_ENDIAN
13045 	u1 += IPPROTO_TCP;
13046 #else
13047 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13048 #endif
13049 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13050 
13051 	/*
13052 	 * Revert to software checksum calculation if the interface
13053 	 * isn't capable of checksum offload or if IPsec is present.
13054 	 */
13055 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
13056 		hck_flags = DB_CKSUMFLAGS(mp);
13057 
13058 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13059 		IP_STAT(ipst, ip_in_sw_cksum);
13060 
13061 	IP_CKSUM_RECV(hck_flags, u1,
13062 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13063 	    (int32_t)((uchar_t *)up - rptr),
13064 	    mp, mp1, cksum_err);
13065 
13066 	if (cksum_err) {
13067 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13068 
13069 		if (hck_flags & HCK_FULLCKSUM)
13070 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13071 		else if (hck_flags & HCK_PARTIALCKSUM)
13072 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13073 		else
13074 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13075 
13076 		goto error;
13077 	}
13078 
13079 try_again:
13080 
13081 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13082 	    zoneid, ipst)) == NULL) {
13083 		/* Send the TH_RST */
13084 		goto no_conn;
13085 	}
13086 
13087 	/*
13088 	 * TCP FAST PATH for AF_INET socket.
13089 	 *
13090 	 * TCP fast path to avoid extra work. An AF_INET socket type
13091 	 * does not have facility to receive extra information via
13092 	 * ip_process or ip_add_info. Also, when the connection was
13093 	 * established, we made a check if this connection is impacted
13094 	 * by any global IPsec policy or per connection policy (a
13095 	 * policy that comes in effect later will not apply to this
13096 	 * connection). Since all this can be determined at the
13097 	 * connection establishment time, a quick check of flags
13098 	 * can avoid extra work.
13099 	 */
13100 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13101 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13102 		ASSERT(first_mp == mp);
13103 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13104 		SET_SQUEUE(mp, tcp_rput_data, connp);
13105 		return (mp);
13106 	}
13107 
13108 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13109 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
13110 		if (IPCL_IS_TCP(connp)) {
13111 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13112 			DB_CKSUMSTART(mp) =
13113 			    (intptr_t)ip_squeue_get(ill_ring);
13114 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13115 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13116 				BUMP_MIB(ill->ill_ip_mib,
13117 				    ipIfStatsHCInDelivers);
13118 				SET_SQUEUE(mp, connp->conn_recv, connp);
13119 				return (mp);
13120 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13121 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13122 				BUMP_MIB(ill->ill_ip_mib,
13123 				    ipIfStatsHCInDelivers);
13124 				ip_squeue_enter_unbound++;
13125 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13126 				    connp);
13127 				return (mp);
13128 			}
13129 			syn_present = B_TRUE;
13130 		}
13131 
13132 	}
13133 
13134 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13135 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13136 
13137 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13138 		/* No need to send this packet to TCP */
13139 		if ((flags & TH_RST) || (flags & TH_URG)) {
13140 			CONN_DEC_REF(connp);
13141 			freemsg(first_mp);
13142 			return (NULL);
13143 		}
13144 		if (flags & TH_ACK) {
13145 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
13146 			    ipst->ips_netstack->netstack_tcp, connp);
13147 			CONN_DEC_REF(connp);
13148 			return (NULL);
13149 		}
13150 
13151 		CONN_DEC_REF(connp);
13152 		freemsg(first_mp);
13153 		return (NULL);
13154 	}
13155 
13156 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13157 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13158 		    ipha, NULL, mctl_present);
13159 		if (first_mp == NULL) {
13160 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13161 			CONN_DEC_REF(connp);
13162 			return (NULL);
13163 		}
13164 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13165 			ASSERT(syn_present);
13166 			if (mctl_present) {
13167 				ASSERT(first_mp != mp);
13168 				first_mp->b_datap->db_struioflag |=
13169 				    STRUIO_POLICY;
13170 			} else {
13171 				ASSERT(first_mp == mp);
13172 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13173 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13174 			}
13175 		} else {
13176 			/*
13177 			 * Discard first_mp early since we're dealing with a
13178 			 * fully-connected conn_t and tcp doesn't do policy in
13179 			 * this case.
13180 			 */
13181 			if (mctl_present) {
13182 				freeb(first_mp);
13183 				mctl_present = B_FALSE;
13184 			}
13185 			first_mp = mp;
13186 		}
13187 	}
13188 
13189 	/* Initiate IPPF processing for fastpath */
13190 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13191 		uint32_t	ill_index;
13192 
13193 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13194 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13195 		if (mp == NULL) {
13196 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13197 			    "deferred/dropped during IPPF processing\n"));
13198 			CONN_DEC_REF(connp);
13199 			if (mctl_present)
13200 				freeb(first_mp);
13201 			return (NULL);
13202 		} else if (mctl_present) {
13203 			/*
13204 			 * ip_process might return a new mp.
13205 			 */
13206 			ASSERT(first_mp != mp);
13207 			first_mp->b_cont = mp;
13208 		} else {
13209 			first_mp = mp;
13210 		}
13211 
13212 	}
13213 
13214 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13215 		/*
13216 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13217 		 * make sure IPF_RECVIF is passed to ip_add_info.
13218 		 */
13219 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13220 		    IPCL_ZONEID(connp), ipst);
13221 		if (mp == NULL) {
13222 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13223 			CONN_DEC_REF(connp);
13224 			if (mctl_present)
13225 				freeb(first_mp);
13226 			return (NULL);
13227 		} else if (mctl_present) {
13228 			/*
13229 			 * ip_add_info might return a new mp.
13230 			 */
13231 			ASSERT(first_mp != mp);
13232 			first_mp->b_cont = mp;
13233 		} else {
13234 			first_mp = mp;
13235 		}
13236 	}
13237 
13238 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13239 	if (IPCL_IS_TCP(connp)) {
13240 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13241 		return (first_mp);
13242 	} else {
13243 		/* SOCK_RAW, IPPROTO_TCP case */
13244 		(connp->conn_recv)(connp, first_mp, NULL);
13245 		CONN_DEC_REF(connp);
13246 		return (NULL);
13247 	}
13248 
13249 no_conn:
13250 	/* Initiate IPPf processing, if needed. */
13251 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13252 		uint32_t ill_index;
13253 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13254 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13255 		if (first_mp == NULL) {
13256 			return (NULL);
13257 		}
13258 	}
13259 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13260 
13261 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13262 	    ipst->ips_netstack->netstack_tcp, NULL);
13263 	return (NULL);
13264 ipoptions:
13265 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13266 		goto slow_done;
13267 	}
13268 
13269 	UPDATE_IB_PKT_COUNT(ire);
13270 	ire->ire_last_used_time = lbolt;
13271 
13272 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13273 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13274 fragmented:
13275 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13276 			if (mctl_present)
13277 				freeb(first_mp);
13278 			goto slow_done;
13279 		}
13280 		/*
13281 		 * Make sure that first_mp points back to mp as
13282 		 * the mp we came in with could have changed in
13283 		 * ip_rput_fragment().
13284 		 */
13285 		ASSERT(!mctl_present);
13286 		ipha = (ipha_t *)mp->b_rptr;
13287 		first_mp = mp;
13288 	}
13289 
13290 	/* Now we have a complete datagram, destined for this machine. */
13291 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13292 
13293 	len = mp->b_wptr - mp->b_rptr;
13294 	/* Pull up a minimal TCP header, if necessary. */
13295 	if (len < (u1 + 20)) {
13296 tcppullup:
13297 		if (!pullupmsg(mp, u1 + 20)) {
13298 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13299 			goto error;
13300 		}
13301 		ipha = (ipha_t *)mp->b_rptr;
13302 		len = mp->b_wptr - mp->b_rptr;
13303 	}
13304 
13305 	/*
13306 	 * Extract the offset field from the TCP header.  As usual, we
13307 	 * try to help the compiler more than the reader.
13308 	 */
13309 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13310 	if (offset != 5) {
13311 tcpoptions:
13312 		if (offset < 5) {
13313 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13314 			goto error;
13315 		}
13316 		/*
13317 		 * There must be TCP options.
13318 		 * Make sure we can grab them.
13319 		 */
13320 		offset <<= 2;
13321 		offset += u1;
13322 		if (len < offset) {
13323 			if (!pullupmsg(mp, offset)) {
13324 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13325 				goto error;
13326 			}
13327 			ipha = (ipha_t *)mp->b_rptr;
13328 			len = mp->b_wptr - rptr;
13329 		}
13330 	}
13331 
13332 	/* Get the total packet length in len, including headers. */
13333 	if (mp->b_cont) {
13334 multipkttcp:
13335 		len = msgdsize(mp);
13336 	}
13337 
13338 	/*
13339 	 * Check the TCP checksum by pulling together the pseudo-
13340 	 * header checksum, and passing it to ip_csum to be added in
13341 	 * with the TCP datagram.
13342 	 *
13343 	 * Since we are not using the hwcksum if available we must
13344 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13345 	 * If either of these fails along the way the mblk is freed.
13346 	 * If this logic ever changes and mblk is reused to say send
13347 	 * ICMP's back, then this flag may need to be cleared in
13348 	 * other places as well.
13349 	 */
13350 	DB_CKSUMFLAGS(mp) = 0;
13351 
13352 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13353 
13354 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13355 #ifdef	_BIG_ENDIAN
13356 	u1 += IPPROTO_TCP;
13357 #else
13358 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13359 #endif
13360 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13361 	/*
13362 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13363 	 */
13364 	IP_STAT(ipst, ip_in_sw_cksum);
13365 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13366 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13367 		goto error;
13368 	}
13369 
13370 	IP_STAT(ipst, ip_tcp_slow_path);
13371 	goto try_again;
13372 #undef  iphs
13373 #undef  rptr
13374 
13375 error:
13376 	freemsg(first_mp);
13377 slow_done:
13378 	return (NULL);
13379 }
13380 
13381 /* ARGSUSED */
13382 static void
13383 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13384     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13385 {
13386 	conn_t		*connp;
13387 	uint32_t	sum;
13388 	uint32_t	u1;
13389 	ssize_t		len;
13390 	sctp_hdr_t	*sctph;
13391 	zoneid_t	zoneid = ire->ire_zoneid;
13392 	uint32_t	pktsum;
13393 	uint32_t	calcsum;
13394 	uint32_t	ports;
13395 	in6_addr_t	map_src, map_dst;
13396 	ill_t		*ill = (ill_t *)q->q_ptr;
13397 	ip_stack_t	*ipst;
13398 	sctp_stack_t	*sctps;
13399 	boolean_t	sctp_csum_err = B_FALSE;
13400 
13401 	ASSERT(recv_ill != NULL);
13402 	ipst = recv_ill->ill_ipst;
13403 	sctps = ipst->ips_netstack->netstack_sctp;
13404 
13405 #define	rptr	((uchar_t *)ipha)
13406 
13407 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13408 	ASSERT(ill != NULL);
13409 
13410 	/* u1 is # words of IP options */
13411 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13412 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13413 
13414 	/* IP options present */
13415 	if (u1 > 0) {
13416 		goto ipoptions;
13417 	} else {
13418 		/* Check the IP header checksum.  */
13419 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill) &&
13420 		    !mctl_present) {
13421 #define	uph	((uint16_t *)ipha)
13422 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13423 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13424 #undef	uph
13425 			/* finish doing IP checksum */
13426 			sum = (sum & 0xFFFF) + (sum >> 16);
13427 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13428 			/*
13429 			 * Don't verify header checksum if this packet
13430 			 * is coming back from AH/ESP as we already did it.
13431 			 */
13432 			if (sum != 0 && sum != 0xFFFF) {
13433 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13434 				goto error;
13435 			}
13436 		}
13437 		/*
13438 		 * Since there is no SCTP h/w cksum support yet, just
13439 		 * clear the flag.
13440 		 */
13441 		DB_CKSUMFLAGS(mp) = 0;
13442 	}
13443 
13444 	/*
13445 	 * Don't verify header checksum if this packet is coming
13446 	 * back from AH/ESP as we already did it.
13447 	 */
13448 	if (!mctl_present) {
13449 		UPDATE_IB_PKT_COUNT(ire);
13450 		ire->ire_last_used_time = lbolt;
13451 	}
13452 
13453 	/* packet part of fragmented IP packet? */
13454 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13455 	if (u1 & (IPH_MF | IPH_OFFSET))
13456 		goto fragmented;
13457 
13458 	/* u1 = IP header length (20 bytes) */
13459 	u1 = IP_SIMPLE_HDR_LENGTH;
13460 
13461 find_sctp_client:
13462 	/* Pullup if we don't have the sctp common header. */
13463 	len = MBLKL(mp);
13464 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13465 		if (mp->b_cont == NULL ||
13466 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13467 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13468 			goto error;
13469 		}
13470 		ipha = (ipha_t *)mp->b_rptr;
13471 		len = MBLKL(mp);
13472 	}
13473 
13474 	sctph = (sctp_hdr_t *)(rptr + u1);
13475 #ifdef	DEBUG
13476 	if (!skip_sctp_cksum) {
13477 #endif
13478 		pktsum = sctph->sh_chksum;
13479 		sctph->sh_chksum = 0;
13480 		calcsum = sctp_cksum(mp, u1);
13481 		sctph->sh_chksum = pktsum;
13482 		if (calcsum != pktsum)
13483 			sctp_csum_err = B_TRUE;
13484 #ifdef	DEBUG	/* skip_sctp_cksum */
13485 	}
13486 #endif
13487 	/* get the ports */
13488 	ports = *(uint32_t *)&sctph->sh_sport;
13489 
13490 	IRE_REFRELE(ire);
13491 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13492 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13493 	if (sctp_csum_err) {
13494 		/*
13495 		 * No potential sctp checksum errors go to the Sun
13496 		 * sctp stack however they might be Adler-32 summed
13497 		 * packets a userland stack bound to a raw IP socket
13498 		 * could reasonably use. Note though that Adler-32 is
13499 		 * a long deprecated algorithm and customer sctp
13500 		 * networks should eventually migrate to CRC-32 at
13501 		 * which time this facility should be removed.
13502 		 */
13503 		flags |= IP_FF_SCTP_CSUM_ERR;
13504 		goto no_conn;
13505 	}
13506 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13507 	    sctps)) == NULL) {
13508 		/* Check for raw socket or OOTB handling */
13509 		goto no_conn;
13510 	}
13511 
13512 	/* Found a client; up it goes */
13513 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13514 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13515 	return;
13516 
13517 no_conn:
13518 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13519 	    ports, mctl_present, flags, B_TRUE, zoneid);
13520 	return;
13521 
13522 ipoptions:
13523 	DB_CKSUMFLAGS(mp) = 0;
13524 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13525 		goto slow_done;
13526 
13527 	UPDATE_IB_PKT_COUNT(ire);
13528 	ire->ire_last_used_time = lbolt;
13529 
13530 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13531 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13532 fragmented:
13533 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13534 			goto slow_done;
13535 		/*
13536 		 * Make sure that first_mp points back to mp as
13537 		 * the mp we came in with could have changed in
13538 		 * ip_rput_fragment().
13539 		 */
13540 		ASSERT(!mctl_present);
13541 		ipha = (ipha_t *)mp->b_rptr;
13542 		first_mp = mp;
13543 	}
13544 
13545 	/* Now we have a complete datagram, destined for this machine. */
13546 	u1 = IPH_HDR_LENGTH(ipha);
13547 	goto find_sctp_client;
13548 #undef  iphs
13549 #undef  rptr
13550 
13551 error:
13552 	freemsg(first_mp);
13553 slow_done:
13554 	IRE_REFRELE(ire);
13555 }
13556 
13557 #define	VER_BITS	0xF0
13558 #define	VERSION_6	0x60
13559 
13560 static boolean_t
13561 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13562     ipaddr_t *dstp, ip_stack_t *ipst)
13563 {
13564 	uint_t	opt_len;
13565 	ipha_t *ipha;
13566 	ssize_t len;
13567 	uint_t	pkt_len;
13568 
13569 	ASSERT(ill != NULL);
13570 	IP_STAT(ipst, ip_ipoptions);
13571 	ipha = *iphapp;
13572 
13573 #define	rptr    ((uchar_t *)ipha)
13574 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13575 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13576 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13577 		freemsg(mp);
13578 		return (B_FALSE);
13579 	}
13580 
13581 	/* multiple mblk or too short */
13582 	pkt_len = ntohs(ipha->ipha_length);
13583 
13584 	/* Get the number of words of IP options in the IP header. */
13585 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13586 	if (opt_len) {
13587 		/* IP Options present!  Validate and process. */
13588 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13589 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13590 			goto done;
13591 		}
13592 		/*
13593 		 * Recompute complete header length and make sure we
13594 		 * have access to all of it.
13595 		 */
13596 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13597 		if (len > (mp->b_wptr - rptr)) {
13598 			if (len > pkt_len) {
13599 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13600 				goto done;
13601 			}
13602 			if (!pullupmsg(mp, len)) {
13603 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13604 				goto done;
13605 			}
13606 			ipha = (ipha_t *)mp->b_rptr;
13607 		}
13608 		/*
13609 		 * Go off to ip_rput_options which returns the next hop
13610 		 * destination address, which may have been affected
13611 		 * by source routing.
13612 		 */
13613 		IP_STAT(ipst, ip_opt);
13614 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13615 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13616 			return (B_FALSE);
13617 		}
13618 	}
13619 	*iphapp = ipha;
13620 	return (B_TRUE);
13621 done:
13622 	/* clear b_prev - used by ip_mroute_decap */
13623 	mp->b_prev = NULL;
13624 	freemsg(mp);
13625 	return (B_FALSE);
13626 #undef  rptr
13627 }
13628 
13629 /*
13630  * Deal with the fact that there is no ire for the destination.
13631  */
13632 static ire_t *
13633 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13634 {
13635 	ipha_t	*ipha;
13636 	ill_t	*ill;
13637 	ire_t	*ire;
13638 	ip_stack_t *ipst;
13639 	enum	ire_forward_action ret_action;
13640 
13641 	ipha = (ipha_t *)mp->b_rptr;
13642 	ill = (ill_t *)q->q_ptr;
13643 
13644 	ASSERT(ill != NULL);
13645 	ipst = ill->ill_ipst;
13646 
13647 	/*
13648 	 * No IRE for this destination, so it can't be for us.
13649 	 * Unless we are forwarding, drop the packet.
13650 	 * We have to let source routed packets through
13651 	 * since we don't yet know if they are 'ping -l'
13652 	 * packets i.e. if they will go out over the
13653 	 * same interface as they came in on.
13654 	 */
13655 	if (ll_multicast) {
13656 		freemsg(mp);
13657 		return (NULL);
13658 	}
13659 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13660 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13661 		freemsg(mp);
13662 		return (NULL);
13663 	}
13664 
13665 	/*
13666 	 * Mark this packet as having originated externally.
13667 	 *
13668 	 * For non-forwarding code path, ire_send later double
13669 	 * checks this interface to see if it is still exists
13670 	 * post-ARP resolution.
13671 	 *
13672 	 * Also, IPQOS uses this to differentiate between
13673 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13674 	 * QOS packet processing in ip_wput_attach_llhdr().
13675 	 * The QoS module can mark the b_band for a fastpath message
13676 	 * or the dl_priority field in a unitdata_req header for
13677 	 * CoS marking. This info can only be found in
13678 	 * ip_wput_attach_llhdr().
13679 	 */
13680 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13681 	/*
13682 	 * Clear the indication that this may have a hardware checksum
13683 	 * as we are not using it
13684 	 */
13685 	DB_CKSUMFLAGS(mp) = 0;
13686 
13687 	ire = ire_forward(dst, &ret_action, NULL, NULL,
13688 	    MBLK_GETLABEL(mp), ipst);
13689 
13690 	if (ire == NULL && ret_action == Forward_check_multirt) {
13691 		/* Let ip_newroute handle CGTP  */
13692 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13693 		return (NULL);
13694 	}
13695 
13696 	if (ire != NULL)
13697 		return (ire);
13698 
13699 	mp->b_prev = mp->b_next = 0;
13700 
13701 	if (ret_action == Forward_blackhole) {
13702 		freemsg(mp);
13703 		return (NULL);
13704 	}
13705 	/* send icmp unreachable */
13706 	q = WR(q);
13707 	/* Sent by forwarding path, and router is global zone */
13708 	if (ip_source_routed(ipha, ipst)) {
13709 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13710 		    GLOBAL_ZONEID, ipst);
13711 	} else {
13712 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13713 		    ipst);
13714 	}
13715 
13716 	return (NULL);
13717 
13718 }
13719 
13720 /*
13721  * check ip header length and align it.
13722  */
13723 static boolean_t
13724 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13725 {
13726 	ssize_t len;
13727 	ill_t *ill;
13728 	ipha_t	*ipha;
13729 
13730 	len = MBLKL(mp);
13731 
13732 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13733 		ill = (ill_t *)q->q_ptr;
13734 
13735 		if (!OK_32PTR(mp->b_rptr))
13736 			IP_STAT(ipst, ip_notaligned1);
13737 		else
13738 			IP_STAT(ipst, ip_notaligned2);
13739 		/* Guard against bogus device drivers */
13740 		if (len < 0) {
13741 			/* clear b_prev - used by ip_mroute_decap */
13742 			mp->b_prev = NULL;
13743 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13744 			freemsg(mp);
13745 			return (B_FALSE);
13746 		}
13747 
13748 		if (ip_rput_pullups++ == 0) {
13749 			ipha = (ipha_t *)mp->b_rptr;
13750 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13751 			    "ip_check_and_align_header: %s forced us to "
13752 			    " pullup pkt, hdr len %ld, hdr addr %p",
13753 			    ill->ill_name, len, ipha);
13754 		}
13755 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13756 			/* clear b_prev - used by ip_mroute_decap */
13757 			mp->b_prev = NULL;
13758 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13759 			freemsg(mp);
13760 			return (B_FALSE);
13761 		}
13762 	}
13763 	return (B_TRUE);
13764 }
13765 
13766 ire_t *
13767 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13768 {
13769 	ire_t		*new_ire;
13770 	ill_t		*ire_ill;
13771 	uint_t		ifindex;
13772 	ip_stack_t	*ipst = ill->ill_ipst;
13773 	boolean_t	strict_check = B_FALSE;
13774 
13775 	/*
13776 	 * This packet came in on an interface other than the one associated
13777 	 * with the first ire we found for the destination address. We do
13778 	 * another ire lookup here, using the ingress ill, to see if the
13779 	 * interface is in an interface group.
13780 	 * As long as the ills belong to the same group, we don't consider
13781 	 * them to be arriving on the wrong interface. Thus, if the switch
13782 	 * is doing inbound load spreading, we won't drop packets when the
13783 	 * ip*_strict_dst_multihoming switch is on. Note, the same holds true
13784 	 * for 'usesrc groups' where the destination address may belong to
13785 	 * another interface to allow multipathing to happen.
13786 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13787 	 * where the local address may not be unique. In this case we were
13788 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13789 	 * actually returned. The new lookup, which is more specific, should
13790 	 * only find the IRE_LOCAL associated with the ingress ill if one
13791 	 * exists.
13792 	 */
13793 
13794 	if (ire->ire_ipversion == IPV4_VERSION) {
13795 		if (ipst->ips_ip_strict_dst_multihoming)
13796 			strict_check = B_TRUE;
13797 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13798 		    ill->ill_ipif, ALL_ZONES, NULL,
13799 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13800 	} else {
13801 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13802 		if (ipst->ips_ipv6_strict_dst_multihoming)
13803 			strict_check = B_TRUE;
13804 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13805 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13806 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13807 	}
13808 	/*
13809 	 * If the same ire that was returned in ip_input() is found then this
13810 	 * is an indication that interface groups are in use. The packet
13811 	 * arrived on a different ill in the group than the one associated with
13812 	 * the destination address.  If a different ire was found then the same
13813 	 * IP address must be hosted on multiple ills. This is possible with
13814 	 * unnumbered point2point interfaces. We switch to use this new ire in
13815 	 * order to have accurate interface statistics.
13816 	 */
13817 	if (new_ire != NULL) {
13818 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13819 			ire_refrele(ire);
13820 			ire = new_ire;
13821 		} else {
13822 			ire_refrele(new_ire);
13823 		}
13824 		return (ire);
13825 	} else if ((ire->ire_rfq == NULL) &&
13826 	    (ire->ire_ipversion == IPV4_VERSION)) {
13827 		/*
13828 		 * The best match could have been the original ire which
13829 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13830 		 * the strict multihoming checks are irrelevant as we consider
13831 		 * local addresses hosted on lo0 to be interface agnostic. We
13832 		 * only expect a null ire_rfq on IREs which are associated with
13833 		 * lo0 hence we can return now.
13834 		 */
13835 		return (ire);
13836 	}
13837 
13838 	/*
13839 	 * Chase pointers once and store locally.
13840 	 */
13841 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13842 	    (ill_t *)(ire->ire_rfq->q_ptr);
13843 	ifindex = ill->ill_usesrc_ifindex;
13844 
13845 	/*
13846 	 * Check if it's a legal address on the 'usesrc' interface.
13847 	 */
13848 	if ((ifindex != 0) && (ire_ill != NULL) &&
13849 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13850 		return (ire);
13851 	}
13852 
13853 	/*
13854 	 * If the ip*_strict_dst_multihoming switch is on then we can
13855 	 * only accept this packet if the interface is marked as routing.
13856 	 */
13857 	if (!(strict_check))
13858 		return (ire);
13859 
13860 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13861 	    ILLF_ROUTER) != 0) {
13862 		return (ire);
13863 	}
13864 
13865 	ire_refrele(ire);
13866 	return (NULL);
13867 }
13868 
13869 ire_t *
13870 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13871 {
13872 	ipha_t	*ipha;
13873 	ire_t	*src_ire;
13874 	ill_t	*stq_ill;
13875 	uint_t	hlen;
13876 	uint_t	pkt_len;
13877 	uint32_t sum;
13878 	queue_t	*dev_q;
13879 	ip_stack_t *ipst = ill->ill_ipst;
13880 	mblk_t *fpmp;
13881 	enum	ire_forward_action ret_action;
13882 
13883 	ipha = (ipha_t *)mp->b_rptr;
13884 
13885 	if (ire != NULL &&
13886 	    ire->ire_zoneid != GLOBAL_ZONEID &&
13887 	    ire->ire_zoneid != ALL_ZONES) {
13888 		/*
13889 		 * Should only use IREs that are visible to the global
13890 		 * zone for forwarding.
13891 		 */
13892 		ire_refrele(ire);
13893 		ire = ire_cache_lookup(dst, GLOBAL_ZONEID, NULL, ipst);
13894 	}
13895 
13896 	/*
13897 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13898 	 * The loopback address check for both src and dst has already
13899 	 * been checked in ip_input
13900 	 */
13901 
13902 	if (dst == INADDR_ANY || CLASSD(ipha->ipha_src)) {
13903 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13904 		goto drop;
13905 	}
13906 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13907 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13908 
13909 	if (src_ire != NULL) {
13910 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13911 		ire_refrele(src_ire);
13912 		goto drop;
13913 	}
13914 
13915 	/* No ire cache of nexthop. So first create one  */
13916 	if (ire == NULL) {
13917 
13918 		ire = ire_forward(dst, &ret_action, NULL, NULL,
13919 		    NULL, ipst);
13920 		/*
13921 		 * We only come to ip_fast_forward if ip_cgtp_filter
13922 		 * is not set. So ire_forward() should not return with
13923 		 * Forward_check_multirt as the next action.
13924 		 */
13925 		ASSERT(ret_action != Forward_check_multirt);
13926 		if (ire == NULL) {
13927 			/* An attempt was made to forward the packet */
13928 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13929 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13930 			mp->b_prev = mp->b_next = 0;
13931 			/* send icmp unreachable */
13932 			/* Sent by forwarding path, and router is global zone */
13933 			if (ret_action == Forward_ret_icmp_err) {
13934 				if (ip_source_routed(ipha, ipst)) {
13935 					icmp_unreachable(ill->ill_wq, mp,
13936 					    ICMP_SOURCE_ROUTE_FAILED,
13937 					    GLOBAL_ZONEID, ipst);
13938 				} else {
13939 					icmp_unreachable(ill->ill_wq, mp,
13940 					    ICMP_HOST_UNREACHABLE,
13941 					    GLOBAL_ZONEID, ipst);
13942 				}
13943 			} else {
13944 				freemsg(mp);
13945 			}
13946 			return (NULL);
13947 		}
13948 	}
13949 
13950 	/*
13951 	 * Forwarding fastpath exception case:
13952 	 * If either of the follwoing case is true, we take
13953 	 * the slowpath
13954 	 *	o forwarding is not enabled
13955 	 *	o incoming and outgoing interface are the same, or the same
13956 	 *	  IPMP group
13957 	 *	o corresponding ire is in incomplete state
13958 	 *	o packet needs fragmentation
13959 	 *	o ARP cache is not resolved
13960 	 *
13961 	 * The codeflow from here on is thus:
13962 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13963 	 */
13964 	pkt_len = ntohs(ipha->ipha_length);
13965 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13966 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13967 	    !(ill->ill_flags & ILLF_ROUTER) ||
13968 	    (ill == stq_ill) ||
13969 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
13970 	    (ire->ire_nce == NULL) ||
13971 	    (pkt_len > ire->ire_max_frag) ||
13972 	    ((fpmp = ire->ire_nce->nce_fp_mp) == NULL) ||
13973 	    ((hlen = MBLKL(fpmp)) > MBLKHEAD(mp)) ||
13974 	    ipha->ipha_ttl <= 1) {
13975 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13976 		    ipha, ill, B_FALSE);
13977 		return (ire);
13978 	}
13979 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13980 
13981 	DTRACE_PROBE4(ip4__forwarding__start,
13982 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13983 
13984 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
13985 	    ipst->ips_ipv4firewall_forwarding,
13986 	    ill, stq_ill, ipha, mp, mp, 0, ipst);
13987 
13988 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13989 
13990 	if (mp == NULL)
13991 		goto drop;
13992 
13993 	mp->b_datap->db_struioun.cksum.flags = 0;
13994 	/* Adjust the checksum to reflect the ttl decrement. */
13995 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13996 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
13997 	ipha->ipha_ttl--;
13998 
13999 	/*
14000 	 * Write the link layer header.  We can do this safely here,
14001 	 * because we have already tested to make sure that the IP
14002 	 * policy is not set, and that we have a fast path destination
14003 	 * header.
14004 	 */
14005 	mp->b_rptr -= hlen;
14006 	bcopy(fpmp->b_rptr, mp->b_rptr, hlen);
14007 
14008 	UPDATE_IB_PKT_COUNT(ire);
14009 	ire->ire_last_used_time = lbolt;
14010 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
14011 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14012 	UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets, pkt_len);
14013 
14014 	dev_q = ire->ire_stq->q_next;
14015 	if ((dev_q->q_next != NULL || dev_q->q_first != NULL) &&
14016 	    !canputnext(ire->ire_stq)) {
14017 		goto indiscard;
14018 	}
14019 	if (ILL_DLS_CAPABLE(stq_ill)) {
14020 		/*
14021 		 * Send the packet directly to DLD, where it
14022 		 * may be queued depending on the availability
14023 		 * of transmit resources at the media layer.
14024 		 */
14025 		IP_DLS_ILL_TX(stq_ill, ipha, mp, ipst);
14026 	} else {
14027 		DTRACE_PROBE4(ip4__physical__out__start,
14028 		    ill_t *, NULL, ill_t *, stq_ill,
14029 		    ipha_t *, ipha, mblk_t *, mp);
14030 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
14031 		    ipst->ips_ipv4firewall_physical_out,
14032 		    NULL, stq_ill, ipha, mp, mp, 0, ipst);
14033 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
14034 		if (mp == NULL)
14035 			goto drop;
14036 
14037 		DTRACE_IP7(send, mblk_t *, mp, conn_t *, NULL, void_ip_t *,
14038 		    ipha, __dtrace_ipsr_ill_t *, stq_ill, ipha_t *, ipha,
14039 		    ip6_t *, NULL, int, 0);
14040 
14041 		putnext(ire->ire_stq, mp);
14042 	}
14043 	return (ire);
14044 
14045 indiscard:
14046 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14047 drop:
14048 	if (mp != NULL)
14049 		freemsg(mp);
14050 	return (ire);
14051 
14052 }
14053 
14054 /*
14055  * This function is called in the forwarding slowpath, when
14056  * either the ire lacks the link-layer address, or the packet needs
14057  * further processing(eg. fragmentation), before transmission.
14058  */
14059 
14060 static void
14061 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14062     ill_t *ill, boolean_t ll_multicast)
14063 {
14064 	ill_group_t	*ill_group;
14065 	ill_group_t	*ire_group;
14066 	queue_t		*dev_q;
14067 	ire_t		*src_ire;
14068 	ip_stack_t	*ipst = ill->ill_ipst;
14069 
14070 	ASSERT(ire->ire_stq != NULL);
14071 
14072 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14073 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14074 
14075 	if (ll_multicast != 0) {
14076 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14077 		goto drop_pkt;
14078 	}
14079 
14080 	/*
14081 	 * check if ipha_src is a broadcast address. Note that this
14082 	 * check is redundant when we get here from ip_fast_forward()
14083 	 * which has already done this check. However, since we can
14084 	 * also get here from ip_rput_process_broadcast() or, for
14085 	 * for the slow path through ip_fast_forward(), we perform
14086 	 * the check again for code-reusability
14087 	 */
14088 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14089 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14090 	if (src_ire != NULL || ipha->ipha_dst == INADDR_ANY) {
14091 		if (src_ire != NULL)
14092 			ire_refrele(src_ire);
14093 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14094 		ip2dbg(("ip_rput_process_forward: Received packet with"
14095 		    " bad src/dst address on %s\n", ill->ill_name));
14096 		goto drop_pkt;
14097 	}
14098 
14099 	ill_group = ill->ill_group;
14100 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
14101 	/*
14102 	 * Check if we want to forward this one at this time.
14103 	 * We allow source routed packets on a host provided that
14104 	 * they go out the same interface or same interface group
14105 	 * as they came in on.
14106 	 *
14107 	 * XXX To be quicker, we may wish to not chase pointers to
14108 	 * get the ILLF_ROUTER flag and instead store the
14109 	 * forwarding policy in the ire.  An unfortunate
14110 	 * side-effect of that would be requiring an ire flush
14111 	 * whenever the ILLF_ROUTER flag changes.
14112 	 */
14113 	if (((ill->ill_flags &
14114 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
14115 	    ILLF_ROUTER) == 0) &&
14116 	    !(ip_source_routed(ipha, ipst) && (ire->ire_rfq == q ||
14117 	    (ill_group != NULL && ill_group == ire_group)))) {
14118 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14119 		if (ip_source_routed(ipha, ipst)) {
14120 			q = WR(q);
14121 			/*
14122 			 * Clear the indication that this may have
14123 			 * hardware checksum as we are not using it.
14124 			 */
14125 			DB_CKSUMFLAGS(mp) = 0;
14126 			/* Sent by forwarding path, and router is global zone */
14127 			icmp_unreachable(q, mp,
14128 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14129 			return;
14130 		}
14131 		goto drop_pkt;
14132 	}
14133 
14134 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14135 
14136 	/* Packet is being forwarded. Turning off hwcksum flag. */
14137 	DB_CKSUMFLAGS(mp) = 0;
14138 	if (ipst->ips_ip_g_send_redirects) {
14139 		/*
14140 		 * Check whether the incoming interface and outgoing
14141 		 * interface is part of the same group. If so,
14142 		 * send redirects.
14143 		 *
14144 		 * Check the source address to see if it originated
14145 		 * on the same logical subnet it is going back out on.
14146 		 * If so, we should be able to send it a redirect.
14147 		 * Avoid sending a redirect if the destination
14148 		 * is directly connected (i.e., ipha_dst is the same
14149 		 * as ire_gateway_addr or the ire_addr of the
14150 		 * nexthop IRE_CACHE ), or if the packet was source
14151 		 * routed out this interface.
14152 		 */
14153 		ipaddr_t src, nhop;
14154 		mblk_t	*mp1;
14155 		ire_t	*nhop_ire = NULL;
14156 
14157 		/*
14158 		 * Check whether ire_rfq and q are from the same ill
14159 		 * or if they are not same, they at least belong
14160 		 * to the same group. If so, send redirects.
14161 		 */
14162 		if ((ire->ire_rfq == q ||
14163 		    (ill_group != NULL && ill_group == ire_group)) &&
14164 		    !ip_source_routed(ipha, ipst)) {
14165 
14166 			nhop = (ire->ire_gateway_addr != 0 ?
14167 			    ire->ire_gateway_addr : ire->ire_addr);
14168 
14169 			if (ipha->ipha_dst == nhop) {
14170 				/*
14171 				 * We avoid sending a redirect if the
14172 				 * destination is directly connected
14173 				 * because it is possible that multiple
14174 				 * IP subnets may have been configured on
14175 				 * the link, and the source may not
14176 				 * be on the same subnet as ip destination,
14177 				 * even though they are on the same
14178 				 * physical link.
14179 				 */
14180 				goto sendit;
14181 			}
14182 
14183 			src = ipha->ipha_src;
14184 
14185 			/*
14186 			 * We look up the interface ire for the nexthop,
14187 			 * to see if ipha_src is in the same subnet
14188 			 * as the nexthop.
14189 			 *
14190 			 * Note that, if, in the future, IRE_CACHE entries
14191 			 * are obsoleted,  this lookup will not be needed,
14192 			 * as the ire passed to this function will be the
14193 			 * same as the nhop_ire computed below.
14194 			 */
14195 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14196 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14197 			    0, NULL, MATCH_IRE_TYPE, ipst);
14198 
14199 			if (nhop_ire != NULL) {
14200 				if ((src & nhop_ire->ire_mask) ==
14201 				    (nhop & nhop_ire->ire_mask)) {
14202 					/*
14203 					 * The source is directly connected.
14204 					 * Just copy the ip header (which is
14205 					 * in the first mblk)
14206 					 */
14207 					mp1 = copyb(mp);
14208 					if (mp1 != NULL) {
14209 						icmp_send_redirect(WR(q), mp1,
14210 						    nhop, ipst);
14211 					}
14212 				}
14213 				ire_refrele(nhop_ire);
14214 			}
14215 		}
14216 	}
14217 sendit:
14218 	dev_q = ire->ire_stq->q_next;
14219 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
14220 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14221 		freemsg(mp);
14222 		return;
14223 	}
14224 
14225 	ip_rput_forward(ire, ipha, mp, ill);
14226 	return;
14227 
14228 drop_pkt:
14229 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14230 	freemsg(mp);
14231 }
14232 
14233 ire_t *
14234 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14235     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14236 {
14237 	queue_t		*q;
14238 	uint16_t	hcksumflags;
14239 	ip_stack_t	*ipst = ill->ill_ipst;
14240 
14241 	q = *qp;
14242 
14243 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14244 
14245 	/*
14246 	 * Clear the indication that this may have hardware
14247 	 * checksum as we are not using it for forwarding.
14248 	 */
14249 	hcksumflags = DB_CKSUMFLAGS(mp);
14250 	DB_CKSUMFLAGS(mp) = 0;
14251 
14252 	/*
14253 	 * Directed broadcast forwarding: if the packet came in over a
14254 	 * different interface then it is routed out over we can forward it.
14255 	 */
14256 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14257 		ire_refrele(ire);
14258 		freemsg(mp);
14259 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14260 		return (NULL);
14261 	}
14262 	/*
14263 	 * For multicast we have set dst to be INADDR_BROADCAST
14264 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
14265 	 * only for broadcast packets.
14266 	 */
14267 	if (!CLASSD(ipha->ipha_dst)) {
14268 		ire_t *new_ire;
14269 		ipif_t *ipif;
14270 		/*
14271 		 * For ill groups, as the switch duplicates broadcasts
14272 		 * across all the ports, we need to filter out and
14273 		 * send up only one copy. There is one copy for every
14274 		 * broadcast address on each ill. Thus, we look for a
14275 		 * specific IRE on this ill and look at IRE_MARK_NORECV
14276 		 * later to see whether this ill is eligible to receive
14277 		 * them or not. ill_nominate_bcast_rcv() nominates only
14278 		 * one set of IREs for receiving.
14279 		 */
14280 
14281 		ipif = ipif_get_next_ipif(NULL, ill);
14282 		if (ipif == NULL) {
14283 			ire_refrele(ire);
14284 			freemsg(mp);
14285 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14286 			return (NULL);
14287 		}
14288 		new_ire = ire_ctable_lookup(dst, 0, 0,
14289 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14290 		ipif_refrele(ipif);
14291 
14292 		if (new_ire != NULL) {
14293 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
14294 				ire_refrele(ire);
14295 				ire_refrele(new_ire);
14296 				freemsg(mp);
14297 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14298 				return (NULL);
14299 			}
14300 			/*
14301 			 * In the special case of multirouted broadcast
14302 			 * packets, we unconditionally need to "gateway"
14303 			 * them to the appropriate interface here.
14304 			 * In the normal case, this cannot happen, because
14305 			 * there is no broadcast IRE tagged with the
14306 			 * RTF_MULTIRT flag.
14307 			 */
14308 			if (new_ire->ire_flags & RTF_MULTIRT) {
14309 				ire_refrele(new_ire);
14310 				if (ire->ire_rfq != NULL) {
14311 					q = ire->ire_rfq;
14312 					*qp = q;
14313 				}
14314 			} else {
14315 				ire_refrele(ire);
14316 				ire = new_ire;
14317 			}
14318 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14319 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14320 				/*
14321 				 * Free the message if
14322 				 * ip_g_forward_directed_bcast is turned
14323 				 * off for non-local broadcast.
14324 				 */
14325 				ire_refrele(ire);
14326 				freemsg(mp);
14327 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14328 				return (NULL);
14329 			}
14330 		} else {
14331 			/*
14332 			 * This CGTP packet successfully passed the
14333 			 * CGTP filter, but the related CGTP
14334 			 * broadcast IRE has not been found,
14335 			 * meaning that the redundant ipif is
14336 			 * probably down. However, if we discarded
14337 			 * this packet, its duplicate would be
14338 			 * filtered out by the CGTP filter so none
14339 			 * of them would get through. So we keep
14340 			 * going with this one.
14341 			 */
14342 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14343 			if (ire->ire_rfq != NULL) {
14344 				q = ire->ire_rfq;
14345 				*qp = q;
14346 			}
14347 		}
14348 	}
14349 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14350 		/*
14351 		 * Verify that there are not more then one
14352 		 * IRE_BROADCAST with this broadcast address which
14353 		 * has ire_stq set.
14354 		 * TODO: simplify, loop over all IRE's
14355 		 */
14356 		ire_t	*ire1;
14357 		int	num_stq = 0;
14358 		mblk_t	*mp1;
14359 
14360 		/* Find the first one with ire_stq set */
14361 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14362 		for (ire1 = ire; ire1 &&
14363 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14364 		    ire1 = ire1->ire_next)
14365 			;
14366 		if (ire1) {
14367 			ire_refrele(ire);
14368 			ire = ire1;
14369 			IRE_REFHOLD(ire);
14370 		}
14371 
14372 		/* Check if there are additional ones with stq set */
14373 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14374 			if (ire->ire_addr != ire1->ire_addr)
14375 				break;
14376 			if (ire1->ire_stq) {
14377 				num_stq++;
14378 				break;
14379 			}
14380 		}
14381 		rw_exit(&ire->ire_bucket->irb_lock);
14382 		if (num_stq == 1 && ire->ire_stq != NULL) {
14383 			ip1dbg(("ip_rput_process_broadcast: directed "
14384 			    "broadcast to 0x%x\n",
14385 			    ntohl(ire->ire_addr)));
14386 			mp1 = copymsg(mp);
14387 			if (mp1) {
14388 				switch (ipha->ipha_protocol) {
14389 				case IPPROTO_UDP:
14390 					ip_udp_input(q, mp1, ipha, ire, ill);
14391 					break;
14392 				default:
14393 					ip_proto_input(q, mp1, ipha, ire, ill,
14394 					    B_FALSE);
14395 					break;
14396 				}
14397 			}
14398 			/*
14399 			 * Adjust ttl to 2 (1+1 - the forward engine
14400 			 * will decrement it by one.
14401 			 */
14402 			if (ip_csum_hdr(ipha)) {
14403 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14404 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14405 				freemsg(mp);
14406 				ire_refrele(ire);
14407 				return (NULL);
14408 			}
14409 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14410 			ipha->ipha_hdr_checksum = 0;
14411 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14412 			ip_rput_process_forward(q, mp, ire, ipha,
14413 			    ill, ll_multicast);
14414 			ire_refrele(ire);
14415 			return (NULL);
14416 		}
14417 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14418 		    ntohl(ire->ire_addr)));
14419 	}
14420 
14421 
14422 	/* Restore any hardware checksum flags */
14423 	DB_CKSUMFLAGS(mp) = hcksumflags;
14424 	return (ire);
14425 }
14426 
14427 /* ARGSUSED */
14428 static boolean_t
14429 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14430     int *ll_multicast, ipaddr_t *dstp)
14431 {
14432 	ip_stack_t	*ipst = ill->ill_ipst;
14433 
14434 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14435 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14436 	    ntohs(ipha->ipha_length));
14437 
14438 	/*
14439 	 * Forward packets only if we have joined the allmulti
14440 	 * group on this interface.
14441 	 */
14442 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14443 		int retval;
14444 
14445 		/*
14446 		 * Clear the indication that this may have hardware
14447 		 * checksum as we are not using it.
14448 		 */
14449 		DB_CKSUMFLAGS(mp) = 0;
14450 		retval = ip_mforward(ill, ipha, mp);
14451 		/* ip_mforward updates mib variables if needed */
14452 		/* clear b_prev - used by ip_mroute_decap */
14453 		mp->b_prev = NULL;
14454 
14455 		switch (retval) {
14456 		case 0:
14457 			/*
14458 			 * pkt is okay and arrived on phyint.
14459 			 *
14460 			 * If we are running as a multicast router
14461 			 * we need to see all IGMP and/or PIM packets.
14462 			 */
14463 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14464 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14465 				goto done;
14466 			}
14467 			break;
14468 		case -1:
14469 			/* pkt is mal-formed, toss it */
14470 			goto drop_pkt;
14471 		case 1:
14472 			/* pkt is okay and arrived on a tunnel */
14473 			/*
14474 			 * If we are running a multicast router
14475 			 *  we need to see all igmp packets.
14476 			 */
14477 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14478 				*dstp = INADDR_BROADCAST;
14479 				*ll_multicast = 1;
14480 				return (B_FALSE);
14481 			}
14482 
14483 			goto drop_pkt;
14484 		}
14485 	}
14486 
14487 	ILM_WALKER_HOLD(ill);
14488 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14489 		/*
14490 		 * This might just be caused by the fact that
14491 		 * multiple IP Multicast addresses map to the same
14492 		 * link layer multicast - no need to increment counter!
14493 		 */
14494 		ILM_WALKER_RELE(ill);
14495 		freemsg(mp);
14496 		return (B_TRUE);
14497 	}
14498 	ILM_WALKER_RELE(ill);
14499 done:
14500 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14501 	/*
14502 	 * This assumes the we deliver to all streams for multicast
14503 	 * and broadcast packets.
14504 	 */
14505 	*dstp = INADDR_BROADCAST;
14506 	*ll_multicast = 1;
14507 	return (B_FALSE);
14508 drop_pkt:
14509 	ip2dbg(("ip_rput: drop pkt\n"));
14510 	freemsg(mp);
14511 	return (B_TRUE);
14512 }
14513 
14514 /*
14515  * This function is used to both return an indication of whether or not
14516  * the packet received is a non-unicast packet (by way of the DL_UNITDATA_IND)
14517  * and in doing so, determine whether or not it is broadcast vs multicast.
14518  * For it to be a broadcast packet, we must have the appropriate mblk_t
14519  * hanging off the ill_t.  If this is either not present or doesn't match
14520  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
14521  * to be multicast.  Thus NICs that have no broadcast address (or no
14522  * capability for one, such as point to point links) cannot return as
14523  * the packet being broadcast.  The use of HPE_BROADCAST/HPE_MULTICAST as
14524  * the return values simplifies the current use of the return value of this
14525  * function, which is to pass through the multicast/broadcast characteristic
14526  * to consumers of the netinfo/pfhooks API.  While this is not cast in stone,
14527  * changing the return value to some other symbol demands the appropriate
14528  * "translation" when hpe_flags is set prior to calling hook_run() for
14529  * packet events.
14530  */
14531 int
14532 ip_get_dlpi_mbcast(ill_t *ill, mblk_t *mb)
14533 {
14534 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
14535 	mblk_t *bmp;
14536 
14537 	if (ind->dl_group_address) {
14538 		if (ind->dl_dest_addr_offset > sizeof (*ind) &&
14539 		    ind->dl_dest_addr_offset + ind->dl_dest_addr_length <
14540 		    MBLKL(mb) &&
14541 		    (bmp = ill->ill_bcast_mp) != NULL) {
14542 			dl_unitdata_req_t *dlur;
14543 			uint8_t *bphys_addr;
14544 
14545 			dlur = (dl_unitdata_req_t *)bmp->b_rptr;
14546 			if (ill->ill_sap_length < 0)
14547 				bphys_addr = (uchar_t *)dlur +
14548 				    dlur->dl_dest_addr_offset;
14549 			else
14550 				bphys_addr = (uchar_t *)dlur +
14551 				    dlur->dl_dest_addr_offset +
14552 				    ill->ill_sap_length;
14553 
14554 			if (bcmp(mb->b_rptr + ind->dl_dest_addr_offset,
14555 			    bphys_addr, ind->dl_dest_addr_length) == 0) {
14556 				return (HPE_BROADCAST);
14557 			}
14558 			return (HPE_MULTICAST);
14559 		}
14560 		return (HPE_MULTICAST);
14561 	}
14562 	return (0);
14563 }
14564 
14565 static boolean_t
14566 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14567     int *ll_multicast, mblk_t **mpp)
14568 {
14569 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14570 	boolean_t must_copy = B_FALSE;
14571 	struct iocblk   *iocp;
14572 	ipha_t		*ipha;
14573 	ip_stack_t	*ipst = ill->ill_ipst;
14574 
14575 #define	rptr    ((uchar_t *)ipha)
14576 
14577 	first_mp = *first_mpp;
14578 	mp = *mpp;
14579 
14580 	ASSERT(first_mp == mp);
14581 
14582 	/*
14583 	 * if db_ref > 1 then copymsg and free original. Packet may be
14584 	 * changed and do not want other entity who has a reference to this
14585 	 * message to trip over the changes. This is a blind change because
14586 	 * trying to catch all places that might change packet is too
14587 	 * difficult (since it may be a module above this one)
14588 	 *
14589 	 * This corresponds to the non-fast path case. We walk down the full
14590 	 * chain in this case, and check the db_ref count of all the dblks,
14591 	 * and do a copymsg if required. It is possible that the db_ref counts
14592 	 * of the data blocks in the mblk chain can be different.
14593 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14594 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14595 	 * 'snoop' is running.
14596 	 */
14597 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14598 		if (mp1->b_datap->db_ref > 1) {
14599 			must_copy = B_TRUE;
14600 			break;
14601 		}
14602 	}
14603 
14604 	if (must_copy) {
14605 		mp1 = copymsg(mp);
14606 		if (mp1 == NULL) {
14607 			for (mp1 = mp; mp1 != NULL;
14608 			    mp1 = mp1->b_cont) {
14609 				mp1->b_next = NULL;
14610 				mp1->b_prev = NULL;
14611 			}
14612 			freemsg(mp);
14613 			if (ill != NULL) {
14614 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14615 			} else {
14616 				BUMP_MIB(&ipst->ips_ip_mib,
14617 				    ipIfStatsInDiscards);
14618 			}
14619 			return (B_TRUE);
14620 		}
14621 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14622 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14623 			/* Copy b_prev - used by ip_mroute_decap */
14624 			to_mp->b_prev = from_mp->b_prev;
14625 			from_mp->b_prev = NULL;
14626 		}
14627 		*first_mpp = first_mp = mp1;
14628 		freemsg(mp);
14629 		mp = mp1;
14630 		*mpp = mp1;
14631 	}
14632 
14633 	ipha = (ipha_t *)mp->b_rptr;
14634 
14635 	/*
14636 	 * previous code has a case for M_DATA.
14637 	 * We want to check how that happens.
14638 	 */
14639 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14640 	switch (first_mp->b_datap->db_type) {
14641 	case M_PROTO:
14642 	case M_PCPROTO:
14643 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14644 		    DL_UNITDATA_IND) {
14645 			/* Go handle anything other than data elsewhere. */
14646 			ip_rput_dlpi(q, mp);
14647 			return (B_TRUE);
14648 		}
14649 
14650 		*ll_multicast = ip_get_dlpi_mbcast(ill, mp);
14651 		/* Ditch the DLPI header. */
14652 		mp1 = mp->b_cont;
14653 		ASSERT(first_mp == mp);
14654 		*first_mpp = mp1;
14655 		freeb(mp);
14656 		*mpp = mp1;
14657 		return (B_FALSE);
14658 	case M_IOCACK:
14659 		ip1dbg(("got iocack "));
14660 		iocp = (struct iocblk *)mp->b_rptr;
14661 		switch (iocp->ioc_cmd) {
14662 		case DL_IOC_HDR_INFO:
14663 			ill = (ill_t *)q->q_ptr;
14664 			ill_fastpath_ack(ill, mp);
14665 			return (B_TRUE);
14666 		case SIOCSTUNPARAM:
14667 		case OSIOCSTUNPARAM:
14668 			/* Go through qwriter_ip */
14669 			break;
14670 		case SIOCGTUNPARAM:
14671 		case OSIOCGTUNPARAM:
14672 			ip_rput_other(NULL, q, mp, NULL);
14673 			return (B_TRUE);
14674 		default:
14675 			putnext(q, mp);
14676 			return (B_TRUE);
14677 		}
14678 		/* FALLTHRU */
14679 	case M_ERROR:
14680 	case M_HANGUP:
14681 		/*
14682 		 * Since this is on the ill stream we unconditionally
14683 		 * bump up the refcount
14684 		 */
14685 		ill_refhold(ill);
14686 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14687 		return (B_TRUE);
14688 	case M_CTL:
14689 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14690 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14691 		    IPHADA_M_CTL)) {
14692 			/*
14693 			 * It's an IPsec accelerated packet.
14694 			 * Make sure that the ill from which we received the
14695 			 * packet has enabled IPsec hardware acceleration.
14696 			 */
14697 			if (!(ill->ill_capabilities &
14698 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14699 				/* IPsec kstats: bean counter */
14700 				freemsg(mp);
14701 				return (B_TRUE);
14702 			}
14703 
14704 			/*
14705 			 * Make mp point to the mblk following the M_CTL,
14706 			 * then process according to type of mp.
14707 			 * After this processing, first_mp will point to
14708 			 * the data-attributes and mp to the pkt following
14709 			 * the M_CTL.
14710 			 */
14711 			mp = first_mp->b_cont;
14712 			if (mp == NULL) {
14713 				freemsg(first_mp);
14714 				return (B_TRUE);
14715 			}
14716 			/*
14717 			 * A Hardware Accelerated packet can only be M_DATA
14718 			 * ESP or AH packet.
14719 			 */
14720 			if (mp->b_datap->db_type != M_DATA) {
14721 				/* non-M_DATA IPsec accelerated packet */
14722 				IPSECHW_DEBUG(IPSECHW_PKT,
14723 				    ("non-M_DATA IPsec accelerated pkt\n"));
14724 				freemsg(first_mp);
14725 				return (B_TRUE);
14726 			}
14727 			ipha = (ipha_t *)mp->b_rptr;
14728 			if (ipha->ipha_protocol != IPPROTO_AH &&
14729 			    ipha->ipha_protocol != IPPROTO_ESP) {
14730 				IPSECHW_DEBUG(IPSECHW_PKT,
14731 				    ("non-M_DATA IPsec accelerated pkt\n"));
14732 				freemsg(first_mp);
14733 				return (B_TRUE);
14734 			}
14735 			*mpp = mp;
14736 			return (B_FALSE);
14737 		}
14738 		putnext(q, mp);
14739 		return (B_TRUE);
14740 	case M_IOCNAK:
14741 		ip1dbg(("got iocnak "));
14742 		iocp = (struct iocblk *)mp->b_rptr;
14743 		switch (iocp->ioc_cmd) {
14744 		case SIOCSTUNPARAM:
14745 		case OSIOCSTUNPARAM:
14746 			/*
14747 			 * Since this is on the ill stream we unconditionally
14748 			 * bump up the refcount
14749 			 */
14750 			ill_refhold(ill);
14751 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14752 			return (B_TRUE);
14753 		case DL_IOC_HDR_INFO:
14754 		case SIOCGTUNPARAM:
14755 		case OSIOCGTUNPARAM:
14756 			ip_rput_other(NULL, q, mp, NULL);
14757 			return (B_TRUE);
14758 		default:
14759 			break;
14760 		}
14761 		/* FALLTHRU */
14762 	default:
14763 		putnext(q, mp);
14764 		return (B_TRUE);
14765 	}
14766 }
14767 
14768 /* Read side put procedure.  Packets coming from the wire arrive here. */
14769 void
14770 ip_rput(queue_t *q, mblk_t *mp)
14771 {
14772 	ill_t	*ill;
14773 	union DL_primitives *dl;
14774 
14775 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14776 
14777 	ill = (ill_t *)q->q_ptr;
14778 
14779 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14780 		/*
14781 		 * If things are opening or closing, only accept high-priority
14782 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14783 		 * created; on close, things hanging off the ill may have been
14784 		 * freed already.)
14785 		 */
14786 		dl = (union DL_primitives *)mp->b_rptr;
14787 		if (DB_TYPE(mp) != M_PCPROTO ||
14788 		    dl->dl_primitive == DL_UNITDATA_IND) {
14789 			/*
14790 			 * SIOC[GS]TUNPARAM ioctls can come here.
14791 			 */
14792 			inet_freemsg(mp);
14793 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14794 			    "ip_rput_end: q %p (%S)", q, "uninit");
14795 			return;
14796 		}
14797 	}
14798 
14799 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14800 	    "ip_rput_end: q %p (%S)", q, "end");
14801 
14802 	ip_input(ill, NULL, mp, NULL);
14803 }
14804 
14805 static mblk_t *
14806 ip_fix_dbref(ill_t *ill, mblk_t *mp)
14807 {
14808 	mblk_t *mp1;
14809 	boolean_t adjusted = B_FALSE;
14810 	ip_stack_t *ipst = ill->ill_ipst;
14811 
14812 	IP_STAT(ipst, ip_db_ref);
14813 	/*
14814 	 * The IP_RECVSLLA option depends on having the
14815 	 * link layer header. First check that:
14816 	 * a> the underlying device is of type ether,
14817 	 * since this option is currently supported only
14818 	 * over ethernet.
14819 	 * b> there is enough room to copy over the link
14820 	 * layer header.
14821 	 *
14822 	 * Once the checks are done, adjust rptr so that
14823 	 * the link layer header will be copied via
14824 	 * copymsg. Note that, IFT_ETHER may be returned
14825 	 * by some non-ethernet drivers but in this case
14826 	 * the second check will fail.
14827 	 */
14828 	if (ill->ill_type == IFT_ETHER &&
14829 	    (mp->b_rptr - mp->b_datap->db_base) >=
14830 	    sizeof (struct ether_header)) {
14831 		mp->b_rptr -= sizeof (struct ether_header);
14832 		adjusted = B_TRUE;
14833 	}
14834 	mp1 = copymsg(mp);
14835 
14836 	if (mp1 == NULL) {
14837 		mp->b_next = NULL;
14838 		/* clear b_prev - used by ip_mroute_decap */
14839 		mp->b_prev = NULL;
14840 		freemsg(mp);
14841 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14842 		return (NULL);
14843 	}
14844 
14845 	if (adjusted) {
14846 		/*
14847 		 * Copy is done. Restore the pointer in
14848 		 * the _new_ mblk
14849 		 */
14850 		mp1->b_rptr += sizeof (struct ether_header);
14851 	}
14852 
14853 	/* Copy b_prev - used by ip_mroute_decap */
14854 	mp1->b_prev = mp->b_prev;
14855 	mp->b_prev = NULL;
14856 
14857 	/* preserve the hardware checksum flags and data, if present */
14858 	if (DB_CKSUMFLAGS(mp) != 0) {
14859 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
14860 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
14861 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
14862 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
14863 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
14864 	}
14865 
14866 	freemsg(mp);
14867 	return (mp1);
14868 }
14869 
14870 /*
14871  * Direct read side procedure capable of dealing with chains. GLDv3 based
14872  * drivers call this function directly with mblk chains while STREAMS
14873  * read side procedure ip_rput() calls this for single packet with ip_ring
14874  * set to NULL to process one packet at a time.
14875  *
14876  * The ill will always be valid if this function is called directly from
14877  * the driver.
14878  *
14879  * If ip_input() is called from GLDv3:
14880  *
14881  *   - This must be a non-VLAN IP stream.
14882  *   - 'mp' is either an untagged or a special priority-tagged packet.
14883  *   - Any VLAN tag that was in the MAC header has been stripped.
14884  *
14885  * If the IP header in packet is not 32-bit aligned, every message in the
14886  * chain will be aligned before further operations. This is required on SPARC
14887  * platform.
14888  */
14889 /* ARGSUSED */
14890 void
14891 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14892     struct mac_header_info_s *mhip)
14893 {
14894 	ipaddr_t		dst = NULL;
14895 	ipaddr_t		prev_dst;
14896 	ire_t			*ire = NULL;
14897 	ipha_t			*ipha;
14898 	uint_t			pkt_len;
14899 	ssize_t			len;
14900 	uint_t			opt_len;
14901 	int			ll_multicast;
14902 	int			cgtp_flt_pkt;
14903 	queue_t			*q = ill->ill_rq;
14904 	squeue_t		*curr_sqp = NULL;
14905 	mblk_t 			*head = NULL;
14906 	mblk_t			*tail = NULL;
14907 	mblk_t			*first_mp;
14908 	mblk_t 			*mp;
14909 	mblk_t			*dmp;
14910 	int			cnt = 0;
14911 	ip_stack_t		*ipst = ill->ill_ipst;
14912 
14913 	ASSERT(mp_chain != NULL);
14914 	ASSERT(ill != NULL);
14915 
14916 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14917 
14918 #define	rptr	((uchar_t *)ipha)
14919 
14920 	while (mp_chain != NULL) {
14921 		first_mp = mp = mp_chain;
14922 		mp_chain = mp_chain->b_next;
14923 		mp->b_next = NULL;
14924 		ll_multicast = 0;
14925 
14926 		/*
14927 		 * We do ire caching from one iteration to
14928 		 * another. In the event the packet chain contains
14929 		 * all packets from the same dst, this caching saves
14930 		 * an ire_cache_lookup for each of the succeeding
14931 		 * packets in a packet chain.
14932 		 */
14933 		prev_dst = dst;
14934 
14935 		/*
14936 		 * if db_ref > 1 then copymsg and free original. Packet
14937 		 * may be changed and we do not want the other entity
14938 		 * who has a reference to this message to trip over the
14939 		 * changes. This is a blind change because trying to
14940 		 * catch all places that might change the packet is too
14941 		 * difficult.
14942 		 *
14943 		 * This corresponds to the fast path case, where we have
14944 		 * a chain of M_DATA mblks.  We check the db_ref count
14945 		 * of only the 1st data block in the mblk chain. There
14946 		 * doesn't seem to be a reason why a device driver would
14947 		 * send up data with varying db_ref counts in the mblk
14948 		 * chain. In any case the Fast path is a private
14949 		 * interface, and our drivers don't do such a thing.
14950 		 * Given the above assumption, there is no need to walk
14951 		 * down the entire mblk chain (which could have a
14952 		 * potential performance problem)
14953 		 */
14954 
14955 		if (DB_REF(mp) > 1) {
14956 			if ((mp = ip_fix_dbref(ill, mp)) == NULL)
14957 				continue;
14958 		}
14959 
14960 		/*
14961 		 * Check and align the IP header.
14962 		 */
14963 		first_mp = mp;
14964 		if (DB_TYPE(mp) == M_DATA) {
14965 			dmp = mp;
14966 		} else if (DB_TYPE(mp) == M_PROTO &&
14967 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14968 			dmp = mp->b_cont;
14969 		} else {
14970 			dmp = NULL;
14971 		}
14972 		if (dmp != NULL) {
14973 			/*
14974 			 * IP header ptr not aligned?
14975 			 * OR IP header not complete in first mblk
14976 			 */
14977 			if (!OK_32PTR(dmp->b_rptr) ||
14978 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
14979 				if (!ip_check_and_align_header(q, dmp, ipst))
14980 					continue;
14981 			}
14982 		}
14983 
14984 		/*
14985 		 * ip_input fast path
14986 		 */
14987 
14988 		/* mblk type is not M_DATA */
14989 		if (DB_TYPE(mp) != M_DATA) {
14990 			if (ip_rput_process_notdata(q, &first_mp, ill,
14991 			    &ll_multicast, &mp))
14992 				continue;
14993 
14994 			/*
14995 			 * The only way we can get here is if we had a
14996 			 * packet that was either a DL_UNITDATA_IND or
14997 			 * an M_CTL for an IPsec accelerated packet.
14998 			 *
14999 			 * In either case, the first_mp will point to
15000 			 * the leading M_PROTO or M_CTL.
15001 			 */
15002 			ASSERT(first_mp != NULL);
15003 		} else if (mhip != NULL) {
15004 			/*
15005 			 * ll_multicast is set here so that it is ready
15006 			 * for easy use with FW_HOOKS().  ip_get_dlpi_mbcast
15007 			 * manipulates ll_multicast in the same fashion when
15008 			 * called from ip_rput_process_notdata.
15009 			 */
15010 			switch (mhip->mhi_dsttype) {
15011 			case MAC_ADDRTYPE_MULTICAST :
15012 				ll_multicast = HPE_MULTICAST;
15013 				break;
15014 			case MAC_ADDRTYPE_BROADCAST :
15015 				ll_multicast = HPE_BROADCAST;
15016 				break;
15017 			default :
15018 				break;
15019 			}
15020 		}
15021 
15022 		/* Make sure its an M_DATA and that its aligned */
15023 		ASSERT(DB_TYPE(mp) == M_DATA);
15024 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
15025 
15026 		ipha = (ipha_t *)mp->b_rptr;
15027 		len = mp->b_wptr - rptr;
15028 		pkt_len = ntohs(ipha->ipha_length);
15029 
15030 		/*
15031 		 * We must count all incoming packets, even if they end
15032 		 * up being dropped later on.
15033 		 */
15034 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15035 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15036 
15037 		/* multiple mblk or too short */
15038 		len -= pkt_len;
15039 		if (len != 0) {
15040 			/*
15041 			 * Make sure we have data length consistent
15042 			 * with the IP header.
15043 			 */
15044 			if (mp->b_cont == NULL) {
15045 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15046 					BUMP_MIB(ill->ill_ip_mib,
15047 					    ipIfStatsInHdrErrors);
15048 					ip2dbg(("ip_input: drop pkt\n"));
15049 					freemsg(mp);
15050 					continue;
15051 				}
15052 				mp->b_wptr = rptr + pkt_len;
15053 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
15054 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15055 					BUMP_MIB(ill->ill_ip_mib,
15056 					    ipIfStatsInHdrErrors);
15057 					ip2dbg(("ip_input: drop pkt\n"));
15058 					freemsg(mp);
15059 					continue;
15060 				}
15061 				(void) adjmsg(mp, -len);
15062 				IP_STAT(ipst, ip_multimblk3);
15063 			}
15064 		}
15065 
15066 		/* Obtain the dst of the current packet */
15067 		dst = ipha->ipha_dst;
15068 
15069 		DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL,
15070 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *,
15071 		    ipha, ip6_t *, NULL, int, 0);
15072 
15073 		/*
15074 		 * The following test for loopback is faster than
15075 		 * IP_LOOPBACK_ADDR(), because it avoids any bitwise
15076 		 * operations.
15077 		 * Note that these addresses are always in network byte order
15078 		 */
15079 		if (((*(uchar_t *)&ipha->ipha_dst) == 127) ||
15080 		    ((*(uchar_t *)&ipha->ipha_src) == 127)) {
15081 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
15082 			freemsg(mp);
15083 			continue;
15084 		}
15085 
15086 		/*
15087 		 * The event for packets being received from a 'physical'
15088 		 * interface is placed after validation of the source and/or
15089 		 * destination address as being local so that packets can be
15090 		 * redirected to loopback addresses using ipnat.
15091 		 */
15092 		DTRACE_PROBE4(ip4__physical__in__start,
15093 		    ill_t *, ill, ill_t *, NULL,
15094 		    ipha_t *, ipha, mblk_t *, first_mp);
15095 
15096 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15097 		    ipst->ips_ipv4firewall_physical_in,
15098 		    ill, NULL, ipha, first_mp, mp, ll_multicast, ipst);
15099 
15100 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15101 
15102 		if (first_mp == NULL) {
15103 			continue;
15104 		}
15105 		dst = ipha->ipha_dst;
15106 
15107 		/*
15108 		 * Attach any necessary label information to
15109 		 * this packet
15110 		 */
15111 		if (is_system_labeled() &&
15112 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15113 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15114 			freemsg(mp);
15115 			continue;
15116 		}
15117 
15118 		/*
15119 		 * Reuse the cached ire only if the ipha_dst of the previous
15120 		 * packet is the same as the current packet AND it is not
15121 		 * INADDR_ANY.
15122 		 */
15123 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15124 		    (ire != NULL)) {
15125 			ire_refrele(ire);
15126 			ire = NULL;
15127 		}
15128 		opt_len = ipha->ipha_version_and_hdr_length -
15129 		    IP_SIMPLE_HDR_VERSION;
15130 
15131 		/*
15132 		 * Check to see if we can take the fastpath.
15133 		 * That is possible if the following conditions are met
15134 		 *	o Tsol disabled
15135 		 *	o CGTP disabled
15136 		 *	o ipp_action_count is 0
15137 		 *	o no options in the packet
15138 		 *	o not a RSVP packet
15139 		 * 	o not a multicast packet
15140 		 *	o ill not in IP_DHCPINIT_IF mode
15141 		 */
15142 		if (!is_system_labeled() &&
15143 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
15144 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15145 		    !ll_multicast && !CLASSD(dst) && ill->ill_dhcpinit == 0) {
15146 			if (ire == NULL)
15147 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL,
15148 				    ipst);
15149 
15150 			/* incoming packet is for forwarding */
15151 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
15152 				ire = ip_fast_forward(ire, dst, ill, mp);
15153 				continue;
15154 			}
15155 			/* incoming packet is for local consumption */
15156 			if (ire->ire_type & IRE_LOCAL)
15157 				goto local;
15158 		}
15159 
15160 		/*
15161 		 * Disable ire caching for anything more complex
15162 		 * than the simple fast path case we checked for above.
15163 		 */
15164 		if (ire != NULL) {
15165 			ire_refrele(ire);
15166 			ire = NULL;
15167 		}
15168 
15169 		/*
15170 		 * Brutal hack for DHCPv4 unicast: RFC2131 allows a DHCP
15171 		 * server to unicast DHCP packets to a DHCP client using the
15172 		 * IP address it is offering to the client.  This can be
15173 		 * disabled through the "broadcast bit", but not all DHCP
15174 		 * servers honor that bit.  Therefore, to interoperate with as
15175 		 * many DHCP servers as possible, the DHCP client allows the
15176 		 * server to unicast, but we treat those packets as broadcast
15177 		 * here.  Note that we don't rewrite the packet itself since
15178 		 * (a) that would mess up the checksums and (b) the DHCP
15179 		 * client conn is bound to INADDR_ANY so ip_fanout_udp() will
15180 		 * hand it the packet regardless.
15181 		 */
15182 		if (ill->ill_dhcpinit != 0 &&
15183 		    IS_SIMPLE_IPH(ipha) && ipha->ipha_protocol == IPPROTO_UDP &&
15184 		    pullupmsg(mp, sizeof (ipha_t) + sizeof (udpha_t)) == 1) {
15185 			udpha_t *udpha;
15186 
15187 			/*
15188 			 * Reload ipha since pullupmsg() can change b_rptr.
15189 			 */
15190 			ipha = (ipha_t *)mp->b_rptr;
15191 			udpha = (udpha_t *)&ipha[1];
15192 
15193 			if (ntohs(udpha->uha_dst_port) == IPPORT_BOOTPC) {
15194 				DTRACE_PROBE2(ip4__dhcpinit__pkt, ill_t *, ill,
15195 				    mblk_t *, mp);
15196 				dst = INADDR_BROADCAST;
15197 			}
15198 		}
15199 
15200 		/* Full-blown slow path */
15201 		if (opt_len != 0) {
15202 			if (len != 0)
15203 				IP_STAT(ipst, ip_multimblk4);
15204 			else
15205 				IP_STAT(ipst, ip_ipoptions);
15206 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15207 			    &dst, ipst))
15208 				continue;
15209 		}
15210 
15211 		/*
15212 		 * Invoke the CGTP (multirouting) filtering module to process
15213 		 * the incoming packet. Packets identified as duplicates
15214 		 * must be discarded. Filtering is active only if the
15215 		 * the ip_cgtp_filter ndd variable is non-zero.
15216 		 */
15217 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15218 		if (ipst->ips_ip_cgtp_filter &&
15219 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15220 			netstackid_t stackid;
15221 
15222 			stackid = ipst->ips_netstack->netstack_stackid;
15223 			cgtp_flt_pkt =
15224 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15225 			    ill->ill_phyint->phyint_ifindex, mp);
15226 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15227 				freemsg(first_mp);
15228 				continue;
15229 			}
15230 		}
15231 
15232 		/*
15233 		 * If rsvpd is running, let RSVP daemon handle its processing
15234 		 * and forwarding of RSVP multicast/unicast packets.
15235 		 * If rsvpd is not running but mrouted is running, RSVP
15236 		 * multicast packets are forwarded as multicast traffic
15237 		 * and RSVP unicast packets are forwarded by unicast router.
15238 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15239 		 * packets are not forwarded, but the unicast packets are
15240 		 * forwarded like unicast traffic.
15241 		 */
15242 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15243 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15244 		    NULL) {
15245 			/* RSVP packet and rsvpd running. Treat as ours */
15246 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15247 			/*
15248 			 * This assumes that we deliver to all streams for
15249 			 * multicast and broadcast packets.
15250 			 * We have to force ll_multicast to 1 to handle the
15251 			 * M_DATA messages passed in from ip_mroute_decap.
15252 			 */
15253 			dst = INADDR_BROADCAST;
15254 			ll_multicast = 1;
15255 		} else if (CLASSD(dst)) {
15256 			/* packet is multicast */
15257 			mp->b_next = NULL;
15258 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15259 			    &ll_multicast, &dst))
15260 				continue;
15261 		}
15262 
15263 		if (ire == NULL) {
15264 			ire = ire_cache_lookup(dst, ALL_ZONES,
15265 			    MBLK_GETLABEL(mp), ipst);
15266 		}
15267 
15268 		if (ire != NULL && ire->ire_stq != NULL &&
15269 		    ire->ire_zoneid != GLOBAL_ZONEID &&
15270 		    ire->ire_zoneid != ALL_ZONES) {
15271 			/*
15272 			 * Should only use IREs that are visible from the
15273 			 * global zone for forwarding.
15274 			 */
15275 			ire_refrele(ire);
15276 			ire = ire_cache_lookup(dst, GLOBAL_ZONEID,
15277 			    MBLK_GETLABEL(mp), ipst);
15278 		}
15279 
15280 		if (ire == NULL) {
15281 			/*
15282 			 * No IRE for this destination, so it can't be for us.
15283 			 * Unless we are forwarding, drop the packet.
15284 			 * We have to let source routed packets through
15285 			 * since we don't yet know if they are 'ping -l'
15286 			 * packets i.e. if they will go out over the
15287 			 * same interface as they came in on.
15288 			 */
15289 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15290 			if (ire == NULL)
15291 				continue;
15292 		}
15293 
15294 		/*
15295 		 * Broadcast IRE may indicate either broadcast or
15296 		 * multicast packet
15297 		 */
15298 		if (ire->ire_type == IRE_BROADCAST) {
15299 			/*
15300 			 * Skip broadcast checks if packet is UDP multicast;
15301 			 * we'd rather not enter ip_rput_process_broadcast()
15302 			 * unless the packet is broadcast for real, since
15303 			 * that routine is a no-op for multicast.
15304 			 */
15305 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15306 			    !CLASSD(ipha->ipha_dst)) {
15307 				ire = ip_rput_process_broadcast(&q, mp,
15308 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15309 				    ll_multicast);
15310 				if (ire == NULL)
15311 					continue;
15312 			}
15313 		} else if (ire->ire_stq != NULL) {
15314 			/* fowarding? */
15315 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15316 			    ll_multicast);
15317 			/* ip_rput_process_forward consumed the packet */
15318 			continue;
15319 		}
15320 
15321 local:
15322 		/*
15323 		 * If the queue in the ire is different to the ingress queue
15324 		 * then we need to check to see if we can accept the packet.
15325 		 * Note that for multicast packets and broadcast packets sent
15326 		 * to a broadcast address which is shared between multiple
15327 		 * interfaces we should not do this since we just got a random
15328 		 * broadcast ire.
15329 		 */
15330 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15331 			if ((ire = ip_check_multihome(&ipha->ipha_dst, ire,
15332 			    ill)) == NULL) {
15333 				/* Drop packet */
15334 				BUMP_MIB(ill->ill_ip_mib,
15335 				    ipIfStatsForwProhibits);
15336 				freemsg(mp);
15337 				continue;
15338 			}
15339 			if (ire->ire_rfq != NULL)
15340 				q = ire->ire_rfq;
15341 		}
15342 
15343 		switch (ipha->ipha_protocol) {
15344 		case IPPROTO_TCP:
15345 			ASSERT(first_mp == mp);
15346 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15347 			    mp, 0, q, ip_ring)) != NULL) {
15348 				if (curr_sqp == NULL) {
15349 					curr_sqp = GET_SQUEUE(mp);
15350 					ASSERT(cnt == 0);
15351 					cnt++;
15352 					head = tail = mp;
15353 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15354 					ASSERT(tail != NULL);
15355 					cnt++;
15356 					tail->b_next = mp;
15357 					tail = mp;
15358 				} else {
15359 					/*
15360 					 * A different squeue. Send the
15361 					 * chain for the previous squeue on
15362 					 * its way. This shouldn't happen
15363 					 * often unless interrupt binding
15364 					 * changes.
15365 					 */
15366 					IP_STAT(ipst, ip_input_multi_squeue);
15367 					squeue_enter_chain(curr_sqp, head,
15368 					    tail, cnt, SQTAG_IP_INPUT);
15369 					curr_sqp = GET_SQUEUE(mp);
15370 					head = mp;
15371 					tail = mp;
15372 					cnt = 1;
15373 				}
15374 			}
15375 			continue;
15376 		case IPPROTO_UDP:
15377 			ASSERT(first_mp == mp);
15378 			ip_udp_input(q, mp, ipha, ire, ill);
15379 			continue;
15380 		case IPPROTO_SCTP:
15381 			ASSERT(first_mp == mp);
15382 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15383 			    q, dst);
15384 			/* ire has been released by ip_sctp_input */
15385 			ire = NULL;
15386 			continue;
15387 		default:
15388 			ip_proto_input(q, first_mp, ipha, ire, ill, B_FALSE);
15389 			continue;
15390 		}
15391 	}
15392 
15393 	if (ire != NULL)
15394 		ire_refrele(ire);
15395 
15396 	if (head != NULL)
15397 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
15398 
15399 	/*
15400 	 * This code is there just to make netperf/ttcp look good.
15401 	 *
15402 	 * Its possible that after being in polling mode (and having cleared
15403 	 * the backlog), squeues have turned the interrupt frequency higher
15404 	 * to improve latency at the expense of more CPU utilization (less
15405 	 * packets per interrupts or more number of interrupts). Workloads
15406 	 * like ttcp/netperf do manage to tickle polling once in a while
15407 	 * but for the remaining time, stay in higher interrupt mode since
15408 	 * their packet arrival rate is pretty uniform and this shows up
15409 	 * as higher CPU utilization. Since people care about CPU utilization
15410 	 * while running netperf/ttcp, turn the interrupt frequency back to
15411 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
15412 	 */
15413 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
15414 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
15415 			ip_ring->rr_poll_state &= ~ILL_POLLING;
15416 			ip_ring->rr_blank(ip_ring->rr_handle,
15417 			    ip_ring->rr_normal_blank_time,
15418 			    ip_ring->rr_normal_pkt_cnt);
15419 		}
15420 		}
15421 
15422 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15423 	    "ip_input_end: q %p (%S)", q, "end");
15424 #undef  rptr
15425 }
15426 
15427 static void
15428 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15429     t_uscalar_t err)
15430 {
15431 	if (dl_err == DL_SYSERR) {
15432 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15433 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15434 		    ill->ill_name, dl_primstr(prim), err);
15435 		return;
15436 	}
15437 
15438 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15439 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
15440 	    dl_errstr(dl_err));
15441 }
15442 
15443 /*
15444  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15445  * than DL_UNITDATA_IND messages. If we need to process this message
15446  * exclusively, we call qwriter_ip, in which case we also need to call
15447  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15448  */
15449 void
15450 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15451 {
15452 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15453 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15454 	ill_t		*ill = q->q_ptr;
15455 	t_uscalar_t	prim = dloa->dl_primitive;
15456 	t_uscalar_t	reqprim = DL_PRIM_INVAL;
15457 
15458 	ip1dbg(("ip_rput_dlpi"));
15459 
15460 	/*
15461 	 * If we received an ACK but didn't send a request for it, then it
15462 	 * can't be part of any pending operation; discard up-front.
15463 	 */
15464 	switch (prim) {
15465 	case DL_ERROR_ACK:
15466 		reqprim = dlea->dl_error_primitive;
15467 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
15468 		    "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
15469 		    reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
15470 		    dlea->dl_unix_errno));
15471 		break;
15472 	case DL_OK_ACK:
15473 		reqprim = dloa->dl_correct_primitive;
15474 		break;
15475 	case DL_INFO_ACK:
15476 		reqprim = DL_INFO_REQ;
15477 		break;
15478 	case DL_BIND_ACK:
15479 		reqprim = DL_BIND_REQ;
15480 		break;
15481 	case DL_PHYS_ADDR_ACK:
15482 		reqprim = DL_PHYS_ADDR_REQ;
15483 		break;
15484 	case DL_NOTIFY_ACK:
15485 		reqprim = DL_NOTIFY_REQ;
15486 		break;
15487 	case DL_CONTROL_ACK:
15488 		reqprim = DL_CONTROL_REQ;
15489 		break;
15490 	case DL_CAPABILITY_ACK:
15491 		reqprim = DL_CAPABILITY_REQ;
15492 		break;
15493 	}
15494 
15495 	if (prim != DL_NOTIFY_IND) {
15496 		if (reqprim == DL_PRIM_INVAL ||
15497 		    !ill_dlpi_pending(ill, reqprim)) {
15498 			/* Not a DLPI message we support or expected */
15499 			freemsg(mp);
15500 			return;
15501 		}
15502 		ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
15503 		    dl_primstr(reqprim)));
15504 	}
15505 
15506 	switch (reqprim) {
15507 	case DL_UNBIND_REQ:
15508 		/*
15509 		 * NOTE: we mark the unbind as complete even if we got a
15510 		 * DL_ERROR_ACK, since there's not much else we can do.
15511 		 */
15512 		mutex_enter(&ill->ill_lock);
15513 		ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15514 		cv_signal(&ill->ill_cv);
15515 		mutex_exit(&ill->ill_lock);
15516 		break;
15517 
15518 	case DL_ENABMULTI_REQ:
15519 		if (prim == DL_OK_ACK) {
15520 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15521 				ill->ill_dlpi_multicast_state = IDS_OK;
15522 		}
15523 		break;
15524 	}
15525 
15526 	/*
15527 	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
15528 	 * need to become writer to continue to process it.  Because an
15529 	 * exclusive operation doesn't complete until replies to all queued
15530 	 * DLPI messages have been received, we know we're in the middle of an
15531 	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
15532 	 *
15533 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15534 	 * Since this is on the ill stream we unconditionally bump up the
15535 	 * refcount without doing ILL_CAN_LOOKUP().
15536 	 */
15537 	ill_refhold(ill);
15538 	if (prim == DL_NOTIFY_IND)
15539 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15540 	else
15541 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15542 }
15543 
15544 /*
15545  * Handling of DLPI messages that require exclusive access to the ipsq.
15546  *
15547  * Need to do ill_pending_mp_release on ioctl completion, which could
15548  * happen here. (along with mi_copy_done)
15549  */
15550 /* ARGSUSED */
15551 static void
15552 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15553 {
15554 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15555 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15556 	int		err = 0;
15557 	ill_t		*ill;
15558 	ipif_t		*ipif = NULL;
15559 	mblk_t		*mp1 = NULL;
15560 	conn_t		*connp = NULL;
15561 	t_uscalar_t	paddrreq;
15562 	mblk_t		*mp_hw;
15563 	boolean_t	success;
15564 	boolean_t	ioctl_aborted = B_FALSE;
15565 	boolean_t	log = B_TRUE;
15566 	ip_stack_t		*ipst;
15567 
15568 	ip1dbg(("ip_rput_dlpi_writer .."));
15569 	ill = (ill_t *)q->q_ptr;
15570 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15571 
15572 	ASSERT(IAM_WRITER_ILL(ill));
15573 
15574 	ipst = ill->ill_ipst;
15575 
15576 	/*
15577 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15578 	 * both are null or non-null. However we can assert that only
15579 	 * after grabbing the ipsq_lock. So we don't make any assertion
15580 	 * here and in other places in the code.
15581 	 */
15582 	ipif = ipsq->ipsq_pending_ipif;
15583 	/*
15584 	 * The current ioctl could have been aborted by the user and a new
15585 	 * ioctl to bring up another ill could have started. We could still
15586 	 * get a response from the driver later.
15587 	 */
15588 	if (ipif != NULL && ipif->ipif_ill != ill)
15589 		ioctl_aborted = B_TRUE;
15590 
15591 	switch (dloa->dl_primitive) {
15592 	case DL_ERROR_ACK:
15593 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15594 		    dl_primstr(dlea->dl_error_primitive)));
15595 
15596 		switch (dlea->dl_error_primitive) {
15597 		case DL_DISABMULTI_REQ:
15598 			if (!ill->ill_isv6)
15599 				ipsq_current_finish(ipsq);
15600 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15601 			break;
15602 		case DL_PROMISCON_REQ:
15603 		case DL_PROMISCOFF_REQ:
15604 		case DL_UNBIND_REQ:
15605 		case DL_ATTACH_REQ:
15606 		case DL_INFO_REQ:
15607 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15608 			break;
15609 		case DL_NOTIFY_REQ:
15610 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15611 			log = B_FALSE;
15612 			break;
15613 		case DL_PHYS_ADDR_REQ:
15614 			/*
15615 			 * For IPv6 only, there are two additional
15616 			 * phys_addr_req's sent to the driver to get the
15617 			 * IPv6 token and lla. This allows IP to acquire
15618 			 * the hardware address format for a given interface
15619 			 * without having built in knowledge of the hardware
15620 			 * address. ill_phys_addr_pend keeps track of the last
15621 			 * DL_PAR sent so we know which response we are
15622 			 * dealing with. ill_dlpi_done will update
15623 			 * ill_phys_addr_pend when it sends the next req.
15624 			 * We don't complete the IOCTL until all three DL_PARs
15625 			 * have been attempted, so set *_len to 0 and break.
15626 			 */
15627 			paddrreq = ill->ill_phys_addr_pend;
15628 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15629 			if (paddrreq == DL_IPV6_TOKEN) {
15630 				ill->ill_token_length = 0;
15631 				log = B_FALSE;
15632 				break;
15633 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15634 				ill->ill_nd_lla_len = 0;
15635 				log = B_FALSE;
15636 				break;
15637 			}
15638 			/*
15639 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15640 			 * We presumably have an IOCTL hanging out waiting
15641 			 * for completion. Find it and complete the IOCTL
15642 			 * with the error noted.
15643 			 * However, ill_dl_phys was called on an ill queue
15644 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15645 			 * set. But the ioctl is known to be pending on ill_wq.
15646 			 */
15647 			if (!ill->ill_ifname_pending)
15648 				break;
15649 			ill->ill_ifname_pending = 0;
15650 			if (!ioctl_aborted)
15651 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15652 			if (mp1 != NULL) {
15653 				/*
15654 				 * This operation (SIOCSLIFNAME) must have
15655 				 * happened on the ill. Assert there is no conn
15656 				 */
15657 				ASSERT(connp == NULL);
15658 				q = ill->ill_wq;
15659 			}
15660 			break;
15661 		case DL_BIND_REQ:
15662 			ill_dlpi_done(ill, DL_BIND_REQ);
15663 			if (ill->ill_ifname_pending)
15664 				break;
15665 			/*
15666 			 * Something went wrong with the bind.  We presumably
15667 			 * have an IOCTL hanging out waiting for completion.
15668 			 * Find it, take down the interface that was coming
15669 			 * up, and complete the IOCTL with the error noted.
15670 			 */
15671 			if (!ioctl_aborted)
15672 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15673 			if (mp1 != NULL) {
15674 				/*
15675 				 * This operation (SIOCSLIFFLAGS) must have
15676 				 * happened from a conn.
15677 				 */
15678 				ASSERT(connp != NULL);
15679 				q = CONNP_TO_WQ(connp);
15680 				if (ill->ill_move_in_progress) {
15681 					ILL_CLEAR_MOVE(ill);
15682 				}
15683 				(void) ipif_down(ipif, NULL, NULL);
15684 				/* error is set below the switch */
15685 			}
15686 			break;
15687 		case DL_ENABMULTI_REQ:
15688 			if (!ill->ill_isv6)
15689 				ipsq_current_finish(ipsq);
15690 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15691 
15692 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15693 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15694 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15695 				ipif_t *ipif;
15696 
15697 				printf("ip: joining multicasts failed (%d)"
15698 				    " on %s - will use link layer "
15699 				    "broadcasts for multicast\n",
15700 				    dlea->dl_errno, ill->ill_name);
15701 
15702 				/*
15703 				 * Set up the multicast mapping alone.
15704 				 * writer, so ok to access ill->ill_ipif
15705 				 * without any lock.
15706 				 */
15707 				ipif = ill->ill_ipif;
15708 				mutex_enter(&ill->ill_phyint->phyint_lock);
15709 				ill->ill_phyint->phyint_flags |=
15710 				    PHYI_MULTI_BCAST;
15711 				mutex_exit(&ill->ill_phyint->phyint_lock);
15712 
15713 				if (!ill->ill_isv6) {
15714 					(void) ipif_arp_setup_multicast(ipif,
15715 					    NULL);
15716 				} else {
15717 					(void) ipif_ndp_setup_multicast(ipif,
15718 					    NULL);
15719 				}
15720 			}
15721 			freemsg(mp);	/* Don't want to pass this up */
15722 			return;
15723 
15724 		case DL_CAPABILITY_REQ:
15725 		case DL_CONTROL_REQ:
15726 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15727 			ill->ill_dlpi_capab_state = IDS_FAILED;
15728 			freemsg(mp);
15729 			return;
15730 		}
15731 		/*
15732 		 * Note the error for IOCTL completion (mp1 is set when
15733 		 * ready to complete ioctl). If ill_ifname_pending_err is
15734 		 * set, an error occured during plumbing (ill_ifname_pending),
15735 		 * so we want to report that error.
15736 		 *
15737 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15738 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15739 		 * expected to get errack'd if the driver doesn't support
15740 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15741 		 * if these error conditions are encountered.
15742 		 */
15743 		if (mp1 != NULL) {
15744 			if (ill->ill_ifname_pending_err != 0)  {
15745 				err = ill->ill_ifname_pending_err;
15746 				ill->ill_ifname_pending_err = 0;
15747 			} else {
15748 				err = dlea->dl_unix_errno ?
15749 				    dlea->dl_unix_errno : ENXIO;
15750 			}
15751 		/*
15752 		 * If we're plumbing an interface and an error hasn't already
15753 		 * been saved, set ill_ifname_pending_err to the error passed
15754 		 * up. Ignore the error if log is B_FALSE (see comment above).
15755 		 */
15756 		} else if (log && ill->ill_ifname_pending &&
15757 		    ill->ill_ifname_pending_err == 0) {
15758 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15759 			    dlea->dl_unix_errno : ENXIO;
15760 		}
15761 
15762 		if (log)
15763 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15764 			    dlea->dl_errno, dlea->dl_unix_errno);
15765 		break;
15766 	case DL_CAPABILITY_ACK:
15767 		/* Call a routine to handle this one. */
15768 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15769 		ill_capability_ack(ill, mp);
15770 
15771 		/*
15772 		 * If the ack is due to renegotiation, we will need to send
15773 		 * a new CAPABILITY_REQ to start the renegotiation.
15774 		 */
15775 		if (ill->ill_capab_reneg) {
15776 			ill->ill_capab_reneg = B_FALSE;
15777 			ill_capability_probe(ill);
15778 		}
15779 		break;
15780 	case DL_CONTROL_ACK:
15781 		/* We treat all of these as "fire and forget" */
15782 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15783 		break;
15784 	case DL_INFO_ACK:
15785 		/* Call a routine to handle this one. */
15786 		ill_dlpi_done(ill, DL_INFO_REQ);
15787 		ip_ll_subnet_defaults(ill, mp);
15788 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15789 		return;
15790 	case DL_BIND_ACK:
15791 		/*
15792 		 * We should have an IOCTL waiting on this unless
15793 		 * sent by ill_dl_phys, in which case just return
15794 		 */
15795 		ill_dlpi_done(ill, DL_BIND_REQ);
15796 		if (ill->ill_ifname_pending)
15797 			break;
15798 
15799 		if (!ioctl_aborted)
15800 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15801 		if (mp1 == NULL)
15802 			break;
15803 		/*
15804 		 * Because mp1 was added by ill_dl_up(), and it always
15805 		 * passes a valid connp, connp must be valid here.
15806 		 */
15807 		ASSERT(connp != NULL);
15808 		q = CONNP_TO_WQ(connp);
15809 
15810 		/*
15811 		 * We are exclusive. So nothing can change even after
15812 		 * we get the pending mp. If need be we can put it back
15813 		 * and restart, as in calling ipif_arp_up()  below.
15814 		 */
15815 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15816 
15817 		mutex_enter(&ill->ill_lock);
15818 		ill->ill_dl_up = 1;
15819 		(void) ill_hook_event_create(ill, 0, NE_UP, NULL, 0);
15820 		mutex_exit(&ill->ill_lock);
15821 
15822 		/*
15823 		 * Now bring up the resolver; when that is complete, we'll
15824 		 * create IREs.  Note that we intentionally mirror what
15825 		 * ipif_up() would have done, because we got here by way of
15826 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15827 		 */
15828 		if (ill->ill_isv6) {
15829 			/*
15830 			 * v6 interfaces.
15831 			 * Unlike ARP which has to do another bind
15832 			 * and attach, once we get here we are
15833 			 * done with NDP. Except in the case of
15834 			 * ILLF_XRESOLV, in which case we send an
15835 			 * AR_INTERFACE_UP to the external resolver.
15836 			 * If all goes well, the ioctl will complete
15837 			 * in ip_rput(). If there's an error, we
15838 			 * complete it here.
15839 			 */
15840 			if ((err = ipif_ndp_up(ipif)) == 0) {
15841 				if (ill->ill_flags & ILLF_XRESOLV) {
15842 					mutex_enter(&connp->conn_lock);
15843 					mutex_enter(&ill->ill_lock);
15844 					success = ipsq_pending_mp_add(
15845 					    connp, ipif, q, mp1, 0);
15846 					mutex_exit(&ill->ill_lock);
15847 					mutex_exit(&connp->conn_lock);
15848 					if (success) {
15849 						err = ipif_resolver_up(ipif,
15850 						    Res_act_initial);
15851 						if (err == EINPROGRESS) {
15852 							freemsg(mp);
15853 							return;
15854 						}
15855 						ASSERT(err != 0);
15856 						mp1 = ipsq_pending_mp_get(ipsq,
15857 						    &connp);
15858 						ASSERT(mp1 != NULL);
15859 					} else {
15860 						/* conn has started closing */
15861 						err = EINTR;
15862 					}
15863 				} else { /* Non XRESOLV interface */
15864 					(void) ipif_resolver_up(ipif,
15865 					    Res_act_initial);
15866 					err = ipif_up_done_v6(ipif);
15867 				}
15868 			}
15869 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
15870 			/*
15871 			 * ARP and other v4 external resolvers.
15872 			 * Leave the pending mblk intact so that
15873 			 * the ioctl completes in ip_rput().
15874 			 */
15875 			mutex_enter(&connp->conn_lock);
15876 			mutex_enter(&ill->ill_lock);
15877 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
15878 			mutex_exit(&ill->ill_lock);
15879 			mutex_exit(&connp->conn_lock);
15880 			if (success) {
15881 				err = ipif_resolver_up(ipif, Res_act_initial);
15882 				if (err == EINPROGRESS) {
15883 					freemsg(mp);
15884 					return;
15885 				}
15886 				ASSERT(err != 0);
15887 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15888 			} else {
15889 				/* The conn has started closing */
15890 				err = EINTR;
15891 			}
15892 		} else {
15893 			/*
15894 			 * This one is complete. Reply to pending ioctl.
15895 			 */
15896 			(void) ipif_resolver_up(ipif, Res_act_initial);
15897 			err = ipif_up_done(ipif);
15898 		}
15899 
15900 		if ((err == 0) && (ill->ill_up_ipifs)) {
15901 			err = ill_up_ipifs(ill, q, mp1);
15902 			if (err == EINPROGRESS) {
15903 				freemsg(mp);
15904 				return;
15905 			}
15906 		}
15907 
15908 		if (ill->ill_up_ipifs) {
15909 			ill_group_cleanup(ill);
15910 		}
15911 
15912 		break;
15913 	case DL_NOTIFY_IND: {
15914 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
15915 		ire_t *ire;
15916 		boolean_t need_ire_walk_v4 = B_FALSE;
15917 		boolean_t need_ire_walk_v6 = B_FALSE;
15918 
15919 		switch (notify->dl_notification) {
15920 		case DL_NOTE_PHYS_ADDR:
15921 			err = ill_set_phys_addr(ill, mp);
15922 			break;
15923 
15924 		case DL_NOTE_FASTPATH_FLUSH:
15925 			ill_fastpath_flush(ill);
15926 			break;
15927 
15928 		case DL_NOTE_SDU_SIZE:
15929 			/*
15930 			 * Change the MTU size of the interface, of all
15931 			 * attached ipif's, and of all relevant ire's.  The
15932 			 * new value's a uint32_t at notify->dl_data.
15933 			 * Mtu change Vs. new ire creation - protocol below.
15934 			 *
15935 			 * a Mark the ipif as IPIF_CHANGING.
15936 			 * b Set the new mtu in the ipif.
15937 			 * c Change the ire_max_frag on all affected ires
15938 			 * d Unmark the IPIF_CHANGING
15939 			 *
15940 			 * To see how the protocol works, assume an interface
15941 			 * route is also being added simultaneously by
15942 			 * ip_rt_add and let 'ipif' be the ipif referenced by
15943 			 * the ire. If the ire is created before step a,
15944 			 * it will be cleaned up by step c. If the ire is
15945 			 * created after step d, it will see the new value of
15946 			 * ipif_mtu. Any attempt to create the ire between
15947 			 * steps a to d will fail because of the IPIF_CHANGING
15948 			 * flag. Note that ire_create() is passed a pointer to
15949 			 * the ipif_mtu, and not the value. During ire_add
15950 			 * under the bucket lock, the ire_max_frag of the
15951 			 * new ire being created is set from the ipif/ire from
15952 			 * which it is being derived.
15953 			 */
15954 			mutex_enter(&ill->ill_lock);
15955 			ill->ill_max_frag = (uint_t)notify->dl_data;
15956 
15957 			/*
15958 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
15959 			 * leave it alone
15960 			 */
15961 			if (ill->ill_mtu_userspecified) {
15962 				mutex_exit(&ill->ill_lock);
15963 				break;
15964 			}
15965 			ill->ill_max_mtu = ill->ill_max_frag;
15966 			if (ill->ill_isv6) {
15967 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
15968 					ill->ill_max_mtu = IPV6_MIN_MTU;
15969 			} else {
15970 				if (ill->ill_max_mtu < IP_MIN_MTU)
15971 					ill->ill_max_mtu = IP_MIN_MTU;
15972 			}
15973 			for (ipif = ill->ill_ipif; ipif != NULL;
15974 			    ipif = ipif->ipif_next) {
15975 				/*
15976 				 * Don't override the mtu if the user
15977 				 * has explicitly set it.
15978 				 */
15979 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
15980 					continue;
15981 				ipif->ipif_mtu = (uint_t)notify->dl_data;
15982 				if (ipif->ipif_isv6)
15983 					ire = ipif_to_ire_v6(ipif);
15984 				else
15985 					ire = ipif_to_ire(ipif);
15986 				if (ire != NULL) {
15987 					ire->ire_max_frag = ipif->ipif_mtu;
15988 					ire_refrele(ire);
15989 				}
15990 				if (ipif->ipif_flags & IPIF_UP) {
15991 					if (ill->ill_isv6)
15992 						need_ire_walk_v6 = B_TRUE;
15993 					else
15994 						need_ire_walk_v4 = B_TRUE;
15995 				}
15996 			}
15997 			mutex_exit(&ill->ill_lock);
15998 			if (need_ire_walk_v4)
15999 				ire_walk_v4(ill_mtu_change, (char *)ill,
16000 				    ALL_ZONES, ipst);
16001 			if (need_ire_walk_v6)
16002 				ire_walk_v6(ill_mtu_change, (char *)ill,
16003 				    ALL_ZONES, ipst);
16004 			break;
16005 		case DL_NOTE_LINK_UP:
16006 		case DL_NOTE_LINK_DOWN: {
16007 			/*
16008 			 * We are writer. ill / phyint / ipsq assocs stable.
16009 			 * The RUNNING flag reflects the state of the link.
16010 			 */
16011 			phyint_t *phyint = ill->ill_phyint;
16012 			uint64_t new_phyint_flags;
16013 			boolean_t changed = B_FALSE;
16014 			boolean_t went_up;
16015 
16016 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
16017 			mutex_enter(&phyint->phyint_lock);
16018 			new_phyint_flags = went_up ?
16019 			    phyint->phyint_flags | PHYI_RUNNING :
16020 			    phyint->phyint_flags & ~PHYI_RUNNING;
16021 			if (new_phyint_flags != phyint->phyint_flags) {
16022 				phyint->phyint_flags = new_phyint_flags;
16023 				changed = B_TRUE;
16024 			}
16025 			mutex_exit(&phyint->phyint_lock);
16026 			/*
16027 			 * ill_restart_dad handles the DAD restart and routing
16028 			 * socket notification logic.
16029 			 */
16030 			if (changed) {
16031 				ill_restart_dad(phyint->phyint_illv4, went_up);
16032 				ill_restart_dad(phyint->phyint_illv6, went_up);
16033 			}
16034 			break;
16035 		}
16036 		case DL_NOTE_PROMISC_ON_PHYS:
16037 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16038 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
16039 			mutex_enter(&ill->ill_lock);
16040 			ill->ill_promisc_on_phys = B_TRUE;
16041 			mutex_exit(&ill->ill_lock);
16042 			break;
16043 		case DL_NOTE_PROMISC_OFF_PHYS:
16044 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16045 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16046 			mutex_enter(&ill->ill_lock);
16047 			ill->ill_promisc_on_phys = B_FALSE;
16048 			mutex_exit(&ill->ill_lock);
16049 			break;
16050 		case DL_NOTE_CAPAB_RENEG:
16051 			/*
16052 			 * Something changed on the driver side.
16053 			 * It wants us to renegotiate the capabilities
16054 			 * on this ill. One possible cause is the aggregation
16055 			 * interface under us where a port got added or
16056 			 * went away.
16057 			 *
16058 			 * If the capability negotiation is already done
16059 			 * or is in progress, reset the capabilities and
16060 			 * mark the ill's ill_capab_reneg to be B_TRUE,
16061 			 * so that when the ack comes back, we can start
16062 			 * the renegotiation process.
16063 			 *
16064 			 * Note that if ill_capab_reneg is already B_TRUE
16065 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
16066 			 * the capability resetting request has been sent
16067 			 * and the renegotiation has not been started yet;
16068 			 * nothing needs to be done in this case.
16069 			 */
16070 			if (ill->ill_dlpi_capab_state != IDS_UNKNOWN) {
16071 				ill_capability_reset(ill);
16072 				ill->ill_capab_reneg = B_TRUE;
16073 			}
16074 			break;
16075 		default:
16076 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16077 			    "type 0x%x for DL_NOTIFY_IND\n",
16078 			    notify->dl_notification));
16079 			break;
16080 		}
16081 
16082 		/*
16083 		 * As this is an asynchronous operation, we
16084 		 * should not call ill_dlpi_done
16085 		 */
16086 		break;
16087 	}
16088 	case DL_NOTIFY_ACK: {
16089 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16090 
16091 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16092 			ill->ill_note_link = 1;
16093 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16094 		break;
16095 	}
16096 	case DL_PHYS_ADDR_ACK: {
16097 		/*
16098 		 * As part of plumbing the interface via SIOCSLIFNAME,
16099 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16100 		 * whose answers we receive here.  As each answer is received,
16101 		 * we call ill_dlpi_done() to dispatch the next request as
16102 		 * we're processing the current one.  Once all answers have
16103 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16104 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16105 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16106 		 * available, but we know the ioctl is pending on ill_wq.)
16107 		 */
16108 		uint_t paddrlen, paddroff;
16109 
16110 		paddrreq = ill->ill_phys_addr_pend;
16111 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16112 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16113 
16114 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16115 		if (paddrreq == DL_IPV6_TOKEN) {
16116 			/*
16117 			 * bcopy to low-order bits of ill_token
16118 			 *
16119 			 * XXX Temporary hack - currently, all known tokens
16120 			 * are 64 bits, so I'll cheat for the moment.
16121 			 */
16122 			bcopy(mp->b_rptr + paddroff,
16123 			    &ill->ill_token.s6_addr32[2], paddrlen);
16124 			ill->ill_token_length = paddrlen;
16125 			break;
16126 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16127 			ASSERT(ill->ill_nd_lla_mp == NULL);
16128 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16129 			mp = NULL;
16130 			break;
16131 		}
16132 
16133 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16134 		ASSERT(ill->ill_phys_addr_mp == NULL);
16135 		if (!ill->ill_ifname_pending)
16136 			break;
16137 		ill->ill_ifname_pending = 0;
16138 		if (!ioctl_aborted)
16139 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16140 		if (mp1 != NULL) {
16141 			ASSERT(connp == NULL);
16142 			q = ill->ill_wq;
16143 		}
16144 		/*
16145 		 * If any error acks received during the plumbing sequence,
16146 		 * ill_ifname_pending_err will be set. Break out and send up
16147 		 * the error to the pending ioctl.
16148 		 */
16149 		if (ill->ill_ifname_pending_err != 0) {
16150 			err = ill->ill_ifname_pending_err;
16151 			ill->ill_ifname_pending_err = 0;
16152 			break;
16153 		}
16154 
16155 		ill->ill_phys_addr_mp = mp;
16156 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16157 		mp = NULL;
16158 
16159 		/*
16160 		 * If paddrlen is zero, the DLPI provider doesn't support
16161 		 * physical addresses.  The other two tests were historical
16162 		 * workarounds for bugs in our former PPP implementation, but
16163 		 * now other things have grown dependencies on them -- e.g.,
16164 		 * the tun module specifies a dl_addr_length of zero in its
16165 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16166 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16167 		 * but only after careful testing ensures that all dependent
16168 		 * broken DLPI providers have been fixed.
16169 		 */
16170 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16171 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16172 			ill->ill_phys_addr = NULL;
16173 		} else if (paddrlen != ill->ill_phys_addr_length) {
16174 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16175 			    paddrlen, ill->ill_phys_addr_length));
16176 			err = EINVAL;
16177 			break;
16178 		}
16179 
16180 		if (ill->ill_nd_lla_mp == NULL) {
16181 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16182 				err = ENOMEM;
16183 				break;
16184 			}
16185 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16186 		}
16187 
16188 		/*
16189 		 * Set the interface token.  If the zeroth interface address
16190 		 * is unspecified, then set it to the link local address.
16191 		 */
16192 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16193 			(void) ill_setdefaulttoken(ill);
16194 
16195 		ASSERT(ill->ill_ipif->ipif_id == 0);
16196 		if (ipif != NULL &&
16197 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16198 			(void) ipif_setlinklocal(ipif);
16199 		}
16200 		break;
16201 	}
16202 	case DL_OK_ACK:
16203 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16204 		    dl_primstr((int)dloa->dl_correct_primitive),
16205 		    dloa->dl_correct_primitive));
16206 		switch (dloa->dl_correct_primitive) {
16207 		case DL_ENABMULTI_REQ:
16208 		case DL_DISABMULTI_REQ:
16209 			if (!ill->ill_isv6)
16210 				ipsq_current_finish(ipsq);
16211 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16212 			break;
16213 		case DL_PROMISCON_REQ:
16214 		case DL_PROMISCOFF_REQ:
16215 		case DL_UNBIND_REQ:
16216 		case DL_ATTACH_REQ:
16217 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16218 			break;
16219 		}
16220 		break;
16221 	default:
16222 		break;
16223 	}
16224 
16225 	freemsg(mp);
16226 	if (mp1 != NULL) {
16227 		/*
16228 		 * The operation must complete without EINPROGRESS
16229 		 * since ipsq_pending_mp_get() has removed the mblk
16230 		 * from ipsq_pending_mp.  Otherwise, the operation
16231 		 * will be stuck forever in the ipsq.
16232 		 */
16233 		ASSERT(err != EINPROGRESS);
16234 
16235 		switch (ipsq->ipsq_current_ioctl) {
16236 		case 0:
16237 			ipsq_current_finish(ipsq);
16238 			break;
16239 
16240 		case SIOCLIFADDIF:
16241 		case SIOCSLIFNAME:
16242 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16243 			break;
16244 
16245 		default:
16246 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16247 			break;
16248 		}
16249 	}
16250 }
16251 
16252 /*
16253  * ip_rput_other is called by ip_rput to handle messages modifying the global
16254  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16255  */
16256 /* ARGSUSED */
16257 void
16258 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16259 {
16260 	ill_t		*ill;
16261 	struct iocblk	*iocp;
16262 	mblk_t		*mp1;
16263 	conn_t		*connp = NULL;
16264 
16265 	ip1dbg(("ip_rput_other "));
16266 	ill = (ill_t *)q->q_ptr;
16267 	/*
16268 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16269 	 * in which case ipsq is NULL.
16270 	 */
16271 	if (ipsq != NULL) {
16272 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16273 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16274 	}
16275 
16276 	switch (mp->b_datap->db_type) {
16277 	case M_ERROR:
16278 	case M_HANGUP:
16279 		/*
16280 		 * The device has a problem.  We force the ILL down.  It can
16281 		 * be brought up again manually using SIOCSIFFLAGS (via
16282 		 * ifconfig or equivalent).
16283 		 */
16284 		ASSERT(ipsq != NULL);
16285 		if (mp->b_rptr < mp->b_wptr)
16286 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16287 		if (ill->ill_error == 0)
16288 			ill->ill_error = ENXIO;
16289 		if (!ill_down_start(q, mp))
16290 			return;
16291 		ipif_all_down_tail(ipsq, q, mp, NULL);
16292 		break;
16293 	case M_IOCACK:
16294 		iocp = (struct iocblk *)mp->b_rptr;
16295 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16296 		switch (iocp->ioc_cmd) {
16297 		case SIOCSTUNPARAM:
16298 		case OSIOCSTUNPARAM:
16299 			ASSERT(ipsq != NULL);
16300 			/*
16301 			 * Finish socket ioctl passed through to tun.
16302 			 * We should have an IOCTL waiting on this.
16303 			 */
16304 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16305 			if (ill->ill_isv6) {
16306 				struct iftun_req *ta;
16307 
16308 				/*
16309 				 * if a source or destination is
16310 				 * being set, try and set the link
16311 				 * local address for the tunnel
16312 				 */
16313 				ta = (struct iftun_req *)mp->b_cont->
16314 				    b_cont->b_rptr;
16315 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16316 					ipif_set_tun_llink(ill, ta);
16317 				}
16318 
16319 			}
16320 			if (mp1 != NULL) {
16321 				/*
16322 				 * Now copy back the b_next/b_prev used by
16323 				 * mi code for the mi_copy* functions.
16324 				 * See ip_sioctl_tunparam() for the reason.
16325 				 * Also protect against missing b_cont.
16326 				 */
16327 				if (mp->b_cont != NULL) {
16328 					mp->b_cont->b_next =
16329 					    mp1->b_cont->b_next;
16330 					mp->b_cont->b_prev =
16331 					    mp1->b_cont->b_prev;
16332 				}
16333 				inet_freemsg(mp1);
16334 				ASSERT(connp != NULL);
16335 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16336 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16337 			} else {
16338 				ASSERT(connp == NULL);
16339 				putnext(q, mp);
16340 			}
16341 			break;
16342 		case SIOCGTUNPARAM:
16343 		case OSIOCGTUNPARAM:
16344 			/*
16345 			 * This is really M_IOCDATA from the tunnel driver.
16346 			 * convert back and complete the ioctl.
16347 			 * We should have an IOCTL waiting on this.
16348 			 */
16349 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16350 			if (mp1) {
16351 				/*
16352 				 * Now copy back the b_next/b_prev used by
16353 				 * mi code for the mi_copy* functions.
16354 				 * See ip_sioctl_tunparam() for the reason.
16355 				 * Also protect against missing b_cont.
16356 				 */
16357 				if (mp->b_cont != NULL) {
16358 					mp->b_cont->b_next =
16359 					    mp1->b_cont->b_next;
16360 					mp->b_cont->b_prev =
16361 					    mp1->b_cont->b_prev;
16362 				}
16363 				inet_freemsg(mp1);
16364 				if (iocp->ioc_error == 0)
16365 					mp->b_datap->db_type = M_IOCDATA;
16366 				ASSERT(connp != NULL);
16367 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16368 				    iocp->ioc_error, COPYOUT, NULL);
16369 			} else {
16370 				ASSERT(connp == NULL);
16371 				putnext(q, mp);
16372 			}
16373 			break;
16374 		default:
16375 			break;
16376 		}
16377 		break;
16378 	case M_IOCNAK:
16379 		iocp = (struct iocblk *)mp->b_rptr;
16380 
16381 		switch (iocp->ioc_cmd) {
16382 		int mode;
16383 
16384 		case DL_IOC_HDR_INFO:
16385 			/*
16386 			 * If this was the first attempt turn of the
16387 			 * fastpath probing.
16388 			 */
16389 			mutex_enter(&ill->ill_lock);
16390 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16391 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16392 				mutex_exit(&ill->ill_lock);
16393 				ill_fastpath_nack(ill);
16394 				ip1dbg(("ip_rput: DLPI fastpath off on "
16395 				    "interface %s\n",
16396 				    ill->ill_name));
16397 			} else {
16398 				mutex_exit(&ill->ill_lock);
16399 			}
16400 			freemsg(mp);
16401 			break;
16402 		case SIOCSTUNPARAM:
16403 		case OSIOCSTUNPARAM:
16404 			ASSERT(ipsq != NULL);
16405 			/*
16406 			 * Finish socket ioctl passed through to tun
16407 			 * We should have an IOCTL waiting on this.
16408 			 */
16409 			/* FALLTHRU */
16410 		case SIOCGTUNPARAM:
16411 		case OSIOCGTUNPARAM:
16412 			/*
16413 			 * This is really M_IOCDATA from the tunnel driver.
16414 			 * convert back and complete the ioctl.
16415 			 * We should have an IOCTL waiting on this.
16416 			 */
16417 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16418 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16419 				mp1 = ill_pending_mp_get(ill, &connp,
16420 				    iocp->ioc_id);
16421 				mode = COPYOUT;
16422 				ipsq = NULL;
16423 			} else {
16424 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16425 				mode = NO_COPYOUT;
16426 			}
16427 			if (mp1 != NULL) {
16428 				/*
16429 				 * Now copy back the b_next/b_prev used by
16430 				 * mi code for the mi_copy* functions.
16431 				 * See ip_sioctl_tunparam() for the reason.
16432 				 * Also protect against missing b_cont.
16433 				 */
16434 				if (mp->b_cont != NULL) {
16435 					mp->b_cont->b_next =
16436 					    mp1->b_cont->b_next;
16437 					mp->b_cont->b_prev =
16438 					    mp1->b_cont->b_prev;
16439 				}
16440 				inet_freemsg(mp1);
16441 				if (iocp->ioc_error == 0)
16442 					iocp->ioc_error = EINVAL;
16443 				ASSERT(connp != NULL);
16444 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16445 				    iocp->ioc_error, mode, ipsq);
16446 			} else {
16447 				ASSERT(connp == NULL);
16448 				putnext(q, mp);
16449 			}
16450 			break;
16451 		default:
16452 			break;
16453 		}
16454 	default:
16455 		break;
16456 	}
16457 }
16458 
16459 /*
16460  * NOTE : This function does not ire_refrele the ire argument passed in.
16461  *
16462  * IPQoS notes
16463  * IP policy is invoked twice for a forwarded packet, once on the read side
16464  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16465  * enabled. An additional parameter, in_ill, has been added for this purpose.
16466  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16467  * because ip_mroute drops this information.
16468  *
16469  */
16470 void
16471 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16472 {
16473 	uint32_t	old_pkt_len;
16474 	uint32_t	pkt_len;
16475 	queue_t	*q;
16476 	uint32_t	sum;
16477 #define	rptr	((uchar_t *)ipha)
16478 	uint32_t	max_frag;
16479 	uint32_t	ill_index;
16480 	ill_t		*out_ill;
16481 	mib2_ipIfStatsEntry_t *mibptr;
16482 	ip_stack_t	*ipst = ((ill_t *)(ire->ire_stq->q_ptr))->ill_ipst;
16483 
16484 	/* Get the ill_index of the incoming ILL */
16485 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16486 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16487 
16488 	/* Initiate Read side IPPF processing */
16489 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16490 		ip_process(IPP_FWD_IN, &mp, ill_index);
16491 		if (mp == NULL) {
16492 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16493 			    "during IPPF processing\n"));
16494 			return;
16495 		}
16496 	}
16497 
16498 	/* Adjust the checksum to reflect the ttl decrement. */
16499 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16500 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16501 
16502 	if (ipha->ipha_ttl-- <= 1) {
16503 		if (ip_csum_hdr(ipha)) {
16504 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16505 			goto drop_pkt;
16506 		}
16507 		/*
16508 		 * Note: ire_stq this will be NULL for multicast
16509 		 * datagrams using the long path through arp (the IRE
16510 		 * is not an IRE_CACHE). This should not cause
16511 		 * problems since we don't generate ICMP errors for
16512 		 * multicast packets.
16513 		 */
16514 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16515 		q = ire->ire_stq;
16516 		if (q != NULL) {
16517 			/* Sent by forwarding path, and router is global zone */
16518 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16519 			    GLOBAL_ZONEID, ipst);
16520 		} else
16521 			freemsg(mp);
16522 		return;
16523 	}
16524 
16525 	/*
16526 	 * Don't forward if the interface is down
16527 	 */
16528 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16529 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16530 		ip2dbg(("ip_rput_forward:interface is down\n"));
16531 		goto drop_pkt;
16532 	}
16533 
16534 	/* Get the ill_index of the outgoing ILL */
16535 	out_ill = ire_to_ill(ire);
16536 	ill_index = out_ill->ill_phyint->phyint_ifindex;
16537 
16538 	DTRACE_PROBE4(ip4__forwarding__start,
16539 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16540 
16541 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16542 	    ipst->ips_ipv4firewall_forwarding,
16543 	    in_ill, out_ill, ipha, mp, mp, 0, ipst);
16544 
16545 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16546 
16547 	if (mp == NULL)
16548 		return;
16549 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16550 
16551 	if (is_system_labeled()) {
16552 		mblk_t *mp1;
16553 
16554 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16555 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16556 			goto drop_pkt;
16557 		}
16558 		/* Size may have changed */
16559 		mp = mp1;
16560 		ipha = (ipha_t *)mp->b_rptr;
16561 		pkt_len = ntohs(ipha->ipha_length);
16562 	}
16563 
16564 	/* Check if there are options to update */
16565 	if (!IS_SIMPLE_IPH(ipha)) {
16566 		if (ip_csum_hdr(ipha)) {
16567 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16568 			goto drop_pkt;
16569 		}
16570 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16571 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16572 			return;
16573 		}
16574 
16575 		ipha->ipha_hdr_checksum = 0;
16576 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16577 	}
16578 	max_frag = ire->ire_max_frag;
16579 	if (pkt_len > max_frag) {
16580 		/*
16581 		 * It needs fragging on its way out.  We haven't
16582 		 * verified the header checksum yet.  Since we
16583 		 * are going to put a surely good checksum in the
16584 		 * outgoing header, we have to make sure that it
16585 		 * was good coming in.
16586 		 */
16587 		if (ip_csum_hdr(ipha)) {
16588 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16589 			goto drop_pkt;
16590 		}
16591 		/* Initiate Write side IPPF processing */
16592 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16593 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16594 			if (mp == NULL) {
16595 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16596 				    " during IPPF processing\n"));
16597 				return;
16598 			}
16599 		}
16600 		/*
16601 		 * Handle labeled packet resizing.
16602 		 *
16603 		 * If we have added a label, inform ip_wput_frag() of its
16604 		 * effect on the MTU for ICMP messages.
16605 		 */
16606 		if (pkt_len > old_pkt_len) {
16607 			uint32_t secopt_size;
16608 
16609 			secopt_size = pkt_len - old_pkt_len;
16610 			if (secopt_size < max_frag)
16611 				max_frag -= secopt_size;
16612 		}
16613 
16614 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
16615 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16616 		return;
16617 	}
16618 
16619 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16620 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16621 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16622 	    ipst->ips_ipv4firewall_physical_out,
16623 	    NULL, out_ill, ipha, mp, mp, 0, ipst);
16624 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16625 	if (mp == NULL)
16626 		return;
16627 
16628 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16629 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16630 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16631 	/* ip_xmit_v4 always consumes the packet */
16632 	return;
16633 
16634 drop_pkt:;
16635 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16636 	freemsg(mp);
16637 #undef	rptr
16638 }
16639 
16640 void
16641 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16642 {
16643 	ire_t	*ire;
16644 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16645 
16646 	ASSERT(!ipif->ipif_isv6);
16647 	/*
16648 	 * Find an IRE which matches the destination and the outgoing
16649 	 * queue in the cache table. All we need is an IRE_CACHE which
16650 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16651 	 * then it is enough to have some IRE_CACHE in the group.
16652 	 */
16653 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16654 		dst = ipif->ipif_pp_dst_addr;
16655 
16656 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16657 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR, ipst);
16658 	if (ire == NULL) {
16659 		/*
16660 		 * Mark this packet to make it be delivered to
16661 		 * ip_rput_forward after the new ire has been
16662 		 * created.
16663 		 */
16664 		mp->b_prev = NULL;
16665 		mp->b_next = mp;
16666 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16667 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16668 	} else {
16669 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16670 		IRE_REFRELE(ire);
16671 	}
16672 }
16673 
16674 /* Update any source route, record route or timestamp options */
16675 static int
16676 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16677 {
16678 	ipoptp_t	opts;
16679 	uchar_t		*opt;
16680 	uint8_t		optval;
16681 	uint8_t		optlen;
16682 	ipaddr_t	dst;
16683 	uint32_t	ts;
16684 	ire_t		*dst_ire = NULL;
16685 	ire_t		*tmp_ire = NULL;
16686 	timestruc_t	now;
16687 
16688 	ip2dbg(("ip_rput_forward_options\n"));
16689 	dst = ipha->ipha_dst;
16690 	for (optval = ipoptp_first(&opts, ipha);
16691 	    optval != IPOPT_EOL;
16692 	    optval = ipoptp_next(&opts)) {
16693 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16694 		opt = opts.ipoptp_cur;
16695 		optlen = opts.ipoptp_len;
16696 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16697 		    optval, opts.ipoptp_len));
16698 		switch (optval) {
16699 			uint32_t off;
16700 		case IPOPT_SSRR:
16701 		case IPOPT_LSRR:
16702 			/* Check if adminstratively disabled */
16703 			if (!ipst->ips_ip_forward_src_routed) {
16704 				if (ire->ire_stq != NULL) {
16705 					/*
16706 					 * Sent by forwarding path, and router
16707 					 * is global zone
16708 					 */
16709 					icmp_unreachable(ire->ire_stq, mp,
16710 					    ICMP_SOURCE_ROUTE_FAILED,
16711 					    GLOBAL_ZONEID, ipst);
16712 				} else {
16713 					ip0dbg(("ip_rput_forward_options: "
16714 					    "unable to send unreach\n"));
16715 					freemsg(mp);
16716 				}
16717 				return (-1);
16718 			}
16719 
16720 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16721 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16722 			if (dst_ire == NULL) {
16723 				/*
16724 				 * Must be partial since ip_rput_options
16725 				 * checked for strict.
16726 				 */
16727 				break;
16728 			}
16729 			off = opt[IPOPT_OFFSET];
16730 			off--;
16731 		redo_srr:
16732 			if (optlen < IP_ADDR_LEN ||
16733 			    off > optlen - IP_ADDR_LEN) {
16734 				/* End of source route */
16735 				ip1dbg((
16736 				    "ip_rput_forward_options: end of SR\n"));
16737 				ire_refrele(dst_ire);
16738 				break;
16739 			}
16740 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16741 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16742 			    IP_ADDR_LEN);
16743 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16744 			    ntohl(dst)));
16745 
16746 			/*
16747 			 * Check if our address is present more than
16748 			 * once as consecutive hops in source route.
16749 			 */
16750 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16751 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16752 			if (tmp_ire != NULL) {
16753 				ire_refrele(tmp_ire);
16754 				off += IP_ADDR_LEN;
16755 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16756 				goto redo_srr;
16757 			}
16758 			ipha->ipha_dst = dst;
16759 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16760 			ire_refrele(dst_ire);
16761 			break;
16762 		case IPOPT_RR:
16763 			off = opt[IPOPT_OFFSET];
16764 			off--;
16765 			if (optlen < IP_ADDR_LEN ||
16766 			    off > optlen - IP_ADDR_LEN) {
16767 				/* No more room - ignore */
16768 				ip1dbg((
16769 				    "ip_rput_forward_options: end of RR\n"));
16770 				break;
16771 			}
16772 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16773 			    IP_ADDR_LEN);
16774 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16775 			break;
16776 		case IPOPT_TS:
16777 			/* Insert timestamp if there is room */
16778 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16779 			case IPOPT_TS_TSONLY:
16780 				off = IPOPT_TS_TIMELEN;
16781 				break;
16782 			case IPOPT_TS_PRESPEC:
16783 			case IPOPT_TS_PRESPEC_RFC791:
16784 				/* Verify that the address matched */
16785 				off = opt[IPOPT_OFFSET] - 1;
16786 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16787 				dst_ire = ire_ctable_lookup(dst, 0,
16788 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16789 				    MATCH_IRE_TYPE, ipst);
16790 				if (dst_ire == NULL) {
16791 					/* Not for us */
16792 					break;
16793 				}
16794 				ire_refrele(dst_ire);
16795 				/* FALLTHRU */
16796 			case IPOPT_TS_TSANDADDR:
16797 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16798 				break;
16799 			default:
16800 				/*
16801 				 * ip_*put_options should have already
16802 				 * dropped this packet.
16803 				 */
16804 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16805 				    "unknown IT - bug in ip_rput_options?\n");
16806 				return (0);	/* Keep "lint" happy */
16807 			}
16808 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16809 				/* Increase overflow counter */
16810 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16811 				opt[IPOPT_POS_OV_FLG] =
16812 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16813 				    (off << 4));
16814 				break;
16815 			}
16816 			off = opt[IPOPT_OFFSET] - 1;
16817 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16818 			case IPOPT_TS_PRESPEC:
16819 			case IPOPT_TS_PRESPEC_RFC791:
16820 			case IPOPT_TS_TSANDADDR:
16821 				bcopy(&ire->ire_src_addr,
16822 				    (char *)opt + off, IP_ADDR_LEN);
16823 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16824 				/* FALLTHRU */
16825 			case IPOPT_TS_TSONLY:
16826 				off = opt[IPOPT_OFFSET] - 1;
16827 				/* Compute # of milliseconds since midnight */
16828 				gethrestime(&now);
16829 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16830 				    now.tv_nsec / (NANOSEC / MILLISEC);
16831 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16832 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16833 				break;
16834 			}
16835 			break;
16836 		}
16837 	}
16838 	return (0);
16839 }
16840 
16841 /*
16842  * This is called after processing at least one of AH/ESP headers.
16843  *
16844  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16845  * the actual, physical interface on which the packet was received,
16846  * but, when ip_strict_dst_multihoming is set to 1, could be the
16847  * interface which had the ipha_dst configured when the packet went
16848  * through ip_rput. The ill_index corresponding to the recv_ill
16849  * is saved in ipsec_in_rill_index
16850  *
16851  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
16852  * cannot assume "ire" points to valid data for any IPv6 cases.
16853  */
16854 void
16855 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16856 {
16857 	mblk_t *mp;
16858 	ipaddr_t dst;
16859 	in6_addr_t *v6dstp;
16860 	ipha_t *ipha;
16861 	ip6_t *ip6h;
16862 	ipsec_in_t *ii;
16863 	boolean_t ill_need_rele = B_FALSE;
16864 	boolean_t rill_need_rele = B_FALSE;
16865 	boolean_t ire_need_rele = B_FALSE;
16866 	netstack_t	*ns;
16867 	ip_stack_t	*ipst;
16868 
16869 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16870 	ASSERT(ii->ipsec_in_ill_index != 0);
16871 	ns = ii->ipsec_in_ns;
16872 	ASSERT(ii->ipsec_in_ns != NULL);
16873 	ipst = ns->netstack_ip;
16874 
16875 	mp = ipsec_mp->b_cont;
16876 	ASSERT(mp != NULL);
16877 
16878 
16879 	if (ill == NULL) {
16880 		ASSERT(recv_ill == NULL);
16881 		/*
16882 		 * We need to get the original queue on which ip_rput_local
16883 		 * or ip_rput_data_v6 was called.
16884 		 */
16885 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16886 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
16887 		ill_need_rele = B_TRUE;
16888 
16889 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16890 			recv_ill = ill_lookup_on_ifindex(
16891 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16892 			    NULL, NULL, NULL, NULL, ipst);
16893 			rill_need_rele = B_TRUE;
16894 		} else {
16895 			recv_ill = ill;
16896 		}
16897 
16898 		if ((ill == NULL) || (recv_ill == NULL)) {
16899 			ip0dbg(("ip_fanout_proto_again: interface "
16900 			    "disappeared\n"));
16901 			if (ill != NULL)
16902 				ill_refrele(ill);
16903 			if (recv_ill != NULL)
16904 				ill_refrele(recv_ill);
16905 			freemsg(ipsec_mp);
16906 			return;
16907 		}
16908 	}
16909 
16910 	ASSERT(ill != NULL && recv_ill != NULL);
16911 
16912 	if (mp->b_datap->db_type == M_CTL) {
16913 		/*
16914 		 * AH/ESP is returning the ICMP message after
16915 		 * removing their headers. Fanout again till
16916 		 * it gets to the right protocol.
16917 		 */
16918 		if (ii->ipsec_in_v4) {
16919 			icmph_t *icmph;
16920 			int iph_hdr_length;
16921 			int hdr_length;
16922 
16923 			ipha = (ipha_t *)mp->b_rptr;
16924 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
16925 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
16926 			ipha = (ipha_t *)&icmph[1];
16927 			hdr_length = IPH_HDR_LENGTH(ipha);
16928 			/*
16929 			 * icmp_inbound_error_fanout may need to do pullupmsg.
16930 			 * Reset the type to M_DATA.
16931 			 */
16932 			mp->b_datap->db_type = M_DATA;
16933 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
16934 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
16935 			    B_FALSE, ill, ii->ipsec_in_zoneid);
16936 		} else {
16937 			icmp6_t *icmp6;
16938 			int hdr_length;
16939 
16940 			ip6h = (ip6_t *)mp->b_rptr;
16941 			/* Don't call hdr_length_v6() unless you have to. */
16942 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
16943 				hdr_length = ip_hdr_length_v6(mp, ip6h);
16944 			else
16945 				hdr_length = IPV6_HDR_LEN;
16946 
16947 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
16948 			/*
16949 			 * icmp_inbound_error_fanout_v6 may need to do
16950 			 * pullupmsg.  Reset the type to M_DATA.
16951 			 */
16952 			mp->b_datap->db_type = M_DATA;
16953 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
16954 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
16955 		}
16956 		if (ill_need_rele)
16957 			ill_refrele(ill);
16958 		if (rill_need_rele)
16959 			ill_refrele(recv_ill);
16960 		return;
16961 	}
16962 
16963 	if (ii->ipsec_in_v4) {
16964 		ipha = (ipha_t *)mp->b_rptr;
16965 		dst = ipha->ipha_dst;
16966 		if (CLASSD(dst)) {
16967 			/*
16968 			 * Multicast has to be delivered to all streams.
16969 			 */
16970 			dst = INADDR_BROADCAST;
16971 		}
16972 
16973 		if (ire == NULL) {
16974 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
16975 			    MBLK_GETLABEL(mp), ipst);
16976 			if (ire == NULL) {
16977 				if (ill_need_rele)
16978 					ill_refrele(ill);
16979 				if (rill_need_rele)
16980 					ill_refrele(recv_ill);
16981 				ip1dbg(("ip_fanout_proto_again: "
16982 				    "IRE not found"));
16983 				freemsg(ipsec_mp);
16984 				return;
16985 			}
16986 			ire_need_rele = B_TRUE;
16987 		}
16988 
16989 		switch (ipha->ipha_protocol) {
16990 			case IPPROTO_UDP:
16991 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
16992 				    recv_ill);
16993 				if (ire_need_rele)
16994 					ire_refrele(ire);
16995 				break;
16996 			case IPPROTO_TCP:
16997 				if (!ire_need_rele)
16998 					IRE_REFHOLD(ire);
16999 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
17000 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
17001 				IRE_REFRELE(ire);
17002 				if (mp != NULL)
17003 					squeue_enter_chain(GET_SQUEUE(mp), mp,
17004 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
17005 				break;
17006 			case IPPROTO_SCTP:
17007 				if (!ire_need_rele)
17008 					IRE_REFHOLD(ire);
17009 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
17010 				    ipsec_mp, 0, ill->ill_rq, dst);
17011 				break;
17012 			default:
17013 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
17014 				    recv_ill, B_FALSE);
17015 				if (ire_need_rele)
17016 					ire_refrele(ire);
17017 				break;
17018 		}
17019 	} else {
17020 		uint32_t rput_flags = 0;
17021 
17022 		ip6h = (ip6_t *)mp->b_rptr;
17023 		v6dstp = &ip6h->ip6_dst;
17024 		/*
17025 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
17026 		 * address.
17027 		 *
17028 		 * Currently, we don't store that state in the IPSEC_IN
17029 		 * message, and we may need to.
17030 		 */
17031 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
17032 		    IP6_IN_LLMCAST : 0);
17033 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
17034 		    NULL, NULL);
17035 	}
17036 	if (ill_need_rele)
17037 		ill_refrele(ill);
17038 	if (rill_need_rele)
17039 		ill_refrele(recv_ill);
17040 }
17041 
17042 /*
17043  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
17044  * returns 'true' if there are still fragments left on the queue, in
17045  * which case we restart the timer.
17046  */
17047 void
17048 ill_frag_timer(void *arg)
17049 {
17050 	ill_t	*ill = (ill_t *)arg;
17051 	boolean_t frag_pending;
17052 	ip_stack_t	*ipst = ill->ill_ipst;
17053 
17054 	mutex_enter(&ill->ill_lock);
17055 	ASSERT(!ill->ill_fragtimer_executing);
17056 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17057 		ill->ill_frag_timer_id = 0;
17058 		mutex_exit(&ill->ill_lock);
17059 		return;
17060 	}
17061 	ill->ill_fragtimer_executing = 1;
17062 	mutex_exit(&ill->ill_lock);
17063 
17064 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
17065 
17066 	/*
17067 	 * Restart the timer, if we have fragments pending or if someone
17068 	 * wanted us to be scheduled again.
17069 	 */
17070 	mutex_enter(&ill->ill_lock);
17071 	ill->ill_fragtimer_executing = 0;
17072 	ill->ill_frag_timer_id = 0;
17073 	if (frag_pending || ill->ill_fragtimer_needrestart)
17074 		ill_frag_timer_start(ill);
17075 	mutex_exit(&ill->ill_lock);
17076 }
17077 
17078 void
17079 ill_frag_timer_start(ill_t *ill)
17080 {
17081 	ip_stack_t	*ipst = ill->ill_ipst;
17082 
17083 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17084 
17085 	/* If the ill is closing or opening don't proceed */
17086 	if (ill->ill_state_flags & ILL_CONDEMNED)
17087 		return;
17088 
17089 	if (ill->ill_fragtimer_executing) {
17090 		/*
17091 		 * ill_frag_timer is currently executing. Just record the
17092 		 * the fact that we want the timer to be restarted.
17093 		 * ill_frag_timer will post a timeout before it returns,
17094 		 * ensuring it will be called again.
17095 		 */
17096 		ill->ill_fragtimer_needrestart = 1;
17097 		return;
17098 	}
17099 
17100 	if (ill->ill_frag_timer_id == 0) {
17101 		/*
17102 		 * The timer is neither running nor is the timeout handler
17103 		 * executing. Post a timeout so that ill_frag_timer will be
17104 		 * called
17105 		 */
17106 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17107 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
17108 		ill->ill_fragtimer_needrestart = 0;
17109 	}
17110 }
17111 
17112 /*
17113  * This routine is needed for loopback when forwarding multicasts.
17114  *
17115  * IPQoS Notes:
17116  * IPPF processing is done in fanout routines.
17117  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17118  * processing for IPsec packets is done when it comes back in clear.
17119  * NOTE : The callers of this function need to do the ire_refrele for the
17120  *	  ire that is being passed in.
17121  */
17122 void
17123 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17124     ill_t *recv_ill, boolean_t esp_in_udp_packet)
17125 {
17126 	ill_t	*ill = (ill_t *)q->q_ptr;
17127 	uint32_t	sum;
17128 	uint32_t	u1;
17129 	uint32_t	u2;
17130 	int		hdr_length;
17131 	boolean_t	mctl_present;
17132 	mblk_t		*first_mp = mp;
17133 	mblk_t		*hada_mp = NULL;
17134 	ipha_t		*inner_ipha;
17135 	ip_stack_t	*ipst;
17136 
17137 	ASSERT(recv_ill != NULL);
17138 	ipst = recv_ill->ill_ipst;
17139 
17140 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17141 	    "ip_rput_locl_start: q %p", q);
17142 
17143 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17144 	ASSERT(ill != NULL);
17145 
17146 
17147 #define	rptr	((uchar_t *)ipha)
17148 #define	iphs	((uint16_t *)ipha)
17149 
17150 	/*
17151 	 * no UDP or TCP packet should come here anymore.
17152 	 */
17153 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
17154 	    ipha->ipha_protocol != IPPROTO_UDP);
17155 
17156 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17157 	if (mctl_present &&
17158 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17159 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17160 
17161 		/*
17162 		 * It's an IPsec accelerated packet.
17163 		 * Keep a pointer to the data attributes around until
17164 		 * we allocate the ipsec_info_t.
17165 		 */
17166 		IPSECHW_DEBUG(IPSECHW_PKT,
17167 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17168 		hada_mp = first_mp;
17169 		hada_mp->b_cont = NULL;
17170 		/*
17171 		 * Since it is accelerated, it comes directly from
17172 		 * the ill and the data attributes is followed by
17173 		 * the packet data.
17174 		 */
17175 		ASSERT(mp->b_datap->db_type != M_CTL);
17176 		first_mp = mp;
17177 		mctl_present = B_FALSE;
17178 	}
17179 
17180 	/*
17181 	 * IF M_CTL is not present, then ipsec_in_is_secure
17182 	 * should return B_TRUE. There is a case where loopback
17183 	 * packets has an M_CTL in the front with all the
17184 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17185 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17186 	 * packets never comes here, it is safe to ASSERT the
17187 	 * following.
17188 	 */
17189 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17190 
17191 	/*
17192 	 * Also, we should never have an mctl_present if this is an
17193 	 * ESP-in-UDP packet.
17194 	 */
17195 	ASSERT(!mctl_present || !esp_in_udp_packet);
17196 
17197 
17198 	/* u1 is # words of IP options */
17199 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17200 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17201 
17202 	/*
17203 	 * Don't verify header checksum if we just removed UDP header or
17204 	 * packet is coming back from AH/ESP.
17205 	 */
17206 	if (!esp_in_udp_packet && !mctl_present) {
17207 		if (u1) {
17208 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17209 				if (hada_mp != NULL)
17210 					freemsg(hada_mp);
17211 				return;
17212 			}
17213 		} else {
17214 			/* Check the IP header checksum.  */
17215 #define	uph	((uint16_t *)ipha)
17216 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17217 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17218 #undef  uph
17219 			/* finish doing IP checksum */
17220 			sum = (sum & 0xFFFF) + (sum >> 16);
17221 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17222 			if (sum && sum != 0xFFFF) {
17223 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17224 				goto drop_pkt;
17225 			}
17226 		}
17227 	}
17228 
17229 	/*
17230 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17231 	 * might be called more than once for secure packets, count only
17232 	 * the first time.
17233 	 */
17234 	if (!mctl_present) {
17235 		UPDATE_IB_PKT_COUNT(ire);
17236 		ire->ire_last_used_time = lbolt;
17237 	}
17238 
17239 	/* Check for fragmentation offset. */
17240 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17241 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17242 	if (u1) {
17243 		/*
17244 		 * We re-assemble fragments before we do the AH/ESP
17245 		 * processing. Thus, M_CTL should not be present
17246 		 * while we are re-assembling.
17247 		 */
17248 		ASSERT(!mctl_present);
17249 		ASSERT(first_mp == mp);
17250 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
17251 			return;
17252 		}
17253 		/*
17254 		 * Make sure that first_mp points back to mp as
17255 		 * the mp we came in with could have changed in
17256 		 * ip_rput_fragment().
17257 		 */
17258 		ipha = (ipha_t *)mp->b_rptr;
17259 		first_mp = mp;
17260 	}
17261 
17262 	/*
17263 	 * Clear hardware checksumming flag as it is currently only
17264 	 * used by TCP and UDP.
17265 	 */
17266 	DB_CKSUMFLAGS(mp) = 0;
17267 
17268 	/* Now we have a complete datagram, destined for this machine. */
17269 	u1 = IPH_HDR_LENGTH(ipha);
17270 	switch (ipha->ipha_protocol) {
17271 	case IPPROTO_ICMP: {
17272 		ire_t		*ire_zone;
17273 		ilm_t		*ilm;
17274 		mblk_t		*mp1;
17275 		zoneid_t	last_zoneid;
17276 
17277 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17278 			ASSERT(ire->ire_type == IRE_BROADCAST);
17279 			/*
17280 			 * In the multicast case, applications may have joined
17281 			 * the group from different zones, so we need to deliver
17282 			 * the packet to each of them. Loop through the
17283 			 * multicast memberships structures (ilm) on the receive
17284 			 * ill and send a copy of the packet up each matching
17285 			 * one. However, we don't do this for multicasts sent on
17286 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17287 			 * they must stay in the sender's zone.
17288 			 *
17289 			 * ilm_add_v6() ensures that ilms in the same zone are
17290 			 * contiguous in the ill_ilm list. We use this property
17291 			 * to avoid sending duplicates needed when two
17292 			 * applications in the same zone join the same group on
17293 			 * different logical interfaces: we ignore the ilm if
17294 			 * its zoneid is the same as the last matching one.
17295 			 * In addition, the sending of the packet for
17296 			 * ire_zoneid is delayed until all of the other ilms
17297 			 * have been exhausted.
17298 			 */
17299 			last_zoneid = -1;
17300 			ILM_WALKER_HOLD(recv_ill);
17301 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17302 			    ilm = ilm->ilm_next) {
17303 				if ((ilm->ilm_flags & ILM_DELETED) ||
17304 				    ipha->ipha_dst != ilm->ilm_addr ||
17305 				    ilm->ilm_zoneid == last_zoneid ||
17306 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17307 				    ilm->ilm_zoneid == ALL_ZONES ||
17308 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17309 					continue;
17310 				mp1 = ip_copymsg(first_mp);
17311 				if (mp1 == NULL)
17312 					continue;
17313 				icmp_inbound(q, mp1, B_TRUE, ill,
17314 				    0, sum, mctl_present, B_TRUE,
17315 				    recv_ill, ilm->ilm_zoneid);
17316 				last_zoneid = ilm->ilm_zoneid;
17317 			}
17318 			ILM_WALKER_RELE(recv_ill);
17319 		} else if (ire->ire_type == IRE_BROADCAST) {
17320 			/*
17321 			 * In the broadcast case, there may be many zones
17322 			 * which need a copy of the packet delivered to them.
17323 			 * There is one IRE_BROADCAST per broadcast address
17324 			 * and per zone; we walk those using a helper function.
17325 			 * In addition, the sending of the packet for ire is
17326 			 * delayed until all of the other ires have been
17327 			 * processed.
17328 			 */
17329 			IRB_REFHOLD(ire->ire_bucket);
17330 			ire_zone = NULL;
17331 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17332 			    ire)) != NULL) {
17333 				mp1 = ip_copymsg(first_mp);
17334 				if (mp1 == NULL)
17335 					continue;
17336 
17337 				UPDATE_IB_PKT_COUNT(ire_zone);
17338 				ire_zone->ire_last_used_time = lbolt;
17339 				icmp_inbound(q, mp1, B_TRUE, ill,
17340 				    0, sum, mctl_present, B_TRUE,
17341 				    recv_ill, ire_zone->ire_zoneid);
17342 			}
17343 			IRB_REFRELE(ire->ire_bucket);
17344 		}
17345 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17346 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17347 		    ire->ire_zoneid);
17348 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17349 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17350 		return;
17351 	}
17352 	case IPPROTO_IGMP:
17353 		/*
17354 		 * If we are not willing to accept IGMP packets in clear,
17355 		 * then check with global policy.
17356 		 */
17357 		if (ipst->ips_igmp_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 raw"));
17366 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17367 			return;
17368 		}
17369 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17370 			/* Bad packet - discarded by igmp_input */
17371 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17372 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17373 			if (mctl_present)
17374 				freeb(first_mp);
17375 			return;
17376 		}
17377 		/*
17378 		 * igmp_input() may have returned the pulled up message.
17379 		 * So first_mp and ipha need to be reinitialized.
17380 		 */
17381 		ipha = (ipha_t *)mp->b_rptr;
17382 		if (mctl_present)
17383 			first_mp->b_cont = mp;
17384 		else
17385 			first_mp = mp;
17386 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17387 		    connf_head != NULL) {
17388 			/* No user-level listener for IGMP packets */
17389 			goto drop_pkt;
17390 		}
17391 		/* deliver to local raw users */
17392 		break;
17393 	case IPPROTO_PIM:
17394 		/*
17395 		 * If we are not willing to accept PIM packets in clear,
17396 		 * then check with global policy.
17397 		 */
17398 		if (ipst->ips_pim_accept_clear_messages == 0) {
17399 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17400 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17401 			if (first_mp == NULL)
17402 				return;
17403 		}
17404 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17405 			freemsg(first_mp);
17406 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17407 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17408 			return;
17409 		}
17410 		if (pim_input(q, mp, ill) != 0) {
17411 			/* Bad packet - discarded by pim_input */
17412 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17413 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17414 			if (mctl_present)
17415 				freeb(first_mp);
17416 			return;
17417 		}
17418 
17419 		/*
17420 		 * pim_input() may have pulled up the message so ipha needs to
17421 		 * be reinitialized.
17422 		 */
17423 		ipha = (ipha_t *)mp->b_rptr;
17424 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17425 		    connf_head != NULL) {
17426 			/* No user-level listener for PIM packets */
17427 			goto drop_pkt;
17428 		}
17429 		/* deliver to local raw users */
17430 		break;
17431 	case IPPROTO_ENCAP:
17432 		/*
17433 		 * Handle self-encapsulated packets (IP-in-IP where
17434 		 * the inner addresses == the outer addresses).
17435 		 */
17436 		hdr_length = IPH_HDR_LENGTH(ipha);
17437 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17438 		    mp->b_wptr) {
17439 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17440 			    sizeof (ipha_t) - mp->b_rptr)) {
17441 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17442 				freemsg(first_mp);
17443 				return;
17444 			}
17445 			ipha = (ipha_t *)mp->b_rptr;
17446 		}
17447 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17448 		/*
17449 		 * Check the sanity of the inner IP header.
17450 		 */
17451 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17452 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17453 			freemsg(first_mp);
17454 			return;
17455 		}
17456 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17457 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17458 			freemsg(first_mp);
17459 			return;
17460 		}
17461 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17462 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17463 			ipsec_in_t *ii;
17464 
17465 			/*
17466 			 * Self-encapsulated tunnel packet. Remove
17467 			 * the outer IP header and fanout again.
17468 			 * We also need to make sure that the inner
17469 			 * header is pulled up until options.
17470 			 */
17471 			mp->b_rptr = (uchar_t *)inner_ipha;
17472 			ipha = inner_ipha;
17473 			hdr_length = IPH_HDR_LENGTH(ipha);
17474 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17475 				if (!pullupmsg(mp, (uchar_t *)ipha +
17476 				    + hdr_length - mp->b_rptr)) {
17477 					freemsg(first_mp);
17478 					return;
17479 				}
17480 				ipha = (ipha_t *)mp->b_rptr;
17481 			}
17482 			if (hdr_length > sizeof (ipha_t)) {
17483 				/* We got options on the inner packet. */
17484 				ipaddr_t dst = ipha->ipha_dst;
17485 
17486 				if (ip_rput_options(q, mp, ipha, &dst, ipst) ==
17487 				    -1) {
17488 					/* Bad options! */
17489 					return;
17490 				}
17491 				if (dst != ipha->ipha_dst) {
17492 					/*
17493 					 * Someone put a source-route in
17494 					 * the inside header of a self-
17495 					 * encapsulated packet.  Drop it
17496 					 * with extreme prejudice and let
17497 					 * the sender know.
17498 					 */
17499 					icmp_unreachable(q, first_mp,
17500 					    ICMP_SOURCE_ROUTE_FAILED,
17501 					    recv_ill->ill_zoneid, ipst);
17502 					return;
17503 				}
17504 			}
17505 			if (!mctl_present) {
17506 				ASSERT(first_mp == mp);
17507 				/*
17508 				 * This means that somebody is sending
17509 				 * Self-encapsualted packets without AH/ESP.
17510 				 * If AH/ESP was present, we would have already
17511 				 * allocated the first_mp.
17512 				 *
17513 				 * Send this packet to find a tunnel endpoint.
17514 				 * if I can't find one, an ICMP
17515 				 * PROTOCOL_UNREACHABLE will get sent.
17516 				 */
17517 				goto fanout;
17518 			}
17519 			/*
17520 			 * We generally store the ill_index if we need to
17521 			 * do IPsec processing as we lose the ill queue when
17522 			 * we come back. But in this case, we never should
17523 			 * have to store the ill_index here as it should have
17524 			 * been stored previously when we processed the
17525 			 * AH/ESP header in this routine or for non-ipsec
17526 			 * cases, we still have the queue. But for some bad
17527 			 * packets from the wire, we can get to IPsec after
17528 			 * this and we better store the index for that case.
17529 			 */
17530 			ill = (ill_t *)q->q_ptr;
17531 			ii = (ipsec_in_t *)first_mp->b_rptr;
17532 			ii->ipsec_in_ill_index =
17533 			    ill->ill_phyint->phyint_ifindex;
17534 			ii->ipsec_in_rill_index =
17535 			    recv_ill->ill_phyint->phyint_ifindex;
17536 			if (ii->ipsec_in_decaps) {
17537 				/*
17538 				 * This packet is self-encapsulated multiple
17539 				 * times. We don't want to recurse infinitely.
17540 				 * To keep it simple, drop the packet.
17541 				 */
17542 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17543 				freemsg(first_mp);
17544 				return;
17545 			}
17546 			ii->ipsec_in_decaps = B_TRUE;
17547 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17548 			    ire);
17549 			return;
17550 		}
17551 		break;
17552 	case IPPROTO_AH:
17553 	case IPPROTO_ESP: {
17554 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17555 
17556 		/*
17557 		 * Fast path for AH/ESP. If this is the first time
17558 		 * we are sending a datagram to AH/ESP, allocate
17559 		 * a IPSEC_IN message and prepend it. Otherwise,
17560 		 * just fanout.
17561 		 */
17562 
17563 		int ipsec_rc;
17564 		ipsec_in_t *ii;
17565 		netstack_t *ns = ipst->ips_netstack;
17566 
17567 		IP_STAT(ipst, ipsec_proto_ahesp);
17568 		if (!mctl_present) {
17569 			ASSERT(first_mp == mp);
17570 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17571 			if (first_mp == NULL) {
17572 				ip1dbg(("ip_proto_input: IPSEC_IN "
17573 				    "allocation failure.\n"));
17574 				freemsg(hada_mp); /* okay ifnull */
17575 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17576 				freemsg(mp);
17577 				return;
17578 			}
17579 			/*
17580 			 * Store the ill_index so that when we come back
17581 			 * from IPsec we ride on the same queue.
17582 			 */
17583 			ill = (ill_t *)q->q_ptr;
17584 			ii = (ipsec_in_t *)first_mp->b_rptr;
17585 			ii->ipsec_in_ill_index =
17586 			    ill->ill_phyint->phyint_ifindex;
17587 			ii->ipsec_in_rill_index =
17588 			    recv_ill->ill_phyint->phyint_ifindex;
17589 			first_mp->b_cont = mp;
17590 			/*
17591 			 * Cache hardware acceleration info.
17592 			 */
17593 			if (hada_mp != NULL) {
17594 				IPSECHW_DEBUG(IPSECHW_PKT,
17595 				    ("ip_rput_local: caching data attr.\n"));
17596 				ii->ipsec_in_accelerated = B_TRUE;
17597 				ii->ipsec_in_da = hada_mp;
17598 				hada_mp = NULL;
17599 			}
17600 		} else {
17601 			ii = (ipsec_in_t *)first_mp->b_rptr;
17602 		}
17603 
17604 		if (!ipsec_loaded(ipss)) {
17605 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17606 			    ire->ire_zoneid, ipst);
17607 			return;
17608 		}
17609 
17610 		ns = ipst->ips_netstack;
17611 		/* select inbound SA and have IPsec process the pkt */
17612 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17613 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17614 			boolean_t esp_in_udp_sa;
17615 			if (esph == NULL)
17616 				return;
17617 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17618 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17619 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
17620 			    IPSA_F_NATT) != 0);
17621 			/*
17622 			 * The following is a fancy, but quick, way of saying:
17623 			 * ESP-in-UDP SA and Raw ESP packet --> drop
17624 			 *    OR
17625 			 * ESP SA and ESP-in-UDP packet --> drop
17626 			 */
17627 			if (esp_in_udp_sa != esp_in_udp_packet) {
17628 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17629 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
17630 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
17631 				    &ns->netstack_ipsec->ipsec_dropper);
17632 				return;
17633 			}
17634 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17635 			    first_mp, esph);
17636 		} else {
17637 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17638 			if (ah == NULL)
17639 				return;
17640 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17641 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17642 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17643 			    first_mp, ah);
17644 		}
17645 
17646 		switch (ipsec_rc) {
17647 		case IPSEC_STATUS_SUCCESS:
17648 			break;
17649 		case IPSEC_STATUS_FAILED:
17650 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17651 			/* FALLTHRU */
17652 		case IPSEC_STATUS_PENDING:
17653 			return;
17654 		}
17655 		/* we're done with IPsec processing, send it up */
17656 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17657 		return;
17658 	}
17659 	default:
17660 		break;
17661 	}
17662 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17663 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17664 		    ire->ire_zoneid));
17665 		goto drop_pkt;
17666 	}
17667 	/*
17668 	 * Handle protocols with which IP is less intimate.  There
17669 	 * can be more than one stream bound to a particular
17670 	 * protocol.  When this is the case, each one gets a copy
17671 	 * of any incoming packets.
17672 	 */
17673 fanout:
17674 	ip_fanout_proto(q, first_mp, ill, ipha,
17675 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17676 	    B_TRUE, recv_ill, ire->ire_zoneid);
17677 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17678 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17679 	return;
17680 
17681 drop_pkt:
17682 	freemsg(first_mp);
17683 	if (hada_mp != NULL)
17684 		freeb(hada_mp);
17685 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17686 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17687 #undef	rptr
17688 #undef  iphs
17689 
17690 }
17691 
17692 /*
17693  * Update any source route, record route or timestamp options.
17694  * Check that we are at end of strict source route.
17695  * The options have already been checked for sanity in ip_rput_options().
17696  */
17697 static boolean_t
17698 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17699     ip_stack_t *ipst)
17700 {
17701 	ipoptp_t	opts;
17702 	uchar_t		*opt;
17703 	uint8_t		optval;
17704 	uint8_t		optlen;
17705 	ipaddr_t	dst;
17706 	uint32_t	ts;
17707 	ire_t		*dst_ire;
17708 	timestruc_t	now;
17709 	zoneid_t	zoneid;
17710 	ill_t		*ill;
17711 
17712 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17713 
17714 	ip2dbg(("ip_rput_local_options\n"));
17715 
17716 	for (optval = ipoptp_first(&opts, ipha);
17717 	    optval != IPOPT_EOL;
17718 	    optval = ipoptp_next(&opts)) {
17719 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17720 		opt = opts.ipoptp_cur;
17721 		optlen = opts.ipoptp_len;
17722 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17723 		    optval, optlen));
17724 		switch (optval) {
17725 			uint32_t off;
17726 		case IPOPT_SSRR:
17727 		case IPOPT_LSRR:
17728 			off = opt[IPOPT_OFFSET];
17729 			off--;
17730 			if (optlen < IP_ADDR_LEN ||
17731 			    off > optlen - IP_ADDR_LEN) {
17732 				/* End of source route */
17733 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17734 				break;
17735 			}
17736 			/*
17737 			 * This will only happen if two consecutive entries
17738 			 * in the source route contains our address or if
17739 			 * it is a packet with a loose source route which
17740 			 * reaches us before consuming the whole source route
17741 			 */
17742 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17743 			if (optval == IPOPT_SSRR) {
17744 				goto bad_src_route;
17745 			}
17746 			/*
17747 			 * Hack: instead of dropping the packet truncate the
17748 			 * source route to what has been used by filling the
17749 			 * rest with IPOPT_NOP.
17750 			 */
17751 			opt[IPOPT_OLEN] = (uint8_t)off;
17752 			while (off < optlen) {
17753 				opt[off++] = IPOPT_NOP;
17754 			}
17755 			break;
17756 		case IPOPT_RR:
17757 			off = opt[IPOPT_OFFSET];
17758 			off--;
17759 			if (optlen < IP_ADDR_LEN ||
17760 			    off > optlen - IP_ADDR_LEN) {
17761 				/* No more room - ignore */
17762 				ip1dbg((
17763 				    "ip_rput_local_options: end of RR\n"));
17764 				break;
17765 			}
17766 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17767 			    IP_ADDR_LEN);
17768 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17769 			break;
17770 		case IPOPT_TS:
17771 			/* Insert timestamp if there is romm */
17772 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17773 			case IPOPT_TS_TSONLY:
17774 				off = IPOPT_TS_TIMELEN;
17775 				break;
17776 			case IPOPT_TS_PRESPEC:
17777 			case IPOPT_TS_PRESPEC_RFC791:
17778 				/* Verify that the address matched */
17779 				off = opt[IPOPT_OFFSET] - 1;
17780 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17781 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17782 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
17783 				    ipst);
17784 				if (dst_ire == NULL) {
17785 					/* Not for us */
17786 					break;
17787 				}
17788 				ire_refrele(dst_ire);
17789 				/* FALLTHRU */
17790 			case IPOPT_TS_TSANDADDR:
17791 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17792 				break;
17793 			default:
17794 				/*
17795 				 * ip_*put_options should have already
17796 				 * dropped this packet.
17797 				 */
17798 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17799 				    "unknown IT - bug in ip_rput_options?\n");
17800 				return (B_TRUE);	/* Keep "lint" happy */
17801 			}
17802 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17803 				/* Increase overflow counter */
17804 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17805 				opt[IPOPT_POS_OV_FLG] =
17806 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17807 				    (off << 4));
17808 				break;
17809 			}
17810 			off = opt[IPOPT_OFFSET] - 1;
17811 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17812 			case IPOPT_TS_PRESPEC:
17813 			case IPOPT_TS_PRESPEC_RFC791:
17814 			case IPOPT_TS_TSANDADDR:
17815 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17816 				    IP_ADDR_LEN);
17817 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17818 				/* FALLTHRU */
17819 			case IPOPT_TS_TSONLY:
17820 				off = opt[IPOPT_OFFSET] - 1;
17821 				/* Compute # of milliseconds since midnight */
17822 				gethrestime(&now);
17823 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17824 				    now.tv_nsec / (NANOSEC / MILLISEC);
17825 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17826 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17827 				break;
17828 			}
17829 			break;
17830 		}
17831 	}
17832 	return (B_TRUE);
17833 
17834 bad_src_route:
17835 	q = WR(q);
17836 	if (q->q_next != NULL)
17837 		ill = q->q_ptr;
17838 	else
17839 		ill = NULL;
17840 
17841 	/* make sure we clear any indication of a hardware checksum */
17842 	DB_CKSUMFLAGS(mp) = 0;
17843 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
17844 	if (zoneid == ALL_ZONES)
17845 		freemsg(mp);
17846 	else
17847 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17848 	return (B_FALSE);
17849 
17850 }
17851 
17852 /*
17853  * Process IP options in an inbound packet.  If an option affects the
17854  * effective destination address, return the next hop address via dstp.
17855  * Returns -1 if something fails in which case an ICMP error has been sent
17856  * and mp freed.
17857  */
17858 static int
17859 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
17860     ip_stack_t *ipst)
17861 {
17862 	ipoptp_t	opts;
17863 	uchar_t		*opt;
17864 	uint8_t		optval;
17865 	uint8_t		optlen;
17866 	ipaddr_t	dst;
17867 	intptr_t	code = 0;
17868 	ire_t		*ire = NULL;
17869 	zoneid_t	zoneid;
17870 	ill_t		*ill;
17871 
17872 	ip2dbg(("ip_rput_options\n"));
17873 	dst = ipha->ipha_dst;
17874 	for (optval = ipoptp_first(&opts, ipha);
17875 	    optval != IPOPT_EOL;
17876 	    optval = ipoptp_next(&opts)) {
17877 		opt = opts.ipoptp_cur;
17878 		optlen = opts.ipoptp_len;
17879 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17880 		    optval, optlen));
17881 		/*
17882 		 * Note: we need to verify the checksum before we
17883 		 * modify anything thus this routine only extracts the next
17884 		 * hop dst from any source route.
17885 		 */
17886 		switch (optval) {
17887 			uint32_t off;
17888 		case IPOPT_SSRR:
17889 		case IPOPT_LSRR:
17890 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17891 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17892 			if (ire == NULL) {
17893 				if (optval == IPOPT_SSRR) {
17894 					ip1dbg(("ip_rput_options: not next"
17895 					    " strict source route 0x%x\n",
17896 					    ntohl(dst)));
17897 					code = (char *)&ipha->ipha_dst -
17898 					    (char *)ipha;
17899 					goto param_prob; /* RouterReq's */
17900 				}
17901 				ip2dbg(("ip_rput_options: "
17902 				    "not next source route 0x%x\n",
17903 				    ntohl(dst)));
17904 				break;
17905 			}
17906 			ire_refrele(ire);
17907 
17908 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17909 				ip1dbg((
17910 				    "ip_rput_options: bad option offset\n"));
17911 				code = (char *)&opt[IPOPT_OLEN] -
17912 				    (char *)ipha;
17913 				goto param_prob;
17914 			}
17915 			off = opt[IPOPT_OFFSET];
17916 			off--;
17917 		redo_srr:
17918 			if (optlen < IP_ADDR_LEN ||
17919 			    off > optlen - IP_ADDR_LEN) {
17920 				/* End of source route */
17921 				ip1dbg(("ip_rput_options: end of SR\n"));
17922 				break;
17923 			}
17924 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17925 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
17926 			    ntohl(dst)));
17927 
17928 			/*
17929 			 * Check if our address is present more than
17930 			 * once as consecutive hops in source route.
17931 			 * XXX verify per-interface ip_forwarding
17932 			 * for source route?
17933 			 */
17934 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17935 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17936 
17937 			if (ire != NULL) {
17938 				ire_refrele(ire);
17939 				off += IP_ADDR_LEN;
17940 				goto redo_srr;
17941 			}
17942 
17943 			if (dst == htonl(INADDR_LOOPBACK)) {
17944 				ip1dbg(("ip_rput_options: loopback addr in "
17945 				    "source route!\n"));
17946 				goto bad_src_route;
17947 			}
17948 			/*
17949 			 * For strict: verify that dst is directly
17950 			 * reachable.
17951 			 */
17952 			if (optval == IPOPT_SSRR) {
17953 				ire = ire_ftable_lookup(dst, 0, 0,
17954 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
17955 				    MBLK_GETLABEL(mp),
17956 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
17957 				if (ire == NULL) {
17958 					ip1dbg(("ip_rput_options: SSRR not "
17959 					    "directly reachable: 0x%x\n",
17960 					    ntohl(dst)));
17961 					goto bad_src_route;
17962 				}
17963 				ire_refrele(ire);
17964 			}
17965 			/*
17966 			 * Defer update of the offset and the record route
17967 			 * until the packet is forwarded.
17968 			 */
17969 			break;
17970 		case IPOPT_RR:
17971 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17972 				ip1dbg((
17973 				    "ip_rput_options: bad option offset\n"));
17974 				code = (char *)&opt[IPOPT_OLEN] -
17975 				    (char *)ipha;
17976 				goto param_prob;
17977 			}
17978 			break;
17979 		case IPOPT_TS:
17980 			/*
17981 			 * Verify that length >= 5 and that there is either
17982 			 * room for another timestamp or that the overflow
17983 			 * counter is not maxed out.
17984 			 */
17985 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
17986 			if (optlen < IPOPT_MINLEN_IT) {
17987 				goto param_prob;
17988 			}
17989 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17990 				ip1dbg((
17991 				    "ip_rput_options: bad option offset\n"));
17992 				code = (char *)&opt[IPOPT_OFFSET] -
17993 				    (char *)ipha;
17994 				goto param_prob;
17995 			}
17996 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17997 			case IPOPT_TS_TSONLY:
17998 				off = IPOPT_TS_TIMELEN;
17999 				break;
18000 			case IPOPT_TS_TSANDADDR:
18001 			case IPOPT_TS_PRESPEC:
18002 			case IPOPT_TS_PRESPEC_RFC791:
18003 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18004 				break;
18005 			default:
18006 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
18007 				    (char *)ipha;
18008 				goto param_prob;
18009 			}
18010 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
18011 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
18012 				/*
18013 				 * No room and the overflow counter is 15
18014 				 * already.
18015 				 */
18016 				goto param_prob;
18017 			}
18018 			break;
18019 		}
18020 	}
18021 
18022 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
18023 		*dstp = dst;
18024 		return (0);
18025 	}
18026 
18027 	ip1dbg(("ip_rput_options: error processing IP options."));
18028 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
18029 
18030 param_prob:
18031 	q = WR(q);
18032 	if (q->q_next != NULL)
18033 		ill = q->q_ptr;
18034 	else
18035 		ill = NULL;
18036 
18037 	/* make sure we clear any indication of a hardware checksum */
18038 	DB_CKSUMFLAGS(mp) = 0;
18039 	/* Don't know whether this is for non-global or global/forwarding */
18040 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18041 	if (zoneid == ALL_ZONES)
18042 		freemsg(mp);
18043 	else
18044 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
18045 	return (-1);
18046 
18047 bad_src_route:
18048 	q = WR(q);
18049 	if (q->q_next != NULL)
18050 		ill = q->q_ptr;
18051 	else
18052 		ill = NULL;
18053 
18054 	/* make sure we clear any indication of a hardware checksum */
18055 	DB_CKSUMFLAGS(mp) = 0;
18056 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18057 	if (zoneid == ALL_ZONES)
18058 		freemsg(mp);
18059 	else
18060 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18061 	return (-1);
18062 }
18063 
18064 /*
18065  * IP & ICMP info in >=14 msg's ...
18066  *  - ip fixed part (mib2_ip_t)
18067  *  - icmp fixed part (mib2_icmp_t)
18068  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18069  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18070  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18071  *  - ipRouteAttributeTable (ip 102)	labeled routes
18072  *  - ip multicast membership (ip_member_t)
18073  *  - ip multicast source filtering (ip_grpsrc_t)
18074  *  - igmp fixed part (struct igmpstat)
18075  *  - multicast routing stats (struct mrtstat)
18076  *  - multicast routing vifs (array of struct vifctl)
18077  *  - multicast routing routes (array of struct mfcctl)
18078  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18079  *					One per ill plus one generic
18080  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18081  *					One per ill plus one generic
18082  *  - ipv6RouteEntry			all IPv6 IREs
18083  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18084  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18085  *  - ipv6AddrEntry			all IPv6 ipifs
18086  *  - ipv6 multicast membership (ipv6_member_t)
18087  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18088  *
18089  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18090  *
18091  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18092  * already filled in by the caller.
18093  * Return value of 0 indicates that no messages were sent and caller
18094  * should free mpctl.
18095  */
18096 int
18097 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
18098 {
18099 	ip_stack_t *ipst;
18100 	sctp_stack_t *sctps;
18101 
18102 	if (q->q_next != NULL) {
18103 		ipst = ILLQ_TO_IPST(q);
18104 	} else {
18105 		ipst = CONNQ_TO_IPST(q);
18106 	}
18107 	ASSERT(ipst != NULL);
18108 	sctps = ipst->ips_netstack->netstack_sctp;
18109 
18110 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18111 		return (0);
18112 	}
18113 
18114 	/*
18115 	 * For the purposes of the (broken) packet shell use
18116 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
18117 	 * to make TCP and UDP appear first in the list of mib items.
18118 	 * TBD: We could expand this and use it in netstat so that
18119 	 * the kernel doesn't have to produce large tables (connections,
18120 	 * routes, etc) when netstat only wants the statistics or a particular
18121 	 * table.
18122 	 */
18123 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
18124 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
18125 			return (1);
18126 		}
18127 	}
18128 
18129 	if (level != MIB2_TCP) {
18130 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
18131 			return (1);
18132 		}
18133 	}
18134 
18135 	if (level != MIB2_UDP) {
18136 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
18137 			return (1);
18138 		}
18139 	}
18140 
18141 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18142 	    ipst)) == NULL) {
18143 		return (1);
18144 	}
18145 
18146 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18147 		return (1);
18148 	}
18149 
18150 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18151 		return (1);
18152 	}
18153 
18154 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18155 		return (1);
18156 	}
18157 
18158 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18159 		return (1);
18160 	}
18161 
18162 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18163 		return (1);
18164 	}
18165 
18166 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18167 		return (1);
18168 	}
18169 
18170 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18171 		return (1);
18172 	}
18173 
18174 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18175 		return (1);
18176 	}
18177 
18178 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18179 		return (1);
18180 	}
18181 
18182 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18183 		return (1);
18184 	}
18185 
18186 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18187 		return (1);
18188 	}
18189 
18190 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18191 		return (1);
18192 	}
18193 
18194 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18195 		return (1);
18196 	}
18197 
18198 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, ipst)) == NULL) {
18199 		return (1);
18200 	}
18201 
18202 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, ipst);
18203 	if (mpctl == NULL) {
18204 		return (1);
18205 	}
18206 
18207 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18208 		return (1);
18209 	}
18210 	freemsg(mpctl);
18211 	return (1);
18212 }
18213 
18214 
18215 /* Get global (legacy) IPv4 statistics */
18216 static mblk_t *
18217 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18218     ip_stack_t *ipst)
18219 {
18220 	mib2_ip_t		old_ip_mib;
18221 	struct opthdr		*optp;
18222 	mblk_t			*mp2ctl;
18223 
18224 	/*
18225 	 * make a copy of the original message
18226 	 */
18227 	mp2ctl = copymsg(mpctl);
18228 
18229 	/* fixed length IP structure... */
18230 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18231 	optp->level = MIB2_IP;
18232 	optp->name = 0;
18233 	SET_MIB(old_ip_mib.ipForwarding,
18234 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18235 	SET_MIB(old_ip_mib.ipDefaultTTL,
18236 	    (uint32_t)ipst->ips_ip_def_ttl);
18237 	SET_MIB(old_ip_mib.ipReasmTimeout,
18238 	    ipst->ips_ip_g_frag_timeout);
18239 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18240 	    sizeof (mib2_ipAddrEntry_t));
18241 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18242 	    sizeof (mib2_ipRouteEntry_t));
18243 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18244 	    sizeof (mib2_ipNetToMediaEntry_t));
18245 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18246 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18247 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18248 	    sizeof (mib2_ipAttributeEntry_t));
18249 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18250 
18251 	/*
18252 	 * Grab the statistics from the new IP MIB
18253 	 */
18254 	SET_MIB(old_ip_mib.ipInReceives,
18255 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18256 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18257 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18258 	SET_MIB(old_ip_mib.ipForwDatagrams,
18259 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18260 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18261 	    ipmib->ipIfStatsInUnknownProtos);
18262 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18263 	SET_MIB(old_ip_mib.ipInDelivers,
18264 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18265 	SET_MIB(old_ip_mib.ipOutRequests,
18266 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18267 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18268 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18269 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18270 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18271 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18272 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18273 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18274 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18275 
18276 	/* ipRoutingDiscards is not being used */
18277 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18278 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18279 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18280 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18281 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18282 	    ipmib->ipIfStatsReasmDuplicates);
18283 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18284 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18285 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18286 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18287 	SET_MIB(old_ip_mib.rawipInOverflows,
18288 	    ipmib->rawipIfStatsInOverflows);
18289 
18290 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18291 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18292 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18293 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18294 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18295 	    ipmib->ipIfStatsOutSwitchIPVersion);
18296 
18297 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18298 	    (int)sizeof (old_ip_mib))) {
18299 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18300 		    (uint_t)sizeof (old_ip_mib)));
18301 	}
18302 
18303 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18304 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18305 	    (int)optp->level, (int)optp->name, (int)optp->len));
18306 	qreply(q, mpctl);
18307 	return (mp2ctl);
18308 }
18309 
18310 /* Per interface IPv4 statistics */
18311 static mblk_t *
18312 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18313 {
18314 	struct opthdr		*optp;
18315 	mblk_t			*mp2ctl;
18316 	ill_t			*ill;
18317 	ill_walk_context_t	ctx;
18318 	mblk_t			*mp_tail = NULL;
18319 	mib2_ipIfStatsEntry_t	global_ip_mib;
18320 
18321 	/*
18322 	 * Make a copy of the original message
18323 	 */
18324 	mp2ctl = copymsg(mpctl);
18325 
18326 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18327 	optp->level = MIB2_IP;
18328 	optp->name = MIB2_IP_TRAFFIC_STATS;
18329 	/* Include "unknown interface" ip_mib */
18330 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18331 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18332 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18333 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18334 	    (ipst->ips_ip_g_forward ? 1 : 2));
18335 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18336 	    (uint32_t)ipst->ips_ip_def_ttl);
18337 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18338 	    sizeof (mib2_ipIfStatsEntry_t));
18339 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18340 	    sizeof (mib2_ipAddrEntry_t));
18341 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18342 	    sizeof (mib2_ipRouteEntry_t));
18343 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18344 	    sizeof (mib2_ipNetToMediaEntry_t));
18345 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18346 	    sizeof (ip_member_t));
18347 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18348 	    sizeof (ip_grpsrc_t));
18349 
18350 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18351 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18352 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18353 		    "failed to allocate %u bytes\n",
18354 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18355 	}
18356 
18357 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18358 
18359 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18360 	ill = ILL_START_WALK_V4(&ctx, ipst);
18361 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18362 		ill->ill_ip_mib->ipIfStatsIfIndex =
18363 		    ill->ill_phyint->phyint_ifindex;
18364 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18365 		    (ipst->ips_ip_g_forward ? 1 : 2));
18366 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18367 		    (uint32_t)ipst->ips_ip_def_ttl);
18368 
18369 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18370 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18371 		    (char *)ill->ill_ip_mib,
18372 		    (int)sizeof (*ill->ill_ip_mib))) {
18373 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18374 			    "failed to allocate %u bytes\n",
18375 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18376 		}
18377 	}
18378 	rw_exit(&ipst->ips_ill_g_lock);
18379 
18380 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18381 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18382 	    "level %d, name %d, len %d\n",
18383 	    (int)optp->level, (int)optp->name, (int)optp->len));
18384 	qreply(q, mpctl);
18385 
18386 	if (mp2ctl == NULL)
18387 		return (NULL);
18388 
18389 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18390 }
18391 
18392 /* Global IPv4 ICMP statistics */
18393 static mblk_t *
18394 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18395 {
18396 	struct opthdr		*optp;
18397 	mblk_t			*mp2ctl;
18398 
18399 	/*
18400 	 * Make a copy of the original message
18401 	 */
18402 	mp2ctl = copymsg(mpctl);
18403 
18404 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18405 	optp->level = MIB2_ICMP;
18406 	optp->name = 0;
18407 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18408 	    (int)sizeof (ipst->ips_icmp_mib))) {
18409 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18410 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18411 	}
18412 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18413 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18414 	    (int)optp->level, (int)optp->name, (int)optp->len));
18415 	qreply(q, mpctl);
18416 	return (mp2ctl);
18417 }
18418 
18419 /* Global IPv4 IGMP statistics */
18420 static mblk_t *
18421 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18422 {
18423 	struct opthdr		*optp;
18424 	mblk_t			*mp2ctl;
18425 
18426 	/*
18427 	 * make a copy of the original message
18428 	 */
18429 	mp2ctl = copymsg(mpctl);
18430 
18431 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18432 	optp->level = EXPER_IGMP;
18433 	optp->name = 0;
18434 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18435 	    (int)sizeof (ipst->ips_igmpstat))) {
18436 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18437 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18438 	}
18439 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18440 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18441 	    (int)optp->level, (int)optp->name, (int)optp->len));
18442 	qreply(q, mpctl);
18443 	return (mp2ctl);
18444 }
18445 
18446 /* Global IPv4 Multicast Routing statistics */
18447 static mblk_t *
18448 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18449 {
18450 	struct opthdr		*optp;
18451 	mblk_t			*mp2ctl;
18452 
18453 	/*
18454 	 * make a copy of the original message
18455 	 */
18456 	mp2ctl = copymsg(mpctl);
18457 
18458 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18459 	optp->level = EXPER_DVMRP;
18460 	optp->name = 0;
18461 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18462 		ip0dbg(("ip_mroute_stats: failed\n"));
18463 	}
18464 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18465 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18466 	    (int)optp->level, (int)optp->name, (int)optp->len));
18467 	qreply(q, mpctl);
18468 	return (mp2ctl);
18469 }
18470 
18471 /* IPv4 address information */
18472 static mblk_t *
18473 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18474 {
18475 	struct opthdr		*optp;
18476 	mblk_t			*mp2ctl;
18477 	mblk_t			*mp_tail = NULL;
18478 	ill_t			*ill;
18479 	ipif_t			*ipif;
18480 	uint_t			bitval;
18481 	mib2_ipAddrEntry_t	mae;
18482 	zoneid_t		zoneid;
18483 	ill_walk_context_t ctx;
18484 
18485 	/*
18486 	 * make a copy of the original message
18487 	 */
18488 	mp2ctl = copymsg(mpctl);
18489 
18490 	/* ipAddrEntryTable */
18491 
18492 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18493 	optp->level = MIB2_IP;
18494 	optp->name = MIB2_IP_ADDR;
18495 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18496 
18497 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18498 	ill = ILL_START_WALK_V4(&ctx, ipst);
18499 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18500 		for (ipif = ill->ill_ipif; ipif != NULL;
18501 		    ipif = ipif->ipif_next) {
18502 			if (ipif->ipif_zoneid != zoneid &&
18503 			    ipif->ipif_zoneid != ALL_ZONES)
18504 				continue;
18505 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18506 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18507 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18508 
18509 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18510 			    OCTET_LENGTH);
18511 			mae.ipAdEntIfIndex.o_length =
18512 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18513 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18514 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18515 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18516 			mae.ipAdEntInfo.ae_subnet_len =
18517 			    ip_mask_to_plen(ipif->ipif_net_mask);
18518 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18519 			for (bitval = 1;
18520 			    bitval &&
18521 			    !(bitval & ipif->ipif_brd_addr);
18522 			    bitval <<= 1)
18523 				noop;
18524 			mae.ipAdEntBcastAddr = bitval;
18525 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18526 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18527 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18528 			mae.ipAdEntInfo.ae_broadcast_addr =
18529 			    ipif->ipif_brd_addr;
18530 			mae.ipAdEntInfo.ae_pp_dst_addr =
18531 			    ipif->ipif_pp_dst_addr;
18532 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18533 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18534 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18535 
18536 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18537 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18538 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18539 				    "allocate %u bytes\n",
18540 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18541 			}
18542 		}
18543 	}
18544 	rw_exit(&ipst->ips_ill_g_lock);
18545 
18546 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18547 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18548 	    (int)optp->level, (int)optp->name, (int)optp->len));
18549 	qreply(q, mpctl);
18550 	return (mp2ctl);
18551 }
18552 
18553 /* IPv6 address information */
18554 static mblk_t *
18555 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18556 {
18557 	struct opthdr		*optp;
18558 	mblk_t			*mp2ctl;
18559 	mblk_t			*mp_tail = NULL;
18560 	ill_t			*ill;
18561 	ipif_t			*ipif;
18562 	mib2_ipv6AddrEntry_t	mae6;
18563 	zoneid_t		zoneid;
18564 	ill_walk_context_t	ctx;
18565 
18566 	/*
18567 	 * make a copy of the original message
18568 	 */
18569 	mp2ctl = copymsg(mpctl);
18570 
18571 	/* ipv6AddrEntryTable */
18572 
18573 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18574 	optp->level = MIB2_IP6;
18575 	optp->name = MIB2_IP6_ADDR;
18576 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18577 
18578 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18579 	ill = ILL_START_WALK_V6(&ctx, ipst);
18580 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18581 		for (ipif = ill->ill_ipif; ipif != NULL;
18582 		    ipif = ipif->ipif_next) {
18583 			if (ipif->ipif_zoneid != zoneid &&
18584 			    ipif->ipif_zoneid != ALL_ZONES)
18585 				continue;
18586 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18587 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18588 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18589 
18590 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18591 			    OCTET_LENGTH);
18592 			mae6.ipv6AddrIfIndex.o_length =
18593 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18594 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18595 			mae6.ipv6AddrPfxLength =
18596 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18597 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18598 			mae6.ipv6AddrInfo.ae_subnet_len =
18599 			    mae6.ipv6AddrPfxLength;
18600 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18601 
18602 			/* Type: stateless(1), stateful(2), unknown(3) */
18603 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18604 				mae6.ipv6AddrType = 1;
18605 			else
18606 				mae6.ipv6AddrType = 2;
18607 			/* Anycast: true(1), false(2) */
18608 			if (ipif->ipif_flags & IPIF_ANYCAST)
18609 				mae6.ipv6AddrAnycastFlag = 1;
18610 			else
18611 				mae6.ipv6AddrAnycastFlag = 2;
18612 
18613 			/*
18614 			 * Address status: preferred(1), deprecated(2),
18615 			 * invalid(3), inaccessible(4), unknown(5)
18616 			 */
18617 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18618 				mae6.ipv6AddrStatus = 3;
18619 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18620 				mae6.ipv6AddrStatus = 2;
18621 			else
18622 				mae6.ipv6AddrStatus = 1;
18623 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18624 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18625 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18626 			    ipif->ipif_v6pp_dst_addr;
18627 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18628 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18629 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18630 			mae6.ipv6AddrIdentifier = ill->ill_token;
18631 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18632 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18633 			mae6.ipv6AddrRetransmitTime =
18634 			    ill->ill_reachable_retrans_time;
18635 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18636 			    (char *)&mae6,
18637 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18638 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18639 				    "allocate %u bytes\n",
18640 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18641 			}
18642 		}
18643 	}
18644 	rw_exit(&ipst->ips_ill_g_lock);
18645 
18646 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18647 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18648 	    (int)optp->level, (int)optp->name, (int)optp->len));
18649 	qreply(q, mpctl);
18650 	return (mp2ctl);
18651 }
18652 
18653 /* IPv4 multicast group membership. */
18654 static mblk_t *
18655 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18656 {
18657 	struct opthdr		*optp;
18658 	mblk_t			*mp2ctl;
18659 	ill_t			*ill;
18660 	ipif_t			*ipif;
18661 	ilm_t			*ilm;
18662 	ip_member_t		ipm;
18663 	mblk_t			*mp_tail = NULL;
18664 	ill_walk_context_t	ctx;
18665 	zoneid_t		zoneid;
18666 
18667 	/*
18668 	 * make a copy of the original message
18669 	 */
18670 	mp2ctl = copymsg(mpctl);
18671 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18672 
18673 	/* ipGroupMember table */
18674 	optp = (struct opthdr *)&mpctl->b_rptr[
18675 	    sizeof (struct T_optmgmt_ack)];
18676 	optp->level = MIB2_IP;
18677 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18678 
18679 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18680 	ill = ILL_START_WALK_V4(&ctx, ipst);
18681 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18682 		ILM_WALKER_HOLD(ill);
18683 		for (ipif = ill->ill_ipif; ipif != NULL;
18684 		    ipif = ipif->ipif_next) {
18685 			if (ipif->ipif_zoneid != zoneid &&
18686 			    ipif->ipif_zoneid != ALL_ZONES)
18687 				continue;	/* not this zone */
18688 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
18689 			    OCTET_LENGTH);
18690 			ipm.ipGroupMemberIfIndex.o_length =
18691 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18692 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18693 				ASSERT(ilm->ilm_ipif != NULL);
18694 				ASSERT(ilm->ilm_ill == NULL);
18695 				if (ilm->ilm_ipif != ipif)
18696 					continue;
18697 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18698 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18699 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18700 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18701 				    (char *)&ipm, (int)sizeof (ipm))) {
18702 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18703 					    "failed to allocate %u bytes\n",
18704 					    (uint_t)sizeof (ipm)));
18705 				}
18706 			}
18707 		}
18708 		ILM_WALKER_RELE(ill);
18709 	}
18710 	rw_exit(&ipst->ips_ill_g_lock);
18711 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18712 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18713 	    (int)optp->level, (int)optp->name, (int)optp->len));
18714 	qreply(q, mpctl);
18715 	return (mp2ctl);
18716 }
18717 
18718 /* IPv6 multicast group membership. */
18719 static mblk_t *
18720 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18721 {
18722 	struct opthdr		*optp;
18723 	mblk_t			*mp2ctl;
18724 	ill_t			*ill;
18725 	ilm_t			*ilm;
18726 	ipv6_member_t		ipm6;
18727 	mblk_t			*mp_tail = NULL;
18728 	ill_walk_context_t	ctx;
18729 	zoneid_t		zoneid;
18730 
18731 	/*
18732 	 * make a copy of the original message
18733 	 */
18734 	mp2ctl = copymsg(mpctl);
18735 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18736 
18737 	/* ip6GroupMember table */
18738 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18739 	optp->level = MIB2_IP6;
18740 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18741 
18742 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18743 	ill = ILL_START_WALK_V6(&ctx, ipst);
18744 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18745 		ILM_WALKER_HOLD(ill);
18746 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18747 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18748 			ASSERT(ilm->ilm_ipif == NULL);
18749 			ASSERT(ilm->ilm_ill != NULL);
18750 			if (ilm->ilm_zoneid != zoneid)
18751 				continue;	/* not this zone */
18752 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18753 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18754 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18755 			if (!snmp_append_data2(mpctl->b_cont,
18756 			    &mp_tail,
18757 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18758 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18759 				    "failed to allocate %u bytes\n",
18760 				    (uint_t)sizeof (ipm6)));
18761 			}
18762 		}
18763 		ILM_WALKER_RELE(ill);
18764 	}
18765 	rw_exit(&ipst->ips_ill_g_lock);
18766 
18767 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18768 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18769 	    (int)optp->level, (int)optp->name, (int)optp->len));
18770 	qreply(q, mpctl);
18771 	return (mp2ctl);
18772 }
18773 
18774 /* IP multicast filtered sources */
18775 static mblk_t *
18776 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18777 {
18778 	struct opthdr		*optp;
18779 	mblk_t			*mp2ctl;
18780 	ill_t			*ill;
18781 	ipif_t			*ipif;
18782 	ilm_t			*ilm;
18783 	ip_grpsrc_t		ips;
18784 	mblk_t			*mp_tail = NULL;
18785 	ill_walk_context_t	ctx;
18786 	zoneid_t		zoneid;
18787 	int			i;
18788 	slist_t			*sl;
18789 
18790 	/*
18791 	 * make a copy of the original message
18792 	 */
18793 	mp2ctl = copymsg(mpctl);
18794 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18795 
18796 	/* ipGroupSource table */
18797 	optp = (struct opthdr *)&mpctl->b_rptr[
18798 	    sizeof (struct T_optmgmt_ack)];
18799 	optp->level = MIB2_IP;
18800 	optp->name = EXPER_IP_GROUP_SOURCES;
18801 
18802 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18803 	ill = ILL_START_WALK_V4(&ctx, ipst);
18804 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18805 		ILM_WALKER_HOLD(ill);
18806 		for (ipif = ill->ill_ipif; ipif != NULL;
18807 		    ipif = ipif->ipif_next) {
18808 			if (ipif->ipif_zoneid != zoneid)
18809 				continue;	/* not this zone */
18810 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
18811 			    OCTET_LENGTH);
18812 			ips.ipGroupSourceIfIndex.o_length =
18813 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18814 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18815 				ASSERT(ilm->ilm_ipif != NULL);
18816 				ASSERT(ilm->ilm_ill == NULL);
18817 				sl = ilm->ilm_filter;
18818 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18819 					continue;
18820 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18821 				for (i = 0; i < sl->sl_numsrc; i++) {
18822 					if (!IN6_IS_ADDR_V4MAPPED(
18823 					    &sl->sl_addr[i]))
18824 						continue;
18825 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18826 					    ips.ipGroupSourceAddress);
18827 					if (snmp_append_data2(mpctl->b_cont,
18828 					    &mp_tail, (char *)&ips,
18829 					    (int)sizeof (ips)) == 0) {
18830 						ip1dbg(("ip_snmp_get_mib2_"
18831 						    "ip_group_src: failed to "
18832 						    "allocate %u bytes\n",
18833 						    (uint_t)sizeof (ips)));
18834 					}
18835 				}
18836 			}
18837 		}
18838 		ILM_WALKER_RELE(ill);
18839 	}
18840 	rw_exit(&ipst->ips_ill_g_lock);
18841 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18842 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18843 	    (int)optp->level, (int)optp->name, (int)optp->len));
18844 	qreply(q, mpctl);
18845 	return (mp2ctl);
18846 }
18847 
18848 /* IPv6 multicast filtered sources. */
18849 static mblk_t *
18850 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18851 {
18852 	struct opthdr		*optp;
18853 	mblk_t			*mp2ctl;
18854 	ill_t			*ill;
18855 	ilm_t			*ilm;
18856 	ipv6_grpsrc_t		ips6;
18857 	mblk_t			*mp_tail = NULL;
18858 	ill_walk_context_t	ctx;
18859 	zoneid_t		zoneid;
18860 	int			i;
18861 	slist_t			*sl;
18862 
18863 	/*
18864 	 * make a copy of the original message
18865 	 */
18866 	mp2ctl = copymsg(mpctl);
18867 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18868 
18869 	/* ip6GroupMember table */
18870 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18871 	optp->level = MIB2_IP6;
18872 	optp->name = EXPER_IP6_GROUP_SOURCES;
18873 
18874 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18875 	ill = ILL_START_WALK_V6(&ctx, ipst);
18876 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18877 		ILM_WALKER_HOLD(ill);
18878 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18879 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18880 			ASSERT(ilm->ilm_ipif == NULL);
18881 			ASSERT(ilm->ilm_ill != NULL);
18882 			sl = ilm->ilm_filter;
18883 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18884 				continue;
18885 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18886 			for (i = 0; i < sl->sl_numsrc; i++) {
18887 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18888 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18889 				    (char *)&ips6, (int)sizeof (ips6))) {
18890 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18891 					    "group_src: failed to allocate "
18892 					    "%u bytes\n",
18893 					    (uint_t)sizeof (ips6)));
18894 				}
18895 			}
18896 		}
18897 		ILM_WALKER_RELE(ill);
18898 	}
18899 	rw_exit(&ipst->ips_ill_g_lock);
18900 
18901 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18902 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18903 	    (int)optp->level, (int)optp->name, (int)optp->len));
18904 	qreply(q, mpctl);
18905 	return (mp2ctl);
18906 }
18907 
18908 /* Multicast routing virtual interface table. */
18909 static mblk_t *
18910 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18911 {
18912 	struct opthdr		*optp;
18913 	mblk_t			*mp2ctl;
18914 
18915 	/*
18916 	 * make a copy of the original message
18917 	 */
18918 	mp2ctl = copymsg(mpctl);
18919 
18920 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18921 	optp->level = EXPER_DVMRP;
18922 	optp->name = EXPER_DVMRP_VIF;
18923 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
18924 		ip0dbg(("ip_mroute_vif: failed\n"));
18925 	}
18926 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18927 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
18928 	    (int)optp->level, (int)optp->name, (int)optp->len));
18929 	qreply(q, mpctl);
18930 	return (mp2ctl);
18931 }
18932 
18933 /* Multicast routing table. */
18934 static mblk_t *
18935 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18936 {
18937 	struct opthdr		*optp;
18938 	mblk_t			*mp2ctl;
18939 
18940 	/*
18941 	 * make a copy of the original message
18942 	 */
18943 	mp2ctl = copymsg(mpctl);
18944 
18945 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18946 	optp->level = EXPER_DVMRP;
18947 	optp->name = EXPER_DVMRP_MRT;
18948 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
18949 		ip0dbg(("ip_mroute_mrt: failed\n"));
18950 	}
18951 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18952 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
18953 	    (int)optp->level, (int)optp->name, (int)optp->len));
18954 	qreply(q, mpctl);
18955 	return (mp2ctl);
18956 }
18957 
18958 /*
18959  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
18960  * in one IRE walk.
18961  */
18962 static mblk_t *
18963 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18964 {
18965 	struct opthdr	*optp;
18966 	mblk_t		*mp2ctl;	/* Returned */
18967 	mblk_t		*mp3ctl;	/* nettomedia */
18968 	mblk_t		*mp4ctl;	/* routeattrs */
18969 	iproutedata_t	ird;
18970 	zoneid_t	zoneid;
18971 
18972 	/*
18973 	 * make copies of the original message
18974 	 *	- mp2ctl is returned unchanged to the caller for his use
18975 	 *	- mpctl is sent upstream as ipRouteEntryTable
18976 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
18977 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
18978 	 */
18979 	mp2ctl = copymsg(mpctl);
18980 	mp3ctl = copymsg(mpctl);
18981 	mp4ctl = copymsg(mpctl);
18982 	if (mp3ctl == NULL || mp4ctl == NULL) {
18983 		freemsg(mp4ctl);
18984 		freemsg(mp3ctl);
18985 		freemsg(mp2ctl);
18986 		freemsg(mpctl);
18987 		return (NULL);
18988 	}
18989 
18990 	bzero(&ird, sizeof (ird));
18991 
18992 	ird.ird_route.lp_head = mpctl->b_cont;
18993 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18994 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18995 
18996 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18997 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
18998 
18999 	/* ipRouteEntryTable in mpctl */
19000 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19001 	optp->level = MIB2_IP;
19002 	optp->name = MIB2_IP_ROUTE;
19003 	optp->len = msgdsize(ird.ird_route.lp_head);
19004 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19005 	    (int)optp->level, (int)optp->name, (int)optp->len));
19006 	qreply(q, mpctl);
19007 
19008 	/* ipNetToMediaEntryTable in mp3ctl */
19009 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19010 	optp->level = MIB2_IP;
19011 	optp->name = MIB2_IP_MEDIA;
19012 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19013 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19014 	    (int)optp->level, (int)optp->name, (int)optp->len));
19015 	qreply(q, mp3ctl);
19016 
19017 	/* ipRouteAttributeTable in mp4ctl */
19018 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19019 	optp->level = MIB2_IP;
19020 	optp->name = EXPER_IP_RTATTR;
19021 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19022 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19023 	    (int)optp->level, (int)optp->name, (int)optp->len));
19024 	if (optp->len == 0)
19025 		freemsg(mp4ctl);
19026 	else
19027 		qreply(q, mp4ctl);
19028 
19029 	return (mp2ctl);
19030 }
19031 
19032 /*
19033  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
19034  * ipv6NetToMediaEntryTable in an NDP walk.
19035  */
19036 static mblk_t *
19037 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19038 {
19039 	struct opthdr	*optp;
19040 	mblk_t		*mp2ctl;	/* Returned */
19041 	mblk_t		*mp3ctl;	/* nettomedia */
19042 	mblk_t		*mp4ctl;	/* routeattrs */
19043 	iproutedata_t	ird;
19044 	zoneid_t	zoneid;
19045 
19046 	/*
19047 	 * make copies of the original message
19048 	 *	- mp2ctl is returned unchanged to the caller for his use
19049 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19050 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19051 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19052 	 */
19053 	mp2ctl = copymsg(mpctl);
19054 	mp3ctl = copymsg(mpctl);
19055 	mp4ctl = copymsg(mpctl);
19056 	if (mp3ctl == NULL || mp4ctl == NULL) {
19057 		freemsg(mp4ctl);
19058 		freemsg(mp3ctl);
19059 		freemsg(mp2ctl);
19060 		freemsg(mpctl);
19061 		return (NULL);
19062 	}
19063 
19064 	bzero(&ird, sizeof (ird));
19065 
19066 	ird.ird_route.lp_head = mpctl->b_cont;
19067 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19068 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19069 
19070 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19071 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19072 
19073 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19074 	optp->level = MIB2_IP6;
19075 	optp->name = MIB2_IP6_ROUTE;
19076 	optp->len = msgdsize(ird.ird_route.lp_head);
19077 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19078 	    (int)optp->level, (int)optp->name, (int)optp->len));
19079 	qreply(q, mpctl);
19080 
19081 	/* ipv6NetToMediaEntryTable in mp3ctl */
19082 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19083 
19084 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19085 	optp->level = MIB2_IP6;
19086 	optp->name = MIB2_IP6_MEDIA;
19087 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19088 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19089 	    (int)optp->level, (int)optp->name, (int)optp->len));
19090 	qreply(q, mp3ctl);
19091 
19092 	/* ipv6RouteAttributeTable in mp4ctl */
19093 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19094 	optp->level = MIB2_IP6;
19095 	optp->name = EXPER_IP_RTATTR;
19096 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19097 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19098 	    (int)optp->level, (int)optp->name, (int)optp->len));
19099 	if (optp->len == 0)
19100 		freemsg(mp4ctl);
19101 	else
19102 		qreply(q, mp4ctl);
19103 
19104 	return (mp2ctl);
19105 }
19106 
19107 /*
19108  * IPv6 mib: One per ill
19109  */
19110 static mblk_t *
19111 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19112 {
19113 	struct opthdr		*optp;
19114 	mblk_t			*mp2ctl;
19115 	ill_t			*ill;
19116 	ill_walk_context_t	ctx;
19117 	mblk_t			*mp_tail = NULL;
19118 
19119 	/*
19120 	 * Make a copy of the original message
19121 	 */
19122 	mp2ctl = copymsg(mpctl);
19123 
19124 	/* fixed length IPv6 structure ... */
19125 
19126 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19127 	optp->level = MIB2_IP6;
19128 	optp->name = 0;
19129 	/* Include "unknown interface" ip6_mib */
19130 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19131 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19132 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19133 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19134 	    ipst->ips_ipv6_forward ? 1 : 2);
19135 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19136 	    ipst->ips_ipv6_def_hops);
19137 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19138 	    sizeof (mib2_ipIfStatsEntry_t));
19139 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19140 	    sizeof (mib2_ipv6AddrEntry_t));
19141 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19142 	    sizeof (mib2_ipv6RouteEntry_t));
19143 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19144 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19145 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19146 	    sizeof (ipv6_member_t));
19147 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19148 	    sizeof (ipv6_grpsrc_t));
19149 
19150 	/*
19151 	 * Synchronize 64- and 32-bit counters
19152 	 */
19153 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19154 	    ipIfStatsHCInReceives);
19155 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19156 	    ipIfStatsHCInDelivers);
19157 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19158 	    ipIfStatsHCOutRequests);
19159 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19160 	    ipIfStatsHCOutForwDatagrams);
19161 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19162 	    ipIfStatsHCOutMcastPkts);
19163 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19164 	    ipIfStatsHCInMcastPkts);
19165 
19166 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19167 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19168 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19169 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19170 	}
19171 
19172 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19173 	ill = ILL_START_WALK_V6(&ctx, ipst);
19174 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19175 		ill->ill_ip_mib->ipIfStatsIfIndex =
19176 		    ill->ill_phyint->phyint_ifindex;
19177 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19178 		    ipst->ips_ipv6_forward ? 1 : 2);
19179 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19180 		    ill->ill_max_hops);
19181 
19182 		/*
19183 		 * Synchronize 64- and 32-bit counters
19184 		 */
19185 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19186 		    ipIfStatsHCInReceives);
19187 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19188 		    ipIfStatsHCInDelivers);
19189 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19190 		    ipIfStatsHCOutRequests);
19191 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19192 		    ipIfStatsHCOutForwDatagrams);
19193 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19194 		    ipIfStatsHCOutMcastPkts);
19195 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19196 		    ipIfStatsHCInMcastPkts);
19197 
19198 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19199 		    (char *)ill->ill_ip_mib,
19200 		    (int)sizeof (*ill->ill_ip_mib))) {
19201 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19202 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19203 		}
19204 	}
19205 	rw_exit(&ipst->ips_ill_g_lock);
19206 
19207 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19208 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19209 	    (int)optp->level, (int)optp->name, (int)optp->len));
19210 	qreply(q, mpctl);
19211 	return (mp2ctl);
19212 }
19213 
19214 /*
19215  * ICMPv6 mib: One per ill
19216  */
19217 static mblk_t *
19218 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19219 {
19220 	struct opthdr		*optp;
19221 	mblk_t			*mp2ctl;
19222 	ill_t			*ill;
19223 	ill_walk_context_t	ctx;
19224 	mblk_t			*mp_tail = NULL;
19225 	/*
19226 	 * Make a copy of the original message
19227 	 */
19228 	mp2ctl = copymsg(mpctl);
19229 
19230 	/* fixed length ICMPv6 structure ... */
19231 
19232 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19233 	optp->level = MIB2_ICMP6;
19234 	optp->name = 0;
19235 	/* Include "unknown interface" icmp6_mib */
19236 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19237 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19238 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19239 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19240 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19241 	    (char *)&ipst->ips_icmp6_mib,
19242 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19243 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19244 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19245 	}
19246 
19247 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19248 	ill = ILL_START_WALK_V6(&ctx, ipst);
19249 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19250 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19251 		    ill->ill_phyint->phyint_ifindex;
19252 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19253 		    (char *)ill->ill_icmp6_mib,
19254 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19255 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19256 			    "%u bytes\n",
19257 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19258 		}
19259 	}
19260 	rw_exit(&ipst->ips_ill_g_lock);
19261 
19262 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19263 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19264 	    (int)optp->level, (int)optp->name, (int)optp->len));
19265 	qreply(q, mpctl);
19266 	return (mp2ctl);
19267 }
19268 
19269 /*
19270  * ire_walk routine to create both ipRouteEntryTable and
19271  * ipRouteAttributeTable in one IRE walk
19272  */
19273 static void
19274 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19275 {
19276 	ill_t				*ill;
19277 	ipif_t				*ipif;
19278 	mib2_ipRouteEntry_t		*re;
19279 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19280 	ipaddr_t			gw_addr;
19281 	tsol_ire_gw_secattr_t		*attrp;
19282 	tsol_gc_t			*gc = NULL;
19283 	tsol_gcgrp_t			*gcgrp = NULL;
19284 	uint_t				sacnt = 0;
19285 	int				i;
19286 
19287 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19288 
19289 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19290 		return;
19291 
19292 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19293 		mutex_enter(&attrp->igsa_lock);
19294 		if ((gc = attrp->igsa_gc) != NULL) {
19295 			gcgrp = gc->gc_grp;
19296 			ASSERT(gcgrp != NULL);
19297 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19298 			sacnt = 1;
19299 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19300 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19301 			gc = gcgrp->gcgrp_head;
19302 			sacnt = gcgrp->gcgrp_count;
19303 		}
19304 		mutex_exit(&attrp->igsa_lock);
19305 
19306 		/* do nothing if there's no gc to report */
19307 		if (gc == NULL) {
19308 			ASSERT(sacnt == 0);
19309 			if (gcgrp != NULL) {
19310 				/* we might as well drop the lock now */
19311 				rw_exit(&gcgrp->gcgrp_rwlock);
19312 				gcgrp = NULL;
19313 			}
19314 			attrp = NULL;
19315 		}
19316 
19317 		ASSERT(gc == NULL || (gcgrp != NULL &&
19318 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19319 	}
19320 	ASSERT(sacnt == 0 || gc != NULL);
19321 
19322 	if (sacnt != 0 &&
19323 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19324 		kmem_free(re, sizeof (*re));
19325 		rw_exit(&gcgrp->gcgrp_rwlock);
19326 		return;
19327 	}
19328 
19329 	/*
19330 	 * Return all IRE types for route table... let caller pick and choose
19331 	 */
19332 	re->ipRouteDest = ire->ire_addr;
19333 	ipif = ire->ire_ipif;
19334 	re->ipRouteIfIndex.o_length = 0;
19335 	if (ire->ire_type == IRE_CACHE) {
19336 		ill = (ill_t *)ire->ire_stq->q_ptr;
19337 		re->ipRouteIfIndex.o_length =
19338 		    ill->ill_name_length == 0 ? 0 :
19339 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19340 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19341 		    re->ipRouteIfIndex.o_length);
19342 	} else if (ipif != NULL) {
19343 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19344 		re->ipRouteIfIndex.o_length =
19345 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19346 	}
19347 	re->ipRouteMetric1 = -1;
19348 	re->ipRouteMetric2 = -1;
19349 	re->ipRouteMetric3 = -1;
19350 	re->ipRouteMetric4 = -1;
19351 
19352 	gw_addr = ire->ire_gateway_addr;
19353 
19354 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19355 		re->ipRouteNextHop = ire->ire_src_addr;
19356 	else
19357 		re->ipRouteNextHop = gw_addr;
19358 	/* indirect(4), direct(3), or invalid(2) */
19359 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19360 		re->ipRouteType = 2;
19361 	else
19362 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19363 	re->ipRouteProto = -1;
19364 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19365 	re->ipRouteMask = ire->ire_mask;
19366 	re->ipRouteMetric5 = -1;
19367 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19368 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19369 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19370 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19371 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19372 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19373 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19374 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19375 
19376 	if (ire->ire_flags & RTF_DYNAMIC) {
19377 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19378 	} else {
19379 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19380 	}
19381 
19382 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19383 	    (char *)re, (int)sizeof (*re))) {
19384 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19385 		    (uint_t)sizeof (*re)));
19386 	}
19387 
19388 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19389 		iaeptr->iae_routeidx = ird->ird_idx;
19390 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19391 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19392 	}
19393 
19394 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19395 	    (char *)iae, sacnt * sizeof (*iae))) {
19396 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19397 		    (unsigned)(sacnt * sizeof (*iae))));
19398 	}
19399 
19400 	/* bump route index for next pass */
19401 	ird->ird_idx++;
19402 
19403 	kmem_free(re, sizeof (*re));
19404 	if (sacnt != 0)
19405 		kmem_free(iae, sacnt * sizeof (*iae));
19406 
19407 	if (gcgrp != NULL)
19408 		rw_exit(&gcgrp->gcgrp_rwlock);
19409 }
19410 
19411 /*
19412  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19413  */
19414 static void
19415 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19416 {
19417 	ill_t				*ill;
19418 	ipif_t				*ipif;
19419 	mib2_ipv6RouteEntry_t		*re;
19420 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19421 	in6_addr_t			gw_addr_v6;
19422 	tsol_ire_gw_secattr_t		*attrp;
19423 	tsol_gc_t			*gc = NULL;
19424 	tsol_gcgrp_t			*gcgrp = NULL;
19425 	uint_t				sacnt = 0;
19426 	int				i;
19427 
19428 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19429 
19430 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19431 		return;
19432 
19433 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19434 		mutex_enter(&attrp->igsa_lock);
19435 		if ((gc = attrp->igsa_gc) != NULL) {
19436 			gcgrp = gc->gc_grp;
19437 			ASSERT(gcgrp != NULL);
19438 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19439 			sacnt = 1;
19440 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19441 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19442 			gc = gcgrp->gcgrp_head;
19443 			sacnt = gcgrp->gcgrp_count;
19444 		}
19445 		mutex_exit(&attrp->igsa_lock);
19446 
19447 		/* do nothing if there's no gc to report */
19448 		if (gc == NULL) {
19449 			ASSERT(sacnt == 0);
19450 			if (gcgrp != NULL) {
19451 				/* we might as well drop the lock now */
19452 				rw_exit(&gcgrp->gcgrp_rwlock);
19453 				gcgrp = NULL;
19454 			}
19455 			attrp = NULL;
19456 		}
19457 
19458 		ASSERT(gc == NULL || (gcgrp != NULL &&
19459 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19460 	}
19461 	ASSERT(sacnt == 0 || gc != NULL);
19462 
19463 	if (sacnt != 0 &&
19464 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19465 		kmem_free(re, sizeof (*re));
19466 		rw_exit(&gcgrp->gcgrp_rwlock);
19467 		return;
19468 	}
19469 
19470 	/*
19471 	 * Return all IRE types for route table... let caller pick and choose
19472 	 */
19473 	re->ipv6RouteDest = ire->ire_addr_v6;
19474 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19475 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19476 	re->ipv6RouteIfIndex.o_length = 0;
19477 	ipif = ire->ire_ipif;
19478 	if (ire->ire_type == IRE_CACHE) {
19479 		ill = (ill_t *)ire->ire_stq->q_ptr;
19480 		re->ipv6RouteIfIndex.o_length =
19481 		    ill->ill_name_length == 0 ? 0 :
19482 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19483 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19484 		    re->ipv6RouteIfIndex.o_length);
19485 	} else if (ipif != NULL) {
19486 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19487 		re->ipv6RouteIfIndex.o_length =
19488 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19489 	}
19490 
19491 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19492 
19493 	mutex_enter(&ire->ire_lock);
19494 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19495 	mutex_exit(&ire->ire_lock);
19496 
19497 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19498 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19499 	else
19500 		re->ipv6RouteNextHop = gw_addr_v6;
19501 
19502 	/* remote(4), local(3), or discard(2) */
19503 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19504 		re->ipv6RouteType = 2;
19505 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19506 		re->ipv6RouteType = 3;
19507 	else
19508 		re->ipv6RouteType = 4;
19509 
19510 	re->ipv6RouteProtocol	= -1;
19511 	re->ipv6RoutePolicy	= 0;
19512 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19513 	re->ipv6RouteNextHopRDI	= 0;
19514 	re->ipv6RouteWeight	= 0;
19515 	re->ipv6RouteMetric	= 0;
19516 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19517 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19518 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19519 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19520 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19521 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19522 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19523 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19524 
19525 	if (ire->ire_flags & RTF_DYNAMIC) {
19526 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19527 	} else {
19528 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19529 	}
19530 
19531 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19532 	    (char *)re, (int)sizeof (*re))) {
19533 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19534 		    (uint_t)sizeof (*re)));
19535 	}
19536 
19537 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19538 		iaeptr->iae_routeidx = ird->ird_idx;
19539 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19540 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19541 	}
19542 
19543 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19544 	    (char *)iae, sacnt * sizeof (*iae))) {
19545 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19546 		    (unsigned)(sacnt * sizeof (*iae))));
19547 	}
19548 
19549 	/* bump route index for next pass */
19550 	ird->ird_idx++;
19551 
19552 	kmem_free(re, sizeof (*re));
19553 	if (sacnt != 0)
19554 		kmem_free(iae, sacnt * sizeof (*iae));
19555 
19556 	if (gcgrp != NULL)
19557 		rw_exit(&gcgrp->gcgrp_rwlock);
19558 }
19559 
19560 /*
19561  * ndp_walk routine to create ipv6NetToMediaEntryTable
19562  */
19563 static int
19564 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19565 {
19566 	ill_t				*ill;
19567 	mib2_ipv6NetToMediaEntry_t	ntme;
19568 	dl_unitdata_req_t		*dl;
19569 
19570 	ill = nce->nce_ill;
19571 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19572 		return (0);
19573 
19574 	/*
19575 	 * Neighbor cache entry attached to IRE with on-link
19576 	 * destination.
19577 	 */
19578 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19579 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19580 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19581 	    (nce->nce_res_mp != NULL)) {
19582 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19583 		ntme.ipv6NetToMediaPhysAddress.o_length =
19584 		    dl->dl_dest_addr_length;
19585 	} else {
19586 		ntme.ipv6NetToMediaPhysAddress.o_length =
19587 		    ill->ill_phys_addr_length;
19588 	}
19589 	if (nce->nce_res_mp != NULL) {
19590 		bcopy((char *)nce->nce_res_mp->b_rptr +
19591 		    NCE_LL_ADDR_OFFSET(ill),
19592 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19593 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19594 	} else {
19595 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19596 		    ill->ill_phys_addr_length);
19597 	}
19598 	/*
19599 	 * Note: Returns ND_* states. Should be:
19600 	 * reachable(1), stale(2), delay(3), probe(4),
19601 	 * invalid(5), unknown(6)
19602 	 */
19603 	ntme.ipv6NetToMediaState = nce->nce_state;
19604 	ntme.ipv6NetToMediaLastUpdated = 0;
19605 
19606 	/* other(1), dynamic(2), static(3), local(4) */
19607 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19608 		ntme.ipv6NetToMediaType = 4;
19609 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19610 		ntme.ipv6NetToMediaType = 1;
19611 	} else {
19612 		ntme.ipv6NetToMediaType = 2;
19613 	}
19614 
19615 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19616 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19617 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19618 		    (uint_t)sizeof (ntme)));
19619 	}
19620 	return (0);
19621 }
19622 
19623 /*
19624  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19625  */
19626 /* ARGSUSED */
19627 int
19628 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19629 {
19630 	switch (level) {
19631 	case MIB2_IP:
19632 	case MIB2_ICMP:
19633 		switch (name) {
19634 		default:
19635 			break;
19636 		}
19637 		return (1);
19638 	default:
19639 		return (1);
19640 	}
19641 }
19642 
19643 /*
19644  * When there exists both a 64- and 32-bit counter of a particular type
19645  * (i.e., InReceives), only the 64-bit counters are added.
19646  */
19647 void
19648 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19649 {
19650 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19651 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19652 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19653 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19654 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19655 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19656 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19657 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19658 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19659 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19660 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19661 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19662 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19663 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19664 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19665 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19666 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19667 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19668 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19669 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19670 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19671 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19672 	    o2->ipIfStatsInWrongIPVersion);
19673 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19674 	    o2->ipIfStatsInWrongIPVersion);
19675 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19676 	    o2->ipIfStatsOutSwitchIPVersion);
19677 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19678 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19679 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19680 	    o2->ipIfStatsHCInForwDatagrams);
19681 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19682 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19683 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19684 	    o2->ipIfStatsHCOutForwDatagrams);
19685 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19686 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19687 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19688 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19689 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19690 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19691 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19692 	    o2->ipIfStatsHCOutMcastOctets);
19693 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19694 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19695 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19696 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19697 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19698 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19699 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19700 }
19701 
19702 void
19703 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19704 {
19705 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19706 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19707 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19708 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19709 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19710 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19711 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19712 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19713 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19714 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19715 	    o2->ipv6IfIcmpInRouterSolicits);
19716 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19717 	    o2->ipv6IfIcmpInRouterAdvertisements);
19718 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19719 	    o2->ipv6IfIcmpInNeighborSolicits);
19720 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19721 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19722 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19723 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19724 	    o2->ipv6IfIcmpInGroupMembQueries);
19725 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19726 	    o2->ipv6IfIcmpInGroupMembResponses);
19727 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19728 	    o2->ipv6IfIcmpInGroupMembReductions);
19729 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19730 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19731 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19732 	    o2->ipv6IfIcmpOutDestUnreachs);
19733 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19734 	    o2->ipv6IfIcmpOutAdminProhibs);
19735 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19736 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19737 	    o2->ipv6IfIcmpOutParmProblems);
19738 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19739 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19740 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19741 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19742 	    o2->ipv6IfIcmpOutRouterSolicits);
19743 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19744 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19745 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19746 	    o2->ipv6IfIcmpOutNeighborSolicits);
19747 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19748 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19749 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19750 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19751 	    o2->ipv6IfIcmpOutGroupMembQueries);
19752 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19753 	    o2->ipv6IfIcmpOutGroupMembResponses);
19754 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19755 	    o2->ipv6IfIcmpOutGroupMembReductions);
19756 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19757 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19758 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19759 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19760 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19761 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19762 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19763 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19764 	    o2->ipv6IfIcmpInGroupMembTotal);
19765 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19766 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19767 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19768 	    o2->ipv6IfIcmpInGroupMembBadReports);
19769 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19770 	    o2->ipv6IfIcmpInGroupMembOurReports);
19771 }
19772 
19773 /*
19774  * Called before the options are updated to check if this packet will
19775  * be source routed from here.
19776  * This routine assumes that the options are well formed i.e. that they
19777  * have already been checked.
19778  */
19779 static boolean_t
19780 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
19781 {
19782 	ipoptp_t	opts;
19783 	uchar_t		*opt;
19784 	uint8_t		optval;
19785 	uint8_t		optlen;
19786 	ipaddr_t	dst;
19787 	ire_t		*ire;
19788 
19789 	if (IS_SIMPLE_IPH(ipha)) {
19790 		ip2dbg(("not source routed\n"));
19791 		return (B_FALSE);
19792 	}
19793 	dst = ipha->ipha_dst;
19794 	for (optval = ipoptp_first(&opts, ipha);
19795 	    optval != IPOPT_EOL;
19796 	    optval = ipoptp_next(&opts)) {
19797 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19798 		opt = opts.ipoptp_cur;
19799 		optlen = opts.ipoptp_len;
19800 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19801 		    optval, optlen));
19802 		switch (optval) {
19803 			uint32_t off;
19804 		case IPOPT_SSRR:
19805 		case IPOPT_LSRR:
19806 			/*
19807 			 * If dst is one of our addresses and there are some
19808 			 * entries left in the source route return (true).
19809 			 */
19810 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19811 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
19812 			if (ire == NULL) {
19813 				ip2dbg(("ip_source_routed: not next"
19814 				    " source route 0x%x\n",
19815 				    ntohl(dst)));
19816 				return (B_FALSE);
19817 			}
19818 			ire_refrele(ire);
19819 			off = opt[IPOPT_OFFSET];
19820 			off--;
19821 			if (optlen < IP_ADDR_LEN ||
19822 			    off > optlen - IP_ADDR_LEN) {
19823 				/* End of source route */
19824 				ip1dbg(("ip_source_routed: end of SR\n"));
19825 				return (B_FALSE);
19826 			}
19827 			return (B_TRUE);
19828 		}
19829 	}
19830 	ip2dbg(("not source routed\n"));
19831 	return (B_FALSE);
19832 }
19833 
19834 /*
19835  * Check if the packet contains any source route.
19836  */
19837 static boolean_t
19838 ip_source_route_included(ipha_t *ipha)
19839 {
19840 	ipoptp_t	opts;
19841 	uint8_t		optval;
19842 
19843 	if (IS_SIMPLE_IPH(ipha))
19844 		return (B_FALSE);
19845 	for (optval = ipoptp_first(&opts, ipha);
19846 	    optval != IPOPT_EOL;
19847 	    optval = ipoptp_next(&opts)) {
19848 		switch (optval) {
19849 		case IPOPT_SSRR:
19850 		case IPOPT_LSRR:
19851 			return (B_TRUE);
19852 		}
19853 	}
19854 	return (B_FALSE);
19855 }
19856 
19857 /*
19858  * Called when the IRE expiration timer fires.
19859  */
19860 void
19861 ip_trash_timer_expire(void *args)
19862 {
19863 	int			flush_flag = 0;
19864 	ire_expire_arg_t	iea;
19865 	ip_stack_t		*ipst = (ip_stack_t *)args;
19866 
19867 	iea.iea_ipst = ipst;	/* No netstack_hold */
19868 
19869 	/*
19870 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19871 	 * This lock makes sure that a new invocation of this function
19872 	 * that occurs due to an almost immediate timer firing will not
19873 	 * progress beyond this point until the current invocation is done
19874 	 */
19875 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19876 	ipst->ips_ip_ire_expire_id = 0;
19877 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19878 
19879 	/* Periodic timer */
19880 	if (ipst->ips_ip_ire_arp_time_elapsed >=
19881 	    ipst->ips_ip_ire_arp_interval) {
19882 		/*
19883 		 * Remove all IRE_CACHE entries since they might
19884 		 * contain arp information.
19885 		 */
19886 		flush_flag |= FLUSH_ARP_TIME;
19887 		ipst->ips_ip_ire_arp_time_elapsed = 0;
19888 		IP_STAT(ipst, ip_ire_arp_timer_expired);
19889 	}
19890 	if (ipst->ips_ip_ire_rd_time_elapsed >=
19891 	    ipst->ips_ip_ire_redir_interval) {
19892 		/* Remove all redirects */
19893 		flush_flag |= FLUSH_REDIRECT_TIME;
19894 		ipst->ips_ip_ire_rd_time_elapsed = 0;
19895 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
19896 	}
19897 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
19898 	    ipst->ips_ip_ire_pathmtu_interval) {
19899 		/* Increase path mtu */
19900 		flush_flag |= FLUSH_MTU_TIME;
19901 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
19902 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
19903 	}
19904 
19905 	/*
19906 	 * Optimize for the case when there are no redirects in the
19907 	 * ftable, that is, no need to walk the ftable in that case.
19908 	 */
19909 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
19910 		iea.iea_flush_flag = flush_flag;
19911 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
19912 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
19913 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
19914 		    NULL, ALL_ZONES, ipst);
19915 	}
19916 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
19917 	    ipst->ips_ip_redirect_cnt > 0) {
19918 		iea.iea_flush_flag = flush_flag;
19919 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
19920 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
19921 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
19922 	}
19923 	if (flush_flag & FLUSH_MTU_TIME) {
19924 		/*
19925 		 * Walk all IPv6 IRE's and update them
19926 		 * Note that ARP and redirect timers are not
19927 		 * needed since NUD handles stale entries.
19928 		 */
19929 		flush_flag = FLUSH_MTU_TIME;
19930 		iea.iea_flush_flag = flush_flag;
19931 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
19932 		    ALL_ZONES, ipst);
19933 	}
19934 
19935 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
19936 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
19937 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
19938 
19939 	/*
19940 	 * Hold the lock to serialize timeout calls and prevent
19941 	 * stale values in ip_ire_expire_id. Otherwise it is possible
19942 	 * for the timer to fire and a new invocation of this function
19943 	 * to start before the return value of timeout has been stored
19944 	 * in ip_ire_expire_id by the current invocation.
19945 	 */
19946 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19947 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
19948 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
19949 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19950 }
19951 
19952 /*
19953  * Called by the memory allocator subsystem directly, when the system
19954  * is running low on memory.
19955  */
19956 /* ARGSUSED */
19957 void
19958 ip_trash_ire_reclaim(void *args)
19959 {
19960 	netstack_handle_t nh;
19961 	netstack_t *ns;
19962 
19963 	netstack_next_init(&nh);
19964 	while ((ns = netstack_next(&nh)) != NULL) {
19965 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
19966 		netstack_rele(ns);
19967 	}
19968 	netstack_next_fini(&nh);
19969 }
19970 
19971 static void
19972 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
19973 {
19974 	ire_cache_count_t icc;
19975 	ire_cache_reclaim_t icr;
19976 	ncc_cache_count_t ncc;
19977 	nce_cache_reclaim_t ncr;
19978 	uint_t delete_cnt;
19979 	/*
19980 	 * Memory reclaim call back.
19981 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
19982 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
19983 	 * entries, determine what fraction to free for
19984 	 * each category of IRE_CACHE entries giving absolute priority
19985 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
19986 	 * entry will be freed unless all offlink entries are freed).
19987 	 */
19988 	icc.icc_total = 0;
19989 	icc.icc_unused = 0;
19990 	icc.icc_offlink = 0;
19991 	icc.icc_pmtu = 0;
19992 	icc.icc_onlink = 0;
19993 	ire_walk(ire_cache_count, (char *)&icc, ipst);
19994 
19995 	/*
19996 	 * Free NCEs for IPv6 like the onlink ires.
19997 	 */
19998 	ncc.ncc_total = 0;
19999 	ncc.ncc_host = 0;
20000 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
20001 
20002 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
20003 	    icc.icc_pmtu + icc.icc_onlink);
20004 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
20005 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
20006 	if (delete_cnt == 0)
20007 		return;
20008 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
20009 	/* Always delete all unused offlink entries */
20010 	icr.icr_ipst = ipst;
20011 	icr.icr_unused = 1;
20012 	if (delete_cnt <= icc.icc_unused) {
20013 		/*
20014 		 * Only need to free unused entries.  In other words,
20015 		 * there are enough unused entries to free to meet our
20016 		 * target number of freed ire cache entries.
20017 		 */
20018 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
20019 		ncr.ncr_host = 0;
20020 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
20021 		/*
20022 		 * Only need to free unused entries, plus a fraction of offlink
20023 		 * entries.  It follows from the first if statement that
20024 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
20025 		 */
20026 		delete_cnt -= icc.icc_unused;
20027 		/* Round up # deleted by truncating fraction */
20028 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
20029 		icr.icr_pmtu = icr.icr_onlink = 0;
20030 		ncr.ncr_host = 0;
20031 	} else if (delete_cnt <=
20032 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
20033 		/*
20034 		 * Free all unused and offlink entries, plus a fraction of
20035 		 * pmtu entries.  It follows from the previous if statement
20036 		 * that icc_pmtu is non-zero, and that
20037 		 * delete_cnt != icc_unused + icc_offlink.
20038 		 */
20039 		icr.icr_offlink = 1;
20040 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
20041 		/* Round up # deleted by truncating fraction */
20042 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20043 		icr.icr_onlink = 0;
20044 		ncr.ncr_host = 0;
20045 	} else {
20046 		/*
20047 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20048 		 * of onlink entries.  If we're here, then we know that
20049 		 * icc_onlink is non-zero, and that
20050 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20051 		 */
20052 		icr.icr_offlink = icr.icr_pmtu = 1;
20053 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20054 		    icc.icc_pmtu;
20055 		/* Round up # deleted by truncating fraction */
20056 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20057 		/* Using the same delete fraction as for onlink IREs */
20058 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20059 	}
20060 #ifdef DEBUG
20061 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20062 	    "fractions %d/%d/%d/%d\n",
20063 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20064 	    icc.icc_unused, icc.icc_offlink,
20065 	    icc.icc_pmtu, icc.icc_onlink,
20066 	    icr.icr_unused, icr.icr_offlink,
20067 	    icr.icr_pmtu, icr.icr_onlink));
20068 #endif
20069 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20070 	if (ncr.ncr_host != 0)
20071 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20072 		    (uchar_t *)&ncr, ipst);
20073 #ifdef DEBUG
20074 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20075 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20076 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20077 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20078 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20079 	    icc.icc_pmtu, icc.icc_onlink));
20080 #endif
20081 }
20082 
20083 /*
20084  * ip_unbind is called when a copy of an unbind request is received from the
20085  * upper level protocol.  We remove this conn from any fanout hash list it is
20086  * on, and zero out the bind information.  No reply is expected up above.
20087  */
20088 mblk_t *
20089 ip_unbind(queue_t *q, mblk_t *mp)
20090 {
20091 	conn_t	*connp = Q_TO_CONN(q);
20092 
20093 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20094 
20095 	if (is_system_labeled() && connp->conn_anon_port) {
20096 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20097 		    connp->conn_mlp_type, connp->conn_ulp,
20098 		    ntohs(connp->conn_lport), B_FALSE);
20099 		connp->conn_anon_port = 0;
20100 	}
20101 	connp->conn_mlp_type = mlptSingle;
20102 
20103 	ipcl_hash_remove(connp);
20104 
20105 	ASSERT(mp->b_cont == NULL);
20106 	/*
20107 	 * Convert mp into a T_OK_ACK
20108 	 */
20109 	mp = mi_tpi_ok_ack_alloc(mp);
20110 
20111 	/*
20112 	 * should not happen in practice... T_OK_ACK is smaller than the
20113 	 * original message.
20114 	 */
20115 	if (mp == NULL)
20116 		return (NULL);
20117 
20118 	return (mp);
20119 }
20120 
20121 /*
20122  * Write side put procedure.  Outbound data, IOCTLs, responses from
20123  * resolvers, etc, come down through here.
20124  *
20125  * arg2 is always a queue_t *.
20126  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20127  * the zoneid.
20128  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20129  */
20130 void
20131 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20132 {
20133 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20134 }
20135 
20136 void
20137 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20138     ip_opt_info_t *infop)
20139 {
20140 	conn_t		*connp = NULL;
20141 	queue_t		*q = (queue_t *)arg2;
20142 	ipha_t		*ipha;
20143 #define	rptr	((uchar_t *)ipha)
20144 	ire_t		*ire = NULL;
20145 	ire_t		*sctp_ire = NULL;
20146 	uint32_t	v_hlen_tos_len;
20147 	ipaddr_t	dst;
20148 	mblk_t		*first_mp = NULL;
20149 	boolean_t	mctl_present;
20150 	ipsec_out_t	*io;
20151 	int		match_flags;
20152 	ill_t		*attach_ill = NULL;
20153 					/* Bind to IPIF_NOFAILOVER ill etc. */
20154 	ill_t		*xmit_ill = NULL;	/* IP_PKTINFO etc. */
20155 	ipif_t		*dst_ipif;
20156 	boolean_t	multirt_need_resolve = B_FALSE;
20157 	mblk_t		*copy_mp = NULL;
20158 	int		err;
20159 	zoneid_t	zoneid;
20160 	boolean_t	need_decref = B_FALSE;
20161 	boolean_t	ignore_dontroute = B_FALSE;
20162 	boolean_t	ignore_nexthop = B_FALSE;
20163 	boolean_t	ip_nexthop = B_FALSE;
20164 	ipaddr_t	nexthop_addr;
20165 	ip_stack_t	*ipst;
20166 
20167 #ifdef	_BIG_ENDIAN
20168 #define	V_HLEN	(v_hlen_tos_len >> 24)
20169 #else
20170 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20171 #endif
20172 
20173 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20174 	    "ip_wput_start: q %p", q);
20175 
20176 	/*
20177 	 * ip_wput fast path
20178 	 */
20179 
20180 	/* is packet from ARP ? */
20181 	if (q->q_next != NULL) {
20182 		zoneid = (zoneid_t)(uintptr_t)arg;
20183 		goto qnext;
20184 	}
20185 
20186 	connp = (conn_t *)arg;
20187 	ASSERT(connp != NULL);
20188 	zoneid = connp->conn_zoneid;
20189 	ipst = connp->conn_netstack->netstack_ip;
20190 
20191 	/* is queue flow controlled? */
20192 	if ((q->q_first != NULL || connp->conn_draining) &&
20193 	    (caller == IP_WPUT)) {
20194 		ASSERT(!need_decref);
20195 		(void) putq(q, mp);
20196 		return;
20197 	}
20198 
20199 	/* Multidata transmit? */
20200 	if (DB_TYPE(mp) == M_MULTIDATA) {
20201 		/*
20202 		 * We should never get here, since all Multidata messages
20203 		 * originating from tcp should have been directed over to
20204 		 * tcp_multisend() in the first place.
20205 		 */
20206 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20207 		freemsg(mp);
20208 		return;
20209 	} else if (DB_TYPE(mp) != M_DATA)
20210 		goto notdata;
20211 
20212 	if (mp->b_flag & MSGHASREF) {
20213 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20214 		mp->b_flag &= ~MSGHASREF;
20215 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20216 		need_decref = B_TRUE;
20217 	}
20218 	ipha = (ipha_t *)mp->b_rptr;
20219 
20220 	/* is IP header non-aligned or mblk smaller than basic IP header */
20221 #ifndef SAFETY_BEFORE_SPEED
20222 	if (!OK_32PTR(rptr) ||
20223 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20224 		goto hdrtoosmall;
20225 #endif
20226 
20227 	ASSERT(OK_32PTR(ipha));
20228 
20229 	/*
20230 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20231 	 * wrong version, we'll catch it again in ip_output_v6.
20232 	 *
20233 	 * Note that this is *only* locally-generated output here, and never
20234 	 * forwarded data, and that we need to deal only with transports that
20235 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20236 	 * label.)
20237 	 */
20238 	if (is_system_labeled() &&
20239 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20240 	    !connp->conn_ulp_labeled) {
20241 		err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20242 		    connp->conn_mac_exempt, ipst);
20243 		ipha = (ipha_t *)mp->b_rptr;
20244 		if (err != 0) {
20245 			first_mp = mp;
20246 			if (err == EINVAL)
20247 				goto icmp_parameter_problem;
20248 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20249 			goto discard_pkt;
20250 		}
20251 	}
20252 
20253 	ASSERT(infop != NULL);
20254 
20255 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20256 		/*
20257 		 * IP_PKTINFO ancillary option is present.
20258 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20259 		 * allows using address of any zone as the source address.
20260 		 */
20261 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20262 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20263 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20264 		if (ire == NULL)
20265 			goto drop_pkt;
20266 		ire_refrele(ire);
20267 		ire = NULL;
20268 	}
20269 
20270 	/*
20271 	 * IP_DONTFAILOVER_IF and IP_BOUND_IF have precedence over ill index
20272 	 * passed in IP_PKTINFO.
20273 	 */
20274 	if (infop->ip_opt_ill_index != 0 &&
20275 	    connp->conn_outgoing_ill == NULL &&
20276 	    connp->conn_nofailover_ill == NULL) {
20277 
20278 		xmit_ill = ill_lookup_on_ifindex(
20279 		    infop->ip_opt_ill_index, B_FALSE, NULL, NULL, NULL, NULL,
20280 		    ipst);
20281 
20282 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20283 			goto drop_pkt;
20284 		/*
20285 		 * check that there is an ipif belonging
20286 		 * to our zone. IPCL_ZONEID is not used because
20287 		 * IP_ALLZONES option is valid only when the ill is
20288 		 * accessible from all zones i.e has a valid ipif in
20289 		 * all zones.
20290 		 */
20291 		if (!ipif_lookup_zoneid_group(xmit_ill, zoneid, 0, NULL)) {
20292 			goto drop_pkt;
20293 		}
20294 	}
20295 
20296 	/*
20297 	 * If there is a policy, try to attach an ipsec_out in
20298 	 * the front. At the end, first_mp either points to a
20299 	 * M_DATA message or IPSEC_OUT message linked to a
20300 	 * M_DATA message. We have to do it now as we might
20301 	 * lose the "conn" if we go through ip_newroute.
20302 	 */
20303 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20304 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20305 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20306 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20307 			if (need_decref)
20308 				CONN_DEC_REF(connp);
20309 			return;
20310 		} else {
20311 			ASSERT(mp->b_datap->db_type == M_CTL);
20312 			first_mp = mp;
20313 			mp = mp->b_cont;
20314 			mctl_present = B_TRUE;
20315 		}
20316 	} else {
20317 		first_mp = mp;
20318 		mctl_present = B_FALSE;
20319 	}
20320 
20321 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20322 
20323 	/* is wrong version or IP options present */
20324 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20325 		goto version_hdrlen_check;
20326 	dst = ipha->ipha_dst;
20327 
20328 	if (connp->conn_nofailover_ill != NULL) {
20329 		attach_ill = conn_get_held_ill(connp,
20330 		    &connp->conn_nofailover_ill, &err);
20331 		if (err == ILL_LOOKUP_FAILED) {
20332 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20333 			if (need_decref)
20334 				CONN_DEC_REF(connp);
20335 			freemsg(first_mp);
20336 			return;
20337 		}
20338 	}
20339 
20340 	/* If IP_BOUND_IF has been set, use that ill. */
20341 	if (connp->conn_outgoing_ill != NULL) {
20342 		xmit_ill = conn_get_held_ill(connp,
20343 		    &connp->conn_outgoing_ill, &err);
20344 		if (err == ILL_LOOKUP_FAILED)
20345 			goto drop_pkt;
20346 
20347 		goto send_from_ill;
20348 	}
20349 
20350 	/* is packet multicast? */
20351 	if (CLASSD(dst))
20352 		goto multicast;
20353 
20354 	/*
20355 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20356 	 * takes precedence over conn_dontroute and conn_nexthop_set
20357 	 */
20358 	if (xmit_ill != NULL)
20359 		goto send_from_ill;
20360 
20361 	if (connp->conn_dontroute || connp->conn_nexthop_set) {
20362 		/*
20363 		 * If the destination is a broadcast, local, or loopback
20364 		 * address, SO_DONTROUTE and IP_NEXTHOP go through the
20365 		 * standard path.
20366 		 */
20367 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20368 		if ((ire == NULL) || (ire->ire_type &
20369 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK)) == 0) {
20370 			if (ire != NULL) {
20371 				ire_refrele(ire);
20372 				/* No more access to ire */
20373 				ire = NULL;
20374 			}
20375 			/*
20376 			 * bypass routing checks and go directly to interface.
20377 			 */
20378 			if (connp->conn_dontroute)
20379 				goto dontroute;
20380 
20381 			ASSERT(connp->conn_nexthop_set);
20382 			ip_nexthop = B_TRUE;
20383 			nexthop_addr = connp->conn_nexthop_v4;
20384 			goto send_from_ill;
20385 		}
20386 
20387 		/* Must be a broadcast, a loopback or a local ire */
20388 		ire_refrele(ire);
20389 		/* No more access to ire */
20390 		ire = NULL;
20391 	}
20392 
20393 	if (attach_ill != NULL)
20394 		goto send_from_ill;
20395 
20396 	/*
20397 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20398 	 * this for the tcp global queue and listen end point
20399 	 * as it does not really have a real destination to
20400 	 * talk to.  This is also true for SCTP.
20401 	 */
20402 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20403 	    !connp->conn_fully_bound) {
20404 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20405 		if (ire == NULL)
20406 			goto noirefound;
20407 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20408 		    "ip_wput_end: q %p (%S)", q, "end");
20409 
20410 		/*
20411 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20412 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20413 		 */
20414 		if (ire->ire_flags & RTF_MULTIRT) {
20415 
20416 			/*
20417 			 * Force the TTL of multirouted packets if required.
20418 			 * The TTL of such packets is bounded by the
20419 			 * ip_multirt_ttl ndd variable.
20420 			 */
20421 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20422 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20423 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20424 				    "(was %d), dst 0x%08x\n",
20425 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20426 				    ntohl(ire->ire_addr)));
20427 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20428 			}
20429 			/*
20430 			 * We look at this point if there are pending
20431 			 * unresolved routes. ire_multirt_resolvable()
20432 			 * checks in O(n) that all IRE_OFFSUBNET ire
20433 			 * entries for the packet's destination and
20434 			 * flagged RTF_MULTIRT are currently resolved.
20435 			 * If some remain unresolved, we make a copy
20436 			 * of the current message. It will be used
20437 			 * to initiate additional route resolutions.
20438 			 */
20439 			multirt_need_resolve =
20440 			    ire_multirt_need_resolve(ire->ire_addr,
20441 			    MBLK_GETLABEL(first_mp), ipst);
20442 			ip2dbg(("ip_wput[TCP]: ire %p, "
20443 			    "multirt_need_resolve %d, first_mp %p\n",
20444 			    (void *)ire, multirt_need_resolve,
20445 			    (void *)first_mp));
20446 			if (multirt_need_resolve) {
20447 				copy_mp = copymsg(first_mp);
20448 				if (copy_mp != NULL) {
20449 					MULTIRT_DEBUG_TAG(copy_mp);
20450 				}
20451 			}
20452 		}
20453 
20454 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20455 
20456 		/*
20457 		 * Try to resolve another multiroute if
20458 		 * ire_multirt_need_resolve() deemed it necessary.
20459 		 */
20460 		if (copy_mp != NULL)
20461 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20462 		if (need_decref)
20463 			CONN_DEC_REF(connp);
20464 		return;
20465 	}
20466 
20467 	/*
20468 	 * Access to conn_ire_cache. (protected by conn_lock)
20469 	 *
20470 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20471 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20472 	 * send a packet or two with the IRE_CACHE that is going away.
20473 	 * Access to the ire requires an ire refhold on the ire prior to
20474 	 * its use since an interface unplumb thread may delete the cached
20475 	 * ire and release the refhold at any time.
20476 	 *
20477 	 * Caching an ire in the conn_ire_cache
20478 	 *
20479 	 * o Caching an ire pointer in the conn requires a strict check for
20480 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20481 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20482 	 * in the conn is done after making sure under the bucket lock that the
20483 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20484 	 * caching an ire after the unplumb thread has cleaned up the conn.
20485 	 * If the conn does not send a packet subsequently the unplumb thread
20486 	 * will be hanging waiting for the ire count to drop to zero.
20487 	 *
20488 	 * o We also need to atomically test for a null conn_ire_cache and
20489 	 * set the conn_ire_cache under the the protection of the conn_lock
20490 	 * to avoid races among concurrent threads trying to simultaneously
20491 	 * cache an ire in the conn_ire_cache.
20492 	 */
20493 	mutex_enter(&connp->conn_lock);
20494 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20495 
20496 	if (ire != NULL && ire->ire_addr == dst &&
20497 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20498 
20499 		IRE_REFHOLD(ire);
20500 		mutex_exit(&connp->conn_lock);
20501 
20502 	} else {
20503 		boolean_t cached = B_FALSE;
20504 		connp->conn_ire_cache = NULL;
20505 		mutex_exit(&connp->conn_lock);
20506 		/* Release the old ire */
20507 		if (ire != NULL && sctp_ire == NULL)
20508 			IRE_REFRELE_NOTR(ire);
20509 
20510 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20511 		if (ire == NULL)
20512 			goto noirefound;
20513 		IRE_REFHOLD_NOTR(ire);
20514 
20515 		mutex_enter(&connp->conn_lock);
20516 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20517 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20518 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20519 				if (connp->conn_ulp == IPPROTO_TCP)
20520 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20521 				connp->conn_ire_cache = ire;
20522 				cached = B_TRUE;
20523 			}
20524 			rw_exit(&ire->ire_bucket->irb_lock);
20525 		}
20526 		mutex_exit(&connp->conn_lock);
20527 
20528 		/*
20529 		 * We can continue to use the ire but since it was
20530 		 * not cached, we should drop the extra reference.
20531 		 */
20532 		if (!cached)
20533 			IRE_REFRELE_NOTR(ire);
20534 	}
20535 
20536 
20537 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20538 	    "ip_wput_end: q %p (%S)", q, "end");
20539 
20540 	/*
20541 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20542 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20543 	 */
20544 	if (ire->ire_flags & RTF_MULTIRT) {
20545 
20546 		/*
20547 		 * Force the TTL of multirouted packets if required.
20548 		 * The TTL of such packets is bounded by the
20549 		 * ip_multirt_ttl ndd variable.
20550 		 */
20551 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20552 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20553 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20554 			    "(was %d), dst 0x%08x\n",
20555 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20556 			    ntohl(ire->ire_addr)));
20557 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20558 		}
20559 
20560 		/*
20561 		 * At this point, we check to see if there are any pending
20562 		 * unresolved routes. ire_multirt_resolvable()
20563 		 * checks in O(n) that all IRE_OFFSUBNET ire
20564 		 * entries for the packet's destination and
20565 		 * flagged RTF_MULTIRT are currently resolved.
20566 		 * If some remain unresolved, we make a copy
20567 		 * of the current message. It will be used
20568 		 * to initiate additional route resolutions.
20569 		 */
20570 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20571 		    MBLK_GETLABEL(first_mp), ipst);
20572 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20573 		    "multirt_need_resolve %d, first_mp %p\n",
20574 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20575 		if (multirt_need_resolve) {
20576 			copy_mp = copymsg(first_mp);
20577 			if (copy_mp != NULL) {
20578 				MULTIRT_DEBUG_TAG(copy_mp);
20579 			}
20580 		}
20581 	}
20582 
20583 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20584 
20585 	/*
20586 	 * Try to resolve another multiroute if
20587 	 * ire_multirt_resolvable() deemed it necessary
20588 	 */
20589 	if (copy_mp != NULL)
20590 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20591 	if (need_decref)
20592 		CONN_DEC_REF(connp);
20593 	return;
20594 
20595 qnext:
20596 	/*
20597 	 * Upper Level Protocols pass down complete IP datagrams
20598 	 * as M_DATA messages.	Everything else is a sideshow.
20599 	 *
20600 	 * 1) We could be re-entering ip_wput because of ip_neworute
20601 	 *    in which case we could have a IPSEC_OUT message. We
20602 	 *    need to pass through ip_wput like other datagrams and
20603 	 *    hence cannot branch to ip_wput_nondata.
20604 	 *
20605 	 * 2) ARP, AH, ESP, and other clients who are on the module
20606 	 *    instance of IP stream, give us something to deal with.
20607 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20608 	 *
20609 	 * 3) ICMP replies also could come here.
20610 	 */
20611 	ipst = ILLQ_TO_IPST(q);
20612 
20613 	if (DB_TYPE(mp) != M_DATA) {
20614 notdata:
20615 		if (DB_TYPE(mp) == M_CTL) {
20616 			/*
20617 			 * M_CTL messages are used by ARP, AH and ESP to
20618 			 * communicate with IP. We deal with IPSEC_IN and
20619 			 * IPSEC_OUT here. ip_wput_nondata handles other
20620 			 * cases.
20621 			 */
20622 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20623 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20624 				first_mp = mp->b_cont;
20625 				first_mp->b_flag &= ~MSGHASREF;
20626 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20627 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20628 				CONN_DEC_REF(connp);
20629 				connp = NULL;
20630 			}
20631 			if (ii->ipsec_info_type == IPSEC_IN) {
20632 				/*
20633 				 * Either this message goes back to
20634 				 * IPsec for further processing or to
20635 				 * ULP after policy checks.
20636 				 */
20637 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20638 				return;
20639 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20640 				io = (ipsec_out_t *)ii;
20641 				if (io->ipsec_out_proc_begin) {
20642 					/*
20643 					 * IPsec processing has already started.
20644 					 * Complete it.
20645 					 * IPQoS notes: We don't care what is
20646 					 * in ipsec_out_ill_index since this
20647 					 * won't be processed for IPQoS policies
20648 					 * in ipsec_out_process.
20649 					 */
20650 					ipsec_out_process(q, mp, NULL,
20651 					    io->ipsec_out_ill_index);
20652 					return;
20653 				} else {
20654 					connp = (q->q_next != NULL) ?
20655 					    NULL : Q_TO_CONN(q);
20656 					first_mp = mp;
20657 					mp = mp->b_cont;
20658 					mctl_present = B_TRUE;
20659 				}
20660 				zoneid = io->ipsec_out_zoneid;
20661 				ASSERT(zoneid != ALL_ZONES);
20662 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20663 				/*
20664 				 * It's an IPsec control message requesting
20665 				 * an SADB update to be sent to the IPsec
20666 				 * hardware acceleration capable ills.
20667 				 */
20668 				ipsec_ctl_t *ipsec_ctl =
20669 				    (ipsec_ctl_t *)mp->b_rptr;
20670 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20671 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20672 				mblk_t *cmp = mp->b_cont;
20673 
20674 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20675 				ASSERT(cmp != NULL);
20676 
20677 				freeb(mp);
20678 				ill_ipsec_capab_send_all(satype, cmp, sa,
20679 				    ipst->ips_netstack);
20680 				return;
20681 			} else {
20682 				/*
20683 				 * This must be ARP or special TSOL signaling.
20684 				 */
20685 				ip_wput_nondata(NULL, q, mp, NULL);
20686 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20687 				    "ip_wput_end: q %p (%S)", q, "nondata");
20688 				return;
20689 			}
20690 		} else {
20691 			/*
20692 			 * This must be non-(ARP/AH/ESP) messages.
20693 			 */
20694 			ASSERT(!need_decref);
20695 			ip_wput_nondata(NULL, q, mp, NULL);
20696 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20697 			    "ip_wput_end: q %p (%S)", q, "nondata");
20698 			return;
20699 		}
20700 	} else {
20701 		first_mp = mp;
20702 		mctl_present = B_FALSE;
20703 	}
20704 
20705 	ASSERT(first_mp != NULL);
20706 	/*
20707 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20708 	 * to make sure that this packet goes out on the same interface it
20709 	 * came in. We handle that here.
20710 	 */
20711 	if (mctl_present) {
20712 		uint_t ifindex;
20713 
20714 		io = (ipsec_out_t *)first_mp->b_rptr;
20715 		if (io->ipsec_out_attach_if || io->ipsec_out_ip_nexthop) {
20716 			/*
20717 			 * We may have lost the conn context if we are
20718 			 * coming here from ip_newroute(). Copy the
20719 			 * nexthop information.
20720 			 */
20721 			if (io->ipsec_out_ip_nexthop) {
20722 				ip_nexthop = B_TRUE;
20723 				nexthop_addr = io->ipsec_out_nexthop_addr;
20724 
20725 				ipha = (ipha_t *)mp->b_rptr;
20726 				dst = ipha->ipha_dst;
20727 				goto send_from_ill;
20728 			} else {
20729 				ASSERT(io->ipsec_out_ill_index != 0);
20730 				ifindex = io->ipsec_out_ill_index;
20731 				attach_ill = ill_lookup_on_ifindex(ifindex,
20732 				    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20733 				if (attach_ill == NULL) {
20734 					ASSERT(xmit_ill == NULL);
20735 					ip1dbg(("ip_output: bad ifindex for "
20736 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20737 					    ifindex));
20738 					freemsg(first_mp);
20739 					BUMP_MIB(&ipst->ips_ip_mib,
20740 					    ipIfStatsOutDiscards);
20741 					ASSERT(!need_decref);
20742 					return;
20743 				}
20744 			}
20745 		}
20746 	}
20747 
20748 	ASSERT(xmit_ill == NULL);
20749 
20750 	/* We have a complete IP datagram heading outbound. */
20751 	ipha = (ipha_t *)mp->b_rptr;
20752 
20753 #ifndef SPEED_BEFORE_SAFETY
20754 	/*
20755 	 * Make sure we have a full-word aligned message and that at least
20756 	 * a simple IP header is accessible in the first message.  If not,
20757 	 * try a pullup.  For labeled systems we need to always take this
20758 	 * path as M_CTLs are "notdata" but have trailing data to process.
20759 	 */
20760 	if (!OK_32PTR(rptr) ||
20761 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH || is_system_labeled()) {
20762 hdrtoosmall:
20763 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20764 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20765 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20766 			if (first_mp == NULL)
20767 				first_mp = mp;
20768 			goto discard_pkt;
20769 		}
20770 
20771 		/* This function assumes that mp points to an IPv4 packet. */
20772 		if (is_system_labeled() && q->q_next == NULL &&
20773 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20774 		    !connp->conn_ulp_labeled) {
20775 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20776 			    connp->conn_mac_exempt, ipst);
20777 			ipha = (ipha_t *)mp->b_rptr;
20778 			if (first_mp != NULL)
20779 				first_mp->b_cont = mp;
20780 			if (err != 0) {
20781 				if (first_mp == NULL)
20782 					first_mp = mp;
20783 				if (err == EINVAL)
20784 					goto icmp_parameter_problem;
20785 				ip2dbg(("ip_wput: label check failed (%d)\n",
20786 				    err));
20787 				goto discard_pkt;
20788 			}
20789 		}
20790 
20791 		ipha = (ipha_t *)mp->b_rptr;
20792 		if (first_mp == NULL) {
20793 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20794 			/*
20795 			 * If we got here because of "goto hdrtoosmall"
20796 			 * We need to attach a IPSEC_OUT.
20797 			 */
20798 			if (connp->conn_out_enforce_policy) {
20799 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
20800 				    NULL, ipha->ipha_protocol,
20801 				    ipst->ips_netstack)) == NULL)) {
20802 					BUMP_MIB(&ipst->ips_ip_mib,
20803 					    ipIfStatsOutDiscards);
20804 					if (need_decref)
20805 						CONN_DEC_REF(connp);
20806 					return;
20807 				} else {
20808 					ASSERT(mp->b_datap->db_type == M_CTL);
20809 					first_mp = mp;
20810 					mp = mp->b_cont;
20811 					mctl_present = B_TRUE;
20812 				}
20813 			} else {
20814 				first_mp = mp;
20815 				mctl_present = B_FALSE;
20816 			}
20817 		}
20818 	}
20819 #endif
20820 
20821 	/* Most of the code below is written for speed, not readability */
20822 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20823 
20824 	/*
20825 	 * If ip_newroute() fails, we're going to need a full
20826 	 * header for the icmp wraparound.
20827 	 */
20828 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20829 		uint_t	v_hlen;
20830 version_hdrlen_check:
20831 		ASSERT(first_mp != NULL);
20832 		v_hlen = V_HLEN;
20833 		/*
20834 		 * siphon off IPv6 packets coming down from transport
20835 		 * layer modules here.
20836 		 * Note: high-order bit carries NUD reachability confirmation
20837 		 */
20838 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20839 			/*
20840 			 * FIXME: assume that callers of ip_output* call
20841 			 * the right version?
20842 			 */
20843 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
20844 			ASSERT(xmit_ill == NULL);
20845 			if (attach_ill != NULL)
20846 				ill_refrele(attach_ill);
20847 			if (need_decref)
20848 				mp->b_flag |= MSGHASREF;
20849 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20850 			return;
20851 		}
20852 
20853 		if ((v_hlen >> 4) != IP_VERSION) {
20854 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20855 			    "ip_wput_end: q %p (%S)", q, "badvers");
20856 			goto discard_pkt;
20857 		}
20858 		/*
20859 		 * Is the header length at least 20 bytes?
20860 		 *
20861 		 * Are there enough bytes accessible in the header?  If
20862 		 * not, try a pullup.
20863 		 */
20864 		v_hlen &= 0xF;
20865 		v_hlen <<= 2;
20866 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20867 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20868 			    "ip_wput_end: q %p (%S)", q, "badlen");
20869 			goto discard_pkt;
20870 		}
20871 		if (v_hlen > (mp->b_wptr - rptr)) {
20872 			if (!pullupmsg(mp, v_hlen)) {
20873 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20874 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20875 				goto discard_pkt;
20876 			}
20877 			ipha = (ipha_t *)mp->b_rptr;
20878 		}
20879 		/*
20880 		 * Move first entry from any source route into ipha_dst and
20881 		 * verify the options
20882 		 */
20883 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
20884 		    zoneid, ipst)) {
20885 			ASSERT(xmit_ill == NULL);
20886 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20887 			if (attach_ill != NULL)
20888 				ill_refrele(attach_ill);
20889 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20890 			    "ip_wput_end: q %p (%S)", q, "badopts");
20891 			if (need_decref)
20892 				CONN_DEC_REF(connp);
20893 			return;
20894 		}
20895 	}
20896 	dst = ipha->ipha_dst;
20897 
20898 	/*
20899 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20900 	 * we have to run the packet through ip_newroute which will take
20901 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
20902 	 * a resolver, or assigning a default gateway, etc.
20903 	 */
20904 	if (CLASSD(dst)) {
20905 		ipif_t	*ipif;
20906 		uint32_t setsrc = 0;
20907 
20908 multicast:
20909 		ASSERT(first_mp != NULL);
20910 		ip2dbg(("ip_wput: CLASSD\n"));
20911 		if (connp == NULL) {
20912 			/*
20913 			 * Use the first good ipif on the ill.
20914 			 * XXX Should this ever happen? (Appears
20915 			 * to show up with just ppp and no ethernet due
20916 			 * to in.rdisc.)
20917 			 * However, ire_send should be able to
20918 			 * call ip_wput_ire directly.
20919 			 *
20920 			 * XXX Also, this can happen for ICMP and other packets
20921 			 * with multicast source addresses.  Perhaps we should
20922 			 * fix things so that we drop the packet in question,
20923 			 * but for now, just run with it.
20924 			 */
20925 			ill_t *ill = (ill_t *)q->q_ptr;
20926 
20927 			/*
20928 			 * Don't honor attach_if for this case. If ill
20929 			 * is part of the group, ipif could belong to
20930 			 * any ill and we cannot maintain attach_ill
20931 			 * and ipif_ill same anymore and the assert
20932 			 * below would fail.
20933 			 */
20934 			if (mctl_present && io->ipsec_out_attach_if) {
20935 				io->ipsec_out_ill_index = 0;
20936 				io->ipsec_out_attach_if = B_FALSE;
20937 				ASSERT(attach_ill != NULL);
20938 				ill_refrele(attach_ill);
20939 				attach_ill = NULL;
20940 			}
20941 
20942 			ASSERT(attach_ill == NULL);
20943 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
20944 			if (ipif == NULL) {
20945 				if (need_decref)
20946 					CONN_DEC_REF(connp);
20947 				freemsg(first_mp);
20948 				return;
20949 			}
20950 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
20951 			    ntohl(dst), ill->ill_name));
20952 		} else {
20953 			/*
20954 			 * The order of precedence is IP_BOUND_IF, IP_PKTINFO
20955 			 * and IP_MULTICAST_IF.  The block comment above this
20956 			 * function explains the locking mechanism used here.
20957 			 */
20958 			if (xmit_ill == NULL) {
20959 				xmit_ill = conn_get_held_ill(connp,
20960 				    &connp->conn_outgoing_ill, &err);
20961 				if (err == ILL_LOOKUP_FAILED) {
20962 					ip1dbg(("ip_wput: No ill for "
20963 					    "IP_BOUND_IF\n"));
20964 					BUMP_MIB(&ipst->ips_ip_mib,
20965 					    ipIfStatsOutNoRoutes);
20966 					goto drop_pkt;
20967 				}
20968 			}
20969 
20970 			if (xmit_ill == NULL) {
20971 				ipif = conn_get_held_ipif(connp,
20972 				    &connp->conn_multicast_ipif, &err);
20973 				if (err == IPIF_LOOKUP_FAILED) {
20974 					ip1dbg(("ip_wput: No ipif for "
20975 					    "multicast\n"));
20976 					BUMP_MIB(&ipst->ips_ip_mib,
20977 					    ipIfStatsOutNoRoutes);
20978 					goto drop_pkt;
20979 				}
20980 			}
20981 			if (xmit_ill != NULL) {
20982 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20983 				if (ipif == NULL) {
20984 					ip1dbg(("ip_wput: No ipif for "
20985 					    "xmit_ill\n"));
20986 					BUMP_MIB(&ipst->ips_ip_mib,
20987 					    ipIfStatsOutNoRoutes);
20988 					goto drop_pkt;
20989 				}
20990 			} else if (ipif == NULL || ipif->ipif_isv6) {
20991 				/*
20992 				 * We must do this ipif determination here
20993 				 * else we could pass through ip_newroute
20994 				 * and come back here without the conn context.
20995 				 *
20996 				 * Note: we do late binding i.e. we bind to
20997 				 * the interface when the first packet is sent.
20998 				 * For performance reasons we do not rebind on
20999 				 * each packet but keep the binding until the
21000 				 * next IP_MULTICAST_IF option.
21001 				 *
21002 				 * conn_multicast_{ipif,ill} are shared between
21003 				 * IPv4 and IPv6 and AF_INET6 sockets can
21004 				 * send both IPv4 and IPv6 packets. Hence
21005 				 * we have to check that "isv6" matches above.
21006 				 */
21007 				if (ipif != NULL)
21008 					ipif_refrele(ipif);
21009 				ipif = ipif_lookup_group(dst, zoneid, ipst);
21010 				if (ipif == NULL) {
21011 					ip1dbg(("ip_wput: No ipif for "
21012 					    "multicast\n"));
21013 					BUMP_MIB(&ipst->ips_ip_mib,
21014 					    ipIfStatsOutNoRoutes);
21015 					goto drop_pkt;
21016 				}
21017 				err = conn_set_held_ipif(connp,
21018 				    &connp->conn_multicast_ipif, ipif);
21019 				if (err == IPIF_LOOKUP_FAILED) {
21020 					ipif_refrele(ipif);
21021 					ip1dbg(("ip_wput: No ipif for "
21022 					    "multicast\n"));
21023 					BUMP_MIB(&ipst->ips_ip_mib,
21024 					    ipIfStatsOutNoRoutes);
21025 					goto drop_pkt;
21026 				}
21027 			}
21028 		}
21029 		ASSERT(!ipif->ipif_isv6);
21030 		/*
21031 		 * As we may lose the conn by the time we reach ip_wput_ire,
21032 		 * we copy conn_multicast_loop and conn_dontroute on to an
21033 		 * ipsec_out. In case if this datagram goes out secure,
21034 		 * we need the ill_index also. Copy that also into the
21035 		 * ipsec_out.
21036 		 */
21037 		if (mctl_present) {
21038 			io = (ipsec_out_t *)first_mp->b_rptr;
21039 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21040 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21041 		} else {
21042 			ASSERT(mp == first_mp);
21043 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21044 			    BPRI_HI)) == NULL) {
21045 				ipif_refrele(ipif);
21046 				first_mp = mp;
21047 				goto discard_pkt;
21048 			}
21049 			first_mp->b_datap->db_type = M_CTL;
21050 			first_mp->b_wptr += sizeof (ipsec_info_t);
21051 			/* ipsec_out_secure is B_FALSE now */
21052 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21053 			io = (ipsec_out_t *)first_mp->b_rptr;
21054 			io->ipsec_out_type = IPSEC_OUT;
21055 			io->ipsec_out_len = sizeof (ipsec_out_t);
21056 			io->ipsec_out_use_global_policy = B_TRUE;
21057 			io->ipsec_out_ns = ipst->ips_netstack;
21058 			first_mp->b_cont = mp;
21059 			mctl_present = B_TRUE;
21060 		}
21061 		if (attach_ill != NULL) {
21062 			ASSERT(attach_ill == ipif->ipif_ill);
21063 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21064 
21065 			/*
21066 			 * Check if we need an ire that will not be
21067 			 * looked up by anybody else i.e. HIDDEN.
21068 			 */
21069 			if (ill_is_probeonly(attach_ill)) {
21070 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21071 			}
21072 			io->ipsec_out_ill_index =
21073 			    attach_ill->ill_phyint->phyint_ifindex;
21074 			io->ipsec_out_attach_if = B_TRUE;
21075 		} else {
21076 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21077 			io->ipsec_out_ill_index =
21078 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21079 		}
21080 		if (connp != NULL) {
21081 			io->ipsec_out_multicast_loop =
21082 			    connp->conn_multicast_loop;
21083 			io->ipsec_out_dontroute = connp->conn_dontroute;
21084 			io->ipsec_out_zoneid = connp->conn_zoneid;
21085 		}
21086 		/*
21087 		 * If the application uses IP_MULTICAST_IF with
21088 		 * different logical addresses of the same ILL, we
21089 		 * need to make sure that the soruce address of
21090 		 * the packet matches the logical IP address used
21091 		 * in the option. We do it by initializing ipha_src
21092 		 * here. This should keep IPsec also happy as
21093 		 * when we return from IPsec processing, we don't
21094 		 * have to worry about getting the right address on
21095 		 * the packet. Thus it is sufficient to look for
21096 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21097 		 * MATCH_IRE_IPIF.
21098 		 *
21099 		 * NOTE : We need to do it for non-secure case also as
21100 		 * this might go out secure if there is a global policy
21101 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
21102 		 * address, the source should be initialized already and
21103 		 * hence we won't be initializing here.
21104 		 *
21105 		 * As we do not have the ire yet, it is possible that
21106 		 * we set the source address here and then later discover
21107 		 * that the ire implies the source address to be assigned
21108 		 * through the RTF_SETSRC flag.
21109 		 * In that case, the setsrc variable will remind us
21110 		 * that overwritting the source address by the one
21111 		 * of the RTF_SETSRC-flagged ire is allowed.
21112 		 */
21113 		if (ipha->ipha_src == INADDR_ANY &&
21114 		    (connp == NULL || !connp->conn_unspec_src)) {
21115 			ipha->ipha_src = ipif->ipif_src_addr;
21116 			setsrc = RTF_SETSRC;
21117 		}
21118 		/*
21119 		 * Find an IRE which matches the destination and the outgoing
21120 		 * queue (i.e. the outgoing interface.)
21121 		 * For loopback use a unicast IP address for
21122 		 * the ire lookup.
21123 		 */
21124 		if (IS_LOOPBACK(ipif->ipif_ill))
21125 			dst = ipif->ipif_lcl_addr;
21126 
21127 		/*
21128 		 * If xmit_ill is set, we branch out to ip_newroute_ipif.
21129 		 * We don't need to lookup ire in ctable as the packet
21130 		 * needs to be sent to the destination through the specified
21131 		 * ill irrespective of ires in the cache table.
21132 		 */
21133 		ire = NULL;
21134 		if (xmit_ill == NULL) {
21135 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21136 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21137 		}
21138 
21139 		/*
21140 		 * refrele attach_ill as its not needed anymore.
21141 		 */
21142 		if (attach_ill != NULL) {
21143 			ill_refrele(attach_ill);
21144 			attach_ill = NULL;
21145 		}
21146 
21147 		if (ire == NULL) {
21148 			/*
21149 			 * Multicast loopback and multicast forwarding is
21150 			 * done in ip_wput_ire.
21151 			 *
21152 			 * Mark this packet to make it be delivered to
21153 			 * ip_wput_ire after the new ire has been
21154 			 * created.
21155 			 *
21156 			 * The call to ip_newroute_ipif takes into account
21157 			 * the setsrc reminder. In any case, we take care
21158 			 * of the RTF_MULTIRT flag.
21159 			 */
21160 			mp->b_prev = mp->b_next = NULL;
21161 			if (xmit_ill == NULL ||
21162 			    xmit_ill->ill_ipif_up_count > 0) {
21163 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21164 				    setsrc | RTF_MULTIRT, zoneid, infop);
21165 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21166 				    "ip_wput_end: q %p (%S)", q, "noire");
21167 			} else {
21168 				freemsg(first_mp);
21169 			}
21170 			ipif_refrele(ipif);
21171 			if (xmit_ill != NULL)
21172 				ill_refrele(xmit_ill);
21173 			if (need_decref)
21174 				CONN_DEC_REF(connp);
21175 			return;
21176 		}
21177 
21178 		ipif_refrele(ipif);
21179 		ipif = NULL;
21180 		ASSERT(xmit_ill == NULL);
21181 
21182 		/*
21183 		 * Honor the RTF_SETSRC flag for multicast packets,
21184 		 * if allowed by the setsrc reminder.
21185 		 */
21186 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21187 			ipha->ipha_src = ire->ire_src_addr;
21188 		}
21189 
21190 		/*
21191 		 * Unconditionally force the TTL to 1 for
21192 		 * multirouted multicast packets:
21193 		 * multirouted multicast should not cross
21194 		 * multicast routers.
21195 		 */
21196 		if (ire->ire_flags & RTF_MULTIRT) {
21197 			if (ipha->ipha_ttl > 1) {
21198 				ip2dbg(("ip_wput: forcing multicast "
21199 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21200 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21201 				ipha->ipha_ttl = 1;
21202 			}
21203 		}
21204 	} else {
21205 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
21206 		if ((ire != NULL) && (ire->ire_type &
21207 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21208 			ignore_dontroute = B_TRUE;
21209 			ignore_nexthop = B_TRUE;
21210 		}
21211 		if (ire != NULL) {
21212 			ire_refrele(ire);
21213 			ire = NULL;
21214 		}
21215 		/*
21216 		 * Guard against coming in from arp in which case conn is NULL.
21217 		 * Also guard against non M_DATA with dontroute set but
21218 		 * destined to local, loopback or broadcast addresses.
21219 		 */
21220 		if (connp != NULL && connp->conn_dontroute &&
21221 		    !ignore_dontroute) {
21222 dontroute:
21223 			/*
21224 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21225 			 * routing protocols from seeing false direct
21226 			 * connectivity.
21227 			 */
21228 			ipha->ipha_ttl = 1;
21229 
21230 			/* If suitable ipif not found, drop packet */
21231 			dst_ipif = ipif_lookup_onlink_addr(dst, zoneid, ipst);
21232 			if (dst_ipif == NULL) {
21233 noroute:
21234 				ip1dbg(("ip_wput: no route for dst using"
21235 				    " SO_DONTROUTE\n"));
21236 				BUMP_MIB(&ipst->ips_ip_mib,
21237 				    ipIfStatsOutNoRoutes);
21238 				mp->b_prev = mp->b_next = NULL;
21239 				if (first_mp == NULL)
21240 					first_mp = mp;
21241 				goto drop_pkt;
21242 			} else {
21243 				/*
21244 				 * If suitable ipif has been found, set
21245 				 * xmit_ill to the corresponding
21246 				 * ipif_ill because we'll be using the
21247 				 * send_from_ill logic below.
21248 				 */
21249 				ASSERT(xmit_ill == NULL);
21250 				xmit_ill = dst_ipif->ipif_ill;
21251 				mutex_enter(&xmit_ill->ill_lock);
21252 				if (!ILL_CAN_LOOKUP(xmit_ill)) {
21253 					mutex_exit(&xmit_ill->ill_lock);
21254 					xmit_ill = NULL;
21255 					ipif_refrele(dst_ipif);
21256 					goto noroute;
21257 				}
21258 				ill_refhold_locked(xmit_ill);
21259 				mutex_exit(&xmit_ill->ill_lock);
21260 				ipif_refrele(dst_ipif);
21261 			}
21262 		}
21263 		/*
21264 		 * If we are bound to IPIF_NOFAILOVER address, look for
21265 		 * an IRE_CACHE matching the ill.
21266 		 */
21267 send_from_ill:
21268 		if (attach_ill != NULL) {
21269 			ipif_t	*attach_ipif;
21270 
21271 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21272 
21273 			/*
21274 			 * Check if we need an ire that will not be
21275 			 * looked up by anybody else i.e. HIDDEN.
21276 			 */
21277 			if (ill_is_probeonly(attach_ill)) {
21278 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21279 			}
21280 
21281 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
21282 			if (attach_ipif == NULL) {
21283 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
21284 				goto discard_pkt;
21285 			}
21286 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
21287 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21288 			ipif_refrele(attach_ipif);
21289 		} else if (xmit_ill != NULL) {
21290 			ipif_t *ipif;
21291 
21292 			/*
21293 			 * Mark this packet as originated locally
21294 			 */
21295 			mp->b_prev = mp->b_next = NULL;
21296 
21297 			/*
21298 			 * Could be SO_DONTROUTE case also.
21299 			 * Verify that at least one ipif is up on the ill.
21300 			 */
21301 			if (xmit_ill->ill_ipif_up_count == 0) {
21302 				ip1dbg(("ip_output: xmit_ill %s is down\n",
21303 				    xmit_ill->ill_name));
21304 				goto drop_pkt;
21305 			}
21306 
21307 			ipif = ipif_get_next_ipif(NULL, xmit_ill);
21308 			if (ipif == NULL) {
21309 				ip1dbg(("ip_output: xmit_ill %s NULL ipif\n",
21310 				    xmit_ill->ill_name));
21311 				goto drop_pkt;
21312 			}
21313 
21314 			/*
21315 			 * Look for a ire that is part of the group,
21316 			 * if found use it else call ip_newroute_ipif.
21317 			 * IPCL_ZONEID is not used for matching because
21318 			 * IP_ALLZONES option is valid only when the
21319 			 * ill is accessible from all zones i.e has a
21320 			 * valid ipif in all zones.
21321 			 */
21322 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21323 			ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21324 			    MBLK_GETLABEL(mp), match_flags, ipst);
21325 			/*
21326 			 * If an ire exists use it or else create
21327 			 * an ire but don't add it to the cache.
21328 			 * Adding an ire may cause issues with
21329 			 * asymmetric routing.
21330 			 * In case of multiroute always act as if
21331 			 * ire does not exist.
21332 			 */
21333 			if (ire == NULL || ire->ire_flags & RTF_MULTIRT) {
21334 				if (ire != NULL)
21335 					ire_refrele(ire);
21336 				ip_newroute_ipif(q, first_mp, ipif,
21337 				    dst, connp, 0, zoneid, infop);
21338 				ipif_refrele(ipif);
21339 				ip1dbg(("ip_output: xmit_ill via %s\n",
21340 				    xmit_ill->ill_name));
21341 				ill_refrele(xmit_ill);
21342 				if (need_decref)
21343 					CONN_DEC_REF(connp);
21344 				return;
21345 			}
21346 			ipif_refrele(ipif);
21347 		} else if (ip_nexthop || (connp != NULL &&
21348 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21349 			if (!ip_nexthop) {
21350 				ip_nexthop = B_TRUE;
21351 				nexthop_addr = connp->conn_nexthop_v4;
21352 			}
21353 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21354 			    MATCH_IRE_GW;
21355 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21356 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21357 		} else {
21358 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp),
21359 			    ipst);
21360 		}
21361 		if (!ire) {
21362 			/*
21363 			 * Make sure we don't load spread if this
21364 			 * is IPIF_NOFAILOVER case.
21365 			 */
21366 			if ((attach_ill != NULL) ||
21367 			    (ip_nexthop && !ignore_nexthop)) {
21368 				if (mctl_present) {
21369 					io = (ipsec_out_t *)first_mp->b_rptr;
21370 					ASSERT(first_mp->b_datap->db_type ==
21371 					    M_CTL);
21372 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21373 				} else {
21374 					ASSERT(mp == first_mp);
21375 					first_mp = allocb(
21376 					    sizeof (ipsec_info_t), BPRI_HI);
21377 					if (first_mp == NULL) {
21378 						first_mp = mp;
21379 						goto discard_pkt;
21380 					}
21381 					first_mp->b_datap->db_type = M_CTL;
21382 					first_mp->b_wptr +=
21383 					    sizeof (ipsec_info_t);
21384 					/* ipsec_out_secure is B_FALSE now */
21385 					bzero(first_mp->b_rptr,
21386 					    sizeof (ipsec_info_t));
21387 					io = (ipsec_out_t *)first_mp->b_rptr;
21388 					io->ipsec_out_type = IPSEC_OUT;
21389 					io->ipsec_out_len =
21390 					    sizeof (ipsec_out_t);
21391 					io->ipsec_out_use_global_policy =
21392 					    B_TRUE;
21393 					io->ipsec_out_ns = ipst->ips_netstack;
21394 					first_mp->b_cont = mp;
21395 					mctl_present = B_TRUE;
21396 				}
21397 				if (attach_ill != NULL) {
21398 					io->ipsec_out_ill_index = attach_ill->
21399 					    ill_phyint->phyint_ifindex;
21400 					io->ipsec_out_attach_if = B_TRUE;
21401 				} else {
21402 					io->ipsec_out_ip_nexthop = ip_nexthop;
21403 					io->ipsec_out_nexthop_addr =
21404 					    nexthop_addr;
21405 				}
21406 			}
21407 noirefound:
21408 			/*
21409 			 * Mark this packet as having originated on
21410 			 * this machine.  This will be noted in
21411 			 * ire_add_then_send, which needs to know
21412 			 * whether to run it back through ip_wput or
21413 			 * ip_rput following successful resolution.
21414 			 */
21415 			mp->b_prev = NULL;
21416 			mp->b_next = NULL;
21417 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21418 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21419 			    "ip_wput_end: q %p (%S)", q, "newroute");
21420 			if (attach_ill != NULL)
21421 				ill_refrele(attach_ill);
21422 			if (xmit_ill != NULL)
21423 				ill_refrele(xmit_ill);
21424 			if (need_decref)
21425 				CONN_DEC_REF(connp);
21426 			return;
21427 		}
21428 	}
21429 
21430 	/* We now know where we are going with it. */
21431 
21432 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21433 	    "ip_wput_end: q %p (%S)", q, "end");
21434 
21435 	/*
21436 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21437 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21438 	 */
21439 	if (ire->ire_flags & RTF_MULTIRT) {
21440 		/*
21441 		 * Force the TTL of multirouted packets if required.
21442 		 * The TTL of such packets is bounded by the
21443 		 * ip_multirt_ttl ndd variable.
21444 		 */
21445 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21446 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21447 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21448 			    "(was %d), dst 0x%08x\n",
21449 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21450 			    ntohl(ire->ire_addr)));
21451 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21452 		}
21453 		/*
21454 		 * At this point, we check to see if there are any pending
21455 		 * unresolved routes. ire_multirt_resolvable()
21456 		 * checks in O(n) that all IRE_OFFSUBNET ire
21457 		 * entries for the packet's destination and
21458 		 * flagged RTF_MULTIRT are currently resolved.
21459 		 * If some remain unresolved, we make a copy
21460 		 * of the current message. It will be used
21461 		 * to initiate additional route resolutions.
21462 		 */
21463 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21464 		    MBLK_GETLABEL(first_mp), ipst);
21465 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21466 		    "multirt_need_resolve %d, first_mp %p\n",
21467 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21468 		if (multirt_need_resolve) {
21469 			copy_mp = copymsg(first_mp);
21470 			if (copy_mp != NULL) {
21471 				MULTIRT_DEBUG_TAG(copy_mp);
21472 			}
21473 		}
21474 	}
21475 
21476 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21477 	/*
21478 	 * Try to resolve another multiroute if
21479 	 * ire_multirt_resolvable() deemed it necessary.
21480 	 * At this point, we need to distinguish
21481 	 * multicasts from other packets. For multicasts,
21482 	 * we call ip_newroute_ipif() and request that both
21483 	 * multirouting and setsrc flags are checked.
21484 	 */
21485 	if (copy_mp != NULL) {
21486 		if (CLASSD(dst)) {
21487 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21488 			if (ipif) {
21489 				ASSERT(infop->ip_opt_ill_index == 0);
21490 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21491 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21492 				ipif_refrele(ipif);
21493 			} else {
21494 				MULTIRT_DEBUG_UNTAG(copy_mp);
21495 				freemsg(copy_mp);
21496 				copy_mp = NULL;
21497 			}
21498 		} else {
21499 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21500 		}
21501 	}
21502 	if (attach_ill != NULL)
21503 		ill_refrele(attach_ill);
21504 	if (xmit_ill != NULL)
21505 		ill_refrele(xmit_ill);
21506 	if (need_decref)
21507 		CONN_DEC_REF(connp);
21508 	return;
21509 
21510 icmp_parameter_problem:
21511 	/* could not have originated externally */
21512 	ASSERT(mp->b_prev == NULL);
21513 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21514 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21515 		/* it's the IP header length that's in trouble */
21516 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21517 		first_mp = NULL;
21518 	}
21519 
21520 discard_pkt:
21521 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21522 drop_pkt:
21523 	ip1dbg(("ip_wput: dropped packet\n"));
21524 	if (ire != NULL)
21525 		ire_refrele(ire);
21526 	if (need_decref)
21527 		CONN_DEC_REF(connp);
21528 	freemsg(first_mp);
21529 	if (attach_ill != NULL)
21530 		ill_refrele(attach_ill);
21531 	if (xmit_ill != NULL)
21532 		ill_refrele(xmit_ill);
21533 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21534 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21535 }
21536 
21537 /*
21538  * If this is a conn_t queue, then we pass in the conn. This includes the
21539  * zoneid.
21540  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21541  * in which case we use the global zoneid since those are all part of
21542  * the global zone.
21543  */
21544 void
21545 ip_wput(queue_t *q, mblk_t *mp)
21546 {
21547 	if (CONN_Q(q))
21548 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21549 	else
21550 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21551 }
21552 
21553 /*
21554  *
21555  * The following rules must be observed when accessing any ipif or ill
21556  * that has been cached in the conn. Typically conn_nofailover_ill,
21557  * conn_outgoing_ill, conn_multicast_ipif and conn_multicast_ill.
21558  *
21559  * Access: The ipif or ill pointed to from the conn can be accessed under
21560  * the protection of the conn_lock or after it has been refheld under the
21561  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21562  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21563  * The reason for this is that a concurrent unplumb could actually be
21564  * cleaning up these cached pointers by walking the conns and might have
21565  * finished cleaning up the conn in question. The macros check that an
21566  * unplumb has not yet started on the ipif or ill.
21567  *
21568  * Caching: An ipif or ill pointer may be cached in the conn only after
21569  * making sure that an unplumb has not started. So the caching is done
21570  * while holding both the conn_lock and the ill_lock and after using the
21571  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21572  * flag before starting the cleanup of conns.
21573  *
21574  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21575  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21576  * or a reference to the ipif or a reference to an ire that references the
21577  * ipif. An ipif does not change its ill except for failover/failback. Since
21578  * failover/failback happens only after bringing down the ipif and making sure
21579  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
21580  * the above holds.
21581  */
21582 ipif_t *
21583 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21584 {
21585 	ipif_t	*ipif;
21586 	ill_t	*ill;
21587 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21588 
21589 	*err = 0;
21590 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21591 	mutex_enter(&connp->conn_lock);
21592 	ipif = *ipifp;
21593 	if (ipif != NULL) {
21594 		ill = ipif->ipif_ill;
21595 		mutex_enter(&ill->ill_lock);
21596 		if (IPIF_CAN_LOOKUP(ipif)) {
21597 			ipif_refhold_locked(ipif);
21598 			mutex_exit(&ill->ill_lock);
21599 			mutex_exit(&connp->conn_lock);
21600 			rw_exit(&ipst->ips_ill_g_lock);
21601 			return (ipif);
21602 		} else {
21603 			*err = IPIF_LOOKUP_FAILED;
21604 		}
21605 		mutex_exit(&ill->ill_lock);
21606 	}
21607 	mutex_exit(&connp->conn_lock);
21608 	rw_exit(&ipst->ips_ill_g_lock);
21609 	return (NULL);
21610 }
21611 
21612 ill_t *
21613 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21614 {
21615 	ill_t	*ill;
21616 
21617 	*err = 0;
21618 	mutex_enter(&connp->conn_lock);
21619 	ill = *illp;
21620 	if (ill != NULL) {
21621 		mutex_enter(&ill->ill_lock);
21622 		if (ILL_CAN_LOOKUP(ill)) {
21623 			ill_refhold_locked(ill);
21624 			mutex_exit(&ill->ill_lock);
21625 			mutex_exit(&connp->conn_lock);
21626 			return (ill);
21627 		} else {
21628 			*err = ILL_LOOKUP_FAILED;
21629 		}
21630 		mutex_exit(&ill->ill_lock);
21631 	}
21632 	mutex_exit(&connp->conn_lock);
21633 	return (NULL);
21634 }
21635 
21636 static int
21637 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21638 {
21639 	ill_t	*ill;
21640 
21641 	ill = ipif->ipif_ill;
21642 	mutex_enter(&connp->conn_lock);
21643 	mutex_enter(&ill->ill_lock);
21644 	if (IPIF_CAN_LOOKUP(ipif)) {
21645 		*ipifp = ipif;
21646 		mutex_exit(&ill->ill_lock);
21647 		mutex_exit(&connp->conn_lock);
21648 		return (0);
21649 	}
21650 	mutex_exit(&ill->ill_lock);
21651 	mutex_exit(&connp->conn_lock);
21652 	return (IPIF_LOOKUP_FAILED);
21653 }
21654 
21655 /*
21656  * This is called if the outbound datagram needs fragmentation.
21657  *
21658  * NOTE : This function does not ire_refrele the ire argument passed in.
21659  */
21660 static void
21661 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21662     ip_stack_t *ipst)
21663 {
21664 	ipha_t		*ipha;
21665 	mblk_t		*mp;
21666 	uint32_t	v_hlen_tos_len;
21667 	uint32_t	max_frag;
21668 	uint32_t	frag_flag;
21669 	boolean_t	dont_use;
21670 
21671 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21672 		mp = ipsec_mp->b_cont;
21673 	} else {
21674 		mp = ipsec_mp;
21675 	}
21676 
21677 	ipha = (ipha_t *)mp->b_rptr;
21678 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21679 
21680 #ifdef	_BIG_ENDIAN
21681 #define	V_HLEN	(v_hlen_tos_len >> 24)
21682 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21683 #else
21684 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21685 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21686 #endif
21687 
21688 #ifndef SPEED_BEFORE_SAFETY
21689 	/*
21690 	 * Check that ipha_length is consistent with
21691 	 * the mblk length
21692 	 */
21693 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21694 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21695 		    LENGTH, msgdsize(mp)));
21696 		freemsg(ipsec_mp);
21697 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21698 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21699 		    "packet length mismatch");
21700 		return;
21701 	}
21702 #endif
21703 	/*
21704 	 * Don't use frag_flag if pre-built packet or source
21705 	 * routed or if multicast (since multicast packets do not solicit
21706 	 * ICMP "packet too big" messages). Get the values of
21707 	 * max_frag and frag_flag atomically by acquiring the
21708 	 * ire_lock.
21709 	 */
21710 	mutex_enter(&ire->ire_lock);
21711 	max_frag = ire->ire_max_frag;
21712 	frag_flag = ire->ire_frag_flag;
21713 	mutex_exit(&ire->ire_lock);
21714 
21715 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21716 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21717 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21718 
21719 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21720 	    (dont_use ? 0 : frag_flag), zoneid, ipst);
21721 }
21722 
21723 /*
21724  * Used for deciding the MSS size for the upper layer. Thus
21725  * we need to check the outbound policy values in the conn.
21726  */
21727 int
21728 conn_ipsec_length(conn_t *connp)
21729 {
21730 	ipsec_latch_t *ipl;
21731 
21732 	ipl = connp->conn_latch;
21733 	if (ipl == NULL)
21734 		return (0);
21735 
21736 	if (ipl->ipl_out_policy == NULL)
21737 		return (0);
21738 
21739 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21740 }
21741 
21742 /*
21743  * Returns an estimate of the IPsec headers size. This is used if
21744  * we don't want to call into IPsec to get the exact size.
21745  */
21746 int
21747 ipsec_out_extra_length(mblk_t *ipsec_mp)
21748 {
21749 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21750 	ipsec_action_t *a;
21751 
21752 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21753 	if (!io->ipsec_out_secure)
21754 		return (0);
21755 
21756 	a = io->ipsec_out_act;
21757 
21758 	if (a == NULL) {
21759 		ASSERT(io->ipsec_out_policy != NULL);
21760 		a = io->ipsec_out_policy->ipsp_act;
21761 	}
21762 	ASSERT(a != NULL);
21763 
21764 	return (a->ipa_ovhd);
21765 }
21766 
21767 /*
21768  * Returns an estimate of the IPsec headers size. This is used if
21769  * we don't want to call into IPsec to get the exact size.
21770  */
21771 int
21772 ipsec_in_extra_length(mblk_t *ipsec_mp)
21773 {
21774 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21775 	ipsec_action_t *a;
21776 
21777 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21778 
21779 	a = ii->ipsec_in_action;
21780 	return (a == NULL ? 0 : a->ipa_ovhd);
21781 }
21782 
21783 /*
21784  * If there are any source route options, return the true final
21785  * destination. Otherwise, return the destination.
21786  */
21787 ipaddr_t
21788 ip_get_dst(ipha_t *ipha)
21789 {
21790 	ipoptp_t	opts;
21791 	uchar_t		*opt;
21792 	uint8_t		optval;
21793 	uint8_t		optlen;
21794 	ipaddr_t	dst;
21795 	uint32_t off;
21796 
21797 	dst = ipha->ipha_dst;
21798 
21799 	if (IS_SIMPLE_IPH(ipha))
21800 		return (dst);
21801 
21802 	for (optval = ipoptp_first(&opts, ipha);
21803 	    optval != IPOPT_EOL;
21804 	    optval = ipoptp_next(&opts)) {
21805 		opt = opts.ipoptp_cur;
21806 		optlen = opts.ipoptp_len;
21807 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21808 		switch (optval) {
21809 		case IPOPT_SSRR:
21810 		case IPOPT_LSRR:
21811 			off = opt[IPOPT_OFFSET];
21812 			/*
21813 			 * If one of the conditions is true, it means
21814 			 * end of options and dst already has the right
21815 			 * value.
21816 			 */
21817 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21818 				off = optlen - IP_ADDR_LEN;
21819 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21820 			}
21821 			return (dst);
21822 		default:
21823 			break;
21824 		}
21825 	}
21826 
21827 	return (dst);
21828 }
21829 
21830 mblk_t *
21831 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21832     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21833 {
21834 	ipsec_out_t	*io;
21835 	mblk_t		*first_mp;
21836 	boolean_t policy_present;
21837 	ip_stack_t	*ipst;
21838 	ipsec_stack_t	*ipss;
21839 
21840 	ASSERT(ire != NULL);
21841 	ipst = ire->ire_ipst;
21842 	ipss = ipst->ips_netstack->netstack_ipsec;
21843 
21844 	first_mp = mp;
21845 	if (mp->b_datap->db_type == M_CTL) {
21846 		io = (ipsec_out_t *)first_mp->b_rptr;
21847 		/*
21848 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21849 		 *
21850 		 * 1) There is per-socket policy (including cached global
21851 		 *    policy) or a policy on the IP-in-IP tunnel.
21852 		 * 2) There is no per-socket policy, but it is
21853 		 *    a multicast packet that needs to go out
21854 		 *    on a specific interface. This is the case
21855 		 *    where (ip_wput and ip_wput_multicast) attaches
21856 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21857 		 *
21858 		 * In case (2) we check with global policy to
21859 		 * see if there is a match and set the ill_index
21860 		 * appropriately so that we can lookup the ire
21861 		 * properly in ip_wput_ipsec_out.
21862 		 */
21863 
21864 		/*
21865 		 * ipsec_out_use_global_policy is set to B_FALSE
21866 		 * in ipsec_in_to_out(). Refer to that function for
21867 		 * details.
21868 		 */
21869 		if ((io->ipsec_out_latch == NULL) &&
21870 		    (io->ipsec_out_use_global_policy)) {
21871 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21872 			    ire, connp, unspec_src, zoneid));
21873 		}
21874 		if (!io->ipsec_out_secure) {
21875 			/*
21876 			 * If this is not a secure packet, drop
21877 			 * the IPSEC_OUT mp and treat it as a clear
21878 			 * packet. This happens when we are sending
21879 			 * a ICMP reply back to a clear packet. See
21880 			 * ipsec_in_to_out() for details.
21881 			 */
21882 			mp = first_mp->b_cont;
21883 			freeb(first_mp);
21884 		}
21885 		return (mp);
21886 	}
21887 	/*
21888 	 * See whether we need to attach a global policy here. We
21889 	 * don't depend on the conn (as it could be null) for deciding
21890 	 * what policy this datagram should go through because it
21891 	 * should have happened in ip_wput if there was some
21892 	 * policy. This normally happens for connections which are not
21893 	 * fully bound preventing us from caching policies in
21894 	 * ip_bind. Packets coming from the TCP listener/global queue
21895 	 * - which are non-hard_bound - could also be affected by
21896 	 * applying policy here.
21897 	 *
21898 	 * If this packet is coming from tcp global queue or listener,
21899 	 * we will be applying policy here.  This may not be *right*
21900 	 * if these packets are coming from the detached connection as
21901 	 * it could have gone in clear before. This happens only if a
21902 	 * TCP connection started when there is no policy and somebody
21903 	 * added policy before it became detached. Thus packets of the
21904 	 * detached connection could go out secure and the other end
21905 	 * would drop it because it will be expecting in clear. The
21906 	 * converse is not true i.e if somebody starts a TCP
21907 	 * connection and deletes the policy, all the packets will
21908 	 * still go out with the policy that existed before deleting
21909 	 * because ip_unbind sends up policy information which is used
21910 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21911 	 * TCP to attach a dummy IPSEC_OUT and set
21912 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21913 	 * affect performance for normal cases, we are not doing it.
21914 	 * Thus, set policy before starting any TCP connections.
21915 	 *
21916 	 * NOTE - We might apply policy even for a hard bound connection
21917 	 * - for which we cached policy in ip_bind - if somebody added
21918 	 * global policy after we inherited the policy in ip_bind.
21919 	 * This means that the packets that were going out in clear
21920 	 * previously would start going secure and hence get dropped
21921 	 * on the other side. To fix this, TCP attaches a dummy
21922 	 * ipsec_out and make sure that we don't apply global policy.
21923 	 */
21924 	if (ipha != NULL)
21925 		policy_present = ipss->ipsec_outbound_v4_policy_present;
21926 	else
21927 		policy_present = ipss->ipsec_outbound_v6_policy_present;
21928 	if (!policy_present)
21929 		return (mp);
21930 
21931 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21932 	    zoneid));
21933 }
21934 
21935 ire_t *
21936 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
21937 {
21938 	ipaddr_t addr;
21939 	ire_t *save_ire;
21940 	irb_t *irb;
21941 	ill_group_t *illgrp;
21942 	int	err;
21943 
21944 	save_ire = ire;
21945 	addr = ire->ire_addr;
21946 
21947 	ASSERT(ire->ire_type == IRE_BROADCAST);
21948 
21949 	illgrp = connp->conn_outgoing_ill->ill_group;
21950 	if (illgrp == NULL) {
21951 		*conn_outgoing_ill = conn_get_held_ill(connp,
21952 		    &connp->conn_outgoing_ill, &err);
21953 		if (err == ILL_LOOKUP_FAILED) {
21954 			ire_refrele(save_ire);
21955 			return (NULL);
21956 		}
21957 		return (save_ire);
21958 	}
21959 	/*
21960 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
21961 	 * If it is part of the group, we need to send on the ire
21962 	 * that has been cleared of IRE_MARK_NORECV and that belongs
21963 	 * to this group. This is okay as IP_BOUND_IF really means
21964 	 * any ill in the group. We depend on the fact that the
21965 	 * first ire in the group is always cleared of IRE_MARK_NORECV
21966 	 * if such an ire exists. This is possible only if you have
21967 	 * at least one ill in the group that has not failed.
21968 	 *
21969 	 * First get to the ire that matches the address and group.
21970 	 *
21971 	 * We don't look for an ire with a matching zoneid because a given zone
21972 	 * won't always have broadcast ires on all ills in the group.
21973 	 */
21974 	irb = ire->ire_bucket;
21975 	rw_enter(&irb->irb_lock, RW_READER);
21976 	if (ire->ire_marks & IRE_MARK_NORECV) {
21977 		/*
21978 		 * If the current zone only has an ire broadcast for this
21979 		 * address marked NORECV, the ire we want is ahead in the
21980 		 * bucket, so we look it up deliberately ignoring the zoneid.
21981 		 */
21982 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
21983 			if (ire->ire_addr != addr)
21984 				continue;
21985 			/* skip over deleted ires */
21986 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
21987 				continue;
21988 		}
21989 	}
21990 	while (ire != NULL) {
21991 		/*
21992 		 * If a new interface is coming up, we could end up
21993 		 * seeing the loopback ire and the non-loopback ire
21994 		 * may not have been added yet. So check for ire_stq
21995 		 */
21996 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
21997 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
21998 			break;
21999 		}
22000 		ire = ire->ire_next;
22001 	}
22002 	if (ire != NULL && ire->ire_addr == addr &&
22003 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
22004 		IRE_REFHOLD(ire);
22005 		rw_exit(&irb->irb_lock);
22006 		ire_refrele(save_ire);
22007 		*conn_outgoing_ill = ire_to_ill(ire);
22008 		/*
22009 		 * Refhold the ill to make the conn_outgoing_ill
22010 		 * independent of the ire. ip_wput_ire goes in a loop
22011 		 * and may refrele the ire. Since we have an ire at this
22012 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
22013 		 */
22014 		ill_refhold(*conn_outgoing_ill);
22015 		return (ire);
22016 	}
22017 	rw_exit(&irb->irb_lock);
22018 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
22019 	/*
22020 	 * If we can't find a suitable ire, return the original ire.
22021 	 */
22022 	return (save_ire);
22023 }
22024 
22025 /*
22026  * This function does the ire_refrele of the ire passed in as the
22027  * argument. As this function looks up more ires i.e broadcast ires,
22028  * it needs to REFRELE them. Currently, for simplicity we don't
22029  * differentiate the one passed in and looked up here. We always
22030  * REFRELE.
22031  * IPQoS Notes:
22032  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
22033  * IPsec packets are done in ipsec_out_process.
22034  *
22035  */
22036 void
22037 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
22038     zoneid_t zoneid)
22039 {
22040 	ipha_t		*ipha;
22041 #define	rptr	((uchar_t *)ipha)
22042 	queue_t		*stq;
22043 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
22044 	uint32_t	v_hlen_tos_len;
22045 	uint32_t	ttl_protocol;
22046 	ipaddr_t	src;
22047 	ipaddr_t	dst;
22048 	uint32_t	cksum;
22049 	ipaddr_t	orig_src;
22050 	ire_t		*ire1;
22051 	mblk_t		*next_mp;
22052 	uint_t		hlen;
22053 	uint16_t	*up;
22054 	uint32_t	max_frag = ire->ire_max_frag;
22055 	ill_t		*ill = ire_to_ill(ire);
22056 	int		clusterwide;
22057 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
22058 	int		ipsec_len;
22059 	mblk_t		*first_mp;
22060 	ipsec_out_t	*io;
22061 	boolean_t	conn_dontroute;		/* conn value for multicast */
22062 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
22063 	boolean_t	multicast_forward;	/* Should we forward ? */
22064 	boolean_t	unspec_src;
22065 	ill_t		*conn_outgoing_ill = NULL;
22066 	ill_t		*ire_ill;
22067 	ill_t		*ire1_ill;
22068 	ill_t		*out_ill;
22069 	uint32_t 	ill_index = 0;
22070 	boolean_t	multirt_send = B_FALSE;
22071 	int		err;
22072 	ipxmit_state_t	pktxmit_state;
22073 	ip_stack_t	*ipst = ire->ire_ipst;
22074 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22075 
22076 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22077 	    "ip_wput_ire_start: q %p", q);
22078 
22079 	multicast_forward = B_FALSE;
22080 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22081 
22082 	if (ire->ire_flags & RTF_MULTIRT) {
22083 		/*
22084 		 * Multirouting case. The bucket where ire is stored
22085 		 * probably holds other RTF_MULTIRT flagged ire
22086 		 * to the destination. In this call to ip_wput_ire,
22087 		 * we attempt to send the packet through all
22088 		 * those ires. Thus, we first ensure that ire is the
22089 		 * first RTF_MULTIRT ire in the bucket,
22090 		 * before walking the ire list.
22091 		 */
22092 		ire_t *first_ire;
22093 		irb_t *irb = ire->ire_bucket;
22094 		ASSERT(irb != NULL);
22095 
22096 		/* Make sure we do not omit any multiroute ire. */
22097 		IRB_REFHOLD(irb);
22098 		for (first_ire = irb->irb_ire;
22099 		    first_ire != NULL;
22100 		    first_ire = first_ire->ire_next) {
22101 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22102 			    (first_ire->ire_addr == ire->ire_addr) &&
22103 			    !(first_ire->ire_marks &
22104 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
22105 				break;
22106 			}
22107 		}
22108 
22109 		if ((first_ire != NULL) && (first_ire != ire)) {
22110 			IRE_REFHOLD(first_ire);
22111 			ire_refrele(ire);
22112 			ire = first_ire;
22113 			ill = ire_to_ill(ire);
22114 		}
22115 		IRB_REFRELE(irb);
22116 	}
22117 
22118 	/*
22119 	 * conn_outgoing_ill variable is used only in the broadcast loop.
22120 	 * for performance we don't grab the mutexs in the fastpath
22121 	 */
22122 	if ((connp != NULL) &&
22123 	    (ire->ire_type == IRE_BROADCAST) &&
22124 	    ((connp->conn_nofailover_ill != NULL) ||
22125 	    (connp->conn_outgoing_ill != NULL))) {
22126 		/*
22127 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
22128 		 * option. So, see if this endpoint is bound to a
22129 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
22130 		 * that if the interface is failed, we will still send
22131 		 * the packet on the same ill which is what we want.
22132 		 */
22133 		conn_outgoing_ill = conn_get_held_ill(connp,
22134 		    &connp->conn_nofailover_ill, &err);
22135 		if (err == ILL_LOOKUP_FAILED) {
22136 			ire_refrele(ire);
22137 			freemsg(mp);
22138 			return;
22139 		}
22140 		if (conn_outgoing_ill == NULL) {
22141 			/*
22142 			 * Choose a good ill in the group to send the
22143 			 * packets on.
22144 			 */
22145 			ire = conn_set_outgoing_ill(connp, ire,
22146 			    &conn_outgoing_ill);
22147 			if (ire == NULL) {
22148 				freemsg(mp);
22149 				return;
22150 			}
22151 		}
22152 	}
22153 
22154 	if (mp->b_datap->db_type != M_CTL) {
22155 		ipha = (ipha_t *)mp->b_rptr;
22156 	} else {
22157 		io = (ipsec_out_t *)mp->b_rptr;
22158 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22159 		ASSERT(zoneid == io->ipsec_out_zoneid);
22160 		ASSERT(zoneid != ALL_ZONES);
22161 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22162 		dst = ipha->ipha_dst;
22163 		/*
22164 		 * For the multicast case, ipsec_out carries conn_dontroute and
22165 		 * conn_multicast_loop as conn may not be available here. We
22166 		 * need this for multicast loopback and forwarding which is done
22167 		 * later in the code.
22168 		 */
22169 		if (CLASSD(dst)) {
22170 			conn_dontroute = io->ipsec_out_dontroute;
22171 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22172 			/*
22173 			 * If conn_dontroute is not set or conn_multicast_loop
22174 			 * is set, we need to do forwarding/loopback. For
22175 			 * datagrams from ip_wput_multicast, conn_dontroute is
22176 			 * set to B_TRUE and conn_multicast_loop is set to
22177 			 * B_FALSE so that we neither do forwarding nor
22178 			 * loopback.
22179 			 */
22180 			if (!conn_dontroute || conn_multicast_loop)
22181 				multicast_forward = B_TRUE;
22182 		}
22183 	}
22184 
22185 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22186 	    ire->ire_zoneid != ALL_ZONES) {
22187 		/*
22188 		 * When a zone sends a packet to another zone, we try to deliver
22189 		 * the packet under the same conditions as if the destination
22190 		 * was a real node on the network. To do so, we look for a
22191 		 * matching route in the forwarding table.
22192 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22193 		 * ip_newroute() does.
22194 		 * Note that IRE_LOCAL are special, since they are used
22195 		 * when the zoneid doesn't match in some cases. This means that
22196 		 * we need to handle ipha_src differently since ire_src_addr
22197 		 * belongs to the receiving zone instead of the sending zone.
22198 		 * When ip_restrict_interzone_loopback is set, then
22199 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22200 		 * for loopback between zones when the logical "Ethernet" would
22201 		 * have looped them back.
22202 		 */
22203 		ire_t *src_ire;
22204 
22205 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22206 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22207 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22208 		if (src_ire != NULL &&
22209 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22210 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22211 		    ire_local_same_ill_group(ire, src_ire))) {
22212 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22213 				ipha->ipha_src = src_ire->ire_src_addr;
22214 			ire_refrele(src_ire);
22215 		} else {
22216 			ire_refrele(ire);
22217 			if (conn_outgoing_ill != NULL)
22218 				ill_refrele(conn_outgoing_ill);
22219 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22220 			if (src_ire != NULL) {
22221 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22222 					ire_refrele(src_ire);
22223 					freemsg(mp);
22224 					return;
22225 				}
22226 				ire_refrele(src_ire);
22227 			}
22228 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22229 				/* Failed */
22230 				freemsg(mp);
22231 				return;
22232 			}
22233 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22234 			    ipst);
22235 			return;
22236 		}
22237 	}
22238 
22239 	if (mp->b_datap->db_type == M_CTL ||
22240 	    ipss->ipsec_outbound_v4_policy_present) {
22241 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22242 		    unspec_src, zoneid);
22243 		if (mp == NULL) {
22244 			ire_refrele(ire);
22245 			if (conn_outgoing_ill != NULL)
22246 				ill_refrele(conn_outgoing_ill);
22247 			return;
22248 		}
22249 		/*
22250 		 * Trusted Extensions supports all-zones interfaces, so
22251 		 * zoneid == ALL_ZONES is valid, but IPsec maps ALL_ZONES to
22252 		 * the global zone.
22253 		 */
22254 		if (zoneid == ALL_ZONES && mp->b_datap->db_type == M_CTL) {
22255 			io = (ipsec_out_t *)mp->b_rptr;
22256 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
22257 			zoneid = io->ipsec_out_zoneid;
22258 		}
22259 	}
22260 
22261 	first_mp = mp;
22262 	ipsec_len = 0;
22263 
22264 	if (first_mp->b_datap->db_type == M_CTL) {
22265 		io = (ipsec_out_t *)first_mp->b_rptr;
22266 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22267 		mp = first_mp->b_cont;
22268 		ipsec_len = ipsec_out_extra_length(first_mp);
22269 		ASSERT(ipsec_len >= 0);
22270 		/* We already picked up the zoneid from the M_CTL above */
22271 		ASSERT(zoneid == io->ipsec_out_zoneid);
22272 		ASSERT(zoneid != ALL_ZONES);
22273 
22274 		/*
22275 		 * Drop M_CTL here if IPsec processing is not needed.
22276 		 * (Non-IPsec use of M_CTL extracted any information it
22277 		 * needed above).
22278 		 */
22279 		if (ipsec_len == 0) {
22280 			freeb(first_mp);
22281 			first_mp = mp;
22282 		}
22283 	}
22284 
22285 	/*
22286 	 * Fast path for ip_wput_ire
22287 	 */
22288 
22289 	ipha = (ipha_t *)mp->b_rptr;
22290 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22291 	dst = ipha->ipha_dst;
22292 
22293 	/*
22294 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22295 	 * if the socket is a SOCK_RAW type. The transport checksum should
22296 	 * be provided in the pre-built packet, so we don't need to compute it.
22297 	 * Also, other application set flags, like DF, should not be altered.
22298 	 * Other transport MUST pass down zero.
22299 	 */
22300 	ip_hdr_included = ipha->ipha_ident;
22301 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22302 
22303 	if (CLASSD(dst)) {
22304 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22305 		    ntohl(dst),
22306 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22307 		    ntohl(ire->ire_addr)));
22308 	}
22309 
22310 /* Macros to extract header fields from data already in registers */
22311 #ifdef	_BIG_ENDIAN
22312 #define	V_HLEN	(v_hlen_tos_len >> 24)
22313 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22314 #define	PROTO	(ttl_protocol & 0xFF)
22315 #else
22316 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22317 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22318 #define	PROTO	(ttl_protocol >> 8)
22319 #endif
22320 
22321 
22322 	orig_src = src = ipha->ipha_src;
22323 	/* (The loop back to "another" is explained down below.) */
22324 another:;
22325 	/*
22326 	 * Assign an ident value for this packet.  We assign idents on
22327 	 * a per destination basis out of the IRE.  There could be
22328 	 * other threads targeting the same destination, so we have to
22329 	 * arrange for a atomic increment.  Note that we use a 32-bit
22330 	 * atomic add because it has better performance than its
22331 	 * 16-bit sibling.
22332 	 *
22333 	 * If running in cluster mode and if the source address
22334 	 * belongs to a replicated service then vector through
22335 	 * cl_inet_ipident vector to allocate ip identifier
22336 	 * NOTE: This is a contract private interface with the
22337 	 * clustering group.
22338 	 */
22339 	clusterwide = 0;
22340 	if (cl_inet_ipident) {
22341 		ASSERT(cl_inet_isclusterwide);
22342 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
22343 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
22344 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
22345 			    AF_INET, (uint8_t *)(uintptr_t)src,
22346 			    (uint8_t *)(uintptr_t)dst);
22347 			clusterwide = 1;
22348 		}
22349 	}
22350 	if (!clusterwide) {
22351 		ipha->ipha_ident =
22352 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22353 	}
22354 
22355 #ifndef _BIG_ENDIAN
22356 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22357 #endif
22358 
22359 	/*
22360 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22361 	 * This is needed to obey conn_unspec_src when packets go through
22362 	 * ip_newroute + arp.
22363 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22364 	 */
22365 	if (src == INADDR_ANY && !unspec_src) {
22366 		/*
22367 		 * Assign the appropriate source address from the IRE if none
22368 		 * was specified.
22369 		 */
22370 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22371 
22372 		/*
22373 		 * With IP multipathing, broadcast packets are sent on the ire
22374 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
22375 		 * the group. However, this ire might not be in the same zone so
22376 		 * we can't always use its source address. We look for a
22377 		 * broadcast ire in the same group and in the right zone.
22378 		 */
22379 		if (ire->ire_type == IRE_BROADCAST &&
22380 		    ire->ire_zoneid != zoneid) {
22381 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
22382 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
22383 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
22384 			if (src_ire != NULL) {
22385 				src = src_ire->ire_src_addr;
22386 				ire_refrele(src_ire);
22387 			} else {
22388 				ire_refrele(ire);
22389 				if (conn_outgoing_ill != NULL)
22390 					ill_refrele(conn_outgoing_ill);
22391 				freemsg(first_mp);
22392 				if (ill != NULL) {
22393 					BUMP_MIB(ill->ill_ip_mib,
22394 					    ipIfStatsOutDiscards);
22395 				} else {
22396 					BUMP_MIB(&ipst->ips_ip_mib,
22397 					    ipIfStatsOutDiscards);
22398 				}
22399 				return;
22400 			}
22401 		} else {
22402 			src = ire->ire_src_addr;
22403 		}
22404 
22405 		if (connp == NULL) {
22406 			ip1dbg(("ip_wput_ire: no connp and no src "
22407 			    "address for dst 0x%x, using src 0x%x\n",
22408 			    ntohl(dst),
22409 			    ntohl(src)));
22410 		}
22411 		ipha->ipha_src = src;
22412 	}
22413 	stq = ire->ire_stq;
22414 
22415 	/*
22416 	 * We only allow ire chains for broadcasts since there will
22417 	 * be multiple IRE_CACHE entries for the same multicast
22418 	 * address (one per ipif).
22419 	 */
22420 	next_mp = NULL;
22421 
22422 	/* broadcast packet */
22423 	if (ire->ire_type == IRE_BROADCAST)
22424 		goto broadcast;
22425 
22426 	/* loopback ? */
22427 	if (stq == NULL)
22428 		goto nullstq;
22429 
22430 	/* The ill_index for outbound ILL */
22431 	ill_index = Q_TO_INDEX(stq);
22432 
22433 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22434 	ttl_protocol = ((uint16_t *)ipha)[4];
22435 
22436 	/* pseudo checksum (do it in parts for IP header checksum) */
22437 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22438 
22439 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22440 		queue_t *dev_q = stq->q_next;
22441 
22442 		/* flow controlled */
22443 		if ((dev_q->q_next || dev_q->q_first) &&
22444 		    !canput(dev_q))
22445 			goto blocked;
22446 		if ((PROTO == IPPROTO_UDP) &&
22447 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22448 			hlen = (V_HLEN & 0xF) << 2;
22449 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22450 			if (*up != 0) {
22451 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22452 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22453 				/* Software checksum? */
22454 				if (DB_CKSUMFLAGS(mp) == 0) {
22455 					IP_STAT(ipst, ip_out_sw_cksum);
22456 					IP_STAT_UPDATE(ipst,
22457 					    ip_udp_out_sw_cksum_bytes,
22458 					    LENGTH - hlen);
22459 				}
22460 			}
22461 		}
22462 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22463 		hlen = (V_HLEN & 0xF) << 2;
22464 		if (PROTO == IPPROTO_TCP) {
22465 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22466 			/*
22467 			 * The packet header is processed once and for all, even
22468 			 * in the multirouting case. We disable hardware
22469 			 * checksum if the packet is multirouted, as it will be
22470 			 * replicated via several interfaces, and not all of
22471 			 * them may have this capability.
22472 			 */
22473 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22474 			    LENGTH, max_frag, ipsec_len, cksum);
22475 			/* Software checksum? */
22476 			if (DB_CKSUMFLAGS(mp) == 0) {
22477 				IP_STAT(ipst, ip_out_sw_cksum);
22478 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22479 				    LENGTH - hlen);
22480 			}
22481 		} else {
22482 			sctp_hdr_t	*sctph;
22483 
22484 			ASSERT(PROTO == IPPROTO_SCTP);
22485 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22486 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22487 			/*
22488 			 * Zero out the checksum field to ensure proper
22489 			 * checksum calculation.
22490 			 */
22491 			sctph->sh_chksum = 0;
22492 #ifdef	DEBUG
22493 			if (!skip_sctp_cksum)
22494 #endif
22495 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22496 		}
22497 	}
22498 
22499 	/*
22500 	 * If this is a multicast packet and originated from ip_wput
22501 	 * we need to do loopback and forwarding checks. If it comes
22502 	 * from ip_wput_multicast, we SHOULD not do this.
22503 	 */
22504 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22505 
22506 	/* checksum */
22507 	cksum += ttl_protocol;
22508 
22509 	/* fragment the packet */
22510 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22511 		goto fragmentit;
22512 	/*
22513 	 * Don't use frag_flag if packet is pre-built or source
22514 	 * routed or if multicast (since multicast packets do
22515 	 * not solicit ICMP "packet too big" messages).
22516 	 */
22517 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22518 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22519 	    !ip_source_route_included(ipha)) &&
22520 	    !CLASSD(ipha->ipha_dst))
22521 		ipha->ipha_fragment_offset_and_flags |=
22522 		    htons(ire->ire_frag_flag);
22523 
22524 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22525 		/* calculate IP header checksum */
22526 		cksum += ipha->ipha_ident;
22527 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22528 		cksum += ipha->ipha_fragment_offset_and_flags;
22529 
22530 		/* IP options present */
22531 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22532 		if (hlen)
22533 			goto checksumoptions;
22534 
22535 		/* calculate hdr checksum */
22536 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22537 		cksum = ~(cksum + (cksum >> 16));
22538 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22539 	}
22540 	if (ipsec_len != 0) {
22541 		/*
22542 		 * We will do the rest of the processing after
22543 		 * we come back from IPsec in ip_wput_ipsec_out().
22544 		 */
22545 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22546 
22547 		io = (ipsec_out_t *)first_mp->b_rptr;
22548 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
22549 		    ill_phyint->phyint_ifindex;
22550 
22551 		ipsec_out_process(q, first_mp, ire, ill_index);
22552 		ire_refrele(ire);
22553 		if (conn_outgoing_ill != NULL)
22554 			ill_refrele(conn_outgoing_ill);
22555 		return;
22556 	}
22557 
22558 	/*
22559 	 * In most cases, the emission loop below is entered only
22560 	 * once. Only in the case where the ire holds the
22561 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22562 	 * flagged ires in the bucket, and send the packet
22563 	 * through all crossed RTF_MULTIRT routes.
22564 	 */
22565 	if (ire->ire_flags & RTF_MULTIRT) {
22566 		multirt_send = B_TRUE;
22567 	}
22568 	do {
22569 		if (multirt_send) {
22570 			irb_t *irb;
22571 			/*
22572 			 * We are in a multiple send case, need to get
22573 			 * the next ire and make a duplicate of the packet.
22574 			 * ire1 holds here the next ire to process in the
22575 			 * bucket. If multirouting is expected,
22576 			 * any non-RTF_MULTIRT ire that has the
22577 			 * right destination address is ignored.
22578 			 */
22579 			irb = ire->ire_bucket;
22580 			ASSERT(irb != NULL);
22581 
22582 			IRB_REFHOLD(irb);
22583 			for (ire1 = ire->ire_next;
22584 			    ire1 != NULL;
22585 			    ire1 = ire1->ire_next) {
22586 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22587 					continue;
22588 				if (ire1->ire_addr != ire->ire_addr)
22589 					continue;
22590 				if (ire1->ire_marks &
22591 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22592 					continue;
22593 
22594 				/* Got one */
22595 				IRE_REFHOLD(ire1);
22596 				break;
22597 			}
22598 			IRB_REFRELE(irb);
22599 
22600 			if (ire1 != NULL) {
22601 				next_mp = copyb(mp);
22602 				if ((next_mp == NULL) ||
22603 				    ((mp->b_cont != NULL) &&
22604 				    ((next_mp->b_cont =
22605 				    dupmsg(mp->b_cont)) == NULL))) {
22606 					freemsg(next_mp);
22607 					next_mp = NULL;
22608 					ire_refrele(ire1);
22609 					ire1 = NULL;
22610 				}
22611 			}
22612 
22613 			/* Last multiroute ire; don't loop anymore. */
22614 			if (ire1 == NULL) {
22615 				multirt_send = B_FALSE;
22616 			}
22617 		}
22618 
22619 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22620 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22621 		    mblk_t *, mp);
22622 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22623 		    ipst->ips_ipv4firewall_physical_out,
22624 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, 0, ipst);
22625 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22626 		if (mp == NULL)
22627 			goto release_ire_and_ill;
22628 
22629 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22630 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22631 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
22632 		if ((pktxmit_state == SEND_FAILED) ||
22633 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22634 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22635 			    "- packet dropped\n"));
22636 release_ire_and_ill:
22637 			ire_refrele(ire);
22638 			if (next_mp != NULL) {
22639 				freemsg(next_mp);
22640 				ire_refrele(ire1);
22641 			}
22642 			if (conn_outgoing_ill != NULL)
22643 				ill_refrele(conn_outgoing_ill);
22644 			return;
22645 		}
22646 
22647 		if (CLASSD(dst)) {
22648 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22649 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22650 			    LENGTH);
22651 		}
22652 
22653 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22654 		    "ip_wput_ire_end: q %p (%S)",
22655 		    q, "last copy out");
22656 		IRE_REFRELE(ire);
22657 
22658 		if (multirt_send) {
22659 			ASSERT(ire1);
22660 			/*
22661 			 * Proceed with the next RTF_MULTIRT ire,
22662 			 * Also set up the send-to queue accordingly.
22663 			 */
22664 			ire = ire1;
22665 			ire1 = NULL;
22666 			stq = ire->ire_stq;
22667 			mp = next_mp;
22668 			next_mp = NULL;
22669 			ipha = (ipha_t *)mp->b_rptr;
22670 			ill_index = Q_TO_INDEX(stq);
22671 			ill = (ill_t *)stq->q_ptr;
22672 		}
22673 	} while (multirt_send);
22674 	if (conn_outgoing_ill != NULL)
22675 		ill_refrele(conn_outgoing_ill);
22676 	return;
22677 
22678 	/*
22679 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22680 	 */
22681 broadcast:
22682 	{
22683 		/*
22684 		 * To avoid broadcast storms, we usually set the TTL to 1 for
22685 		 * broadcasts.  However, if SO_DONTROUTE isn't set, this value
22686 		 * can be overridden stack-wide through the ip_broadcast_ttl
22687 		 * ndd tunable, or on a per-connection basis through the
22688 		 * IP_BROADCAST_TTL socket option.
22689 		 *
22690 		 * In the event that we are replying to incoming ICMP packets,
22691 		 * connp could be NULL.
22692 		 */
22693 		ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22694 		if (connp != NULL) {
22695 			if (connp->conn_dontroute)
22696 				ipha->ipha_ttl = 1;
22697 			else if (connp->conn_broadcast_ttl != 0)
22698 				ipha->ipha_ttl = connp->conn_broadcast_ttl;
22699 		}
22700 
22701 		/*
22702 		 * Note that we are not doing a IRB_REFHOLD here.
22703 		 * Actually we don't care if the list changes i.e
22704 		 * if somebody deletes an IRE from the list while
22705 		 * we drop the lock, the next time we come around
22706 		 * ire_next will be NULL and hence we won't send
22707 		 * out multiple copies which is fine.
22708 		 */
22709 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22710 		ire1 = ire->ire_next;
22711 		if (conn_outgoing_ill != NULL) {
22712 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22713 				ASSERT(ire1 == ire->ire_next);
22714 				if (ire1 != NULL && ire1->ire_addr == dst) {
22715 					ire_refrele(ire);
22716 					ire = ire1;
22717 					IRE_REFHOLD(ire);
22718 					ire1 = ire->ire_next;
22719 					continue;
22720 				}
22721 				rw_exit(&ire->ire_bucket->irb_lock);
22722 				/* Did not find a matching ill */
22723 				ip1dbg(("ip_wput_ire: broadcast with no "
22724 				    "matching IP_BOUND_IF ill %s dst %x\n",
22725 				    conn_outgoing_ill->ill_name, dst));
22726 				freemsg(first_mp);
22727 				if (ire != NULL)
22728 					ire_refrele(ire);
22729 				ill_refrele(conn_outgoing_ill);
22730 				return;
22731 			}
22732 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22733 			/*
22734 			 * If the next IRE has the same address and is not one
22735 			 * of the two copies that we need to send, try to see
22736 			 * whether this copy should be sent at all. This
22737 			 * assumes that we insert loopbacks first and then
22738 			 * non-loopbacks. This is acheived by inserting the
22739 			 * loopback always before non-loopback.
22740 			 * This is used to send a single copy of a broadcast
22741 			 * packet out all physical interfaces that have an
22742 			 * matching IRE_BROADCAST while also looping
22743 			 * back one copy (to ip_wput_local) for each
22744 			 * matching physical interface. However, we avoid
22745 			 * sending packets out different logical that match by
22746 			 * having ipif_up/ipif_down supress duplicate
22747 			 * IRE_BROADCASTS.
22748 			 *
22749 			 * This feature is currently used to get broadcasts
22750 			 * sent to multiple interfaces, when the broadcast
22751 			 * address being used applies to multiple interfaces.
22752 			 * For example, a whole net broadcast will be
22753 			 * replicated on every connected subnet of
22754 			 * the target net.
22755 			 *
22756 			 * Each zone has its own set of IRE_BROADCASTs, so that
22757 			 * we're able to distribute inbound packets to multiple
22758 			 * zones who share a broadcast address. We avoid looping
22759 			 * back outbound packets in different zones but on the
22760 			 * same ill, as the application would see duplicates.
22761 			 *
22762 			 * If the interfaces are part of the same group,
22763 			 * we would want to send only one copy out for
22764 			 * whole group.
22765 			 *
22766 			 * This logic assumes that ire_add_v4() groups the
22767 			 * IRE_BROADCAST entries so that those with the same
22768 			 * ire_addr and ill_group are kept together.
22769 			 */
22770 			ire_ill = ire->ire_ipif->ipif_ill;
22771 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22772 				if (ire_ill->ill_group != NULL &&
22773 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22774 					/*
22775 					 * If the current zone only has an ire
22776 					 * broadcast for this address marked
22777 					 * NORECV, the ire we want is ahead in
22778 					 * the bucket, so we look it up
22779 					 * deliberately ignoring the zoneid.
22780 					 */
22781 					for (ire1 = ire->ire_bucket->irb_ire;
22782 					    ire1 != NULL;
22783 					    ire1 = ire1->ire_next) {
22784 						ire1_ill =
22785 						    ire1->ire_ipif->ipif_ill;
22786 						if (ire1->ire_addr != dst)
22787 							continue;
22788 						/* skip over the current ire */
22789 						if (ire1 == ire)
22790 							continue;
22791 						/* skip over deleted ires */
22792 						if (ire1->ire_marks &
22793 						    IRE_MARK_CONDEMNED)
22794 							continue;
22795 						/*
22796 						 * non-loopback ire in our
22797 						 * group: use it for the next
22798 						 * pass in the loop
22799 						 */
22800 						if (ire1->ire_stq != NULL &&
22801 						    ire1_ill->ill_group ==
22802 						    ire_ill->ill_group)
22803 							break;
22804 					}
22805 				}
22806 			} else {
22807 				while (ire1 != NULL && ire1->ire_addr == dst) {
22808 					ire1_ill = ire1->ire_ipif->ipif_ill;
22809 					/*
22810 					 * We can have two broadcast ires on the
22811 					 * same ill in different zones; here
22812 					 * we'll send a copy of the packet on
22813 					 * each ill and the fanout code will
22814 					 * call conn_wantpacket() to check that
22815 					 * the zone has the broadcast address
22816 					 * configured on the ill. If the two
22817 					 * ires are in the same group we only
22818 					 * send one copy up.
22819 					 */
22820 					if (ire1_ill != ire_ill &&
22821 					    (ire1_ill->ill_group == NULL ||
22822 					    ire_ill->ill_group == NULL ||
22823 					    ire1_ill->ill_group !=
22824 					    ire_ill->ill_group)) {
22825 						break;
22826 					}
22827 					ire1 = ire1->ire_next;
22828 				}
22829 			}
22830 		}
22831 		ASSERT(multirt_send == B_FALSE);
22832 		if (ire1 != NULL && ire1->ire_addr == dst) {
22833 			if ((ire->ire_flags & RTF_MULTIRT) &&
22834 			    (ire1->ire_flags & RTF_MULTIRT)) {
22835 				/*
22836 				 * We are in the multirouting case.
22837 				 * The message must be sent at least
22838 				 * on both ires. These ires have been
22839 				 * inserted AFTER the standard ones
22840 				 * in ip_rt_add(). There are thus no
22841 				 * other ire entries for the destination
22842 				 * address in the rest of the bucket
22843 				 * that do not have the RTF_MULTIRT
22844 				 * flag. We don't process a copy
22845 				 * of the message here. This will be
22846 				 * done in the final sending loop.
22847 				 */
22848 				multirt_send = B_TRUE;
22849 			} else {
22850 				next_mp = ip_copymsg(first_mp);
22851 				if (next_mp != NULL)
22852 					IRE_REFHOLD(ire1);
22853 			}
22854 		}
22855 		rw_exit(&ire->ire_bucket->irb_lock);
22856 	}
22857 
22858 	if (stq) {
22859 		/*
22860 		 * A non-NULL send-to queue means this packet is going
22861 		 * out of this machine.
22862 		 */
22863 		out_ill = (ill_t *)stq->q_ptr;
22864 
22865 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22866 		ttl_protocol = ((uint16_t *)ipha)[4];
22867 		/*
22868 		 * We accumulate the pseudo header checksum in cksum.
22869 		 * This is pretty hairy code, so watch close.  One
22870 		 * thing to keep in mind is that UDP and TCP have
22871 		 * stored their respective datagram lengths in their
22872 		 * checksum fields.  This lines things up real nice.
22873 		 */
22874 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22875 		    (src >> 16) + (src & 0xFFFF);
22876 		/*
22877 		 * We assume the udp checksum field contains the
22878 		 * length, so to compute the pseudo header checksum,
22879 		 * all we need is the protocol number and src/dst.
22880 		 */
22881 		/* Provide the checksums for UDP and TCP. */
22882 		if ((PROTO == IPPROTO_TCP) &&
22883 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22884 			/* hlen gets the number of uchar_ts in the IP header */
22885 			hlen = (V_HLEN & 0xF) << 2;
22886 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22887 			IP_STAT(ipst, ip_out_sw_cksum);
22888 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22889 			    LENGTH - hlen);
22890 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22891 		} else if (PROTO == IPPROTO_SCTP &&
22892 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22893 			sctp_hdr_t	*sctph;
22894 
22895 			hlen = (V_HLEN & 0xF) << 2;
22896 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22897 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22898 			sctph->sh_chksum = 0;
22899 #ifdef	DEBUG
22900 			if (!skip_sctp_cksum)
22901 #endif
22902 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22903 		} else {
22904 			queue_t *dev_q = stq->q_next;
22905 
22906 			if ((dev_q->q_next || dev_q->q_first) &&
22907 			    !canput(dev_q)) {
22908 blocked:
22909 				ipha->ipha_ident = ip_hdr_included;
22910 				/*
22911 				 * If we don't have a conn to apply
22912 				 * backpressure, free the message.
22913 				 * In the ire_send path, we don't know
22914 				 * the position to requeue the packet. Rather
22915 				 * than reorder packets, we just drop this
22916 				 * packet.
22917 				 */
22918 				if (ipst->ips_ip_output_queue &&
22919 				    connp != NULL &&
22920 				    caller != IRE_SEND) {
22921 					if (caller == IP_WSRV) {
22922 						connp->conn_did_putbq = 1;
22923 						(void) putbq(connp->conn_wq,
22924 						    first_mp);
22925 						conn_drain_insert(connp);
22926 						/*
22927 						 * This is the service thread,
22928 						 * and the queue is already
22929 						 * noenabled. The check for
22930 						 * canput and the putbq is not
22931 						 * atomic. So we need to check
22932 						 * again.
22933 						 */
22934 						if (canput(stq->q_next))
22935 							connp->conn_did_putbq
22936 							    = 0;
22937 						IP_STAT(ipst, ip_conn_flputbq);
22938 					} else {
22939 						/*
22940 						 * We are not the service proc.
22941 						 * ip_wsrv will be scheduled or
22942 						 * is already running.
22943 						 */
22944 						(void) putq(connp->conn_wq,
22945 						    first_mp);
22946 					}
22947 				} else {
22948 					out_ill = (ill_t *)stq->q_ptr;
22949 					BUMP_MIB(out_ill->ill_ip_mib,
22950 					    ipIfStatsOutDiscards);
22951 					freemsg(first_mp);
22952 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22953 					    "ip_wput_ire_end: q %p (%S)",
22954 					    q, "discard");
22955 				}
22956 				ire_refrele(ire);
22957 				if (next_mp) {
22958 					ire_refrele(ire1);
22959 					freemsg(next_mp);
22960 				}
22961 				if (conn_outgoing_ill != NULL)
22962 					ill_refrele(conn_outgoing_ill);
22963 				return;
22964 			}
22965 			if ((PROTO == IPPROTO_UDP) &&
22966 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22967 				/*
22968 				 * hlen gets the number of uchar_ts in the
22969 				 * IP header
22970 				 */
22971 				hlen = (V_HLEN & 0xF) << 2;
22972 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22973 				max_frag = ire->ire_max_frag;
22974 				if (*up != 0) {
22975 					IP_CKSUM_XMIT(out_ill, ire, mp, ipha,
22976 					    up, PROTO, hlen, LENGTH, max_frag,
22977 					    ipsec_len, cksum);
22978 					/* Software checksum? */
22979 					if (DB_CKSUMFLAGS(mp) == 0) {
22980 						IP_STAT(ipst, ip_out_sw_cksum);
22981 						IP_STAT_UPDATE(ipst,
22982 						    ip_udp_out_sw_cksum_bytes,
22983 						    LENGTH - hlen);
22984 					}
22985 				}
22986 			}
22987 		}
22988 		/*
22989 		 * Need to do this even when fragmenting. The local
22990 		 * loopback can be done without computing checksums
22991 		 * but forwarding out other interface must be done
22992 		 * after the IP checksum (and ULP checksums) have been
22993 		 * computed.
22994 		 *
22995 		 * NOTE : multicast_forward is set only if this packet
22996 		 * originated from ip_wput. For packets originating from
22997 		 * ip_wput_multicast, it is not set.
22998 		 */
22999 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
23000 multi_loopback:
23001 			ip2dbg(("ip_wput: multicast, loop %d\n",
23002 			    conn_multicast_loop));
23003 
23004 			/*  Forget header checksum offload */
23005 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
23006 
23007 			/*
23008 			 * Local loopback of multicasts?  Check the
23009 			 * ill.
23010 			 *
23011 			 * Note that the loopback function will not come
23012 			 * in through ip_rput - it will only do the
23013 			 * client fanout thus we need to do an mforward
23014 			 * as well.  The is different from the BSD
23015 			 * logic.
23016 			 */
23017 			if (ill != NULL) {
23018 				ilm_t	*ilm;
23019 
23020 				ILM_WALKER_HOLD(ill);
23021 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
23022 				    ALL_ZONES);
23023 				ILM_WALKER_RELE(ill);
23024 				if (ilm != NULL) {
23025 					/*
23026 					 * Pass along the virtual output q.
23027 					 * ip_wput_local() will distribute the
23028 					 * packet to all the matching zones,
23029 					 * except the sending zone when
23030 					 * IP_MULTICAST_LOOP is false.
23031 					 */
23032 					ip_multicast_loopback(q, ill, first_mp,
23033 					    conn_multicast_loop ? 0 :
23034 					    IP_FF_NO_MCAST_LOOP, zoneid);
23035 				}
23036 			}
23037 			if (ipha->ipha_ttl == 0) {
23038 				/*
23039 				 * 0 => only to this host i.e. we are
23040 				 * done. We are also done if this was the
23041 				 * loopback interface since it is sufficient
23042 				 * to loopback one copy of a multicast packet.
23043 				 */
23044 				freemsg(first_mp);
23045 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23046 				    "ip_wput_ire_end: q %p (%S)",
23047 				    q, "loopback");
23048 				ire_refrele(ire);
23049 				if (conn_outgoing_ill != NULL)
23050 					ill_refrele(conn_outgoing_ill);
23051 				return;
23052 			}
23053 			/*
23054 			 * ILLF_MULTICAST is checked in ip_newroute
23055 			 * i.e. we don't need to check it here since
23056 			 * all IRE_CACHEs come from ip_newroute.
23057 			 * For multicast traffic, SO_DONTROUTE is interpreted
23058 			 * to mean only send the packet out the interface
23059 			 * (optionally specified with IP_MULTICAST_IF)
23060 			 * and do not forward it out additional interfaces.
23061 			 * RSVP and the rsvp daemon is an example of a
23062 			 * protocol and user level process that
23063 			 * handles it's own routing. Hence, it uses the
23064 			 * SO_DONTROUTE option to accomplish this.
23065 			 */
23066 
23067 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
23068 			    ill != NULL) {
23069 				/* Unconditionally redo the checksum */
23070 				ipha->ipha_hdr_checksum = 0;
23071 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23072 
23073 				/*
23074 				 * If this needs to go out secure, we need
23075 				 * to wait till we finish the IPsec
23076 				 * processing.
23077 				 */
23078 				if (ipsec_len == 0 &&
23079 				    ip_mforward(ill, ipha, mp)) {
23080 					freemsg(first_mp);
23081 					ip1dbg(("ip_wput: mforward failed\n"));
23082 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23083 					    "ip_wput_ire_end: q %p (%S)",
23084 					    q, "mforward failed");
23085 					ire_refrele(ire);
23086 					if (conn_outgoing_ill != NULL)
23087 						ill_refrele(conn_outgoing_ill);
23088 					return;
23089 				}
23090 			}
23091 		}
23092 		max_frag = ire->ire_max_frag;
23093 		cksum += ttl_protocol;
23094 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23095 			/* No fragmentation required for this one. */
23096 			/*
23097 			 * Don't use frag_flag if packet is pre-built or source
23098 			 * routed or if multicast (since multicast packets do
23099 			 * not solicit ICMP "packet too big" messages).
23100 			 */
23101 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23102 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23103 			    !ip_source_route_included(ipha)) &&
23104 			    !CLASSD(ipha->ipha_dst))
23105 				ipha->ipha_fragment_offset_and_flags |=
23106 				    htons(ire->ire_frag_flag);
23107 
23108 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23109 				/* Complete the IP header checksum. */
23110 				cksum += ipha->ipha_ident;
23111 				cksum += (v_hlen_tos_len >> 16)+
23112 				    (v_hlen_tos_len & 0xFFFF);
23113 				cksum += ipha->ipha_fragment_offset_and_flags;
23114 				hlen = (V_HLEN & 0xF) -
23115 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23116 				if (hlen) {
23117 checksumoptions:
23118 					/*
23119 					 * Account for the IP Options in the IP
23120 					 * header checksum.
23121 					 */
23122 					up = (uint16_t *)(rptr+
23123 					    IP_SIMPLE_HDR_LENGTH);
23124 					do {
23125 						cksum += up[0];
23126 						cksum += up[1];
23127 						up += 2;
23128 					} while (--hlen);
23129 				}
23130 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23131 				cksum = ~(cksum + (cksum >> 16));
23132 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23133 			}
23134 			if (ipsec_len != 0) {
23135 				ipsec_out_process(q, first_mp, ire, ill_index);
23136 				if (!next_mp) {
23137 					ire_refrele(ire);
23138 					if (conn_outgoing_ill != NULL)
23139 						ill_refrele(conn_outgoing_ill);
23140 					return;
23141 				}
23142 				goto next;
23143 			}
23144 
23145 			/*
23146 			 * multirt_send has already been handled
23147 			 * for broadcast, but not yet for multicast
23148 			 * or IP options.
23149 			 */
23150 			if (next_mp == NULL) {
23151 				if (ire->ire_flags & RTF_MULTIRT) {
23152 					multirt_send = B_TRUE;
23153 				}
23154 			}
23155 
23156 			/*
23157 			 * In most cases, the emission loop below is
23158 			 * entered only once. Only in the case where
23159 			 * the ire holds the RTF_MULTIRT flag, do we loop
23160 			 * to process all RTF_MULTIRT ires in the bucket,
23161 			 * and send the packet through all crossed
23162 			 * RTF_MULTIRT routes.
23163 			 */
23164 			do {
23165 				if (multirt_send) {
23166 					irb_t *irb;
23167 
23168 					irb = ire->ire_bucket;
23169 					ASSERT(irb != NULL);
23170 					/*
23171 					 * We are in a multiple send case,
23172 					 * need to get the next IRE and make
23173 					 * a duplicate of the packet.
23174 					 */
23175 					IRB_REFHOLD(irb);
23176 					for (ire1 = ire->ire_next;
23177 					    ire1 != NULL;
23178 					    ire1 = ire1->ire_next) {
23179 						if (!(ire1->ire_flags &
23180 						    RTF_MULTIRT)) {
23181 							continue;
23182 						}
23183 						if (ire1->ire_addr !=
23184 						    ire->ire_addr) {
23185 							continue;
23186 						}
23187 						if (ire1->ire_marks &
23188 						    (IRE_MARK_CONDEMNED|
23189 						    IRE_MARK_HIDDEN)) {
23190 							continue;
23191 						}
23192 
23193 						/* Got one */
23194 						IRE_REFHOLD(ire1);
23195 						break;
23196 					}
23197 					IRB_REFRELE(irb);
23198 
23199 					if (ire1 != NULL) {
23200 						next_mp = copyb(mp);
23201 						if ((next_mp == NULL) ||
23202 						    ((mp->b_cont != NULL) &&
23203 						    ((next_mp->b_cont =
23204 						    dupmsg(mp->b_cont))
23205 						    == NULL))) {
23206 							freemsg(next_mp);
23207 							next_mp = NULL;
23208 							ire_refrele(ire1);
23209 							ire1 = NULL;
23210 						}
23211 					}
23212 
23213 					/*
23214 					 * Last multiroute ire; don't loop
23215 					 * anymore. The emission is over
23216 					 * and next_mp is NULL.
23217 					 */
23218 					if (ire1 == NULL) {
23219 						multirt_send = B_FALSE;
23220 					}
23221 				}
23222 
23223 				out_ill = ire_to_ill(ire);
23224 				DTRACE_PROBE4(ip4__physical__out__start,
23225 				    ill_t *, NULL,
23226 				    ill_t *, out_ill,
23227 				    ipha_t *, ipha, mblk_t *, mp);
23228 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23229 				    ipst->ips_ipv4firewall_physical_out,
23230 				    NULL, out_ill, ipha, mp, mp, 0, ipst);
23231 				DTRACE_PROBE1(ip4__physical__out__end,
23232 				    mblk_t *, mp);
23233 				if (mp == NULL)
23234 					goto release_ire_and_ill_2;
23235 
23236 				ASSERT(ipsec_len == 0);
23237 				mp->b_prev =
23238 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23239 				DTRACE_PROBE2(ip__xmit__2,
23240 				    mblk_t *, mp, ire_t *, ire);
23241 				pktxmit_state = ip_xmit_v4(mp, ire,
23242 				    NULL, B_TRUE);
23243 				if ((pktxmit_state == SEND_FAILED) ||
23244 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23245 release_ire_and_ill_2:
23246 					if (next_mp) {
23247 						freemsg(next_mp);
23248 						ire_refrele(ire1);
23249 					}
23250 					ire_refrele(ire);
23251 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23252 					    "ip_wput_ire_end: q %p (%S)",
23253 					    q, "discard MDATA");
23254 					if (conn_outgoing_ill != NULL)
23255 						ill_refrele(conn_outgoing_ill);
23256 					return;
23257 				}
23258 
23259 				if (CLASSD(dst)) {
23260 					BUMP_MIB(out_ill->ill_ip_mib,
23261 					    ipIfStatsHCOutMcastPkts);
23262 					UPDATE_MIB(out_ill->ill_ip_mib,
23263 					    ipIfStatsHCOutMcastOctets,
23264 					    LENGTH);
23265 				} else if (ire->ire_type == IRE_BROADCAST) {
23266 					BUMP_MIB(out_ill->ill_ip_mib,
23267 					    ipIfStatsHCOutBcastPkts);
23268 				}
23269 
23270 				if (multirt_send) {
23271 					/*
23272 					 * We are in a multiple send case,
23273 					 * need to re-enter the sending loop
23274 					 * using the next ire.
23275 					 */
23276 					ire_refrele(ire);
23277 					ire = ire1;
23278 					stq = ire->ire_stq;
23279 					mp = next_mp;
23280 					next_mp = NULL;
23281 					ipha = (ipha_t *)mp->b_rptr;
23282 					ill_index = Q_TO_INDEX(stq);
23283 				}
23284 			} while (multirt_send);
23285 
23286 			if (!next_mp) {
23287 				/*
23288 				 * Last copy going out (the ultra-common
23289 				 * case).  Note that we intentionally replicate
23290 				 * the putnext rather than calling it before
23291 				 * the next_mp check in hopes of a little
23292 				 * tail-call action out of the compiler.
23293 				 */
23294 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23295 				    "ip_wput_ire_end: q %p (%S)",
23296 				    q, "last copy out(1)");
23297 				ire_refrele(ire);
23298 				if (conn_outgoing_ill != NULL)
23299 					ill_refrele(conn_outgoing_ill);
23300 				return;
23301 			}
23302 			/* More copies going out below. */
23303 		} else {
23304 			int offset;
23305 fragmentit:
23306 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23307 			/*
23308 			 * If this would generate a icmp_frag_needed message,
23309 			 * we need to handle it before we do the IPsec
23310 			 * processing. Otherwise, we need to strip the IPsec
23311 			 * headers before we send up the message to the ULPs
23312 			 * which becomes messy and difficult.
23313 			 */
23314 			if (ipsec_len != 0) {
23315 				if ((max_frag < (unsigned int)(LENGTH +
23316 				    ipsec_len)) && (offset & IPH_DF)) {
23317 					out_ill = (ill_t *)stq->q_ptr;
23318 					BUMP_MIB(out_ill->ill_ip_mib,
23319 					    ipIfStatsOutFragFails);
23320 					BUMP_MIB(out_ill->ill_ip_mib,
23321 					    ipIfStatsOutFragReqds);
23322 					ipha->ipha_hdr_checksum = 0;
23323 					ipha->ipha_hdr_checksum =
23324 					    (uint16_t)ip_csum_hdr(ipha);
23325 					icmp_frag_needed(ire->ire_stq, first_mp,
23326 					    max_frag, zoneid, ipst);
23327 					if (!next_mp) {
23328 						ire_refrele(ire);
23329 						if (conn_outgoing_ill != NULL) {
23330 							ill_refrele(
23331 							    conn_outgoing_ill);
23332 						}
23333 						return;
23334 					}
23335 				} else {
23336 					/*
23337 					 * This won't cause a icmp_frag_needed
23338 					 * message. to be generated. Send it on
23339 					 * the wire. Note that this could still
23340 					 * cause fragmentation and all we
23341 					 * do is the generation of the message
23342 					 * to the ULP if needed before IPsec.
23343 					 */
23344 					if (!next_mp) {
23345 						ipsec_out_process(q, first_mp,
23346 						    ire, ill_index);
23347 						TRACE_2(TR_FAC_IP,
23348 						    TR_IP_WPUT_IRE_END,
23349 						    "ip_wput_ire_end: q %p "
23350 						    "(%S)", q,
23351 						    "last ipsec_out_process");
23352 						ire_refrele(ire);
23353 						if (conn_outgoing_ill != NULL) {
23354 							ill_refrele(
23355 							    conn_outgoing_ill);
23356 						}
23357 						return;
23358 					}
23359 					ipsec_out_process(q, first_mp,
23360 					    ire, ill_index);
23361 				}
23362 			} else {
23363 				/*
23364 				 * Initiate IPPF processing. For
23365 				 * fragmentable packets we finish
23366 				 * all QOS packet processing before
23367 				 * calling:
23368 				 * ip_wput_ire_fragmentit->ip_wput_frag
23369 				 */
23370 
23371 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23372 					ip_process(IPP_LOCAL_OUT, &mp,
23373 					    ill_index);
23374 					if (mp == NULL) {
23375 						out_ill = (ill_t *)stq->q_ptr;
23376 						BUMP_MIB(out_ill->ill_ip_mib,
23377 						    ipIfStatsOutDiscards);
23378 						if (next_mp != NULL) {
23379 							freemsg(next_mp);
23380 							ire_refrele(ire1);
23381 						}
23382 						ire_refrele(ire);
23383 						TRACE_2(TR_FAC_IP,
23384 						    TR_IP_WPUT_IRE_END,
23385 						    "ip_wput_ire: q %p (%S)",
23386 						    q, "discard MDATA");
23387 						if (conn_outgoing_ill != NULL) {
23388 							ill_refrele(
23389 							    conn_outgoing_ill);
23390 						}
23391 						return;
23392 					}
23393 				}
23394 				if (!next_mp) {
23395 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23396 					    "ip_wput_ire_end: q %p (%S)",
23397 					    q, "last fragmentation");
23398 					ip_wput_ire_fragmentit(mp, ire,
23399 					    zoneid, ipst);
23400 					ire_refrele(ire);
23401 					if (conn_outgoing_ill != NULL)
23402 						ill_refrele(conn_outgoing_ill);
23403 					return;
23404 				}
23405 				ip_wput_ire_fragmentit(mp, ire, zoneid, ipst);
23406 			}
23407 		}
23408 	} else {
23409 nullstq:
23410 		/* A NULL stq means the destination address is local. */
23411 		UPDATE_OB_PKT_COUNT(ire);
23412 		ire->ire_last_used_time = lbolt;
23413 		ASSERT(ire->ire_ipif != NULL);
23414 		if (!next_mp) {
23415 			/*
23416 			 * Is there an "in" and "out" for traffic local
23417 			 * to a host (loopback)?  The code in Solaris doesn't
23418 			 * explicitly draw a line in its code for in vs out,
23419 			 * so we've had to draw a line in the sand: ip_wput_ire
23420 			 * is considered to be the "output" side and
23421 			 * ip_wput_local to be the "input" side.
23422 			 */
23423 			out_ill = ire_to_ill(ire);
23424 
23425 			/*
23426 			 * DTrace this as ip:::send.  A blocked packet will
23427 			 * fire the send probe, but not the receive probe.
23428 			 */
23429 			DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23430 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23431 			    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23432 
23433 			DTRACE_PROBE4(ip4__loopback__out__start,
23434 			    ill_t *, NULL, ill_t *, out_ill,
23435 			    ipha_t *, ipha, mblk_t *, first_mp);
23436 
23437 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23438 			    ipst->ips_ipv4firewall_loopback_out,
23439 			    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23440 
23441 			DTRACE_PROBE1(ip4__loopback__out_end,
23442 			    mblk_t *, first_mp);
23443 
23444 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23445 			    "ip_wput_ire_end: q %p (%S)",
23446 			    q, "local address");
23447 
23448 			if (first_mp != NULL)
23449 				ip_wput_local(q, out_ill, ipha,
23450 				    first_mp, ire, 0, ire->ire_zoneid);
23451 			ire_refrele(ire);
23452 			if (conn_outgoing_ill != NULL)
23453 				ill_refrele(conn_outgoing_ill);
23454 			return;
23455 		}
23456 
23457 		out_ill = ire_to_ill(ire);
23458 
23459 		/*
23460 		 * DTrace this as ip:::send.  A blocked packet will fire the
23461 		 * send probe, but not the receive probe.
23462 		 */
23463 		DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23464 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23465 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23466 
23467 		DTRACE_PROBE4(ip4__loopback__out__start,
23468 		    ill_t *, NULL, ill_t *, out_ill,
23469 		    ipha_t *, ipha, mblk_t *, first_mp);
23470 
23471 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23472 		    ipst->ips_ipv4firewall_loopback_out,
23473 		    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23474 
23475 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23476 
23477 		if (first_mp != NULL)
23478 			ip_wput_local(q, out_ill, ipha,
23479 			    first_mp, ire, 0, ire->ire_zoneid);
23480 	}
23481 next:
23482 	/*
23483 	 * More copies going out to additional interfaces.
23484 	 * ire1 has already been held. We don't need the
23485 	 * "ire" anymore.
23486 	 */
23487 	ire_refrele(ire);
23488 	ire = ire1;
23489 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23490 	mp = next_mp;
23491 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23492 	ill = ire_to_ill(ire);
23493 	first_mp = mp;
23494 	if (ipsec_len != 0) {
23495 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23496 		mp = mp->b_cont;
23497 	}
23498 	dst = ire->ire_addr;
23499 	ipha = (ipha_t *)mp->b_rptr;
23500 	/*
23501 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23502 	 * Restore ipha_ident "no checksum" flag.
23503 	 */
23504 	src = orig_src;
23505 	ipha->ipha_ident = ip_hdr_included;
23506 	goto another;
23507 
23508 #undef	rptr
23509 #undef	Q_TO_INDEX
23510 }
23511 
23512 /*
23513  * Routine to allocate a message that is used to notify the ULP about MDT.
23514  * The caller may provide a pointer to the link-layer MDT capabilities,
23515  * or NULL if MDT is to be disabled on the stream.
23516  */
23517 mblk_t *
23518 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23519 {
23520 	mblk_t *mp;
23521 	ip_mdt_info_t *mdti;
23522 	ill_mdt_capab_t *idst;
23523 
23524 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23525 		DB_TYPE(mp) = M_CTL;
23526 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23527 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23528 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23529 		idst = &(mdti->mdt_capab);
23530 
23531 		/*
23532 		 * If the caller provides us with the capability, copy
23533 		 * it over into our notification message; otherwise
23534 		 * we zero out the capability portion.
23535 		 */
23536 		if (isrc != NULL)
23537 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23538 		else
23539 			bzero((caddr_t)idst, sizeof (*idst));
23540 	}
23541 	return (mp);
23542 }
23543 
23544 /*
23545  * Routine which determines whether MDT can be enabled on the destination
23546  * IRE and IPC combination, and if so, allocates and returns the MDT
23547  * notification mblk that may be used by ULP.  We also check if we need to
23548  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23549  * MDT usage in the past have been lifted.  This gets called during IP
23550  * and ULP binding.
23551  */
23552 mblk_t *
23553 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23554     ill_mdt_capab_t *mdt_cap)
23555 {
23556 	mblk_t *mp;
23557 	boolean_t rc = B_FALSE;
23558 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23559 
23560 	ASSERT(dst_ire != NULL);
23561 	ASSERT(connp != NULL);
23562 	ASSERT(mdt_cap != NULL);
23563 
23564 	/*
23565 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23566 	 * Multidata, which is handled in tcp_multisend().  This
23567 	 * is the reason why we do all these checks here, to ensure
23568 	 * that we don't enable Multidata for the cases which we
23569 	 * can't handle at the moment.
23570 	 */
23571 	do {
23572 		/* Only do TCP at the moment */
23573 		if (connp->conn_ulp != IPPROTO_TCP)
23574 			break;
23575 
23576 		/*
23577 		 * IPsec outbound policy present?  Note that we get here
23578 		 * after calling ipsec_conn_cache_policy() where the global
23579 		 * policy checking is performed.  conn_latch will be
23580 		 * non-NULL as long as there's a policy defined,
23581 		 * i.e. conn_out_enforce_policy may be NULL in such case
23582 		 * when the connection is non-secure, and hence we check
23583 		 * further if the latch refers to an outbound policy.
23584 		 */
23585 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23586 			break;
23587 
23588 		/* CGTP (multiroute) is enabled? */
23589 		if (dst_ire->ire_flags & RTF_MULTIRT)
23590 			break;
23591 
23592 		/* Outbound IPQoS enabled? */
23593 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23594 			/*
23595 			 * In this case, we disable MDT for this and all
23596 			 * future connections going over the interface.
23597 			 */
23598 			mdt_cap->ill_mdt_on = 0;
23599 			break;
23600 		}
23601 
23602 		/* socket option(s) present? */
23603 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23604 			break;
23605 
23606 		rc = B_TRUE;
23607 	/* CONSTCOND */
23608 	} while (0);
23609 
23610 	/* Remember the result */
23611 	connp->conn_mdt_ok = rc;
23612 
23613 	if (!rc)
23614 		return (NULL);
23615 	else if (!mdt_cap->ill_mdt_on) {
23616 		/*
23617 		 * If MDT has been previously turned off in the past, and we
23618 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23619 		 * then enable it for this interface.
23620 		 */
23621 		mdt_cap->ill_mdt_on = 1;
23622 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23623 		    "interface %s\n", ill_name));
23624 	}
23625 
23626 	/* Allocate the MDT info mblk */
23627 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23628 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23629 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23630 		return (NULL);
23631 	}
23632 	return (mp);
23633 }
23634 
23635 /*
23636  * Routine to allocate a message that is used to notify the ULP about LSO.
23637  * The caller may provide a pointer to the link-layer LSO capabilities,
23638  * or NULL if LSO is to be disabled on the stream.
23639  */
23640 mblk_t *
23641 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23642 {
23643 	mblk_t *mp;
23644 	ip_lso_info_t *lsoi;
23645 	ill_lso_capab_t *idst;
23646 
23647 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23648 		DB_TYPE(mp) = M_CTL;
23649 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23650 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23651 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23652 		idst = &(lsoi->lso_capab);
23653 
23654 		/*
23655 		 * If the caller provides us with the capability, copy
23656 		 * it over into our notification message; otherwise
23657 		 * we zero out the capability portion.
23658 		 */
23659 		if (isrc != NULL)
23660 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23661 		else
23662 			bzero((caddr_t)idst, sizeof (*idst));
23663 	}
23664 	return (mp);
23665 }
23666 
23667 /*
23668  * Routine which determines whether LSO can be enabled on the destination
23669  * IRE and IPC combination, and if so, allocates and returns the LSO
23670  * notification mblk that may be used by ULP.  We also check if we need to
23671  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23672  * LSO usage in the past have been lifted.  This gets called during IP
23673  * and ULP binding.
23674  */
23675 mblk_t *
23676 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23677     ill_lso_capab_t *lso_cap)
23678 {
23679 	mblk_t *mp;
23680 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23681 
23682 	ASSERT(dst_ire != NULL);
23683 	ASSERT(connp != NULL);
23684 	ASSERT(lso_cap != NULL);
23685 
23686 	connp->conn_lso_ok = B_TRUE;
23687 
23688 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23689 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23690 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23691 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23692 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23693 		connp->conn_lso_ok = B_FALSE;
23694 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23695 			/*
23696 			 * Disable LSO for this and all future connections going
23697 			 * over the interface.
23698 			 */
23699 			lso_cap->ill_lso_on = 0;
23700 		}
23701 	}
23702 
23703 	if (!connp->conn_lso_ok)
23704 		return (NULL);
23705 	else if (!lso_cap->ill_lso_on) {
23706 		/*
23707 		 * If LSO has been previously turned off in the past, and we
23708 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23709 		 * then enable it for this interface.
23710 		 */
23711 		lso_cap->ill_lso_on = 1;
23712 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23713 		    ill_name));
23714 	}
23715 
23716 	/* Allocate the LSO info mblk */
23717 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23718 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23719 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23720 
23721 	return (mp);
23722 }
23723 
23724 /*
23725  * Create destination address attribute, and fill it with the physical
23726  * destination address and SAP taken from the template DL_UNITDATA_REQ
23727  * message block.
23728  */
23729 boolean_t
23730 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23731 {
23732 	dl_unitdata_req_t *dlurp;
23733 	pattr_t *pa;
23734 	pattrinfo_t pa_info;
23735 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23736 	uint_t das_len, das_off;
23737 
23738 	ASSERT(dlmp != NULL);
23739 
23740 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23741 	das_len = dlurp->dl_dest_addr_length;
23742 	das_off = dlurp->dl_dest_addr_offset;
23743 
23744 	pa_info.type = PATTR_DSTADDRSAP;
23745 	pa_info.len = sizeof (**das) + das_len - 1;
23746 
23747 	/* create and associate the attribute */
23748 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23749 	if (pa != NULL) {
23750 		ASSERT(*das != NULL);
23751 		(*das)->addr_is_group = 0;
23752 		(*das)->addr_len = (uint8_t)das_len;
23753 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23754 	}
23755 
23756 	return (pa != NULL);
23757 }
23758 
23759 /*
23760  * Create hardware checksum attribute and fill it with the values passed.
23761  */
23762 boolean_t
23763 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23764     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23765 {
23766 	pattr_t *pa;
23767 	pattrinfo_t pa_info;
23768 
23769 	ASSERT(mmd != NULL);
23770 
23771 	pa_info.type = PATTR_HCKSUM;
23772 	pa_info.len = sizeof (pattr_hcksum_t);
23773 
23774 	/* create and associate the attribute */
23775 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23776 	if (pa != NULL) {
23777 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23778 
23779 		hck->hcksum_start_offset = start_offset;
23780 		hck->hcksum_stuff_offset = stuff_offset;
23781 		hck->hcksum_end_offset = end_offset;
23782 		hck->hcksum_flags = flags;
23783 	}
23784 	return (pa != NULL);
23785 }
23786 
23787 /*
23788  * Create zerocopy attribute and fill it with the specified flags
23789  */
23790 boolean_t
23791 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23792 {
23793 	pattr_t *pa;
23794 	pattrinfo_t pa_info;
23795 
23796 	ASSERT(mmd != NULL);
23797 	pa_info.type = PATTR_ZCOPY;
23798 	pa_info.len = sizeof (pattr_zcopy_t);
23799 
23800 	/* create and associate the attribute */
23801 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23802 	if (pa != NULL) {
23803 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23804 
23805 		zcopy->zcopy_flags = flags;
23806 	}
23807 	return (pa != NULL);
23808 }
23809 
23810 /*
23811  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23812  * block chain. We could rewrite to handle arbitrary message block chains but
23813  * that would make the code complicated and slow. Right now there three
23814  * restrictions:
23815  *
23816  *   1. The first message block must contain the complete IP header and
23817  *	at least 1 byte of payload data.
23818  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23819  *	so that we can use a single Multidata message.
23820  *   3. No frag must be distributed over two or more message blocks so
23821  *	that we don't need more than two packet descriptors per frag.
23822  *
23823  * The above restrictions allow us to support userland applications (which
23824  * will send down a single message block) and NFS over UDP (which will
23825  * send down a chain of at most three message blocks).
23826  *
23827  * We also don't use MDT for payloads with less than or equal to
23828  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23829  */
23830 boolean_t
23831 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23832 {
23833 	int	blocks;
23834 	ssize_t	total, missing, size;
23835 
23836 	ASSERT(mp != NULL);
23837 	ASSERT(hdr_len > 0);
23838 
23839 	size = MBLKL(mp) - hdr_len;
23840 	if (size <= 0)
23841 		return (B_FALSE);
23842 
23843 	/* The first mblk contains the header and some payload. */
23844 	blocks = 1;
23845 	total = size;
23846 	size %= len;
23847 	missing = (size == 0) ? 0 : (len - size);
23848 	mp = mp->b_cont;
23849 
23850 	while (mp != NULL) {
23851 		/*
23852 		 * Give up if we encounter a zero length message block.
23853 		 * In practice, this should rarely happen and therefore
23854 		 * not worth the trouble of freeing and re-linking the
23855 		 * mblk from the chain to handle such case.
23856 		 */
23857 		if ((size = MBLKL(mp)) == 0)
23858 			return (B_FALSE);
23859 
23860 		/* Too many payload buffers for a single Multidata message? */
23861 		if (++blocks > MULTIDATA_MAX_PBUFS)
23862 			return (B_FALSE);
23863 
23864 		total += size;
23865 		/* Is a frag distributed over two or more message blocks? */
23866 		if (missing > size)
23867 			return (B_FALSE);
23868 		size -= missing;
23869 
23870 		size %= len;
23871 		missing = (size == 0) ? 0 : (len - size);
23872 
23873 		mp = mp->b_cont;
23874 	}
23875 
23876 	return (total > ip_wput_frag_mdt_min);
23877 }
23878 
23879 /*
23880  * Outbound IPv4 fragmentation routine using MDT.
23881  */
23882 static void
23883 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23884     uint32_t frag_flag, int offset)
23885 {
23886 	ipha_t		*ipha_orig;
23887 	int		i1, ip_data_end;
23888 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23889 	mblk_t		*hdr_mp, *md_mp = NULL;
23890 	unsigned char	*hdr_ptr, *pld_ptr;
23891 	multidata_t	*mmd;
23892 	ip_pdescinfo_t	pdi;
23893 	ill_t		*ill;
23894 	ip_stack_t	*ipst = ire->ire_ipst;
23895 
23896 	ASSERT(DB_TYPE(mp) == M_DATA);
23897 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23898 
23899 	ill = ire_to_ill(ire);
23900 	ASSERT(ill != NULL);
23901 
23902 	ipha_orig = (ipha_t *)mp->b_rptr;
23903 	mp->b_rptr += sizeof (ipha_t);
23904 
23905 	/* Calculate how many packets we will send out */
23906 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23907 	pkts = (i1 + len - 1) / len;
23908 	ASSERT(pkts > 1);
23909 
23910 	/* Allocate a message block which will hold all the IP Headers. */
23911 	wroff = ipst->ips_ip_wroff_extra;
23912 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23913 
23914 	i1 = pkts * hdr_chunk_len;
23915 	/*
23916 	 * Create the header buffer, Multidata and destination address
23917 	 * and SAP attribute that should be associated with it.
23918 	 */
23919 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23920 	    ((hdr_mp->b_wptr += i1),
23921 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23922 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23923 		freemsg(mp);
23924 		if (md_mp == NULL) {
23925 			freemsg(hdr_mp);
23926 		} else {
23927 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
23928 			freemsg(md_mp);
23929 		}
23930 		IP_STAT(ipst, ip_frag_mdt_allocfail);
23931 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
23932 		return;
23933 	}
23934 	IP_STAT(ipst, ip_frag_mdt_allocd);
23935 
23936 	/*
23937 	 * Add a payload buffer to the Multidata; this operation must not
23938 	 * fail, or otherwise our logic in this routine is broken.  There
23939 	 * is no memory allocation done by the routine, so any returned
23940 	 * failure simply tells us that we've done something wrong.
23941 	 *
23942 	 * A failure tells us that either we're adding the same payload
23943 	 * buffer more than once, or we're trying to add more buffers than
23944 	 * allowed.  None of the above cases should happen, and we panic
23945 	 * because either there's horrible heap corruption, and/or
23946 	 * programming mistake.
23947 	 */
23948 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23949 		goto pbuf_panic;
23950 
23951 	hdr_ptr = hdr_mp->b_rptr;
23952 	pld_ptr = mp->b_rptr;
23953 
23954 	/* Establish the ending byte offset, based on the starting offset. */
23955 	offset <<= 3;
23956 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23957 	    IP_SIMPLE_HDR_LENGTH;
23958 
23959 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23960 
23961 	while (pld_ptr < mp->b_wptr) {
23962 		ipha_t		*ipha;
23963 		uint16_t	offset_and_flags;
23964 		uint16_t	ip_len;
23965 		int		error;
23966 
23967 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23968 		ipha = (ipha_t *)(hdr_ptr + wroff);
23969 		ASSERT(OK_32PTR(ipha));
23970 		*ipha = *ipha_orig;
23971 
23972 		if (ip_data_end - offset > len) {
23973 			offset_and_flags = IPH_MF;
23974 		} else {
23975 			/*
23976 			 * Last frag. Set len to the length of this last piece.
23977 			 */
23978 			len = ip_data_end - offset;
23979 			/* A frag of a frag might have IPH_MF non-zero */
23980 			offset_and_flags =
23981 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23982 			    IPH_MF;
23983 		}
23984 		offset_and_flags |= (uint16_t)(offset >> 3);
23985 		offset_and_flags |= (uint16_t)frag_flag;
23986 		/* Store the offset and flags in the IP header. */
23987 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23988 
23989 		/* Store the length in the IP header. */
23990 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23991 		ipha->ipha_length = htons(ip_len);
23992 
23993 		/*
23994 		 * Set the IP header checksum.  Note that mp is just
23995 		 * the header, so this is easy to pass to ip_csum.
23996 		 */
23997 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23998 
23999 		DTRACE_IP7(send, mblk_t *, md_mp, conn_t *, NULL, void_ip_t *,
24000 		    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *,
24001 		    NULL, int, 0);
24002 
24003 		/*
24004 		 * Record offset and size of header and data of the next packet
24005 		 * in the multidata message.
24006 		 */
24007 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
24008 		PDESC_PLD_INIT(&pdi);
24009 		i1 = MIN(mp->b_wptr - pld_ptr, len);
24010 		ASSERT(i1 > 0);
24011 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
24012 		if (i1 == len) {
24013 			pld_ptr += len;
24014 		} else {
24015 			i1 = len - i1;
24016 			mp = mp->b_cont;
24017 			ASSERT(mp != NULL);
24018 			ASSERT(MBLKL(mp) >= i1);
24019 			/*
24020 			 * Attach the next payload message block to the
24021 			 * multidata message.
24022 			 */
24023 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24024 				goto pbuf_panic;
24025 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
24026 			pld_ptr = mp->b_rptr + i1;
24027 		}
24028 
24029 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
24030 		    KM_NOSLEEP)) == NULL) {
24031 			/*
24032 			 * Any failure other than ENOMEM indicates that we
24033 			 * have passed in invalid pdesc info or parameters
24034 			 * to mmd_addpdesc, which must not happen.
24035 			 *
24036 			 * EINVAL is a result of failure on boundary checks
24037 			 * against the pdesc info contents.  It should not
24038 			 * happen, and we panic because either there's
24039 			 * horrible heap corruption, and/or programming
24040 			 * mistake.
24041 			 */
24042 			if (error != ENOMEM) {
24043 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
24044 				    "pdesc logic error detected for "
24045 				    "mmd %p pinfo %p (%d)\n",
24046 				    (void *)mmd, (void *)&pdi, error);
24047 				/* NOTREACHED */
24048 			}
24049 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
24050 			/* Free unattached payload message blocks as well */
24051 			md_mp->b_cont = mp->b_cont;
24052 			goto free_mmd;
24053 		}
24054 
24055 		/* Advance fragment offset. */
24056 		offset += len;
24057 
24058 		/* Advance to location for next header in the buffer. */
24059 		hdr_ptr += hdr_chunk_len;
24060 
24061 		/* Did we reach the next payload message block? */
24062 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
24063 			mp = mp->b_cont;
24064 			/*
24065 			 * Attach the next message block with payload
24066 			 * data to the multidata message.
24067 			 */
24068 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24069 				goto pbuf_panic;
24070 			pld_ptr = mp->b_rptr;
24071 		}
24072 	}
24073 
24074 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
24075 	ASSERT(mp->b_wptr == pld_ptr);
24076 
24077 	/* Update IP statistics */
24078 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
24079 
24080 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
24081 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
24082 
24083 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
24084 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
24085 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
24086 
24087 	if (pkt_type == OB_PKT) {
24088 		ire->ire_ob_pkt_count += pkts;
24089 		if (ire->ire_ipif != NULL)
24090 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
24091 	} else {
24092 		/* The type is IB_PKT in the forwarding path. */
24093 		ire->ire_ib_pkt_count += pkts;
24094 		ASSERT(!IRE_IS_LOCAL(ire));
24095 		if (ire->ire_type & IRE_BROADCAST) {
24096 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
24097 		} else {
24098 			UPDATE_MIB(ill->ill_ip_mib,
24099 			    ipIfStatsHCOutForwDatagrams, pkts);
24100 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
24101 		}
24102 	}
24103 	ire->ire_last_used_time = lbolt;
24104 	/* Send it down */
24105 	putnext(ire->ire_stq, md_mp);
24106 	return;
24107 
24108 pbuf_panic:
24109 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
24110 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
24111 	    pbuf_idx);
24112 	/* NOTREACHED */
24113 }
24114 
24115 /*
24116  * Outbound IP fragmentation routine.
24117  *
24118  * NOTE : This routine does not ire_refrele the ire that is passed in
24119  * as the argument.
24120  */
24121 static void
24122 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
24123     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst)
24124 {
24125 	int		i1;
24126 	mblk_t		*ll_hdr_mp;
24127 	int 		ll_hdr_len;
24128 	int		hdr_len;
24129 	mblk_t		*hdr_mp;
24130 	ipha_t		*ipha;
24131 	int		ip_data_end;
24132 	int		len;
24133 	mblk_t		*mp = mp_orig, *mp1;
24134 	int		offset;
24135 	queue_t		*q;
24136 	uint32_t	v_hlen_tos_len;
24137 	mblk_t		*first_mp;
24138 	boolean_t	mctl_present;
24139 	ill_t		*ill;
24140 	ill_t		*out_ill;
24141 	mblk_t		*xmit_mp;
24142 	mblk_t		*carve_mp;
24143 	ire_t		*ire1 = NULL;
24144 	ire_t		*save_ire = NULL;
24145 	mblk_t  	*next_mp = NULL;
24146 	boolean_t	last_frag = B_FALSE;
24147 	boolean_t	multirt_send = B_FALSE;
24148 	ire_t		*first_ire = NULL;
24149 	irb_t		*irb = NULL;
24150 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24151 
24152 	ill = ire_to_ill(ire);
24153 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24154 
24155 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24156 
24157 	if (max_frag == 0) {
24158 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24159 		    " -  dropping packet\n"));
24160 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24161 		freemsg(mp);
24162 		return;
24163 	}
24164 
24165 	/*
24166 	 * IPsec does not allow hw accelerated packets to be fragmented
24167 	 * This check is made in ip_wput_ipsec_out prior to coming here
24168 	 * via ip_wput_ire_fragmentit.
24169 	 *
24170 	 * If at this point we have an ire whose ARP request has not
24171 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24172 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24173 	 * This packet and all fragmentable packets for this ire will
24174 	 * continue to get dropped while ire_nce->nce_state remains in
24175 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24176 	 * ND_REACHABLE, all subsquent large packets for this ire will
24177 	 * get fragemented and sent out by this function.
24178 	 */
24179 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24180 		/* If nce_state is ND_INITIAL, trigger ARP query */
24181 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
24182 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24183 		    " -  dropping packet\n"));
24184 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24185 		freemsg(mp);
24186 		return;
24187 	}
24188 
24189 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24190 	    "ip_wput_frag_start:");
24191 
24192 	if (mp->b_datap->db_type == M_CTL) {
24193 		first_mp = mp;
24194 		mp_orig = mp = mp->b_cont;
24195 		mctl_present = B_TRUE;
24196 	} else {
24197 		first_mp = mp;
24198 		mctl_present = B_FALSE;
24199 	}
24200 
24201 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24202 	ipha = (ipha_t *)mp->b_rptr;
24203 
24204 	/*
24205 	 * If the Don't Fragment flag is on, generate an ICMP destination
24206 	 * unreachable, fragmentation needed.
24207 	 */
24208 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24209 	if (offset & IPH_DF) {
24210 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24211 		if (is_system_labeled()) {
24212 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24213 			    ire->ire_max_frag - max_frag, AF_INET);
24214 		}
24215 		/*
24216 		 * Need to compute hdr checksum if called from ip_wput_ire.
24217 		 * Note that ip_rput_forward verifies the checksum before
24218 		 * calling this routine so in that case this is a noop.
24219 		 */
24220 		ipha->ipha_hdr_checksum = 0;
24221 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24222 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24223 		    ipst);
24224 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24225 		    "ip_wput_frag_end:(%S)",
24226 		    "don't fragment");
24227 		return;
24228 	}
24229 	/*
24230 	 * Labeled systems adjust max_frag if they add a label
24231 	 * to send the correct path mtu.  We need the real mtu since we
24232 	 * are fragmenting the packet after label adjustment.
24233 	 */
24234 	if (is_system_labeled())
24235 		max_frag = ire->ire_max_frag;
24236 	if (mctl_present)
24237 		freeb(first_mp);
24238 	/*
24239 	 * Establish the starting offset.  May not be zero if we are fragging
24240 	 * a fragment that is being forwarded.
24241 	 */
24242 	offset = offset & IPH_OFFSET;
24243 
24244 	/* TODO why is this test needed? */
24245 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24246 	if (((max_frag - LENGTH) & ~7) < 8) {
24247 		/* TODO: notify ulp somehow */
24248 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24249 		freemsg(mp);
24250 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24251 		    "ip_wput_frag_end:(%S)",
24252 		    "len < 8");
24253 		return;
24254 	}
24255 
24256 	hdr_len = (V_HLEN & 0xF) << 2;
24257 
24258 	ipha->ipha_hdr_checksum = 0;
24259 
24260 	/*
24261 	 * Establish the number of bytes maximum per frag, after putting
24262 	 * in the header.
24263 	 */
24264 	len = (max_frag - hdr_len) & ~7;
24265 
24266 	/* Check if we can use MDT to send out the frags. */
24267 	ASSERT(!IRE_IS_LOCAL(ire));
24268 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24269 	    ipst->ips_ip_multidata_outbound &&
24270 	    !(ire->ire_flags & RTF_MULTIRT) &&
24271 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24272 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24273 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24274 		ASSERT(ill->ill_mdt_capab != NULL);
24275 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24276 			/*
24277 			 * If MDT has been previously turned off in the past,
24278 			 * and we currently can do MDT (due to IPQoS policy
24279 			 * removal, etc.) then enable it for this interface.
24280 			 */
24281 			ill->ill_mdt_capab->ill_mdt_on = 1;
24282 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24283 			    ill->ill_name));
24284 		}
24285 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24286 		    offset);
24287 		return;
24288 	}
24289 
24290 	/* Get a copy of the header for the trailing frags */
24291 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst);
24292 	if (!hdr_mp) {
24293 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24294 		freemsg(mp);
24295 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24296 		    "ip_wput_frag_end:(%S)",
24297 		    "couldn't copy hdr");
24298 		return;
24299 	}
24300 	if (DB_CRED(mp) != NULL)
24301 		mblk_setcred(hdr_mp, DB_CRED(mp));
24302 
24303 	/* Store the starting offset, with the MoreFrags flag. */
24304 	i1 = offset | IPH_MF | frag_flag;
24305 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24306 
24307 	/* Establish the ending byte offset, based on the starting offset. */
24308 	offset <<= 3;
24309 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24310 
24311 	/* Store the length of the first fragment in the IP header. */
24312 	i1 = len + hdr_len;
24313 	ASSERT(i1 <= IP_MAXPACKET);
24314 	ipha->ipha_length = htons((uint16_t)i1);
24315 
24316 	/*
24317 	 * Compute the IP header checksum for the first frag.  We have to
24318 	 * watch out that we stop at the end of the header.
24319 	 */
24320 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24321 
24322 	/*
24323 	 * Now carve off the first frag.  Note that this will include the
24324 	 * original IP header.
24325 	 */
24326 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24327 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24328 		freeb(hdr_mp);
24329 		freemsg(mp_orig);
24330 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24331 		    "ip_wput_frag_end:(%S)",
24332 		    "couldn't carve first");
24333 		return;
24334 	}
24335 
24336 	/*
24337 	 * Multirouting case. Each fragment is replicated
24338 	 * via all non-condemned RTF_MULTIRT routes
24339 	 * currently resolved.
24340 	 * We ensure that first_ire is the first RTF_MULTIRT
24341 	 * ire in the bucket.
24342 	 */
24343 	if (ire->ire_flags & RTF_MULTIRT) {
24344 		irb = ire->ire_bucket;
24345 		ASSERT(irb != NULL);
24346 
24347 		multirt_send = B_TRUE;
24348 
24349 		/* Make sure we do not omit any multiroute ire. */
24350 		IRB_REFHOLD(irb);
24351 		for (first_ire = irb->irb_ire;
24352 		    first_ire != NULL;
24353 		    first_ire = first_ire->ire_next) {
24354 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24355 			    (first_ire->ire_addr == ire->ire_addr) &&
24356 			    !(first_ire->ire_marks &
24357 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
24358 				break;
24359 			}
24360 		}
24361 
24362 		if (first_ire != NULL) {
24363 			if (first_ire != ire) {
24364 				IRE_REFHOLD(first_ire);
24365 				/*
24366 				 * Do not release the ire passed in
24367 				 * as the argument.
24368 				 */
24369 				ire = first_ire;
24370 			} else {
24371 				first_ire = NULL;
24372 			}
24373 		}
24374 		IRB_REFRELE(irb);
24375 
24376 		/*
24377 		 * Save the first ire; we will need to restore it
24378 		 * for the trailing frags.
24379 		 * We REFHOLD save_ire, as each iterated ire will be
24380 		 * REFRELEd.
24381 		 */
24382 		save_ire = ire;
24383 		IRE_REFHOLD(save_ire);
24384 	}
24385 
24386 	/*
24387 	 * First fragment emission loop.
24388 	 * In most cases, the emission loop below is entered only
24389 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24390 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24391 	 * bucket, and send the fragment through all crossed
24392 	 * RTF_MULTIRT routes.
24393 	 */
24394 	do {
24395 		if (ire->ire_flags & RTF_MULTIRT) {
24396 			/*
24397 			 * We are in a multiple send case, need to get
24398 			 * the next ire and make a copy of the packet.
24399 			 * ire1 holds here the next ire to process in the
24400 			 * bucket. If multirouting is expected,
24401 			 * any non-RTF_MULTIRT ire that has the
24402 			 * right destination address is ignored.
24403 			 *
24404 			 * We have to take into account the MTU of
24405 			 * each walked ire. max_frag is set by the
24406 			 * the caller and generally refers to
24407 			 * the primary ire entry. Here we ensure that
24408 			 * no route with a lower MTU will be used, as
24409 			 * fragments are carved once for all ires,
24410 			 * then replicated.
24411 			 */
24412 			ASSERT(irb != NULL);
24413 			IRB_REFHOLD(irb);
24414 			for (ire1 = ire->ire_next;
24415 			    ire1 != NULL;
24416 			    ire1 = ire1->ire_next) {
24417 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24418 					continue;
24419 				if (ire1->ire_addr != ire->ire_addr)
24420 					continue;
24421 				if (ire1->ire_marks &
24422 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24423 					continue;
24424 				/*
24425 				 * Ensure we do not exceed the MTU
24426 				 * of the next route.
24427 				 */
24428 				if (ire1->ire_max_frag < max_frag) {
24429 					ip_multirt_bad_mtu(ire1, max_frag);
24430 					continue;
24431 				}
24432 
24433 				/* Got one. */
24434 				IRE_REFHOLD(ire1);
24435 				break;
24436 			}
24437 			IRB_REFRELE(irb);
24438 
24439 			if (ire1 != NULL) {
24440 				next_mp = copyb(mp);
24441 				if ((next_mp == NULL) ||
24442 				    ((mp->b_cont != NULL) &&
24443 				    ((next_mp->b_cont =
24444 				    dupmsg(mp->b_cont)) == NULL))) {
24445 					freemsg(next_mp);
24446 					next_mp = NULL;
24447 					ire_refrele(ire1);
24448 					ire1 = NULL;
24449 				}
24450 			}
24451 
24452 			/* Last multiroute ire; don't loop anymore. */
24453 			if (ire1 == NULL) {
24454 				multirt_send = B_FALSE;
24455 			}
24456 		}
24457 
24458 		ll_hdr_len = 0;
24459 		LOCK_IRE_FP_MP(ire);
24460 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24461 		if (ll_hdr_mp != NULL) {
24462 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24463 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24464 		} else {
24465 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24466 		}
24467 
24468 		/* If there is a transmit header, get a copy for this frag. */
24469 		/*
24470 		 * TODO: should check db_ref before calling ip_carve_mp since
24471 		 * it might give us a dup.
24472 		 */
24473 		if (!ll_hdr_mp) {
24474 			/* No xmit header. */
24475 			xmit_mp = mp;
24476 
24477 		/* We have a link-layer header that can fit in our mblk. */
24478 		} else if (mp->b_datap->db_ref == 1 &&
24479 		    ll_hdr_len != 0 &&
24480 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24481 			/* M_DATA fastpath */
24482 			mp->b_rptr -= ll_hdr_len;
24483 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24484 			xmit_mp = mp;
24485 
24486 		/* Corner case if copyb has failed */
24487 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24488 			UNLOCK_IRE_FP_MP(ire);
24489 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24490 			freeb(hdr_mp);
24491 			freemsg(mp);
24492 			freemsg(mp_orig);
24493 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24494 			    "ip_wput_frag_end:(%S)",
24495 			    "discard");
24496 
24497 			if (multirt_send) {
24498 				ASSERT(ire1);
24499 				ASSERT(next_mp);
24500 
24501 				freemsg(next_mp);
24502 				ire_refrele(ire1);
24503 			}
24504 			if (save_ire != NULL)
24505 				IRE_REFRELE(save_ire);
24506 
24507 			if (first_ire != NULL)
24508 				ire_refrele(first_ire);
24509 			return;
24510 
24511 		/*
24512 		 * Case of res_mp OR the fastpath mp can't fit
24513 		 * in the mblk
24514 		 */
24515 		} else {
24516 			xmit_mp->b_cont = mp;
24517 			if (DB_CRED(mp) != NULL)
24518 				mblk_setcred(xmit_mp, DB_CRED(mp));
24519 			/*
24520 			 * Get priority marking, if any.
24521 			 * We propagate the CoS marking from the
24522 			 * original packet that went to QoS processing
24523 			 * in ip_wput_ire to the newly carved mp.
24524 			 */
24525 			if (DB_TYPE(xmit_mp) == M_DATA)
24526 				xmit_mp->b_band = mp->b_band;
24527 		}
24528 		UNLOCK_IRE_FP_MP(ire);
24529 
24530 		q = ire->ire_stq;
24531 		out_ill = (ill_t *)q->q_ptr;
24532 
24533 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24534 
24535 		DTRACE_PROBE4(ip4__physical__out__start,
24536 		    ill_t *, NULL, ill_t *, out_ill,
24537 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24538 
24539 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24540 		    ipst->ips_ipv4firewall_physical_out,
24541 		    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24542 
24543 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24544 
24545 		if (xmit_mp != NULL) {
24546 			DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *, NULL,
24547 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
24548 			    ipha_t *, ipha, ip6_t *, NULL, int, 0);
24549 
24550 			putnext(q, xmit_mp);
24551 
24552 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24553 			UPDATE_MIB(out_ill->ill_ip_mib,
24554 			    ipIfStatsHCOutOctets, i1);
24555 
24556 			if (pkt_type != OB_PKT) {
24557 				/*
24558 				 * Update the packet count and MIB stats
24559 				 * of trailing RTF_MULTIRT ires.
24560 				 */
24561 				UPDATE_OB_PKT_COUNT(ire);
24562 				BUMP_MIB(out_ill->ill_ip_mib,
24563 				    ipIfStatsOutFragReqds);
24564 			}
24565 		}
24566 
24567 		if (multirt_send) {
24568 			/*
24569 			 * We are in a multiple send case; look for
24570 			 * the next ire and re-enter the loop.
24571 			 */
24572 			ASSERT(ire1);
24573 			ASSERT(next_mp);
24574 			/* REFRELE the current ire before looping */
24575 			ire_refrele(ire);
24576 			ire = ire1;
24577 			ire1 = NULL;
24578 			mp = next_mp;
24579 			next_mp = NULL;
24580 		}
24581 	} while (multirt_send);
24582 
24583 	ASSERT(ire1 == NULL);
24584 
24585 	/* Restore the original ire; we need it for the trailing frags */
24586 	if (save_ire != NULL) {
24587 		/* REFRELE the last iterated ire */
24588 		ire_refrele(ire);
24589 		/* save_ire has been REFHOLDed */
24590 		ire = save_ire;
24591 		save_ire = NULL;
24592 		q = ire->ire_stq;
24593 	}
24594 
24595 	if (pkt_type == OB_PKT) {
24596 		UPDATE_OB_PKT_COUNT(ire);
24597 	} else {
24598 		out_ill = (ill_t *)q->q_ptr;
24599 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24600 		UPDATE_IB_PKT_COUNT(ire);
24601 	}
24602 
24603 	/* Advance the offset to the second frag starting point. */
24604 	offset += len;
24605 	/*
24606 	 * Update hdr_len from the copied header - there might be less options
24607 	 * in the later fragments.
24608 	 */
24609 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24610 	/* Loop until done. */
24611 	for (;;) {
24612 		uint16_t	offset_and_flags;
24613 		uint16_t	ip_len;
24614 
24615 		if (ip_data_end - offset > len) {
24616 			/*
24617 			 * Carve off the appropriate amount from the original
24618 			 * datagram.
24619 			 */
24620 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24621 				mp = NULL;
24622 				break;
24623 			}
24624 			/*
24625 			 * More frags after this one.  Get another copy
24626 			 * of the header.
24627 			 */
24628 			if (carve_mp->b_datap->db_ref == 1 &&
24629 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24630 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24631 				/* Inline IP header */
24632 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24633 				    hdr_mp->b_rptr;
24634 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24635 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24636 				mp = carve_mp;
24637 			} else {
24638 				if (!(mp = copyb(hdr_mp))) {
24639 					freemsg(carve_mp);
24640 					break;
24641 				}
24642 				/* Get priority marking, if any. */
24643 				mp->b_band = carve_mp->b_band;
24644 				mp->b_cont = carve_mp;
24645 			}
24646 			ipha = (ipha_t *)mp->b_rptr;
24647 			offset_and_flags = IPH_MF;
24648 		} else {
24649 			/*
24650 			 * Last frag.  Consume the header. Set len to
24651 			 * the length of this last piece.
24652 			 */
24653 			len = ip_data_end - offset;
24654 
24655 			/*
24656 			 * Carve off the appropriate amount from the original
24657 			 * datagram.
24658 			 */
24659 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24660 				mp = NULL;
24661 				break;
24662 			}
24663 			if (carve_mp->b_datap->db_ref == 1 &&
24664 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24665 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24666 				/* Inline IP header */
24667 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24668 				    hdr_mp->b_rptr;
24669 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24670 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24671 				mp = carve_mp;
24672 				freeb(hdr_mp);
24673 				hdr_mp = mp;
24674 			} else {
24675 				mp = hdr_mp;
24676 				/* Get priority marking, if any. */
24677 				mp->b_band = carve_mp->b_band;
24678 				mp->b_cont = carve_mp;
24679 			}
24680 			ipha = (ipha_t *)mp->b_rptr;
24681 			/* A frag of a frag might have IPH_MF non-zero */
24682 			offset_and_flags =
24683 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24684 			    IPH_MF;
24685 		}
24686 		offset_and_flags |= (uint16_t)(offset >> 3);
24687 		offset_and_flags |= (uint16_t)frag_flag;
24688 		/* Store the offset and flags in the IP header. */
24689 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24690 
24691 		/* Store the length in the IP header. */
24692 		ip_len = (uint16_t)(len + hdr_len);
24693 		ipha->ipha_length = htons(ip_len);
24694 
24695 		/*
24696 		 * Set the IP header checksum.	Note that mp is just
24697 		 * the header, so this is easy to pass to ip_csum.
24698 		 */
24699 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24700 
24701 		/* Attach a transmit header, if any, and ship it. */
24702 		if (pkt_type == OB_PKT) {
24703 			UPDATE_OB_PKT_COUNT(ire);
24704 		} else {
24705 			out_ill = (ill_t *)q->q_ptr;
24706 			BUMP_MIB(out_ill->ill_ip_mib,
24707 			    ipIfStatsHCOutForwDatagrams);
24708 			UPDATE_IB_PKT_COUNT(ire);
24709 		}
24710 
24711 		if (ire->ire_flags & RTF_MULTIRT) {
24712 			irb = ire->ire_bucket;
24713 			ASSERT(irb != NULL);
24714 
24715 			multirt_send = B_TRUE;
24716 
24717 			/*
24718 			 * Save the original ire; we will need to restore it
24719 			 * for the tailing frags.
24720 			 */
24721 			save_ire = ire;
24722 			IRE_REFHOLD(save_ire);
24723 		}
24724 		/*
24725 		 * Emission loop for this fragment, similar
24726 		 * to what is done for the first fragment.
24727 		 */
24728 		do {
24729 			if (multirt_send) {
24730 				/*
24731 				 * We are in a multiple send case, need to get
24732 				 * the next ire and make a copy of the packet.
24733 				 */
24734 				ASSERT(irb != NULL);
24735 				IRB_REFHOLD(irb);
24736 				for (ire1 = ire->ire_next;
24737 				    ire1 != NULL;
24738 				    ire1 = ire1->ire_next) {
24739 					if (!(ire1->ire_flags & RTF_MULTIRT))
24740 						continue;
24741 					if (ire1->ire_addr != ire->ire_addr)
24742 						continue;
24743 					if (ire1->ire_marks &
24744 					    (IRE_MARK_CONDEMNED|
24745 					    IRE_MARK_HIDDEN)) {
24746 						continue;
24747 					}
24748 					/*
24749 					 * Ensure we do not exceed the MTU
24750 					 * of the next route.
24751 					 */
24752 					if (ire1->ire_max_frag < max_frag) {
24753 						ip_multirt_bad_mtu(ire1,
24754 						    max_frag);
24755 						continue;
24756 					}
24757 
24758 					/* Got one. */
24759 					IRE_REFHOLD(ire1);
24760 					break;
24761 				}
24762 				IRB_REFRELE(irb);
24763 
24764 				if (ire1 != NULL) {
24765 					next_mp = copyb(mp);
24766 					if ((next_mp == NULL) ||
24767 					    ((mp->b_cont != NULL) &&
24768 					    ((next_mp->b_cont =
24769 					    dupmsg(mp->b_cont)) == NULL))) {
24770 						freemsg(next_mp);
24771 						next_mp = NULL;
24772 						ire_refrele(ire1);
24773 						ire1 = NULL;
24774 					}
24775 				}
24776 
24777 				/* Last multiroute ire; don't loop anymore. */
24778 				if (ire1 == NULL) {
24779 					multirt_send = B_FALSE;
24780 				}
24781 			}
24782 
24783 			/* Update transmit header */
24784 			ll_hdr_len = 0;
24785 			LOCK_IRE_FP_MP(ire);
24786 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24787 			if (ll_hdr_mp != NULL) {
24788 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24789 				ll_hdr_len = MBLKL(ll_hdr_mp);
24790 			} else {
24791 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24792 			}
24793 
24794 			if (!ll_hdr_mp) {
24795 				xmit_mp = mp;
24796 
24797 			/*
24798 			 * We have link-layer header that can fit in
24799 			 * our mblk.
24800 			 */
24801 			} else if (mp->b_datap->db_ref == 1 &&
24802 			    ll_hdr_len != 0 &&
24803 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24804 				/* M_DATA fastpath */
24805 				mp->b_rptr -= ll_hdr_len;
24806 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24807 				    ll_hdr_len);
24808 				xmit_mp = mp;
24809 
24810 			/*
24811 			 * Case of res_mp OR the fastpath mp can't fit
24812 			 * in the mblk
24813 			 */
24814 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24815 				xmit_mp->b_cont = mp;
24816 				if (DB_CRED(mp) != NULL)
24817 					mblk_setcred(xmit_mp, DB_CRED(mp));
24818 				/* Get priority marking, if any. */
24819 				if (DB_TYPE(xmit_mp) == M_DATA)
24820 					xmit_mp->b_band = mp->b_band;
24821 
24822 			/* Corner case if copyb failed */
24823 			} else {
24824 				/*
24825 				 * Exit both the replication and
24826 				 * fragmentation loops.
24827 				 */
24828 				UNLOCK_IRE_FP_MP(ire);
24829 				goto drop_pkt;
24830 			}
24831 			UNLOCK_IRE_FP_MP(ire);
24832 
24833 			mp1 = mp;
24834 			out_ill = (ill_t *)q->q_ptr;
24835 
24836 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24837 
24838 			DTRACE_PROBE4(ip4__physical__out__start,
24839 			    ill_t *, NULL, ill_t *, out_ill,
24840 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24841 
24842 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24843 			    ipst->ips_ipv4firewall_physical_out,
24844 			    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24845 
24846 			DTRACE_PROBE1(ip4__physical__out__end,
24847 			    mblk_t *, xmit_mp);
24848 
24849 			if (mp != mp1 && hdr_mp == mp1)
24850 				hdr_mp = mp;
24851 			if (mp != mp1 && mp_orig == mp1)
24852 				mp_orig = mp;
24853 
24854 			if (xmit_mp != NULL) {
24855 				DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *,
24856 				    NULL, void_ip_t *, ipha,
24857 				    __dtrace_ipsr_ill_t *, out_ill, ipha_t *,
24858 				    ipha, ip6_t *, NULL, int, 0);
24859 
24860 				putnext(q, xmit_mp);
24861 
24862 				BUMP_MIB(out_ill->ill_ip_mib,
24863 				    ipIfStatsHCOutTransmits);
24864 				UPDATE_MIB(out_ill->ill_ip_mib,
24865 				    ipIfStatsHCOutOctets, ip_len);
24866 
24867 				if (pkt_type != OB_PKT) {
24868 					/*
24869 					 * Update the packet count of trailing
24870 					 * RTF_MULTIRT ires.
24871 					 */
24872 					UPDATE_OB_PKT_COUNT(ire);
24873 				}
24874 			}
24875 
24876 			/* All done if we just consumed the hdr_mp. */
24877 			if (mp == hdr_mp) {
24878 				last_frag = B_TRUE;
24879 				BUMP_MIB(out_ill->ill_ip_mib,
24880 				    ipIfStatsOutFragOKs);
24881 			}
24882 
24883 			if (multirt_send) {
24884 				/*
24885 				 * We are in a multiple send case; look for
24886 				 * the next ire and re-enter the loop.
24887 				 */
24888 				ASSERT(ire1);
24889 				ASSERT(next_mp);
24890 				/* REFRELE the current ire before looping */
24891 				ire_refrele(ire);
24892 				ire = ire1;
24893 				ire1 = NULL;
24894 				q = ire->ire_stq;
24895 				mp = next_mp;
24896 				next_mp = NULL;
24897 			}
24898 		} while (multirt_send);
24899 		/*
24900 		 * Restore the original ire; we need it for the
24901 		 * trailing frags
24902 		 */
24903 		if (save_ire != NULL) {
24904 			ASSERT(ire1 == NULL);
24905 			/* REFRELE the last iterated ire */
24906 			ire_refrele(ire);
24907 			/* save_ire has been REFHOLDed */
24908 			ire = save_ire;
24909 			q = ire->ire_stq;
24910 			save_ire = NULL;
24911 		}
24912 
24913 		if (last_frag) {
24914 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24915 			    "ip_wput_frag_end:(%S)",
24916 			    "consumed hdr_mp");
24917 
24918 			if (first_ire != NULL)
24919 				ire_refrele(first_ire);
24920 			return;
24921 		}
24922 		/* Otherwise, advance and loop. */
24923 		offset += len;
24924 	}
24925 
24926 drop_pkt:
24927 	/* Clean up following allocation failure. */
24928 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24929 	freemsg(mp);
24930 	if (mp != hdr_mp)
24931 		freeb(hdr_mp);
24932 	if (mp != mp_orig)
24933 		freemsg(mp_orig);
24934 
24935 	if (save_ire != NULL)
24936 		IRE_REFRELE(save_ire);
24937 	if (first_ire != NULL)
24938 		ire_refrele(first_ire);
24939 
24940 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24941 	    "ip_wput_frag_end:(%S)",
24942 	    "end--alloc failure");
24943 }
24944 
24945 /*
24946  * Copy the header plus those options which have the copy bit set
24947  */
24948 static mblk_t *
24949 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst)
24950 {
24951 	mblk_t	*mp;
24952 	uchar_t	*up;
24953 
24954 	/*
24955 	 * Quick check if we need to look for options without the copy bit
24956 	 * set
24957 	 */
24958 	mp = allocb(ipst->ips_ip_wroff_extra + hdr_len, BPRI_HI);
24959 	if (!mp)
24960 		return (mp);
24961 	mp->b_rptr += ipst->ips_ip_wroff_extra;
24962 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24963 		bcopy(rptr, mp->b_rptr, hdr_len);
24964 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
24965 		return (mp);
24966 	}
24967 	up  = mp->b_rptr;
24968 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24969 	up += IP_SIMPLE_HDR_LENGTH;
24970 	rptr += IP_SIMPLE_HDR_LENGTH;
24971 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24972 	while (hdr_len > 0) {
24973 		uint32_t optval;
24974 		uint32_t optlen;
24975 
24976 		optval = *rptr;
24977 		if (optval == IPOPT_EOL)
24978 			break;
24979 		if (optval == IPOPT_NOP)
24980 			optlen = 1;
24981 		else
24982 			optlen = rptr[1];
24983 		if (optval & IPOPT_COPY) {
24984 			bcopy(rptr, up, optlen);
24985 			up += optlen;
24986 		}
24987 		rptr += optlen;
24988 		hdr_len -= optlen;
24989 	}
24990 	/*
24991 	 * Make sure that we drop an even number of words by filling
24992 	 * with EOL to the next word boundary.
24993 	 */
24994 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
24995 	    hdr_len & 0x3; hdr_len++)
24996 		*up++ = IPOPT_EOL;
24997 	mp->b_wptr = up;
24998 	/* Update header length */
24999 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
25000 	return (mp);
25001 }
25002 
25003 /*
25004  * Delivery to local recipients including fanout to multiple recipients.
25005  * Does not do checksumming of UDP/TCP.
25006  * Note: q should be the read side queue for either the ill or conn.
25007  * Note: rq should be the read side q for the lower (ill) stream.
25008  * We don't send packets to IPPF processing, thus the last argument
25009  * to all the fanout calls are B_FALSE.
25010  */
25011 void
25012 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
25013     int fanout_flags, zoneid_t zoneid)
25014 {
25015 	uint32_t	protocol;
25016 	mblk_t		*first_mp;
25017 	boolean_t	mctl_present;
25018 	int		ire_type;
25019 #define	rptr	((uchar_t *)ipha)
25020 	ip_stack_t	*ipst = ill->ill_ipst;
25021 
25022 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
25023 	    "ip_wput_local_start: q %p", q);
25024 
25025 	if (ire != NULL) {
25026 		ire_type = ire->ire_type;
25027 	} else {
25028 		/*
25029 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
25030 		 * packet is not multicast, we can't tell the ire type.
25031 		 */
25032 		ASSERT(CLASSD(ipha->ipha_dst));
25033 		ire_type = IRE_BROADCAST;
25034 	}
25035 
25036 	first_mp = mp;
25037 	if (first_mp->b_datap->db_type == M_CTL) {
25038 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
25039 		if (!io->ipsec_out_secure) {
25040 			/*
25041 			 * This ipsec_out_t was allocated in ip_wput
25042 			 * for multicast packets to store the ill_index.
25043 			 * As this is being delivered locally, we don't
25044 			 * need this anymore.
25045 			 */
25046 			mp = first_mp->b_cont;
25047 			freeb(first_mp);
25048 			first_mp = mp;
25049 			mctl_present = B_FALSE;
25050 		} else {
25051 			/*
25052 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
25053 			 * security properties for the looped-back packet.
25054 			 */
25055 			mctl_present = B_TRUE;
25056 			mp = first_mp->b_cont;
25057 			ASSERT(mp != NULL);
25058 			ipsec_out_to_in(first_mp);
25059 		}
25060 	} else {
25061 		mctl_present = B_FALSE;
25062 	}
25063 
25064 	DTRACE_PROBE4(ip4__loopback__in__start,
25065 	    ill_t *, ill, ill_t *, NULL,
25066 	    ipha_t *, ipha, mblk_t *, first_mp);
25067 
25068 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
25069 	    ipst->ips_ipv4firewall_loopback_in,
25070 	    ill, NULL, ipha, first_mp, mp, 0, ipst);
25071 
25072 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
25073 
25074 	if (first_mp == NULL)
25075 		return;
25076 
25077 	DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL, void_ip_t *,
25078 	    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *, NULL,
25079 	    int, 1);
25080 
25081 	ipst->ips_loopback_packets++;
25082 
25083 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
25084 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
25085 	if (!IS_SIMPLE_IPH(ipha)) {
25086 		ip_wput_local_options(ipha, ipst);
25087 	}
25088 
25089 	protocol = ipha->ipha_protocol;
25090 	switch (protocol) {
25091 	case IPPROTO_ICMP: {
25092 		ire_t		*ire_zone;
25093 		ilm_t		*ilm;
25094 		mblk_t		*mp1;
25095 		zoneid_t	last_zoneid;
25096 
25097 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
25098 			ASSERT(ire_type == IRE_BROADCAST);
25099 			/*
25100 			 * In the multicast case, applications may have joined
25101 			 * the group from different zones, so we need to deliver
25102 			 * the packet to each of them. Loop through the
25103 			 * multicast memberships structures (ilm) on the receive
25104 			 * ill and send a copy of the packet up each matching
25105 			 * one. However, we don't do this for multicasts sent on
25106 			 * the loopback interface (PHYI_LOOPBACK flag set) as
25107 			 * they must stay in the sender's zone.
25108 			 *
25109 			 * ilm_add_v6() ensures that ilms in the same zone are
25110 			 * contiguous in the ill_ilm list. We use this property
25111 			 * to avoid sending duplicates needed when two
25112 			 * applications in the same zone join the same group on
25113 			 * different logical interfaces: we ignore the ilm if
25114 			 * it's zoneid is the same as the last matching one.
25115 			 * In addition, the sending of the packet for
25116 			 * ire_zoneid is delayed until all of the other ilms
25117 			 * have been exhausted.
25118 			 */
25119 			last_zoneid = -1;
25120 			ILM_WALKER_HOLD(ill);
25121 			for (ilm = ill->ill_ilm; ilm != NULL;
25122 			    ilm = ilm->ilm_next) {
25123 				if ((ilm->ilm_flags & ILM_DELETED) ||
25124 				    ipha->ipha_dst != ilm->ilm_addr ||
25125 				    ilm->ilm_zoneid == last_zoneid ||
25126 				    ilm->ilm_zoneid == zoneid ||
25127 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25128 					continue;
25129 				mp1 = ip_copymsg(first_mp);
25130 				if (mp1 == NULL)
25131 					continue;
25132 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25133 				    mctl_present, B_FALSE, ill,
25134 				    ilm->ilm_zoneid);
25135 				last_zoneid = ilm->ilm_zoneid;
25136 			}
25137 			ILM_WALKER_RELE(ill);
25138 			/*
25139 			 * Loopback case: the sending endpoint has
25140 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25141 			 * dispatch the multicast packet to the sending zone.
25142 			 */
25143 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25144 				freemsg(first_mp);
25145 				return;
25146 			}
25147 		} else if (ire_type == IRE_BROADCAST) {
25148 			/*
25149 			 * In the broadcast case, there may be many zones
25150 			 * which need a copy of the packet delivered to them.
25151 			 * There is one IRE_BROADCAST per broadcast address
25152 			 * and per zone; we walk those using a helper function.
25153 			 * In addition, the sending of the packet for zoneid is
25154 			 * delayed until all of the other ires have been
25155 			 * processed.
25156 			 */
25157 			IRB_REFHOLD(ire->ire_bucket);
25158 			ire_zone = NULL;
25159 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25160 			    ire)) != NULL) {
25161 				mp1 = ip_copymsg(first_mp);
25162 				if (mp1 == NULL)
25163 					continue;
25164 
25165 				UPDATE_IB_PKT_COUNT(ire_zone);
25166 				ire_zone->ire_last_used_time = lbolt;
25167 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25168 				    mctl_present, B_FALSE, ill,
25169 				    ire_zone->ire_zoneid);
25170 			}
25171 			IRB_REFRELE(ire->ire_bucket);
25172 		}
25173 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25174 		    0, mctl_present, B_FALSE, ill, zoneid);
25175 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25176 		    "ip_wput_local_end: q %p (%S)",
25177 		    q, "icmp");
25178 		return;
25179 	}
25180 	case IPPROTO_IGMP:
25181 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25182 			/* Bad packet - discarded by igmp_input */
25183 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25184 			    "ip_wput_local_end: q %p (%S)",
25185 			    q, "igmp_input--bad packet");
25186 			if (mctl_present)
25187 				freeb(first_mp);
25188 			return;
25189 		}
25190 		/*
25191 		 * igmp_input() may have returned the pulled up message.
25192 		 * So first_mp and ipha need to be reinitialized.
25193 		 */
25194 		ipha = (ipha_t *)mp->b_rptr;
25195 		if (mctl_present)
25196 			first_mp->b_cont = mp;
25197 		else
25198 			first_mp = mp;
25199 		/* deliver to local raw users */
25200 		break;
25201 	case IPPROTO_ENCAP:
25202 		/*
25203 		 * This case is covered by either ip_fanout_proto, or by
25204 		 * the above security processing for self-tunneled packets.
25205 		 */
25206 		break;
25207 	case IPPROTO_UDP: {
25208 		uint16_t	*up;
25209 		uint32_t	ports;
25210 
25211 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25212 		    UDP_PORTS_OFFSET);
25213 		/* Force a 'valid' checksum. */
25214 		up[3] = 0;
25215 
25216 		ports = *(uint32_t *)up;
25217 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25218 		    (ire_type == IRE_BROADCAST),
25219 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25220 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25221 		    ill, zoneid);
25222 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25223 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25224 		return;
25225 	}
25226 	case IPPROTO_TCP: {
25227 
25228 		/*
25229 		 * For TCP, discard broadcast packets.
25230 		 */
25231 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25232 			freemsg(first_mp);
25233 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25234 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25235 			return;
25236 		}
25237 
25238 		if (mp->b_datap->db_type == M_DATA) {
25239 			/*
25240 			 * M_DATA mblk, so init mblk (chain) for no struio().
25241 			 */
25242 			mblk_t	*mp1 = mp;
25243 
25244 			do {
25245 				mp1->b_datap->db_struioflag = 0;
25246 			} while ((mp1 = mp1->b_cont) != NULL);
25247 		}
25248 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25249 		    <= mp->b_wptr);
25250 		ip_fanout_tcp(q, first_mp, ill, ipha,
25251 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25252 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25253 		    mctl_present, B_FALSE, zoneid);
25254 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25255 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25256 		return;
25257 	}
25258 	case IPPROTO_SCTP:
25259 	{
25260 		uint32_t	ports;
25261 
25262 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25263 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25264 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25265 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25266 		return;
25267 	}
25268 
25269 	default:
25270 		break;
25271 	}
25272 	/*
25273 	 * Find a client for some other protocol.  We give
25274 	 * copies to multiple clients, if more than one is
25275 	 * bound.
25276 	 */
25277 	ip_fanout_proto(q, first_mp, ill, ipha,
25278 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25279 	    mctl_present, B_FALSE, ill, zoneid);
25280 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25281 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25282 #undef	rptr
25283 }
25284 
25285 /*
25286  * Update any source route, record route, or timestamp options.
25287  * Check that we are at end of strict source route.
25288  * The options have been sanity checked by ip_wput_options().
25289  */
25290 static void
25291 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25292 {
25293 	ipoptp_t	opts;
25294 	uchar_t		*opt;
25295 	uint8_t		optval;
25296 	uint8_t		optlen;
25297 	ipaddr_t	dst;
25298 	uint32_t	ts;
25299 	ire_t		*ire;
25300 	timestruc_t	now;
25301 
25302 	ip2dbg(("ip_wput_local_options\n"));
25303 	for (optval = ipoptp_first(&opts, ipha);
25304 	    optval != IPOPT_EOL;
25305 	    optval = ipoptp_next(&opts)) {
25306 		opt = opts.ipoptp_cur;
25307 		optlen = opts.ipoptp_len;
25308 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25309 		switch (optval) {
25310 			uint32_t off;
25311 		case IPOPT_SSRR:
25312 		case IPOPT_LSRR:
25313 			off = opt[IPOPT_OFFSET];
25314 			off--;
25315 			if (optlen < IP_ADDR_LEN ||
25316 			    off > optlen - IP_ADDR_LEN) {
25317 				/* End of source route */
25318 				break;
25319 			}
25320 			/*
25321 			 * This will only happen if two consecutive entries
25322 			 * in the source route contains our address or if
25323 			 * it is a packet with a loose source route which
25324 			 * reaches us before consuming the whole source route
25325 			 */
25326 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25327 			if (optval == IPOPT_SSRR) {
25328 				return;
25329 			}
25330 			/*
25331 			 * Hack: instead of dropping the packet truncate the
25332 			 * source route to what has been used by filling the
25333 			 * rest with IPOPT_NOP.
25334 			 */
25335 			opt[IPOPT_OLEN] = (uint8_t)off;
25336 			while (off < optlen) {
25337 				opt[off++] = IPOPT_NOP;
25338 			}
25339 			break;
25340 		case IPOPT_RR:
25341 			off = opt[IPOPT_OFFSET];
25342 			off--;
25343 			if (optlen < IP_ADDR_LEN ||
25344 			    off > optlen - IP_ADDR_LEN) {
25345 				/* No more room - ignore */
25346 				ip1dbg((
25347 				    "ip_wput_forward_options: end of RR\n"));
25348 				break;
25349 			}
25350 			dst = htonl(INADDR_LOOPBACK);
25351 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25352 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25353 			break;
25354 		case IPOPT_TS:
25355 			/* Insert timestamp if there is romm */
25356 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25357 			case IPOPT_TS_TSONLY:
25358 				off = IPOPT_TS_TIMELEN;
25359 				break;
25360 			case IPOPT_TS_PRESPEC:
25361 			case IPOPT_TS_PRESPEC_RFC791:
25362 				/* Verify that the address matched */
25363 				off = opt[IPOPT_OFFSET] - 1;
25364 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25365 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25366 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25367 				    ipst);
25368 				if (ire == NULL) {
25369 					/* Not for us */
25370 					break;
25371 				}
25372 				ire_refrele(ire);
25373 				/* FALLTHRU */
25374 			case IPOPT_TS_TSANDADDR:
25375 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25376 				break;
25377 			default:
25378 				/*
25379 				 * ip_*put_options should have already
25380 				 * dropped this packet.
25381 				 */
25382 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25383 				    "unknown IT - bug in ip_wput_options?\n");
25384 				return;	/* Keep "lint" happy */
25385 			}
25386 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25387 				/* Increase overflow counter */
25388 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25389 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25390 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25391 				    (off << 4);
25392 				break;
25393 			}
25394 			off = opt[IPOPT_OFFSET] - 1;
25395 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25396 			case IPOPT_TS_PRESPEC:
25397 			case IPOPT_TS_PRESPEC_RFC791:
25398 			case IPOPT_TS_TSANDADDR:
25399 				dst = htonl(INADDR_LOOPBACK);
25400 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25401 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25402 				/* FALLTHRU */
25403 			case IPOPT_TS_TSONLY:
25404 				off = opt[IPOPT_OFFSET] - 1;
25405 				/* Compute # of milliseconds since midnight */
25406 				gethrestime(&now);
25407 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25408 				    now.tv_nsec / (NANOSEC / MILLISEC);
25409 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25410 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25411 				break;
25412 			}
25413 			break;
25414 		}
25415 	}
25416 }
25417 
25418 /*
25419  * Send out a multicast packet on interface ipif.
25420  * The sender does not have an conn.
25421  * Caller verifies that this isn't a PHYI_LOOPBACK.
25422  */
25423 void
25424 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25425 {
25426 	ipha_t	*ipha;
25427 	ire_t	*ire;
25428 	ipaddr_t	dst;
25429 	mblk_t		*first_mp;
25430 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25431 
25432 	/* igmp_sendpkt always allocates a ipsec_out_t */
25433 	ASSERT(mp->b_datap->db_type == M_CTL);
25434 	ASSERT(!ipif->ipif_isv6);
25435 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25436 
25437 	first_mp = mp;
25438 	mp = first_mp->b_cont;
25439 	ASSERT(mp->b_datap->db_type == M_DATA);
25440 	ipha = (ipha_t *)mp->b_rptr;
25441 
25442 	/*
25443 	 * Find an IRE which matches the destination and the outgoing
25444 	 * queue (i.e. the outgoing interface.)
25445 	 */
25446 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25447 		dst = ipif->ipif_pp_dst_addr;
25448 	else
25449 		dst = ipha->ipha_dst;
25450 	/*
25451 	 * The source address has already been initialized by the
25452 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25453 	 * be sufficient rather than MATCH_IRE_IPIF.
25454 	 *
25455 	 * This function is used for sending IGMP packets. We need
25456 	 * to make sure that we send the packet out of the interface
25457 	 * (ipif->ipif_ill) where we joined the group. This is to
25458 	 * prevent from switches doing IGMP snooping to send us multicast
25459 	 * packets for a given group on the interface we have joined.
25460 	 * If we can't find an ire, igmp_sendpkt has already initialized
25461 	 * ipsec_out_attach_if so that this will not be load spread in
25462 	 * ip_newroute_ipif.
25463 	 */
25464 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25465 	    MATCH_IRE_ILL, ipst);
25466 	if (!ire) {
25467 		/*
25468 		 * Mark this packet to make it be delivered to
25469 		 * ip_wput_ire after the new ire has been
25470 		 * created.
25471 		 */
25472 		mp->b_prev = NULL;
25473 		mp->b_next = NULL;
25474 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25475 		    zoneid, &zero_info);
25476 		return;
25477 	}
25478 
25479 	/*
25480 	 * Honor the RTF_SETSRC flag; this is the only case
25481 	 * where we force this addr whatever the current src addr is,
25482 	 * because this address is set by igmp_sendpkt(), and
25483 	 * cannot be specified by any user.
25484 	 */
25485 	if (ire->ire_flags & RTF_SETSRC) {
25486 		ipha->ipha_src = ire->ire_src_addr;
25487 	}
25488 
25489 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25490 }
25491 
25492 /*
25493  * NOTE : This function does not ire_refrele the ire argument passed in.
25494  *
25495  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25496  * failure. The nce_fp_mp can vanish any time in the case of
25497  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25498  * the ire_lock to access the nce_fp_mp in this case.
25499  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25500  * prepending a fastpath message IPQoS processing must precede it, we also set
25501  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25502  * (IPQoS might have set the b_band for CoS marking).
25503  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25504  * must follow it so that IPQoS can mark the dl_priority field for CoS
25505  * marking, if needed.
25506  */
25507 static mblk_t *
25508 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc,
25509     uint32_t ill_index, ipha_t **iphap)
25510 {
25511 	uint_t	hlen;
25512 	ipha_t *ipha;
25513 	mblk_t *mp1;
25514 	boolean_t qos_done = B_FALSE;
25515 	uchar_t	*ll_hdr;
25516 	ip_stack_t	*ipst = ire->ire_ipst;
25517 
25518 #define	rptr	((uchar_t *)ipha)
25519 
25520 	ipha = (ipha_t *)mp->b_rptr;
25521 	hlen = 0;
25522 	LOCK_IRE_FP_MP(ire);
25523 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25524 		ASSERT(DB_TYPE(mp1) == M_DATA);
25525 		/* Initiate IPPF processing */
25526 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25527 			UNLOCK_IRE_FP_MP(ire);
25528 			ip_process(proc, &mp, ill_index);
25529 			if (mp == NULL)
25530 				return (NULL);
25531 
25532 			ipha = (ipha_t *)mp->b_rptr;
25533 			LOCK_IRE_FP_MP(ire);
25534 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25535 				qos_done = B_TRUE;
25536 				goto no_fp_mp;
25537 			}
25538 			ASSERT(DB_TYPE(mp1) == M_DATA);
25539 		}
25540 		hlen = MBLKL(mp1);
25541 		/*
25542 		 * Check if we have enough room to prepend fastpath
25543 		 * header
25544 		 */
25545 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25546 			ll_hdr = rptr - hlen;
25547 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25548 			/*
25549 			 * Set the b_rptr to the start of the link layer
25550 			 * header
25551 			 */
25552 			mp->b_rptr = ll_hdr;
25553 			mp1 = mp;
25554 		} else {
25555 			mp1 = copyb(mp1);
25556 			if (mp1 == NULL)
25557 				goto unlock_err;
25558 			mp1->b_band = mp->b_band;
25559 			mp1->b_cont = mp;
25560 			/*
25561 			 * certain system generated traffic may not
25562 			 * have cred/label in ip header block. This
25563 			 * is true even for a labeled system. But for
25564 			 * labeled traffic, inherit the label in the
25565 			 * new header.
25566 			 */
25567 			if (DB_CRED(mp) != NULL)
25568 				mblk_setcred(mp1, DB_CRED(mp));
25569 			/*
25570 			 * XXX disable ICK_VALID and compute checksum
25571 			 * here; can happen if nce_fp_mp changes and
25572 			 * it can't be copied now due to insufficient
25573 			 * space. (unlikely, fp mp can change, but it
25574 			 * does not increase in length)
25575 			 */
25576 		}
25577 		UNLOCK_IRE_FP_MP(ire);
25578 	} else {
25579 no_fp_mp:
25580 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25581 		if (mp1 == NULL) {
25582 unlock_err:
25583 			UNLOCK_IRE_FP_MP(ire);
25584 			freemsg(mp);
25585 			return (NULL);
25586 		}
25587 		UNLOCK_IRE_FP_MP(ire);
25588 		mp1->b_cont = mp;
25589 		/*
25590 		 * certain system generated traffic may not
25591 		 * have cred/label in ip header block. This
25592 		 * is true even for a labeled system. But for
25593 		 * labeled traffic, inherit the label in the
25594 		 * new header.
25595 		 */
25596 		if (DB_CRED(mp) != NULL)
25597 			mblk_setcred(mp1, DB_CRED(mp));
25598 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25599 			ip_process(proc, &mp1, ill_index);
25600 			if (mp1 == NULL)
25601 				return (NULL);
25602 
25603 			if (mp1->b_cont == NULL)
25604 				ipha = NULL;
25605 			else
25606 				ipha = (ipha_t *)mp1->b_cont->b_rptr;
25607 		}
25608 	}
25609 
25610 	*iphap = ipha;
25611 	return (mp1);
25612 #undef rptr
25613 }
25614 
25615 /*
25616  * Finish the outbound IPsec processing for an IPv6 packet. This function
25617  * is called from ipsec_out_process() if the IPsec packet was processed
25618  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25619  * asynchronously.
25620  */
25621 void
25622 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25623     ire_t *ire_arg)
25624 {
25625 	in6_addr_t *v6dstp;
25626 	ire_t *ire;
25627 	mblk_t *mp;
25628 	ip6_t *ip6h1;
25629 	uint_t	ill_index;
25630 	ipsec_out_t *io;
25631 	boolean_t attach_if, hwaccel;
25632 	uint32_t flags = IP6_NO_IPPOLICY;
25633 	int match_flags;
25634 	zoneid_t zoneid;
25635 	boolean_t ill_need_rele = B_FALSE;
25636 	boolean_t ire_need_rele = B_FALSE;
25637 	ip_stack_t	*ipst;
25638 
25639 	mp = ipsec_mp->b_cont;
25640 	ip6h1 = (ip6_t *)mp->b_rptr;
25641 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25642 	ASSERT(io->ipsec_out_ns != NULL);
25643 	ipst = io->ipsec_out_ns->netstack_ip;
25644 	ill_index = io->ipsec_out_ill_index;
25645 	if (io->ipsec_out_reachable) {
25646 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25647 	}
25648 	attach_if = io->ipsec_out_attach_if;
25649 	hwaccel = io->ipsec_out_accelerated;
25650 	zoneid = io->ipsec_out_zoneid;
25651 	ASSERT(zoneid != ALL_ZONES);
25652 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25653 	/* Multicast addresses should have non-zero ill_index. */
25654 	v6dstp = &ip6h->ip6_dst;
25655 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25656 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25657 	ASSERT(!attach_if || ill_index != 0);
25658 	if (ill_index != 0) {
25659 		if (ill == NULL) {
25660 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
25661 			    B_TRUE, ipst);
25662 
25663 			/* Failure case frees things for us. */
25664 			if (ill == NULL)
25665 				return;
25666 
25667 			ill_need_rele = B_TRUE;
25668 		}
25669 		/*
25670 		 * If this packet needs to go out on a particular interface
25671 		 * honor it.
25672 		 */
25673 		if (attach_if) {
25674 			match_flags = MATCH_IRE_ILL;
25675 
25676 			/*
25677 			 * Check if we need an ire that will not be
25678 			 * looked up by anybody else i.e. HIDDEN.
25679 			 */
25680 			if (ill_is_probeonly(ill)) {
25681 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25682 			}
25683 		}
25684 	}
25685 	ASSERT(mp != NULL);
25686 
25687 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25688 		boolean_t unspec_src;
25689 		ipif_t	*ipif;
25690 
25691 		/*
25692 		 * Use the ill_index to get the right ill.
25693 		 */
25694 		unspec_src = io->ipsec_out_unspec_src;
25695 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25696 		if (ipif == NULL) {
25697 			if (ill_need_rele)
25698 				ill_refrele(ill);
25699 			freemsg(ipsec_mp);
25700 			return;
25701 		}
25702 
25703 		if (ire_arg != NULL) {
25704 			ire = ire_arg;
25705 		} else {
25706 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25707 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25708 			ire_need_rele = B_TRUE;
25709 		}
25710 		if (ire != NULL) {
25711 			ipif_refrele(ipif);
25712 			/*
25713 			 * XXX Do the multicast forwarding now, as the IPsec
25714 			 * processing has been done.
25715 			 */
25716 			goto send;
25717 		}
25718 
25719 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25720 		mp->b_prev = NULL;
25721 		mp->b_next = NULL;
25722 
25723 		/*
25724 		 * If the IPsec packet was processed asynchronously,
25725 		 * drop it now.
25726 		 */
25727 		if (q == NULL) {
25728 			if (ill_need_rele)
25729 				ill_refrele(ill);
25730 			freemsg(ipsec_mp);
25731 			return;
25732 		}
25733 
25734 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
25735 		    unspec_src, zoneid);
25736 		ipif_refrele(ipif);
25737 	} else {
25738 		if (attach_if) {
25739 			ipif_t	*ipif;
25740 
25741 			ipif = ipif_get_next_ipif(NULL, ill);
25742 			if (ipif == NULL) {
25743 				if (ill_need_rele)
25744 					ill_refrele(ill);
25745 				freemsg(ipsec_mp);
25746 				return;
25747 			}
25748 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25749 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25750 			ire_need_rele = B_TRUE;
25751 			ipif_refrele(ipif);
25752 		} else {
25753 			if (ire_arg != NULL) {
25754 				ire = ire_arg;
25755 			} else {
25756 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL,
25757 				    ipst);
25758 				ire_need_rele = B_TRUE;
25759 			}
25760 		}
25761 		if (ire != NULL)
25762 			goto send;
25763 		/*
25764 		 * ire disappeared underneath.
25765 		 *
25766 		 * What we need to do here is the ip_newroute
25767 		 * logic to get the ire without doing the IPsec
25768 		 * processing. Follow the same old path. But this
25769 		 * time, ip_wput or ire_add_then_send will call us
25770 		 * directly as all the IPsec operations are done.
25771 		 */
25772 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25773 		mp->b_prev = NULL;
25774 		mp->b_next = NULL;
25775 
25776 		/*
25777 		 * If the IPsec packet was processed asynchronously,
25778 		 * drop it now.
25779 		 */
25780 		if (q == NULL) {
25781 			if (ill_need_rele)
25782 				ill_refrele(ill);
25783 			freemsg(ipsec_mp);
25784 			return;
25785 		}
25786 
25787 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25788 		    zoneid, ipst);
25789 	}
25790 	if (ill != NULL && ill_need_rele)
25791 		ill_refrele(ill);
25792 	return;
25793 send:
25794 	if (ill != NULL && ill_need_rele)
25795 		ill_refrele(ill);
25796 
25797 	/* Local delivery */
25798 	if (ire->ire_stq == NULL) {
25799 		ill_t	*out_ill;
25800 		ASSERT(q != NULL);
25801 
25802 		/* PFHooks: LOOPBACK_OUT */
25803 		out_ill = ire_to_ill(ire);
25804 
25805 		/*
25806 		 * DTrace this as ip:::send.  A blocked packet will fire the
25807 		 * send probe, but not the receive probe.
25808 		 */
25809 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
25810 		    void_ip_t *, ip6h, __dtrace_ipsr_ill_t *, out_ill,
25811 		    ipha_t *, NULL, ip6_t *, ip6h, int, 1);
25812 
25813 		DTRACE_PROBE4(ip6__loopback__out__start,
25814 		    ill_t *, NULL, ill_t *, out_ill,
25815 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25816 
25817 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25818 		    ipst->ips_ipv6firewall_loopback_out,
25819 		    NULL, out_ill, ip6h1, ipsec_mp, mp, 0, ipst);
25820 
25821 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25822 
25823 		if (ipsec_mp != NULL)
25824 			ip_wput_local_v6(RD(q), out_ill,
25825 			    ip6h, ipsec_mp, ire, 0);
25826 		if (ire_need_rele)
25827 			ire_refrele(ire);
25828 		return;
25829 	}
25830 	/*
25831 	 * Everything is done. Send it out on the wire.
25832 	 * We force the insertion of a fragment header using the
25833 	 * IPH_FRAG_HDR flag in two cases:
25834 	 * - after reception of an ICMPv6 "packet too big" message
25835 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25836 	 * - for multirouted IPv6 packets, so that the receiver can
25837 	 *   discard duplicates according to their fragment identifier
25838 	 */
25839 	/* XXX fix flow control problems. */
25840 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25841 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25842 		if (hwaccel) {
25843 			/*
25844 			 * hardware acceleration does not handle these
25845 			 * "slow path" cases.
25846 			 */
25847 			/* IPsec KSTATS: should bump bean counter here. */
25848 			if (ire_need_rele)
25849 				ire_refrele(ire);
25850 			freemsg(ipsec_mp);
25851 			return;
25852 		}
25853 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25854 		    (mp->b_cont ? msgdsize(mp) :
25855 		    mp->b_wptr - (uchar_t *)ip6h)) {
25856 			/* IPsec KSTATS: should bump bean counter here. */
25857 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25858 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25859 			    msgdsize(mp)));
25860 			if (ire_need_rele)
25861 				ire_refrele(ire);
25862 			freemsg(ipsec_mp);
25863 			return;
25864 		}
25865 		ASSERT(mp->b_prev == NULL);
25866 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25867 		    ntohs(ip6h->ip6_plen) +
25868 		    IPV6_HDR_LEN, ire->ire_max_frag));
25869 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25870 		    ire->ire_max_frag);
25871 	} else {
25872 		UPDATE_OB_PKT_COUNT(ire);
25873 		ire->ire_last_used_time = lbolt;
25874 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25875 	}
25876 	if (ire_need_rele)
25877 		ire_refrele(ire);
25878 	freeb(ipsec_mp);
25879 }
25880 
25881 void
25882 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25883 {
25884 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25885 	da_ipsec_t *hada;	/* data attributes */
25886 	ill_t *ill = (ill_t *)q->q_ptr;
25887 
25888 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25889 
25890 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25891 		/* IPsec KSTATS: Bump lose counter here! */
25892 		freemsg(mp);
25893 		return;
25894 	}
25895 
25896 	/*
25897 	 * It's an IPsec packet that must be
25898 	 * accelerated by the Provider, and the
25899 	 * outbound ill is IPsec acceleration capable.
25900 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25901 	 * to the ill.
25902 	 * IPsec KSTATS: should bump packet counter here.
25903 	 */
25904 
25905 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25906 	if (hada_mp == NULL) {
25907 		/* IPsec KSTATS: should bump packet counter here. */
25908 		freemsg(mp);
25909 		return;
25910 	}
25911 
25912 	hada_mp->b_datap->db_type = M_CTL;
25913 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25914 	hada_mp->b_cont = mp;
25915 
25916 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25917 	bzero(hada, sizeof (da_ipsec_t));
25918 	hada->da_type = IPHADA_M_CTL;
25919 
25920 	putnext(q, hada_mp);
25921 }
25922 
25923 /*
25924  * Finish the outbound IPsec processing. This function is called from
25925  * ipsec_out_process() if the IPsec packet was processed
25926  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25927  * asynchronously.
25928  */
25929 void
25930 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25931     ire_t *ire_arg)
25932 {
25933 	uint32_t v_hlen_tos_len;
25934 	ipaddr_t	dst;
25935 	ipif_t	*ipif = NULL;
25936 	ire_t *ire;
25937 	ire_t *ire1 = NULL;
25938 	mblk_t *next_mp = NULL;
25939 	uint32_t max_frag;
25940 	boolean_t multirt_send = B_FALSE;
25941 	mblk_t *mp;
25942 	ipha_t *ipha1;
25943 	uint_t	ill_index;
25944 	ipsec_out_t *io;
25945 	boolean_t attach_if;
25946 	int match_flags;
25947 	irb_t *irb = NULL;
25948 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25949 	zoneid_t zoneid;
25950 	ipxmit_state_t	pktxmit_state;
25951 	ip_stack_t	*ipst;
25952 
25953 #ifdef	_BIG_ENDIAN
25954 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25955 #else
25956 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25957 #endif
25958 
25959 	mp = ipsec_mp->b_cont;
25960 	ipha1 = (ipha_t *)mp->b_rptr;
25961 	ASSERT(mp != NULL);
25962 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25963 	dst = ipha->ipha_dst;
25964 
25965 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25966 	ill_index = io->ipsec_out_ill_index;
25967 	attach_if = io->ipsec_out_attach_if;
25968 	zoneid = io->ipsec_out_zoneid;
25969 	ASSERT(zoneid != ALL_ZONES);
25970 	ipst = io->ipsec_out_ns->netstack_ip;
25971 	ASSERT(io->ipsec_out_ns != NULL);
25972 
25973 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25974 	if (ill_index != 0) {
25975 		if (ill == NULL) {
25976 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
25977 			    ill_index, B_FALSE, ipst);
25978 
25979 			/* Failure case frees things for us. */
25980 			if (ill == NULL)
25981 				return;
25982 
25983 			ill_need_rele = B_TRUE;
25984 		}
25985 		/*
25986 		 * If this packet needs to go out on a particular interface
25987 		 * honor it.
25988 		 */
25989 		if (attach_if) {
25990 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25991 
25992 			/*
25993 			 * Check if we need an ire that will not be
25994 			 * looked up by anybody else i.e. HIDDEN.
25995 			 */
25996 			if (ill_is_probeonly(ill)) {
25997 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25998 			}
25999 		}
26000 	}
26001 
26002 	if (CLASSD(dst)) {
26003 		boolean_t conn_dontroute;
26004 		/*
26005 		 * Use the ill_index to get the right ipif.
26006 		 */
26007 		conn_dontroute = io->ipsec_out_dontroute;
26008 		if (ill_index == 0)
26009 			ipif = ipif_lookup_group(dst, zoneid, ipst);
26010 		else
26011 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
26012 		if (ipif == NULL) {
26013 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
26014 			    " multicast\n"));
26015 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
26016 			freemsg(ipsec_mp);
26017 			goto done;
26018 		}
26019 		/*
26020 		 * ipha_src has already been intialized with the
26021 		 * value of the ipif in ip_wput. All we need now is
26022 		 * an ire to send this downstream.
26023 		 */
26024 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
26025 		    MBLK_GETLABEL(mp), match_flags, ipst);
26026 		if (ire != NULL) {
26027 			ill_t *ill1;
26028 			/*
26029 			 * Do the multicast forwarding now, as the IPsec
26030 			 * processing has been done.
26031 			 */
26032 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
26033 			    (ill1 = ire_to_ill(ire))) {
26034 				if (ip_mforward(ill1, ipha, mp)) {
26035 					freemsg(ipsec_mp);
26036 					ip1dbg(("ip_wput_ipsec_out: mforward "
26037 					    "failed\n"));
26038 					ire_refrele(ire);
26039 					goto done;
26040 				}
26041 			}
26042 			goto send;
26043 		}
26044 
26045 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
26046 		mp->b_prev = NULL;
26047 		mp->b_next = NULL;
26048 
26049 		/*
26050 		 * If the IPsec packet was processed asynchronously,
26051 		 * drop it now.
26052 		 */
26053 		if (q == NULL) {
26054 			freemsg(ipsec_mp);
26055 			goto done;
26056 		}
26057 
26058 		/*
26059 		 * We may be using a wrong ipif to create the ire.
26060 		 * But it is okay as the source address is assigned
26061 		 * for the packet already. Next outbound packet would
26062 		 * create the IRE with the right IPIF in ip_wput.
26063 		 *
26064 		 * Also handle RTF_MULTIRT routes.
26065 		 */
26066 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
26067 		    zoneid, &zero_info);
26068 	} else {
26069 		if (attach_if) {
26070 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
26071 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
26072 		} else {
26073 			if (ire_arg != NULL) {
26074 				ire = ire_arg;
26075 				ire_need_rele = B_FALSE;
26076 			} else {
26077 				ire = ire_cache_lookup(dst, zoneid,
26078 				    MBLK_GETLABEL(mp), ipst);
26079 			}
26080 		}
26081 		if (ire != NULL) {
26082 			goto send;
26083 		}
26084 
26085 		/*
26086 		 * ire disappeared underneath.
26087 		 *
26088 		 * What we need to do here is the ip_newroute
26089 		 * logic to get the ire without doing the IPsec
26090 		 * processing. Follow the same old path. But this
26091 		 * time, ip_wput or ire_add_then_put will call us
26092 		 * directly as all the IPsec operations are done.
26093 		 */
26094 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
26095 		mp->b_prev = NULL;
26096 		mp->b_next = NULL;
26097 
26098 		/*
26099 		 * If the IPsec packet was processed asynchronously,
26100 		 * drop it now.
26101 		 */
26102 		if (q == NULL) {
26103 			freemsg(ipsec_mp);
26104 			goto done;
26105 		}
26106 
26107 		/*
26108 		 * Since we're going through ip_newroute() again, we
26109 		 * need to make sure we don't:
26110 		 *
26111 		 *	1.) Trigger the ASSERT() with the ipha_ident
26112 		 *	    overloading.
26113 		 *	2.) Redo transport-layer checksumming, since we've
26114 		 *	    already done all that to get this far.
26115 		 *
26116 		 * The easiest way not do either of the above is to set
26117 		 * the ipha_ident field to IP_HDR_INCLUDED.
26118 		 */
26119 		ipha->ipha_ident = IP_HDR_INCLUDED;
26120 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
26121 		    zoneid, ipst);
26122 	}
26123 	goto done;
26124 send:
26125 	if (ire->ire_stq == NULL) {
26126 		ill_t	*out_ill;
26127 		/*
26128 		 * Loopbacks go through ip_wput_local except for one case.
26129 		 * We come here if we generate a icmp_frag_needed message
26130 		 * after IPsec processing is over. When this function calls
26131 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
26132 		 * icmp_frag_needed. The message generated comes back here
26133 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
26134 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
26135 		 * source address as it is usually set in ip_wput_ire. As
26136 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
26137 		 * and we end up here. We can't enter ip_wput_ire once the
26138 		 * IPsec processing is over and hence we need to do it here.
26139 		 */
26140 		ASSERT(q != NULL);
26141 		UPDATE_OB_PKT_COUNT(ire);
26142 		ire->ire_last_used_time = lbolt;
26143 		if (ipha->ipha_src == 0)
26144 			ipha->ipha_src = ire->ire_src_addr;
26145 
26146 		/* PFHooks: LOOPBACK_OUT */
26147 		out_ill = ire_to_ill(ire);
26148 
26149 		/*
26150 		 * DTrace this as ip:::send.  A blocked packet will fire the
26151 		 * send probe, but not the receive probe.
26152 		 */
26153 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
26154 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
26155 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
26156 
26157 		DTRACE_PROBE4(ip4__loopback__out__start,
26158 		    ill_t *, NULL, ill_t *, out_ill,
26159 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26160 
26161 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
26162 		    ipst->ips_ipv4firewall_loopback_out,
26163 		    NULL, out_ill, ipha1, ipsec_mp, mp, 0, ipst);
26164 
26165 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26166 
26167 		if (ipsec_mp != NULL)
26168 			ip_wput_local(RD(q), out_ill,
26169 			    ipha, ipsec_mp, ire, 0, zoneid);
26170 		if (ire_need_rele)
26171 			ire_refrele(ire);
26172 		goto done;
26173 	}
26174 
26175 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26176 		/*
26177 		 * We are through with IPsec processing.
26178 		 * Fragment this and send it on the wire.
26179 		 */
26180 		if (io->ipsec_out_accelerated) {
26181 			/*
26182 			 * The packet has been accelerated but must
26183 			 * be fragmented. This should not happen
26184 			 * since AH and ESP must not accelerate
26185 			 * packets that need fragmentation, however
26186 			 * the configuration could have changed
26187 			 * since the AH or ESP processing.
26188 			 * Drop packet.
26189 			 * IPsec KSTATS: bump bean counter here.
26190 			 */
26191 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26192 			    "fragmented accelerated packet!\n"));
26193 			freemsg(ipsec_mp);
26194 		} else {
26195 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid, ipst);
26196 		}
26197 		if (ire_need_rele)
26198 			ire_refrele(ire);
26199 		goto done;
26200 	}
26201 
26202 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26203 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26204 	    (void *)ire->ire_ipif, (void *)ipif));
26205 
26206 	/*
26207 	 * Multiroute the secured packet, unless IPsec really
26208 	 * requires the packet to go out only through a particular
26209 	 * interface.
26210 	 */
26211 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
26212 		ire_t *first_ire;
26213 		irb = ire->ire_bucket;
26214 		ASSERT(irb != NULL);
26215 		/*
26216 		 * This ire has been looked up as the one that
26217 		 * goes through the given ipif;
26218 		 * make sure we do not omit any other multiroute ire
26219 		 * that may be present in the bucket before this one.
26220 		 */
26221 		IRB_REFHOLD(irb);
26222 		for (first_ire = irb->irb_ire;
26223 		    first_ire != NULL;
26224 		    first_ire = first_ire->ire_next) {
26225 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26226 			    (first_ire->ire_addr == ire->ire_addr) &&
26227 			    !(first_ire->ire_marks &
26228 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
26229 				break;
26230 			}
26231 		}
26232 
26233 		if ((first_ire != NULL) && (first_ire != ire)) {
26234 			/*
26235 			 * Don't change the ire if the packet must
26236 			 * be fragmented if sent via this new one.
26237 			 */
26238 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26239 				IRE_REFHOLD(first_ire);
26240 				if (ire_need_rele)
26241 					ire_refrele(ire);
26242 				else
26243 					ire_need_rele = B_TRUE;
26244 				ire = first_ire;
26245 			}
26246 		}
26247 		IRB_REFRELE(irb);
26248 
26249 		multirt_send = B_TRUE;
26250 		max_frag = ire->ire_max_frag;
26251 	} else {
26252 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
26253 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
26254 			    "flag, attach_if %d\n", attach_if));
26255 		}
26256 	}
26257 
26258 	/*
26259 	 * In most cases, the emission loop below is entered only once.
26260 	 * Only in the case where the ire holds the RTF_MULTIRT
26261 	 * flag, we loop to process all RTF_MULTIRT ires in the
26262 	 * bucket, and send the packet through all crossed
26263 	 * RTF_MULTIRT routes.
26264 	 */
26265 	do {
26266 		if (multirt_send) {
26267 			/*
26268 			 * ire1 holds here the next ire to process in the
26269 			 * bucket. If multirouting is expected,
26270 			 * any non-RTF_MULTIRT ire that has the
26271 			 * right destination address is ignored.
26272 			 */
26273 			ASSERT(irb != NULL);
26274 			IRB_REFHOLD(irb);
26275 			for (ire1 = ire->ire_next;
26276 			    ire1 != NULL;
26277 			    ire1 = ire1->ire_next) {
26278 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26279 					continue;
26280 				if (ire1->ire_addr != ire->ire_addr)
26281 					continue;
26282 				if (ire1->ire_marks &
26283 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
26284 					continue;
26285 				/* No loopback here */
26286 				if (ire1->ire_stq == NULL)
26287 					continue;
26288 				/*
26289 				 * Ensure we do not exceed the MTU
26290 				 * of the next route.
26291 				 */
26292 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26293 					ip_multirt_bad_mtu(ire1, max_frag);
26294 					continue;
26295 				}
26296 
26297 				IRE_REFHOLD(ire1);
26298 				break;
26299 			}
26300 			IRB_REFRELE(irb);
26301 			if (ire1 != NULL) {
26302 				/*
26303 				 * We are in a multiple send case, need to
26304 				 * make a copy of the packet.
26305 				 */
26306 				next_mp = copymsg(ipsec_mp);
26307 				if (next_mp == NULL) {
26308 					ire_refrele(ire1);
26309 					ire1 = NULL;
26310 				}
26311 			}
26312 		}
26313 		/*
26314 		 * Everything is done. Send it out on the wire
26315 		 *
26316 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26317 		 * either send it on the wire or, in the case of
26318 		 * HW acceleration, call ipsec_hw_putnext.
26319 		 */
26320 		if (ire->ire_nce &&
26321 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26322 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26323 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26324 			/*
26325 			 * If ire's link-layer is unresolved (this
26326 			 * would only happen if the incomplete ire
26327 			 * was added to cachetable via forwarding path)
26328 			 * don't bother going to ip_xmit_v4. Just drop the
26329 			 * packet.
26330 			 * There is a slight risk here, in that, if we
26331 			 * have the forwarding path create an incomplete
26332 			 * IRE, then until the IRE is completed, any
26333 			 * transmitted IPsec packets will be dropped
26334 			 * instead of being queued waiting for resolution.
26335 			 *
26336 			 * But the likelihood of a forwarding packet and a wput
26337 			 * packet sending to the same dst at the same time
26338 			 * and there not yet be an ARP entry for it is small.
26339 			 * Furthermore, if this actually happens, it might
26340 			 * be likely that wput would generate multiple
26341 			 * packets (and forwarding would also have a train
26342 			 * of packets) for that destination. If this is
26343 			 * the case, some of them would have been dropped
26344 			 * anyway, since ARP only queues a few packets while
26345 			 * waiting for resolution
26346 			 *
26347 			 * NOTE: We should really call ip_xmit_v4,
26348 			 * and let it queue the packet and send the
26349 			 * ARP query and have ARP come back thus:
26350 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26351 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26352 			 * hw accel work. But it's too complex to get
26353 			 * the IPsec hw  acceleration approach to fit
26354 			 * well with ip_xmit_v4 doing ARP without
26355 			 * doing IPsec simplification. For now, we just
26356 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26357 			 * that we can continue with the send on the next
26358 			 * attempt.
26359 			 *
26360 			 * XXX THis should be revisited, when
26361 			 * the IPsec/IP interaction is cleaned up
26362 			 */
26363 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26364 			    " - dropping packet\n"));
26365 			freemsg(ipsec_mp);
26366 			/*
26367 			 * Call ip_xmit_v4() to trigger ARP query
26368 			 * in case the nce_state is ND_INITIAL
26369 			 */
26370 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26371 			goto drop_pkt;
26372 		}
26373 
26374 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26375 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26376 		    mblk_t *, ipsec_mp);
26377 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26378 		    ipst->ips_ipv4firewall_physical_out, NULL,
26379 		    ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, 0, ipst);
26380 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26381 		if (ipsec_mp == NULL)
26382 			goto drop_pkt;
26383 
26384 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26385 		pktxmit_state = ip_xmit_v4(mp, ire,
26386 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
26387 
26388 		if ((pktxmit_state ==  SEND_FAILED) ||
26389 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26390 
26391 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26392 drop_pkt:
26393 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26394 			    ipIfStatsOutDiscards);
26395 			if (ire_need_rele)
26396 				ire_refrele(ire);
26397 			if (ire1 != NULL) {
26398 				ire_refrele(ire1);
26399 				freemsg(next_mp);
26400 			}
26401 			goto done;
26402 		}
26403 
26404 		freeb(ipsec_mp);
26405 		if (ire_need_rele)
26406 			ire_refrele(ire);
26407 
26408 		if (ire1 != NULL) {
26409 			ire = ire1;
26410 			ire_need_rele = B_TRUE;
26411 			ASSERT(next_mp);
26412 			ipsec_mp = next_mp;
26413 			mp = ipsec_mp->b_cont;
26414 			ire1 = NULL;
26415 			next_mp = NULL;
26416 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26417 		} else {
26418 			multirt_send = B_FALSE;
26419 		}
26420 	} while (multirt_send);
26421 done:
26422 	if (ill != NULL && ill_need_rele)
26423 		ill_refrele(ill);
26424 	if (ipif != NULL)
26425 		ipif_refrele(ipif);
26426 }
26427 
26428 /*
26429  * Get the ill corresponding to the specified ire, and compare its
26430  * capabilities with the protocol and algorithms specified by the
26431  * the SA obtained from ipsec_out. If they match, annotate the
26432  * ipsec_out structure to indicate that the packet needs acceleration.
26433  *
26434  *
26435  * A packet is eligible for outbound hardware acceleration if the
26436  * following conditions are satisfied:
26437  *
26438  * 1. the packet will not be fragmented
26439  * 2. the provider supports the algorithm
26440  * 3. there is no pending control message being exchanged
26441  * 4. snoop is not attached
26442  * 5. the destination address is not a broadcast or multicast address.
26443  *
26444  * Rationale:
26445  *	- Hardware drivers do not support fragmentation with
26446  *	  the current interface.
26447  *	- snoop, multicast, and broadcast may result in exposure of
26448  *	  a cleartext datagram.
26449  * We check all five of these conditions here.
26450  *
26451  * XXX would like to nuke "ire_t *" parameter here; problem is that
26452  * IRE is only way to figure out if a v4 address is a broadcast and
26453  * thus ineligible for acceleration...
26454  */
26455 static void
26456 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26457 {
26458 	ipsec_out_t *io;
26459 	mblk_t *data_mp;
26460 	uint_t plen, overhead;
26461 	ip_stack_t	*ipst;
26462 
26463 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26464 		return;
26465 
26466 	if (ill == NULL)
26467 		return;
26468 	ipst = ill->ill_ipst;
26469 	/*
26470 	 * Destination address is a broadcast or multicast.  Punt.
26471 	 */
26472 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26473 	    IRE_LOCAL)))
26474 		return;
26475 
26476 	data_mp = ipsec_mp->b_cont;
26477 
26478 	if (ill->ill_isv6) {
26479 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26480 
26481 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26482 			return;
26483 
26484 		plen = ip6h->ip6_plen;
26485 	} else {
26486 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26487 
26488 		if (CLASSD(ipha->ipha_dst))
26489 			return;
26490 
26491 		plen = ipha->ipha_length;
26492 	}
26493 	/*
26494 	 * Is there a pending DLPI control message being exchanged
26495 	 * between IP/IPsec and the DLS Provider? If there is, it
26496 	 * could be a SADB update, and the state of the DLS Provider
26497 	 * SADB might not be in sync with the SADB maintained by
26498 	 * IPsec. To avoid dropping packets or using the wrong keying
26499 	 * material, we do not accelerate this packet.
26500 	 */
26501 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26502 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26503 		    "ill_dlpi_pending! don't accelerate packet\n"));
26504 		return;
26505 	}
26506 
26507 	/*
26508 	 * Is the Provider in promiscous mode? If it does, we don't
26509 	 * accelerate the packet since it will bounce back up to the
26510 	 * listeners in the clear.
26511 	 */
26512 	if (ill->ill_promisc_on_phys) {
26513 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26514 		    "ill in promiscous mode, don't accelerate packet\n"));
26515 		return;
26516 	}
26517 
26518 	/*
26519 	 * Will the packet require fragmentation?
26520 	 */
26521 
26522 	/*
26523 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26524 	 * as is used elsewhere.
26525 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26526 	 *	+ 2-byte trailer
26527 	 */
26528 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26529 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26530 
26531 	if ((plen + overhead) > ill->ill_max_mtu)
26532 		return;
26533 
26534 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26535 
26536 	/*
26537 	 * Can the ill accelerate this IPsec protocol and algorithm
26538 	 * specified by the SA?
26539 	 */
26540 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26541 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26542 		return;
26543 	}
26544 
26545 	/*
26546 	 * Tell AH or ESP that the outbound ill is capable of
26547 	 * accelerating this packet.
26548 	 */
26549 	io->ipsec_out_is_capab_ill = B_TRUE;
26550 }
26551 
26552 /*
26553  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26554  *
26555  * If this function returns B_TRUE, the requested SA's have been filled
26556  * into the ipsec_out_*_sa pointers.
26557  *
26558  * If the function returns B_FALSE, the packet has been "consumed", most
26559  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26560  *
26561  * The SA references created by the protocol-specific "select"
26562  * function will be released when the ipsec_mp is freed, thanks to the
26563  * ipsec_out_free destructor -- see spd.c.
26564  */
26565 static boolean_t
26566 ipsec_out_select_sa(mblk_t *ipsec_mp)
26567 {
26568 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26569 	ipsec_out_t *io;
26570 	ipsec_policy_t *pp;
26571 	ipsec_action_t *ap;
26572 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26573 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26574 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26575 
26576 	if (!io->ipsec_out_secure) {
26577 		/*
26578 		 * We came here by mistake.
26579 		 * Don't bother with ipsec processing
26580 		 * We should "discourage" this path in the future.
26581 		 */
26582 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26583 		return (B_FALSE);
26584 	}
26585 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26586 	ASSERT((io->ipsec_out_policy != NULL) ||
26587 	    (io->ipsec_out_act != NULL));
26588 
26589 	ASSERT(io->ipsec_out_failed == B_FALSE);
26590 
26591 	/*
26592 	 * IPsec processing has started.
26593 	 */
26594 	io->ipsec_out_proc_begin = B_TRUE;
26595 	ap = io->ipsec_out_act;
26596 	if (ap == NULL) {
26597 		pp = io->ipsec_out_policy;
26598 		ASSERT(pp != NULL);
26599 		ap = pp->ipsp_act;
26600 		ASSERT(ap != NULL);
26601 	}
26602 
26603 	/*
26604 	 * We have an action.  now, let's select SA's.
26605 	 * (In the future, we can cache this in the conn_t..)
26606 	 */
26607 	if (ap->ipa_want_esp) {
26608 		if (io->ipsec_out_esp_sa == NULL) {
26609 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26610 			    IPPROTO_ESP);
26611 		}
26612 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26613 	}
26614 
26615 	if (ap->ipa_want_ah) {
26616 		if (io->ipsec_out_ah_sa == NULL) {
26617 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26618 			    IPPROTO_AH);
26619 		}
26620 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26621 		/*
26622 		 * The ESP and AH processing order needs to be preserved
26623 		 * when both protocols are required (ESP should be applied
26624 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26625 		 * when both ESP and AH are required, and an AH ACQUIRE
26626 		 * is needed.
26627 		 */
26628 		if (ap->ipa_want_esp && need_ah_acquire)
26629 			need_esp_acquire = B_TRUE;
26630 	}
26631 
26632 	/*
26633 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26634 	 * Release SAs that got referenced, but will not be used until we
26635 	 * acquire _all_ of the SAs we need.
26636 	 */
26637 	if (need_ah_acquire || need_esp_acquire) {
26638 		if (io->ipsec_out_ah_sa != NULL) {
26639 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26640 			io->ipsec_out_ah_sa = NULL;
26641 		}
26642 		if (io->ipsec_out_esp_sa != NULL) {
26643 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26644 			io->ipsec_out_esp_sa = NULL;
26645 		}
26646 
26647 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26648 		return (B_FALSE);
26649 	}
26650 
26651 	return (B_TRUE);
26652 }
26653 
26654 /*
26655  * Process an IPSEC_OUT message and see what you can
26656  * do with it.
26657  * IPQoS Notes:
26658  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26659  * IPsec.
26660  * XXX would like to nuke ire_t.
26661  * XXX ill_index better be "real"
26662  */
26663 void
26664 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26665 {
26666 	ipsec_out_t *io;
26667 	ipsec_policy_t *pp;
26668 	ipsec_action_t *ap;
26669 	ipha_t *ipha;
26670 	ip6_t *ip6h;
26671 	mblk_t *mp;
26672 	ill_t *ill;
26673 	zoneid_t zoneid;
26674 	ipsec_status_t ipsec_rc;
26675 	boolean_t ill_need_rele = B_FALSE;
26676 	ip_stack_t	*ipst;
26677 	ipsec_stack_t	*ipss;
26678 
26679 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26680 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26681 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26682 	ipst = io->ipsec_out_ns->netstack_ip;
26683 	mp = ipsec_mp->b_cont;
26684 
26685 	/*
26686 	 * Initiate IPPF processing. We do it here to account for packets
26687 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26688 	 * We can check for ipsec_out_proc_begin even for such packets, as
26689 	 * they will always be false (asserted below).
26690 	 */
26691 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26692 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26693 		    io->ipsec_out_ill_index : ill_index);
26694 		if (mp == NULL) {
26695 			ip2dbg(("ipsec_out_process: packet dropped "\
26696 			    "during IPPF processing\n"));
26697 			freeb(ipsec_mp);
26698 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26699 			return;
26700 		}
26701 	}
26702 
26703 	if (!io->ipsec_out_secure) {
26704 		/*
26705 		 * We came here by mistake.
26706 		 * Don't bother with ipsec processing
26707 		 * Should "discourage" this path in the future.
26708 		 */
26709 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26710 		goto done;
26711 	}
26712 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26713 	ASSERT((io->ipsec_out_policy != NULL) ||
26714 	    (io->ipsec_out_act != NULL));
26715 	ASSERT(io->ipsec_out_failed == B_FALSE);
26716 
26717 	ipss = ipst->ips_netstack->netstack_ipsec;
26718 	if (!ipsec_loaded(ipss)) {
26719 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26720 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26721 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26722 		} else {
26723 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26724 		}
26725 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26726 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26727 		    &ipss->ipsec_dropper);
26728 		return;
26729 	}
26730 
26731 	/*
26732 	 * IPsec processing has started.
26733 	 */
26734 	io->ipsec_out_proc_begin = B_TRUE;
26735 	ap = io->ipsec_out_act;
26736 	if (ap == NULL) {
26737 		pp = io->ipsec_out_policy;
26738 		ASSERT(pp != NULL);
26739 		ap = pp->ipsp_act;
26740 		ASSERT(ap != NULL);
26741 	}
26742 
26743 	/*
26744 	 * Save the outbound ill index. When the packet comes back
26745 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26746 	 * before sending it the accelerated packet.
26747 	 */
26748 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26749 		int ifindex;
26750 		ill = ire_to_ill(ire);
26751 		ifindex = ill->ill_phyint->phyint_ifindex;
26752 		io->ipsec_out_capab_ill_index = ifindex;
26753 	}
26754 
26755 	/*
26756 	 * The order of processing is first insert a IP header if needed.
26757 	 * Then insert the ESP header and then the AH header.
26758 	 */
26759 	if ((io->ipsec_out_se_done == B_FALSE) &&
26760 	    (ap->ipa_want_se)) {
26761 		/*
26762 		 * First get the outer IP header before sending
26763 		 * it to ESP.
26764 		 */
26765 		ipha_t *oipha, *iipha;
26766 		mblk_t *outer_mp, *inner_mp;
26767 
26768 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26769 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26770 			    "ipsec_out_process: "
26771 			    "Self-Encapsulation failed: Out of memory\n");
26772 			freemsg(ipsec_mp);
26773 			if (ill != NULL) {
26774 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26775 			} else {
26776 				BUMP_MIB(&ipst->ips_ip_mib,
26777 				    ipIfStatsOutDiscards);
26778 			}
26779 			return;
26780 		}
26781 		inner_mp = ipsec_mp->b_cont;
26782 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26783 		oipha = (ipha_t *)outer_mp->b_rptr;
26784 		iipha = (ipha_t *)inner_mp->b_rptr;
26785 		*oipha = *iipha;
26786 		outer_mp->b_wptr += sizeof (ipha_t);
26787 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26788 		    sizeof (ipha_t));
26789 		oipha->ipha_protocol = IPPROTO_ENCAP;
26790 		oipha->ipha_version_and_hdr_length =
26791 		    IP_SIMPLE_HDR_VERSION;
26792 		oipha->ipha_hdr_checksum = 0;
26793 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26794 		outer_mp->b_cont = inner_mp;
26795 		ipsec_mp->b_cont = outer_mp;
26796 
26797 		io->ipsec_out_se_done = B_TRUE;
26798 		io->ipsec_out_tunnel = B_TRUE;
26799 	}
26800 
26801 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26802 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26803 	    !ipsec_out_select_sa(ipsec_mp))
26804 		return;
26805 
26806 	/*
26807 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26808 	 * to do the heavy lifting.
26809 	 */
26810 	zoneid = io->ipsec_out_zoneid;
26811 	ASSERT(zoneid != ALL_ZONES);
26812 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26813 		ASSERT(io->ipsec_out_esp_sa != NULL);
26814 		io->ipsec_out_esp_done = B_TRUE;
26815 		/*
26816 		 * Note that since hw accel can only apply one transform,
26817 		 * not two, we skip hw accel for ESP if we also have AH
26818 		 * This is an design limitation of the interface
26819 		 * which should be revisited.
26820 		 */
26821 		ASSERT(ire != NULL);
26822 		if (io->ipsec_out_ah_sa == NULL) {
26823 			ill = (ill_t *)ire->ire_stq->q_ptr;
26824 			ipsec_out_is_accelerated(ipsec_mp,
26825 			    io->ipsec_out_esp_sa, ill, ire);
26826 		}
26827 
26828 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26829 		switch (ipsec_rc) {
26830 		case IPSEC_STATUS_SUCCESS:
26831 			break;
26832 		case IPSEC_STATUS_FAILED:
26833 			if (ill != NULL) {
26834 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26835 			} else {
26836 				BUMP_MIB(&ipst->ips_ip_mib,
26837 				    ipIfStatsOutDiscards);
26838 			}
26839 			/* FALLTHRU */
26840 		case IPSEC_STATUS_PENDING:
26841 			return;
26842 		}
26843 	}
26844 
26845 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26846 		ASSERT(io->ipsec_out_ah_sa != NULL);
26847 		io->ipsec_out_ah_done = B_TRUE;
26848 		if (ire == NULL) {
26849 			int idx = io->ipsec_out_capab_ill_index;
26850 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26851 			    NULL, NULL, NULL, NULL, ipst);
26852 			ill_need_rele = B_TRUE;
26853 		} else {
26854 			ill = (ill_t *)ire->ire_stq->q_ptr;
26855 		}
26856 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26857 		    ire);
26858 
26859 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26860 		switch (ipsec_rc) {
26861 		case IPSEC_STATUS_SUCCESS:
26862 			break;
26863 		case IPSEC_STATUS_FAILED:
26864 			if (ill != NULL) {
26865 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26866 			} else {
26867 				BUMP_MIB(&ipst->ips_ip_mib,
26868 				    ipIfStatsOutDiscards);
26869 			}
26870 			/* FALLTHRU */
26871 		case IPSEC_STATUS_PENDING:
26872 			if (ill != NULL && ill_need_rele)
26873 				ill_refrele(ill);
26874 			return;
26875 		}
26876 	}
26877 	/*
26878 	 * We are done with IPsec processing. Send it over
26879 	 * the wire.
26880 	 */
26881 done:
26882 	mp = ipsec_mp->b_cont;
26883 	ipha = (ipha_t *)mp->b_rptr;
26884 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26885 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
26886 	} else {
26887 		ip6h = (ip6_t *)ipha;
26888 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
26889 	}
26890 	if (ill != NULL && ill_need_rele)
26891 		ill_refrele(ill);
26892 }
26893 
26894 /* ARGSUSED */
26895 void
26896 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26897 {
26898 	opt_restart_t	*or;
26899 	int	err;
26900 	conn_t	*connp;
26901 
26902 	ASSERT(CONN_Q(q));
26903 	connp = Q_TO_CONN(q);
26904 
26905 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26906 	or = (opt_restart_t *)first_mp->b_rptr;
26907 	/*
26908 	 * We don't need to pass any credentials here since this is just
26909 	 * a restart. The credentials are passed in when svr4_optcom_req
26910 	 * is called the first time (from ip_wput_nondata).
26911 	 */
26912 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26913 		err = svr4_optcom_req(q, first_mp, NULL,
26914 		    &ip_opt_obj, B_FALSE);
26915 	} else {
26916 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26917 		err = tpi_optcom_req(q, first_mp, NULL,
26918 		    &ip_opt_obj, B_FALSE);
26919 	}
26920 	if (err != EINPROGRESS) {
26921 		/* operation is done */
26922 		CONN_OPER_PENDING_DONE(connp);
26923 	}
26924 }
26925 
26926 /*
26927  * ioctls that go through a down/up sequence may need to wait for the down
26928  * to complete. This involves waiting for the ire and ipif refcnts to go down
26929  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26930  */
26931 /* ARGSUSED */
26932 void
26933 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26934 {
26935 	struct iocblk *iocp;
26936 	mblk_t *mp1;
26937 	ip_ioctl_cmd_t *ipip;
26938 	int err;
26939 	sin_t	*sin;
26940 	struct lifreq *lifr;
26941 	struct ifreq *ifr;
26942 
26943 	iocp = (struct iocblk *)mp->b_rptr;
26944 	ASSERT(ipsq != NULL);
26945 	/* Existence of mp1 verified in ip_wput_nondata */
26946 	mp1 = mp->b_cont->b_cont;
26947 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26948 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26949 		/*
26950 		 * Special case where ipsq_current_ipif is not set:
26951 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26952 		 * ill could also have become part of a ipmp group in the
26953 		 * process, we are here as were not able to complete the
26954 		 * operation in ipif_set_values because we could not become
26955 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
26956 		 * will not be set so we need to set it.
26957 		 */
26958 		ill_t *ill = q->q_ptr;
26959 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
26960 	}
26961 	ASSERT(ipsq->ipsq_current_ipif != NULL);
26962 
26963 	if (ipip->ipi_cmd_type == IF_CMD) {
26964 		/* This a old style SIOC[GS]IF* command */
26965 		ifr = (struct ifreq *)mp1->b_rptr;
26966 		sin = (sin_t *)&ifr->ifr_addr;
26967 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26968 		/* This a new style SIOC[GS]LIF* command */
26969 		lifr = (struct lifreq *)mp1->b_rptr;
26970 		sin = (sin_t *)&lifr->lifr_addr;
26971 	} else {
26972 		sin = NULL;
26973 	}
26974 
26975 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_current_ipif, sin, q, mp,
26976 	    ipip, mp1->b_rptr);
26977 
26978 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26979 }
26980 
26981 /*
26982  * ioctl processing
26983  *
26984  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
26985  * the ioctl command in the ioctl tables, determines the copyin data size
26986  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
26987  *
26988  * ioctl processing then continues when the M_IOCDATA makes its way down to
26989  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
26990  * associated 'conn' is refheld till the end of the ioctl and the general
26991  * ioctl processing function ip_process_ioctl() is called to extract the
26992  * arguments and process the ioctl.  To simplify extraction, ioctl commands
26993  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
26994  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
26995  * is used to extract the ioctl's arguments.
26996  *
26997  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26998  * so goes thru the serialization primitive ipsq_try_enter. Then the
26999  * appropriate function to handle the ioctl is called based on the entry in
27000  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
27001  * which also refreleases the 'conn' that was refheld at the start of the
27002  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
27003  *
27004  * Many exclusive ioctls go thru an internal down up sequence as part of
27005  * the operation. For example an attempt to change the IP address of an
27006  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
27007  * does all the cleanup such as deleting all ires that use this address.
27008  * Then we need to wait till all references to the interface go away.
27009  */
27010 void
27011 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
27012 {
27013 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
27014 	ip_ioctl_cmd_t *ipip = arg;
27015 	ip_extract_func_t *extract_funcp;
27016 	cmd_info_t ci;
27017 	int err;
27018 	boolean_t entered_ipsq = B_FALSE;
27019 
27020 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
27021 
27022 	if (ipip == NULL)
27023 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27024 
27025 	/*
27026 	 * SIOCLIFADDIF needs to go thru a special path since the
27027 	 * ill may not exist yet. This happens in the case of lo0
27028 	 * which is created using this ioctl.
27029 	 */
27030 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
27031 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
27032 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27033 		return;
27034 	}
27035 
27036 	ci.ci_ipif = NULL;
27037 	if (ipip->ipi_cmd_type == MISC_CMD) {
27038 		/*
27039 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
27040 		 */
27041 		if (ipip->ipi_cmd == IF_UNITSEL) {
27042 			/* ioctl comes down the ill */
27043 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
27044 			ipif_refhold(ci.ci_ipif);
27045 		}
27046 		err = 0;
27047 		ci.ci_sin = NULL;
27048 		ci.ci_sin6 = NULL;
27049 		ci.ci_lifr = NULL;
27050 	} else {
27051 		switch (ipip->ipi_cmd_type) {
27052 		case IF_CMD:
27053 		case LIF_CMD:
27054 			extract_funcp = ip_extract_lifreq;
27055 			break;
27056 
27057 		case ARP_CMD:
27058 		case XARP_CMD:
27059 			extract_funcp = ip_extract_arpreq;
27060 			break;
27061 
27062 		case TUN_CMD:
27063 			extract_funcp = ip_extract_tunreq;
27064 			break;
27065 
27066 		case MSFILT_CMD:
27067 			extract_funcp = ip_extract_msfilter;
27068 			break;
27069 
27070 		default:
27071 			ASSERT(0);
27072 		}
27073 
27074 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
27075 		if (err != 0) {
27076 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27077 			return;
27078 		}
27079 
27080 		/*
27081 		 * All of the extraction functions return a refheld ipif.
27082 		 */
27083 		ASSERT(ci.ci_ipif != NULL);
27084 	}
27085 
27086 	/*
27087 	 * If ipsq is non-null, we are already being called exclusively
27088 	 */
27089 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
27090 	if (!(ipip->ipi_flags & IPI_WR)) {
27091 		/*
27092 		 * A return value of EINPROGRESS means the ioctl is
27093 		 * either queued and waiting for some reason or has
27094 		 * already completed.
27095 		 */
27096 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
27097 		    ci.ci_lifr);
27098 		if (ci.ci_ipif != NULL)
27099 			ipif_refrele(ci.ci_ipif);
27100 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27101 		return;
27102 	}
27103 
27104 	ASSERT(ci.ci_ipif != NULL);
27105 
27106 	if (ipsq == NULL) {
27107 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
27108 		    ip_process_ioctl, NEW_OP, B_TRUE);
27109 		entered_ipsq = B_TRUE;
27110 	}
27111 	/*
27112 	 * Release the ipif so that ipif_down and friends that wait for
27113 	 * references to go away are not misled about the current ipif_refcnt
27114 	 * values. We are writer so we can access the ipif even after releasing
27115 	 * the ipif.
27116 	 */
27117 	ipif_refrele(ci.ci_ipif);
27118 	if (ipsq == NULL)
27119 		return;
27120 
27121 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
27122 
27123 	/*
27124 	 * For most set ioctls that come here, this serves as a single point
27125 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
27126 	 * be any new references to the ipif. This helps functions that go
27127 	 * through this path and end up trying to wait for the refcnts
27128 	 * associated with the ipif to go down to zero. Some exceptions are
27129 	 * Failover, Failback, and Groupname commands that operate on more than
27130 	 * just the ci.ci_ipif. These commands internally determine the
27131 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
27132 	 * flags on that set. Another exception is the Removeif command that
27133 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
27134 	 * ipif to operate on.
27135 	 */
27136 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
27137 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
27138 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
27139 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
27140 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
27141 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
27142 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
27143 
27144 	/*
27145 	 * A return value of EINPROGRESS means the ioctl is
27146 	 * either queued and waiting for some reason or has
27147 	 * already completed.
27148 	 */
27149 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
27150 
27151 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27152 
27153 	if (entered_ipsq)
27154 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
27155 }
27156 
27157 /*
27158  * Complete the ioctl. Typically ioctls use the mi package and need to
27159  * do mi_copyout/mi_copy_done.
27160  */
27161 void
27162 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
27163 {
27164 	conn_t	*connp = NULL;
27165 
27166 	if (err == EINPROGRESS)
27167 		return;
27168 
27169 	if (CONN_Q(q)) {
27170 		connp = Q_TO_CONN(q);
27171 		ASSERT(connp->conn_ref >= 2);
27172 	}
27173 
27174 	switch (mode) {
27175 	case COPYOUT:
27176 		if (err == 0)
27177 			mi_copyout(q, mp);
27178 		else
27179 			mi_copy_done(q, mp, err);
27180 		break;
27181 
27182 	case NO_COPYOUT:
27183 		mi_copy_done(q, mp, err);
27184 		break;
27185 
27186 	default:
27187 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27188 		break;
27189 	}
27190 
27191 	/*
27192 	 * The refhold placed at the start of the ioctl is released here.
27193 	 */
27194 	if (connp != NULL)
27195 		CONN_OPER_PENDING_DONE(connp);
27196 
27197 	if (ipsq != NULL)
27198 		ipsq_current_finish(ipsq);
27199 }
27200 
27201 /*
27202  * This is called from ip_wput_nondata to resume a deferred TCP bind.
27203  */
27204 /* ARGSUSED */
27205 void
27206 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
27207 {
27208 	conn_t *connp = arg;
27209 	tcp_t	*tcp;
27210 
27211 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
27212 	tcp = connp->conn_tcp;
27213 
27214 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
27215 		freemsg(mp);
27216 	else
27217 		tcp_rput_other(tcp, mp);
27218 	CONN_OPER_PENDING_DONE(connp);
27219 }
27220 
27221 /* Called from ip_wput for all non data messages */
27222 /* ARGSUSED */
27223 void
27224 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27225 {
27226 	mblk_t		*mp1;
27227 	ire_t		*ire, *fake_ire;
27228 	ill_t		*ill;
27229 	struct iocblk	*iocp;
27230 	ip_ioctl_cmd_t	*ipip;
27231 	cred_t		*cr;
27232 	conn_t		*connp;
27233 	int		err;
27234 	nce_t		*nce;
27235 	ipif_t		*ipif;
27236 	ip_stack_t	*ipst;
27237 	char		*proto_str;
27238 
27239 	if (CONN_Q(q)) {
27240 		connp = Q_TO_CONN(q);
27241 		ipst = connp->conn_netstack->netstack_ip;
27242 	} else {
27243 		connp = NULL;
27244 		ipst = ILLQ_TO_IPST(q);
27245 	}
27246 
27247 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
27248 
27249 	switch (DB_TYPE(mp)) {
27250 	case M_IOCTL:
27251 		/*
27252 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27253 		 * will arrange to copy in associated control structures.
27254 		 */
27255 		ip_sioctl_copyin_setup(q, mp);
27256 		return;
27257 	case M_IOCDATA:
27258 		/*
27259 		 * Ensure that this is associated with one of our trans-
27260 		 * parent ioctls.  If it's not ours, discard it if we're
27261 		 * running as a driver, or pass it on if we're a module.
27262 		 */
27263 		iocp = (struct iocblk *)mp->b_rptr;
27264 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27265 		if (ipip == NULL) {
27266 			if (q->q_next == NULL) {
27267 				goto nak;
27268 			} else {
27269 				putnext(q, mp);
27270 			}
27271 			return;
27272 		}
27273 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
27274 			/*
27275 			 * the ioctl is one we recognise, but is not
27276 			 * consumed by IP as a module, pass M_IOCDATA
27277 			 * for processing downstream, but only for
27278 			 * common Streams ioctls.
27279 			 */
27280 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27281 				putnext(q, mp);
27282 				return;
27283 			} else {
27284 				goto nak;
27285 			}
27286 		}
27287 
27288 		/* IOCTL continuation following copyin or copyout. */
27289 		if (mi_copy_state(q, mp, NULL) == -1) {
27290 			/*
27291 			 * The copy operation failed.  mi_copy_state already
27292 			 * cleaned up, so we're out of here.
27293 			 */
27294 			return;
27295 		}
27296 		/*
27297 		 * If we just completed a copy in, we become writer and
27298 		 * continue processing in ip_sioctl_copyin_done.  If it
27299 		 * was a copy out, we call mi_copyout again.  If there is
27300 		 * nothing more to copy out, it will complete the IOCTL.
27301 		 */
27302 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27303 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27304 				mi_copy_done(q, mp, EPROTO);
27305 				return;
27306 			}
27307 			/*
27308 			 * Check for cases that need more copying.  A return
27309 			 * value of 0 means a second copyin has been started,
27310 			 * so we return; a return value of 1 means no more
27311 			 * copying is needed, so we continue.
27312 			 */
27313 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27314 			    MI_COPY_COUNT(mp) == 1) {
27315 				if (ip_copyin_msfilter(q, mp) == 0)
27316 					return;
27317 			}
27318 			/*
27319 			 * Refhold the conn, till the ioctl completes. This is
27320 			 * needed in case the ioctl ends up in the pending mp
27321 			 * list. Every mp in the ill_pending_mp list and
27322 			 * the ipsq_pending_mp must have a refhold on the conn
27323 			 * to resume processing. The refhold is released when
27324 			 * the ioctl completes. (normally or abnormally)
27325 			 * In all cases ip_ioctl_finish is called to finish
27326 			 * the ioctl.
27327 			 */
27328 			if (connp != NULL) {
27329 				/* This is not a reentry */
27330 				ASSERT(ipsq == NULL);
27331 				CONN_INC_REF(connp);
27332 			} else {
27333 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27334 					mi_copy_done(q, mp, EINVAL);
27335 					return;
27336 				}
27337 			}
27338 
27339 			ip_process_ioctl(ipsq, q, mp, ipip);
27340 
27341 		} else {
27342 			mi_copyout(q, mp);
27343 		}
27344 		return;
27345 nak:
27346 		iocp->ioc_error = EINVAL;
27347 		mp->b_datap->db_type = M_IOCNAK;
27348 		iocp->ioc_count = 0;
27349 		qreply(q, mp);
27350 		return;
27351 
27352 	case M_IOCNAK:
27353 		/*
27354 		 * The only way we could get here is if a resolver didn't like
27355 		 * an IOCTL we sent it.	 This shouldn't happen.
27356 		 */
27357 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27358 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27359 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27360 		freemsg(mp);
27361 		return;
27362 	case M_IOCACK:
27363 		/* /dev/ip shouldn't see this */
27364 		if (CONN_Q(q))
27365 			goto nak;
27366 
27367 		/* Finish socket ioctls passed through to ARP. */
27368 		ip_sioctl_iocack(q, mp);
27369 		return;
27370 	case M_FLUSH:
27371 		if (*mp->b_rptr & FLUSHW)
27372 			flushq(q, FLUSHALL);
27373 		if (q->q_next) {
27374 			putnext(q, mp);
27375 			return;
27376 		}
27377 		if (*mp->b_rptr & FLUSHR) {
27378 			*mp->b_rptr &= ~FLUSHW;
27379 			qreply(q, mp);
27380 			return;
27381 		}
27382 		freemsg(mp);
27383 		return;
27384 	case IRE_DB_REQ_TYPE:
27385 		if (connp == NULL) {
27386 			proto_str = "IRE_DB_REQ_TYPE";
27387 			goto protonak;
27388 		}
27389 		/* An Upper Level Protocol wants a copy of an IRE. */
27390 		ip_ire_req(q, mp);
27391 		return;
27392 	case M_CTL:
27393 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27394 			break;
27395 
27396 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27397 		    TUN_HELLO) {
27398 			ASSERT(connp != NULL);
27399 			connp->conn_flags |= IPCL_IPTUN;
27400 			freeb(mp);
27401 			return;
27402 		}
27403 
27404 		/* M_CTL messages are used by ARP to tell us things. */
27405 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27406 			break;
27407 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27408 		case AR_ENTRY_SQUERY:
27409 			ip_wput_ctl(q, mp);
27410 			return;
27411 		case AR_CLIENT_NOTIFY:
27412 			ip_arp_news(q, mp);
27413 			return;
27414 		case AR_DLPIOP_DONE:
27415 			ASSERT(q->q_next != NULL);
27416 			ill = (ill_t *)q->q_ptr;
27417 			/* qwriter_ip releases the refhold */
27418 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27419 			ill_refhold(ill);
27420 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27421 			return;
27422 		case AR_ARP_CLOSING:
27423 			/*
27424 			 * ARP (above us) is closing. If no ARP bringup is
27425 			 * currently pending, ack the message so that ARP
27426 			 * can complete its close. Also mark ill_arp_closing
27427 			 * so that new ARP bringups will fail. If any
27428 			 * ARP bringup is currently in progress, we will
27429 			 * ack this when the current ARP bringup completes.
27430 			 */
27431 			ASSERT(q->q_next != NULL);
27432 			ill = (ill_t *)q->q_ptr;
27433 			mutex_enter(&ill->ill_lock);
27434 			ill->ill_arp_closing = 1;
27435 			if (!ill->ill_arp_bringup_pending) {
27436 				mutex_exit(&ill->ill_lock);
27437 				qreply(q, mp);
27438 			} else {
27439 				mutex_exit(&ill->ill_lock);
27440 				freemsg(mp);
27441 			}
27442 			return;
27443 		case AR_ARP_EXTEND:
27444 			/*
27445 			 * The ARP module above us is capable of duplicate
27446 			 * address detection.  Old ATM drivers will not send
27447 			 * this message.
27448 			 */
27449 			ASSERT(q->q_next != NULL);
27450 			ill = (ill_t *)q->q_ptr;
27451 			ill->ill_arp_extend = B_TRUE;
27452 			freemsg(mp);
27453 			return;
27454 		default:
27455 			break;
27456 		}
27457 		break;
27458 	case M_PROTO:
27459 	case M_PCPROTO:
27460 		/*
27461 		 * The only PROTO messages we expect are ULP binds and
27462 		 * copies of option negotiation acknowledgements.
27463 		 */
27464 		switch (((union T_primitives *)mp->b_rptr)->type) {
27465 		case O_T_BIND_REQ:
27466 		case T_BIND_REQ: {
27467 			/* Request can get queued in bind */
27468 			if (connp == NULL) {
27469 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27470 				goto protonak;
27471 			}
27472 			/*
27473 			 * The transports except SCTP call ip_bind_{v4,v6}()
27474 			 * directly instead of a a putnext. SCTP doesn't
27475 			 * generate any T_BIND_REQ since it has its own
27476 			 * fanout data structures. However, ESP and AH
27477 			 * come in for regular binds; all other cases are
27478 			 * bind retries.
27479 			 */
27480 			ASSERT(!IPCL_IS_SCTP(connp));
27481 
27482 			/* Don't increment refcnt if this is a re-entry */
27483 			if (ipsq == NULL)
27484 				CONN_INC_REF(connp);
27485 
27486 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27487 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27488 			if (mp == NULL)
27489 				return;
27490 			if (IPCL_IS_TCP(connp)) {
27491 				/*
27492 				 * In the case of TCP endpoint we
27493 				 * come here only for bind retries
27494 				 */
27495 				ASSERT(ipsq != NULL);
27496 				CONN_INC_REF(connp);
27497 				squeue_fill(connp->conn_sqp, mp,
27498 				    ip_resume_tcp_bind, connp,
27499 				    SQTAG_BIND_RETRY);
27500 			} else if (IPCL_IS_UDP(connp)) {
27501 				/*
27502 				 * In the case of UDP endpoint we
27503 				 * come here only for bind retries
27504 				 */
27505 				ASSERT(ipsq != NULL);
27506 				udp_resume_bind(connp, mp);
27507 			} else if (IPCL_IS_RAWIP(connp)) {
27508 				/*
27509 				 * In the case of RAWIP endpoint we
27510 				 * come here only for bind retries
27511 				 */
27512 				ASSERT(ipsq != NULL);
27513 				rawip_resume_bind(connp, mp);
27514 			} else {
27515 				/* The case of AH and ESP */
27516 				qreply(q, mp);
27517 				CONN_OPER_PENDING_DONE(connp);
27518 			}
27519 			return;
27520 		}
27521 		case T_SVR4_OPTMGMT_REQ:
27522 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27523 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27524 
27525 			if (connp == NULL) {
27526 				proto_str = "T_SVR4_OPTMGMT_REQ";
27527 				goto protonak;
27528 			}
27529 
27530 			if (!snmpcom_req(q, mp, ip_snmp_set,
27531 			    ip_snmp_get, cr)) {
27532 				/*
27533 				 * Call svr4_optcom_req so that it can
27534 				 * generate the ack. We don't come here
27535 				 * if this operation is being restarted.
27536 				 * ip_restart_optmgmt will drop the conn ref.
27537 				 * In the case of ipsec option after the ipsec
27538 				 * load is complete conn_restart_ipsec_waiter
27539 				 * drops the conn ref.
27540 				 */
27541 				ASSERT(ipsq == NULL);
27542 				CONN_INC_REF(connp);
27543 				if (ip_check_for_ipsec_opt(q, mp))
27544 					return;
27545 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj,
27546 				    B_FALSE);
27547 				if (err != EINPROGRESS) {
27548 					/* Operation is done */
27549 					CONN_OPER_PENDING_DONE(connp);
27550 				}
27551 			}
27552 			return;
27553 		case T_OPTMGMT_REQ:
27554 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27555 			/*
27556 			 * Note: No snmpcom_req support through new
27557 			 * T_OPTMGMT_REQ.
27558 			 * Call tpi_optcom_req so that it can
27559 			 * generate the ack.
27560 			 */
27561 			if (connp == NULL) {
27562 				proto_str = "T_OPTMGMT_REQ";
27563 				goto protonak;
27564 			}
27565 
27566 			ASSERT(ipsq == NULL);
27567 			/*
27568 			 * We don't come here for restart. ip_restart_optmgmt
27569 			 * will drop the conn ref. In the case of ipsec option
27570 			 * after the ipsec load is complete
27571 			 * conn_restart_ipsec_waiter drops the conn ref.
27572 			 */
27573 			CONN_INC_REF(connp);
27574 			if (ip_check_for_ipsec_opt(q, mp))
27575 				return;
27576 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj, B_FALSE);
27577 			if (err != EINPROGRESS) {
27578 				/* Operation is done */
27579 				CONN_OPER_PENDING_DONE(connp);
27580 			}
27581 			return;
27582 		case T_UNBIND_REQ:
27583 			if (connp == NULL) {
27584 				proto_str = "T_UNBIND_REQ";
27585 				goto protonak;
27586 			}
27587 			mp = ip_unbind(q, mp);
27588 			qreply(q, mp);
27589 			return;
27590 		default:
27591 			/*
27592 			 * Have to drop any DLPI messages coming down from
27593 			 * arp (such as an info_req which would cause ip
27594 			 * to receive an extra info_ack if it was passed
27595 			 * through.
27596 			 */
27597 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27598 			    (int)*(uint_t *)mp->b_rptr));
27599 			freemsg(mp);
27600 			return;
27601 		}
27602 		/* NOTREACHED */
27603 	case IRE_DB_TYPE: {
27604 		nce_t		*nce;
27605 		ill_t		*ill;
27606 		in6_addr_t	gw_addr_v6;
27607 
27608 
27609 		/*
27610 		 * This is a response back from a resolver.  It
27611 		 * consists of a message chain containing:
27612 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27613 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27614 		 * The LL_HDR_MBLK is the DLPI header to use to get
27615 		 * the attached packet, and subsequent ones for the
27616 		 * same destination, transmitted.
27617 		 */
27618 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27619 			break;
27620 		/*
27621 		 * First, check to make sure the resolution succeeded.
27622 		 * If it failed, the second mblk will be empty.
27623 		 * If it is, free the chain, dropping the packet.
27624 		 * (We must ire_delete the ire; that frees the ire mblk)
27625 		 * We're doing this now to support PVCs for ATM; it's
27626 		 * a partial xresolv implementation. When we fully implement
27627 		 * xresolv interfaces, instead of freeing everything here
27628 		 * we'll initiate neighbor discovery.
27629 		 *
27630 		 * For v4 (ARP and other external resolvers) the resolver
27631 		 * frees the message, so no check is needed. This check
27632 		 * is required, though, for a full xresolve implementation.
27633 		 * Including this code here now both shows how external
27634 		 * resolvers can NACK a resolution request using an
27635 		 * existing design that has no specific provisions for NACKs,
27636 		 * and also takes into account that the current non-ARP
27637 		 * external resolver has been coded to use this method of
27638 		 * NACKing for all IPv6 (xresolv) cases,
27639 		 * whether our xresolv implementation is complete or not.
27640 		 *
27641 		 */
27642 		ire = (ire_t *)mp->b_rptr;
27643 		ill = ire_to_ill(ire);
27644 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27645 		if (mp1->b_rptr == mp1->b_wptr) {
27646 			if (ire->ire_ipversion == IPV6_VERSION) {
27647 				/*
27648 				 * XRESOLV interface.
27649 				 */
27650 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27651 				mutex_enter(&ire->ire_lock);
27652 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27653 				mutex_exit(&ire->ire_lock);
27654 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27655 					nce = ndp_lookup_v6(ill,
27656 					    &ire->ire_addr_v6, B_FALSE);
27657 				} else {
27658 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
27659 					    B_FALSE);
27660 				}
27661 				if (nce != NULL) {
27662 					nce_resolv_failed(nce);
27663 					ndp_delete(nce);
27664 					NCE_REFRELE(nce);
27665 				}
27666 			}
27667 			mp->b_cont = NULL;
27668 			freemsg(mp1);		/* frees the pkt as well */
27669 			ASSERT(ire->ire_nce == NULL);
27670 			ire_delete((ire_t *)mp->b_rptr);
27671 			return;
27672 		}
27673 
27674 		/*
27675 		 * Split them into IRE_MBLK and pkt and feed it into
27676 		 * ire_add_then_send. Then in ire_add_then_send
27677 		 * the IRE will be added, and then the packet will be
27678 		 * run back through ip_wput. This time it will make
27679 		 * it to the wire.
27680 		 */
27681 		mp->b_cont = NULL;
27682 		mp = mp1->b_cont;		/* now, mp points to pkt */
27683 		mp1->b_cont = NULL;
27684 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27685 		if (ire->ire_ipversion == IPV6_VERSION) {
27686 			/*
27687 			 * XRESOLV interface. Find the nce and put a copy
27688 			 * of the dl_unitdata_req in nce_res_mp
27689 			 */
27690 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27691 			mutex_enter(&ire->ire_lock);
27692 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27693 			mutex_exit(&ire->ire_lock);
27694 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27695 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
27696 				    B_FALSE);
27697 			} else {
27698 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
27699 			}
27700 			if (nce != NULL) {
27701 				/*
27702 				 * We have to protect nce_res_mp here
27703 				 * from being accessed by other threads
27704 				 * while we change the mblk pointer.
27705 				 * Other functions will also lock the nce when
27706 				 * accessing nce_res_mp.
27707 				 *
27708 				 * The reason we change the mblk pointer
27709 				 * here rather than copying the resolved address
27710 				 * into the template is that, unlike with
27711 				 * ethernet, we have no guarantee that the
27712 				 * resolved address length will be
27713 				 * smaller than or equal to the lla length
27714 				 * with which the template was allocated,
27715 				 * (for ethernet, they're equal)
27716 				 * so we have to use the actual resolved
27717 				 * address mblk - which holds the real
27718 				 * dl_unitdata_req with the resolved address.
27719 				 *
27720 				 * Doing this is the same behavior as was
27721 				 * previously used in the v4 ARP case.
27722 				 */
27723 				mutex_enter(&nce->nce_lock);
27724 				if (nce->nce_res_mp != NULL)
27725 					freemsg(nce->nce_res_mp);
27726 				nce->nce_res_mp = mp1;
27727 				mutex_exit(&nce->nce_lock);
27728 				/*
27729 				 * We do a fastpath probe here because
27730 				 * we have resolved the address without
27731 				 * using Neighbor Discovery.
27732 				 * In the non-XRESOLV v6 case, the fastpath
27733 				 * probe is done right after neighbor
27734 				 * discovery completes.
27735 				 */
27736 				if (nce->nce_res_mp != NULL) {
27737 					int res;
27738 					nce_fastpath_list_add(nce);
27739 					res = ill_fastpath_probe(ill,
27740 					    nce->nce_res_mp);
27741 					if (res != 0 && res != EAGAIN)
27742 						nce_fastpath_list_delete(nce);
27743 				}
27744 
27745 				ire_add_then_send(q, ire, mp);
27746 				/*
27747 				 * Now we have to clean out any packets
27748 				 * that may have been queued on the nce
27749 				 * while it was waiting for address resolution
27750 				 * to complete.
27751 				 */
27752 				mutex_enter(&nce->nce_lock);
27753 				mp1 = nce->nce_qd_mp;
27754 				nce->nce_qd_mp = NULL;
27755 				mutex_exit(&nce->nce_lock);
27756 				while (mp1 != NULL) {
27757 					mblk_t *nxt_mp;
27758 					queue_t *fwdq = NULL;
27759 					ill_t   *inbound_ill;
27760 					uint_t ifindex;
27761 
27762 					nxt_mp = mp1->b_next;
27763 					mp1->b_next = NULL;
27764 					/*
27765 					 * Retrieve ifindex stored in
27766 					 * ip_rput_data_v6()
27767 					 */
27768 					ifindex =
27769 					    (uint_t)(uintptr_t)mp1->b_prev;
27770 					inbound_ill =
27771 					    ill_lookup_on_ifindex(ifindex,
27772 					    B_TRUE, NULL, NULL, NULL,
27773 					    NULL, ipst);
27774 					mp1->b_prev = NULL;
27775 					if (inbound_ill != NULL)
27776 						fwdq = inbound_ill->ill_rq;
27777 
27778 					if (fwdq != NULL) {
27779 						put(fwdq, mp1);
27780 						ill_refrele(inbound_ill);
27781 					} else
27782 						put(WR(ill->ill_rq), mp1);
27783 					mp1 = nxt_mp;
27784 				}
27785 				NCE_REFRELE(nce);
27786 			} else {	/* nce is NULL; clean up */
27787 				ire_delete(ire);
27788 				freemsg(mp);
27789 				freemsg(mp1);
27790 				return;
27791 			}
27792 		} else {
27793 			nce_t *arpce;
27794 			/*
27795 			 * Link layer resolution succeeded. Recompute the
27796 			 * ire_nce.
27797 			 */
27798 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27799 			if ((arpce = ndp_lookup_v4(ill,
27800 			    (ire->ire_gateway_addr != INADDR_ANY ?
27801 			    &ire->ire_gateway_addr : &ire->ire_addr),
27802 			    B_FALSE)) == NULL) {
27803 				freeb(ire->ire_mp);
27804 				freeb(mp1);
27805 				freemsg(mp);
27806 				return;
27807 			}
27808 			mutex_enter(&arpce->nce_lock);
27809 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27810 			if (arpce->nce_state == ND_REACHABLE) {
27811 				/*
27812 				 * Someone resolved this before us;
27813 				 * cleanup the res_mp. Since ire has
27814 				 * not been added yet, the call to ire_add_v4
27815 				 * from ire_add_then_send (when a dup is
27816 				 * detected) will clean up the ire.
27817 				 */
27818 				freeb(mp1);
27819 			} else {
27820 				ASSERT(arpce->nce_res_mp == NULL);
27821 				arpce->nce_res_mp = mp1;
27822 				arpce->nce_state = ND_REACHABLE;
27823 			}
27824 			mutex_exit(&arpce->nce_lock);
27825 			if (ire->ire_marks & IRE_MARK_NOADD) {
27826 				/*
27827 				 * this ire will not be added to the ire
27828 				 * cache table, so we can set the ire_nce
27829 				 * here, as there are no atomicity constraints.
27830 				 */
27831 				ire->ire_nce = arpce;
27832 				/*
27833 				 * We are associating this nce with the ire
27834 				 * so change the nce ref taken in
27835 				 * ndp_lookup_v4() from
27836 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27837 				 */
27838 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27839 			} else {
27840 				NCE_REFRELE(arpce);
27841 			}
27842 			ire_add_then_send(q, ire, mp);
27843 		}
27844 		return;	/* All is well, the packet has been sent. */
27845 	}
27846 	case IRE_ARPRESOLVE_TYPE: {
27847 
27848 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27849 			break;
27850 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27851 		mp->b_cont = NULL;
27852 		/*
27853 		 * First, check to make sure the resolution succeeded.
27854 		 * If it failed, the second mblk will be empty.
27855 		 */
27856 		if (mp1->b_rptr == mp1->b_wptr) {
27857 			/* cleanup  the incomplete ire, free queued packets */
27858 			freemsg(mp); /* fake ire */
27859 			freeb(mp1);  /* dl_unitdata response */
27860 			return;
27861 		}
27862 
27863 		/*
27864 		 * update any incomplete nce_t found. we lookup the ctable
27865 		 * and find the nce from the ire->ire_nce because we need
27866 		 * to pass the ire to ip_xmit_v4 later, and can find both
27867 		 * ire and nce in one lookup from the ctable.
27868 		 */
27869 		fake_ire = (ire_t *)mp->b_rptr;
27870 		/*
27871 		 * By the time we come back here from ARP
27872 		 * the logical outgoing interface  of the incomplete ire
27873 		 * we added in ire_forward could have disappeared,
27874 		 * causing the incomplete ire to also have
27875 		 * dissapeared. So we need to retreive the
27876 		 * proper ipif for the ire  before looking
27877 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
27878 		 */
27879 		ill = q->q_ptr;
27880 
27881 		/* Get the outgoing ipif */
27882 		mutex_enter(&ill->ill_lock);
27883 		if (ill->ill_state_flags & ILL_CONDEMNED) {
27884 			mutex_exit(&ill->ill_lock);
27885 			freemsg(mp); /* fake ire */
27886 			freeb(mp1);  /* dl_unitdata response */
27887 			return;
27888 		}
27889 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27890 
27891 		if (ipif == NULL) {
27892 			mutex_exit(&ill->ill_lock);
27893 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27894 			freemsg(mp);
27895 			freeb(mp1);
27896 			return;
27897 		}
27898 		ipif_refhold_locked(ipif);
27899 		mutex_exit(&ill->ill_lock);
27900 		ire = ire_ctable_lookup(fake_ire->ire_addr,
27901 		    fake_ire->ire_gateway_addr, IRE_CACHE,
27902 		    ipif, fake_ire->ire_zoneid, NULL,
27903 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY|
27904 		    MATCH_IRE_TYPE), ipst);
27905 		ipif_refrele(ipif);
27906 		if (ire == NULL) {
27907 			/*
27908 			 * no ire was found; check if there is an nce
27909 			 * for this lookup; if it has no ire's pointing at it
27910 			 * cleanup.
27911 			 */
27912 			if ((nce = ndp_lookup_v4(ill,
27913 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27914 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27915 			    B_FALSE)) != NULL) {
27916 				/*
27917 				 * cleanup:
27918 				 * We check for refcnt 2 (one for the nce
27919 				 * hash list + 1 for the ref taken by
27920 				 * ndp_lookup_v4) to check that there are
27921 				 * no ire's pointing at the nce.
27922 				 */
27923 				if (nce->nce_refcnt == 2)
27924 					ndp_delete(nce);
27925 				NCE_REFRELE(nce);
27926 			}
27927 			freeb(mp1);  /* dl_unitdata response */
27928 			freemsg(mp); /* fake ire */
27929 			return;
27930 		}
27931 		nce = ire->ire_nce;
27932 		DTRACE_PROBE2(ire__arpresolve__type,
27933 		    ire_t *, ire, nce_t *, nce);
27934 		ASSERT(nce->nce_state != ND_INITIAL);
27935 		mutex_enter(&nce->nce_lock);
27936 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27937 		if (nce->nce_state == ND_REACHABLE) {
27938 			/*
27939 			 * Someone resolved this before us;
27940 			 * our response is not needed any more.
27941 			 */
27942 			mutex_exit(&nce->nce_lock);
27943 			freeb(mp1);  /* dl_unitdata response */
27944 		} else {
27945 			ASSERT(nce->nce_res_mp == NULL);
27946 			nce->nce_res_mp = mp1;
27947 			nce->nce_state = ND_REACHABLE;
27948 			mutex_exit(&nce->nce_lock);
27949 			nce_fastpath(nce);
27950 		}
27951 		/*
27952 		 * The cached nce_t has been updated to be reachable;
27953 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
27954 		 */
27955 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27956 		freemsg(mp);
27957 		/*
27958 		 * send out queued packets.
27959 		 */
27960 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
27961 
27962 		IRE_REFRELE(ire);
27963 		return;
27964 	}
27965 	default:
27966 		break;
27967 	}
27968 	if (q->q_next) {
27969 		putnext(q, mp);
27970 	} else
27971 		freemsg(mp);
27972 	return;
27973 
27974 protonak:
27975 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
27976 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
27977 		qreply(q, mp);
27978 }
27979 
27980 /*
27981  * Process IP options in an outbound packet.  Modify the destination if there
27982  * is a source route option.
27983  * Returns non-zero if something fails in which case an ICMP error has been
27984  * sent and mp freed.
27985  */
27986 static int
27987 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27988     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
27989 {
27990 	ipoptp_t	opts;
27991 	uchar_t		*opt;
27992 	uint8_t		optval;
27993 	uint8_t		optlen;
27994 	ipaddr_t	dst;
27995 	intptr_t	code = 0;
27996 	mblk_t		*mp;
27997 	ire_t		*ire = NULL;
27998 
27999 	ip2dbg(("ip_wput_options\n"));
28000 	mp = ipsec_mp;
28001 	if (mctl_present) {
28002 		mp = ipsec_mp->b_cont;
28003 	}
28004 
28005 	dst = ipha->ipha_dst;
28006 	for (optval = ipoptp_first(&opts, ipha);
28007 	    optval != IPOPT_EOL;
28008 	    optval = ipoptp_next(&opts)) {
28009 		opt = opts.ipoptp_cur;
28010 		optlen = opts.ipoptp_len;
28011 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
28012 		    optval, optlen));
28013 		switch (optval) {
28014 			uint32_t off;
28015 		case IPOPT_SSRR:
28016 		case IPOPT_LSRR:
28017 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28018 				ip1dbg((
28019 				    "ip_wput_options: bad option offset\n"));
28020 				code = (char *)&opt[IPOPT_OLEN] -
28021 				    (char *)ipha;
28022 				goto param_prob;
28023 			}
28024 			off = opt[IPOPT_OFFSET];
28025 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
28026 			    ntohl(dst)));
28027 			/*
28028 			 * For strict: verify that dst is directly
28029 			 * reachable.
28030 			 */
28031 			if (optval == IPOPT_SSRR) {
28032 				ire = ire_ftable_lookup(dst, 0, 0,
28033 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
28034 				    MBLK_GETLABEL(mp),
28035 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
28036 				if (ire == NULL) {
28037 					ip1dbg(("ip_wput_options: SSRR not"
28038 					    " directly reachable: 0x%x\n",
28039 					    ntohl(dst)));
28040 					goto bad_src_route;
28041 				}
28042 				ire_refrele(ire);
28043 			}
28044 			break;
28045 		case IPOPT_RR:
28046 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28047 				ip1dbg((
28048 				    "ip_wput_options: bad option offset\n"));
28049 				code = (char *)&opt[IPOPT_OLEN] -
28050 				    (char *)ipha;
28051 				goto param_prob;
28052 			}
28053 			break;
28054 		case IPOPT_TS:
28055 			/*
28056 			 * Verify that length >=5 and that there is either
28057 			 * room for another timestamp or that the overflow
28058 			 * counter is not maxed out.
28059 			 */
28060 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
28061 			if (optlen < IPOPT_MINLEN_IT) {
28062 				goto param_prob;
28063 			}
28064 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28065 				ip1dbg((
28066 				    "ip_wput_options: bad option offset\n"));
28067 				code = (char *)&opt[IPOPT_OFFSET] -
28068 				    (char *)ipha;
28069 				goto param_prob;
28070 			}
28071 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
28072 			case IPOPT_TS_TSONLY:
28073 				off = IPOPT_TS_TIMELEN;
28074 				break;
28075 			case IPOPT_TS_TSANDADDR:
28076 			case IPOPT_TS_PRESPEC:
28077 			case IPOPT_TS_PRESPEC_RFC791:
28078 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
28079 				break;
28080 			default:
28081 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
28082 				    (char *)ipha;
28083 				goto param_prob;
28084 			}
28085 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
28086 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
28087 				/*
28088 				 * No room and the overflow counter is 15
28089 				 * already.
28090 				 */
28091 				goto param_prob;
28092 			}
28093 			break;
28094 		}
28095 	}
28096 
28097 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
28098 		return (0);
28099 
28100 	ip1dbg(("ip_wput_options: error processing IP options."));
28101 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
28102 
28103 param_prob:
28104 	/*
28105 	 * Since ip_wput() isn't close to finished, we fill
28106 	 * in enough of the header for credible error reporting.
28107 	 */
28108 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28109 		/* Failed */
28110 		freemsg(ipsec_mp);
28111 		return (-1);
28112 	}
28113 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
28114 	return (-1);
28115 
28116 bad_src_route:
28117 	/*
28118 	 * Since ip_wput() isn't close to finished, we fill
28119 	 * in enough of the header for credible error reporting.
28120 	 */
28121 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28122 		/* Failed */
28123 		freemsg(ipsec_mp);
28124 		return (-1);
28125 	}
28126 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
28127 	return (-1);
28128 }
28129 
28130 /*
28131  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
28132  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
28133  * thru /etc/system.
28134  */
28135 #define	CONN_MAXDRAINCNT	64
28136 
28137 static void
28138 conn_drain_init(ip_stack_t *ipst)
28139 {
28140 	int i;
28141 
28142 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
28143 
28144 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
28145 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
28146 		/*
28147 		 * Default value of the number of drainers is the
28148 		 * number of cpus, subject to maximum of 8 drainers.
28149 		 */
28150 		if (boot_max_ncpus != -1)
28151 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
28152 		else
28153 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
28154 	}
28155 
28156 	ipst->ips_conn_drain_list = kmem_zalloc(ipst->ips_conn_drain_list_cnt *
28157 	    sizeof (idl_t), KM_SLEEP);
28158 
28159 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28160 		mutex_init(&ipst->ips_conn_drain_list[i].idl_lock, NULL,
28161 		    MUTEX_DEFAULT, NULL);
28162 	}
28163 }
28164 
28165 static void
28166 conn_drain_fini(ip_stack_t *ipst)
28167 {
28168 	int i;
28169 
28170 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++)
28171 		mutex_destroy(&ipst->ips_conn_drain_list[i].idl_lock);
28172 	kmem_free(ipst->ips_conn_drain_list,
28173 	    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28174 	ipst->ips_conn_drain_list = NULL;
28175 }
28176 
28177 /*
28178  * Note: For an overview of how flowcontrol is handled in IP please see the
28179  * IP Flowcontrol notes at the top of this file.
28180  *
28181  * Flow control has blocked us from proceeding. Insert the given conn in one
28182  * of the conn drain lists. These conn wq's will be qenabled later on when
28183  * STREAMS flow control does a backenable. conn_walk_drain will enable
28184  * the first conn in each of these drain lists. Each of these qenabled conns
28185  * in turn enables the next in the list, after it runs, or when it closes,
28186  * thus sustaining the drain process.
28187  *
28188  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
28189  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
28190  * running at any time, on a given conn, since there can be only 1 service proc
28191  * running on a queue at any time.
28192  */
28193 void
28194 conn_drain_insert(conn_t *connp)
28195 {
28196 	idl_t	*idl;
28197 	uint_t	index;
28198 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28199 
28200 	mutex_enter(&connp->conn_lock);
28201 	if (connp->conn_state_flags & CONN_CLOSING) {
28202 		/*
28203 		 * The conn is closing as a result of which CONN_CLOSING
28204 		 * is set. Return.
28205 		 */
28206 		mutex_exit(&connp->conn_lock);
28207 		return;
28208 	} else if (connp->conn_idl == NULL) {
28209 		/*
28210 		 * Assign the next drain list round robin. We dont' use
28211 		 * a lock, and thus it may not be strictly round robin.
28212 		 * Atomicity of load/stores is enough to make sure that
28213 		 * conn_drain_list_index is always within bounds.
28214 		 */
28215 		index = ipst->ips_conn_drain_list_index;
28216 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28217 		connp->conn_idl = &ipst->ips_conn_drain_list[index];
28218 		index++;
28219 		if (index == ipst->ips_conn_drain_list_cnt)
28220 			index = 0;
28221 		ipst->ips_conn_drain_list_index = index;
28222 	}
28223 	mutex_exit(&connp->conn_lock);
28224 
28225 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28226 	if ((connp->conn_drain_prev != NULL) ||
28227 	    (connp->conn_state_flags & CONN_CLOSING)) {
28228 		/*
28229 		 * The conn is already in the drain list, OR
28230 		 * the conn is closing. We need to check again for
28231 		 * the closing case again since close can happen
28232 		 * after we drop the conn_lock, and before we
28233 		 * acquire the CONN_DRAIN_LIST_LOCK.
28234 		 */
28235 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28236 		return;
28237 	} else {
28238 		idl = connp->conn_idl;
28239 	}
28240 
28241 	/*
28242 	 * The conn is not in the drain list. Insert it at the
28243 	 * tail of the drain list. The drain list is circular
28244 	 * and doubly linked. idl_conn points to the 1st element
28245 	 * in the list.
28246 	 */
28247 	if (idl->idl_conn == NULL) {
28248 		idl->idl_conn = connp;
28249 		connp->conn_drain_next = connp;
28250 		connp->conn_drain_prev = connp;
28251 	} else {
28252 		conn_t *head = idl->idl_conn;
28253 
28254 		connp->conn_drain_next = head;
28255 		connp->conn_drain_prev = head->conn_drain_prev;
28256 		head->conn_drain_prev->conn_drain_next = connp;
28257 		head->conn_drain_prev = connp;
28258 	}
28259 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28260 }
28261 
28262 /*
28263  * This conn is closing, and we are called from ip_close. OR
28264  * This conn has been serviced by ip_wsrv, and we need to do the tail
28265  * processing.
28266  * If this conn is part of the drain list, we may need to sustain the drain
28267  * process by qenabling the next conn in the drain list. We may also need to
28268  * remove this conn from the list, if it is done.
28269  */
28270 static void
28271 conn_drain_tail(conn_t *connp, boolean_t closing)
28272 {
28273 	idl_t *idl;
28274 
28275 	/*
28276 	 * connp->conn_idl is stable at this point, and no lock is needed
28277 	 * to check it. If we are called from ip_close, close has already
28278 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28279 	 * called us only because conn_idl is non-null. If we are called thru
28280 	 * service, conn_idl could be null, but it cannot change because
28281 	 * service is single-threaded per queue, and there cannot be another
28282 	 * instance of service trying to call conn_drain_insert on this conn
28283 	 * now.
28284 	 */
28285 	ASSERT(!closing || (connp->conn_idl != NULL));
28286 
28287 	/*
28288 	 * If connp->conn_idl is null, the conn has not been inserted into any
28289 	 * drain list even once since creation of the conn. Just return.
28290 	 */
28291 	if (connp->conn_idl == NULL)
28292 		return;
28293 
28294 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28295 
28296 	if (connp->conn_drain_prev == NULL) {
28297 		/* This conn is currently not in the drain list.  */
28298 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28299 		return;
28300 	}
28301 	idl = connp->conn_idl;
28302 	if (idl->idl_conn_draining == connp) {
28303 		/*
28304 		 * This conn is the current drainer. If this is the last conn
28305 		 * in the drain list, we need to do more checks, in the 'if'
28306 		 * below. Otherwwise we need to just qenable the next conn,
28307 		 * to sustain the draining, and is handled in the 'else'
28308 		 * below.
28309 		 */
28310 		if (connp->conn_drain_next == idl->idl_conn) {
28311 			/*
28312 			 * This conn is the last in this list. This round
28313 			 * of draining is complete. If idl_repeat is set,
28314 			 * it means another flow enabling has happened from
28315 			 * the driver/streams and we need to another round
28316 			 * of draining.
28317 			 * If there are more than 2 conns in the drain list,
28318 			 * do a left rotate by 1, so that all conns except the
28319 			 * conn at the head move towards the head by 1, and the
28320 			 * the conn at the head goes to the tail. This attempts
28321 			 * a more even share for all queues that are being
28322 			 * drained.
28323 			 */
28324 			if ((connp->conn_drain_next != connp) &&
28325 			    (idl->idl_conn->conn_drain_next != connp)) {
28326 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28327 			}
28328 			if (idl->idl_repeat) {
28329 				qenable(idl->idl_conn->conn_wq);
28330 				idl->idl_conn_draining = idl->idl_conn;
28331 				idl->idl_repeat = 0;
28332 			} else {
28333 				idl->idl_conn_draining = NULL;
28334 			}
28335 		} else {
28336 			/*
28337 			 * If the next queue that we are now qenable'ing,
28338 			 * is closing, it will remove itself from this list
28339 			 * and qenable the subsequent queue in ip_close().
28340 			 * Serialization is acheived thru idl_lock.
28341 			 */
28342 			qenable(connp->conn_drain_next->conn_wq);
28343 			idl->idl_conn_draining = connp->conn_drain_next;
28344 		}
28345 	}
28346 	if (!connp->conn_did_putbq || closing) {
28347 		/*
28348 		 * Remove ourself from the drain list, if we did not do
28349 		 * a putbq, or if the conn is closing.
28350 		 * Note: It is possible that q->q_first is non-null. It means
28351 		 * that these messages landed after we did a enableok() in
28352 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28353 		 * service them.
28354 		 */
28355 		if (connp->conn_drain_next == connp) {
28356 			/* Singleton in the list */
28357 			ASSERT(connp->conn_drain_prev == connp);
28358 			idl->idl_conn = NULL;
28359 			idl->idl_conn_draining = NULL;
28360 		} else {
28361 			connp->conn_drain_prev->conn_drain_next =
28362 			    connp->conn_drain_next;
28363 			connp->conn_drain_next->conn_drain_prev =
28364 			    connp->conn_drain_prev;
28365 			if (idl->idl_conn == connp)
28366 				idl->idl_conn = connp->conn_drain_next;
28367 			ASSERT(idl->idl_conn_draining != connp);
28368 
28369 		}
28370 		connp->conn_drain_next = NULL;
28371 		connp->conn_drain_prev = NULL;
28372 	}
28373 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28374 }
28375 
28376 /*
28377  * Write service routine. Shared perimeter entry point.
28378  * ip_wsrv can be called in any of the following ways.
28379  * 1. The device queue's messages has fallen below the low water mark
28380  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28381  *    the drain lists and backenable the first conn in each list.
28382  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28383  *    qenabled non-tcp upper layers. We start dequeing messages and call
28384  *    ip_wput for each message.
28385  */
28386 
28387 void
28388 ip_wsrv(queue_t *q)
28389 {
28390 	conn_t	*connp;
28391 	ill_t	*ill;
28392 	mblk_t	*mp;
28393 
28394 	if (q->q_next) {
28395 		ill = (ill_t *)q->q_ptr;
28396 		if (ill->ill_state_flags == 0) {
28397 			/*
28398 			 * The device flow control has opened up.
28399 			 * Walk through conn drain lists and qenable the
28400 			 * first conn in each list. This makes sense only
28401 			 * if the stream is fully plumbed and setup.
28402 			 * Hence the if check above.
28403 			 */
28404 			ip1dbg(("ip_wsrv: walking\n"));
28405 			conn_walk_drain(ill->ill_ipst);
28406 		}
28407 		return;
28408 	}
28409 
28410 	connp = Q_TO_CONN(q);
28411 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28412 
28413 	/*
28414 	 * 1. Set conn_draining flag to signal that service is active.
28415 	 *
28416 	 * 2. ip_output determines whether it has been called from service,
28417 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28418 	 *    has been called from service.
28419 	 *
28420 	 * 3. Message ordering is preserved by the following logic.
28421 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28422 	 *    the message at the tail, if conn_draining is set (i.e. service
28423 	 *    is running) or if q->q_first is non-null.
28424 	 *
28425 	 *    ii. If ip_output is called from service, and if ip_output cannot
28426 	 *    putnext due to flow control, it does a putbq.
28427 	 *
28428 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28429 	 *    (causing an infinite loop).
28430 	 */
28431 	ASSERT(!connp->conn_did_putbq);
28432 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28433 		connp->conn_draining = 1;
28434 		noenable(q);
28435 		while ((mp = getq(q)) != NULL) {
28436 			ASSERT(CONN_Q(q));
28437 
28438 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28439 			if (connp->conn_did_putbq) {
28440 				/* ip_wput did a putbq */
28441 				break;
28442 			}
28443 		}
28444 		/*
28445 		 * At this point, a thread coming down from top, calling
28446 		 * ip_wput, may end up queueing the message. We have not yet
28447 		 * enabled the queue, so ip_wsrv won't be called again.
28448 		 * To avoid this race, check q->q_first again (in the loop)
28449 		 * If the other thread queued the message before we call
28450 		 * enableok(), we will catch it in the q->q_first check.
28451 		 * If the other thread queues the message after we call
28452 		 * enableok(), ip_wsrv will be called again by STREAMS.
28453 		 */
28454 		connp->conn_draining = 0;
28455 		enableok(q);
28456 	}
28457 
28458 	/* Enable the next conn for draining */
28459 	conn_drain_tail(connp, B_FALSE);
28460 
28461 	connp->conn_did_putbq = 0;
28462 }
28463 
28464 /*
28465  * Walk the list of all conn's calling the function provided with the
28466  * specified argument for each.	 Note that this only walks conn's that
28467  * have been bound.
28468  * Applies to both IPv4 and IPv6.
28469  */
28470 static void
28471 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28472 {
28473 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28474 	    ipst->ips_ipcl_udp_fanout_size,
28475 	    func, arg, zoneid);
28476 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28477 	    ipst->ips_ipcl_conn_fanout_size,
28478 	    func, arg, zoneid);
28479 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28480 	    ipst->ips_ipcl_bind_fanout_size,
28481 	    func, arg, zoneid);
28482 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28483 	    IPPROTO_MAX, func, arg, zoneid);
28484 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28485 	    IPPROTO_MAX, func, arg, zoneid);
28486 }
28487 
28488 /*
28489  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28490  * of conns that need to be drained, check if drain is already in progress.
28491  * If so set the idl_repeat bit, indicating that the last conn in the list
28492  * needs to reinitiate the drain once again, for the list. If drain is not
28493  * in progress for the list, initiate the draining, by qenabling the 1st
28494  * conn in the list. The drain is self-sustaining, each qenabled conn will
28495  * in turn qenable the next conn, when it is done/blocked/closing.
28496  */
28497 static void
28498 conn_walk_drain(ip_stack_t *ipst)
28499 {
28500 	int i;
28501 	idl_t *idl;
28502 
28503 	IP_STAT(ipst, ip_conn_walk_drain);
28504 
28505 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28506 		idl = &ipst->ips_conn_drain_list[i];
28507 		mutex_enter(&idl->idl_lock);
28508 		if (idl->idl_conn == NULL) {
28509 			mutex_exit(&idl->idl_lock);
28510 			continue;
28511 		}
28512 		/*
28513 		 * If this list is not being drained currently by
28514 		 * an ip_wsrv thread, start the process.
28515 		 */
28516 		if (idl->idl_conn_draining == NULL) {
28517 			ASSERT(idl->idl_repeat == 0);
28518 			qenable(idl->idl_conn->conn_wq);
28519 			idl->idl_conn_draining = idl->idl_conn;
28520 		} else {
28521 			idl->idl_repeat = 1;
28522 		}
28523 		mutex_exit(&idl->idl_lock);
28524 	}
28525 }
28526 
28527 /*
28528  * Walk an conn hash table of `count' buckets, calling func for each entry.
28529  */
28530 static void
28531 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28532     zoneid_t zoneid)
28533 {
28534 	conn_t	*connp;
28535 
28536 	while (count-- > 0) {
28537 		mutex_enter(&connfp->connf_lock);
28538 		for (connp = connfp->connf_head; connp != NULL;
28539 		    connp = connp->conn_next) {
28540 			if (zoneid == GLOBAL_ZONEID ||
28541 			    zoneid == connp->conn_zoneid) {
28542 				CONN_INC_REF(connp);
28543 				mutex_exit(&connfp->connf_lock);
28544 				(*func)(connp, arg);
28545 				mutex_enter(&connfp->connf_lock);
28546 				CONN_DEC_REF(connp);
28547 			}
28548 		}
28549 		mutex_exit(&connfp->connf_lock);
28550 		connfp++;
28551 	}
28552 }
28553 
28554 /* conn_walk_fanout routine invoked for ip_conn_report for each conn. */
28555 static void
28556 conn_report1(conn_t *connp, void *mp)
28557 {
28558 	char	buf1[INET6_ADDRSTRLEN];
28559 	char	buf2[INET6_ADDRSTRLEN];
28560 	uint_t	print_len, buf_len;
28561 
28562 	ASSERT(connp != NULL);
28563 
28564 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28565 	if (buf_len <= 0)
28566 		return;
28567 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1));
28568 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2));
28569 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28570 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28571 	    "%5d %s/%05d %s/%05d\n",
28572 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28573 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28574 	    buf1, connp->conn_lport,
28575 	    buf2, connp->conn_fport);
28576 	if (print_len < buf_len) {
28577 		((mblk_t *)mp)->b_wptr += print_len;
28578 	} else {
28579 		((mblk_t *)mp)->b_wptr += buf_len;
28580 	}
28581 }
28582 
28583 /*
28584  * Named Dispatch routine to produce a formatted report on all conns
28585  * that are listed in one of the fanout tables.
28586  * This report is accessed by using the ndd utility to "get" ND variable
28587  * "ip_conn_status".
28588  */
28589 /* ARGSUSED */
28590 static int
28591 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28592 {
28593 	conn_t *connp = Q_TO_CONN(q);
28594 
28595 	(void) mi_mpprintf(mp,
28596 	    "CONN      " MI_COL_HDRPAD_STR
28597 	    "rfq      " MI_COL_HDRPAD_STR
28598 	    "stq      " MI_COL_HDRPAD_STR
28599 	    " zone local                 remote");
28600 
28601 	/*
28602 	 * Because of the ndd constraint, at most we can have 64K buffer
28603 	 * to put in all conn info.  So to be more efficient, just
28604 	 * allocate a 64K buffer here, assuming we need that large buffer.
28605 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28606 	 */
28607 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28608 		/* The following may work even if we cannot get a large buf. */
28609 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28610 		return (0);
28611 	}
28612 
28613 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
28614 	    connp->conn_netstack->netstack_ip);
28615 	return (0);
28616 }
28617 
28618 /*
28619  * Determine if the ill and multicast aspects of that packets
28620  * "matches" the conn.
28621  */
28622 boolean_t
28623 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28624     zoneid_t zoneid)
28625 {
28626 	ill_t *in_ill;
28627 	boolean_t found;
28628 	ipif_t *ipif;
28629 	ire_t *ire;
28630 	ipaddr_t dst, src;
28631 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28632 
28633 	dst = ipha->ipha_dst;
28634 	src = ipha->ipha_src;
28635 
28636 	/*
28637 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28638 	 * unicast, broadcast and multicast reception to
28639 	 * conn_incoming_ill. conn_wantpacket itself is called
28640 	 * only for BROADCAST and multicast.
28641 	 *
28642 	 * 1) ip_rput supresses duplicate broadcasts if the ill
28643 	 *    is part of a group. Hence, we should be receiving
28644 	 *    just one copy of broadcast for the whole group.
28645 	 *    Thus, if it is part of the group the packet could
28646 	 *    come on any ill of the group and hence we need a
28647 	 *    match on the group. Otherwise, match on ill should
28648 	 *    be sufficient.
28649 	 *
28650 	 * 2) ip_rput does not suppress duplicate multicast packets.
28651 	 *    If there are two interfaces in a ill group and we have
28652 	 *    2 applications (conns) joined a multicast group G on
28653 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
28654 	 *    will give us two packets because we join G on both the
28655 	 *    interfaces rather than nominating just one interface
28656 	 *    for receiving multicast like broadcast above. So,
28657 	 *    we have to call ilg_lookup_ill to filter out duplicate
28658 	 *    copies, if ill is part of a group.
28659 	 */
28660 	in_ill = connp->conn_incoming_ill;
28661 	if (in_ill != NULL) {
28662 		if (in_ill->ill_group == NULL) {
28663 			if (in_ill != ill)
28664 				return (B_FALSE);
28665 		} else if (in_ill->ill_group != ill->ill_group) {
28666 			return (B_FALSE);
28667 		}
28668 	}
28669 
28670 	if (!CLASSD(dst)) {
28671 		if (IPCL_ZONE_MATCH(connp, zoneid))
28672 			return (B_TRUE);
28673 		/*
28674 		 * The conn is in a different zone; we need to check that this
28675 		 * broadcast address is configured in the application's zone and
28676 		 * on one ill in the group.
28677 		 */
28678 		ipif = ipif_get_next_ipif(NULL, ill);
28679 		if (ipif == NULL)
28680 			return (B_FALSE);
28681 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28682 		    connp->conn_zoneid, NULL,
28683 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
28684 		ipif_refrele(ipif);
28685 		if (ire != NULL) {
28686 			ire_refrele(ire);
28687 			return (B_TRUE);
28688 		} else {
28689 			return (B_FALSE);
28690 		}
28691 	}
28692 
28693 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28694 	    connp->conn_zoneid == zoneid) {
28695 		/*
28696 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28697 		 * disabled, therefore we don't dispatch the multicast packet to
28698 		 * the sending zone.
28699 		 */
28700 		return (B_FALSE);
28701 	}
28702 
28703 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28704 		/*
28705 		 * Multicast packet on the loopback interface: we only match
28706 		 * conns who joined the group in the specified zone.
28707 		 */
28708 		return (B_FALSE);
28709 	}
28710 
28711 	if (connp->conn_multi_router) {
28712 		/* multicast packet and multicast router socket: send up */
28713 		return (B_TRUE);
28714 	}
28715 
28716 	mutex_enter(&connp->conn_lock);
28717 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28718 	mutex_exit(&connp->conn_lock);
28719 	return (found);
28720 }
28721 
28722 /*
28723  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28724  */
28725 /* ARGSUSED */
28726 static void
28727 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28728 {
28729 	ill_t *ill = (ill_t *)q->q_ptr;
28730 	mblk_t	*mp1, *mp2;
28731 	ipif_t  *ipif;
28732 	int err = 0;
28733 	conn_t *connp = NULL;
28734 	ipsq_t	*ipsq;
28735 	arc_t	*arc;
28736 
28737 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28738 
28739 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28740 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28741 
28742 	ASSERT(IAM_WRITER_ILL(ill));
28743 	mp2 = mp->b_cont;
28744 	mp->b_cont = NULL;
28745 
28746 	/*
28747 	 * We have now received the arp bringup completion message
28748 	 * from ARP. Mark the arp bringup as done. Also if the arp
28749 	 * stream has already started closing, send up the AR_ARP_CLOSING
28750 	 * ack now since ARP is waiting in close for this ack.
28751 	 */
28752 	mutex_enter(&ill->ill_lock);
28753 	ill->ill_arp_bringup_pending = 0;
28754 	if (ill->ill_arp_closing) {
28755 		mutex_exit(&ill->ill_lock);
28756 		/* Let's reuse the mp for sending the ack */
28757 		arc = (arc_t *)mp->b_rptr;
28758 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28759 		arc->arc_cmd = AR_ARP_CLOSING;
28760 		qreply(q, mp);
28761 	} else {
28762 		mutex_exit(&ill->ill_lock);
28763 		freeb(mp);
28764 	}
28765 
28766 	ipsq = ill->ill_phyint->phyint_ipsq;
28767 	ipif = ipsq->ipsq_pending_ipif;
28768 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28769 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28770 	if (mp1 == NULL) {
28771 		/* bringup was aborted by the user */
28772 		freemsg(mp2);
28773 		return;
28774 	}
28775 
28776 	/*
28777 	 * If an IOCTL is waiting on this (ipsq_current_ioctl != 0), then we
28778 	 * must have an associated conn_t.  Otherwise, we're bringing this
28779 	 * interface back up as part of handling an asynchronous event (e.g.,
28780 	 * physical address change).
28781 	 */
28782 	if (ipsq->ipsq_current_ioctl != 0) {
28783 		ASSERT(connp != NULL);
28784 		q = CONNP_TO_WQ(connp);
28785 	} else {
28786 		ASSERT(connp == NULL);
28787 		q = ill->ill_rq;
28788 	}
28789 
28790 	/*
28791 	 * If the DL_BIND_REQ fails, it is noted
28792 	 * in arc_name_offset.
28793 	 */
28794 	err = *((int *)mp2->b_rptr);
28795 	if (err == 0) {
28796 		if (ipif->ipif_isv6) {
28797 			if ((err = ipif_up_done_v6(ipif)) != 0)
28798 				ip0dbg(("ip_arp_done: init failed\n"));
28799 		} else {
28800 			if ((err = ipif_up_done(ipif)) != 0)
28801 				ip0dbg(("ip_arp_done: init failed\n"));
28802 		}
28803 	} else {
28804 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28805 	}
28806 
28807 	freemsg(mp2);
28808 
28809 	if ((err == 0) && (ill->ill_up_ipifs)) {
28810 		err = ill_up_ipifs(ill, q, mp1);
28811 		if (err == EINPROGRESS)
28812 			return;
28813 	}
28814 
28815 	if (ill->ill_up_ipifs)
28816 		ill_group_cleanup(ill);
28817 
28818 	/*
28819 	 * The operation must complete without EINPROGRESS since
28820 	 * ipsq_pending_mp_get() has removed the mblk from ipsq_pending_mp.
28821 	 * Otherwise, the operation will be stuck forever in the ipsq.
28822 	 */
28823 	ASSERT(err != EINPROGRESS);
28824 	if (ipsq->ipsq_current_ioctl != 0)
28825 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28826 	else
28827 		ipsq_current_finish(ipsq);
28828 }
28829 
28830 /* Allocate the private structure */
28831 static int
28832 ip_priv_alloc(void **bufp)
28833 {
28834 	void	*buf;
28835 
28836 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28837 		return (ENOMEM);
28838 
28839 	*bufp = buf;
28840 	return (0);
28841 }
28842 
28843 /* Function to delete the private structure */
28844 void
28845 ip_priv_free(void *buf)
28846 {
28847 	ASSERT(buf != NULL);
28848 	kmem_free(buf, sizeof (ip_priv_t));
28849 }
28850 
28851 /*
28852  * The entry point for IPPF processing.
28853  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28854  * routine just returns.
28855  *
28856  * When called, ip_process generates an ipp_packet_t structure
28857  * which holds the state information for this packet and invokes the
28858  * the classifier (via ipp_packet_process). The classification, depending on
28859  * configured filters, results in a list of actions for this packet. Invoking
28860  * an action may cause the packet to be dropped, in which case the resulting
28861  * mblk (*mpp) is NULL. proc indicates the callout position for
28862  * this packet and ill_index is the interface this packet on or will leave
28863  * on (inbound and outbound resp.).
28864  */
28865 void
28866 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28867 {
28868 	mblk_t		*mp;
28869 	ip_priv_t	*priv;
28870 	ipp_action_id_t	aid;
28871 	int		rc = 0;
28872 	ipp_packet_t	*pp;
28873 #define	IP_CLASS	"ip"
28874 
28875 	/* If the classifier is not loaded, return  */
28876 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28877 		return;
28878 	}
28879 
28880 	mp = *mpp;
28881 	ASSERT(mp != NULL);
28882 
28883 	/* Allocate the packet structure */
28884 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28885 	if (rc != 0) {
28886 		*mpp = NULL;
28887 		freemsg(mp);
28888 		return;
28889 	}
28890 
28891 	/* Allocate the private structure */
28892 	rc = ip_priv_alloc((void **)&priv);
28893 	if (rc != 0) {
28894 		*mpp = NULL;
28895 		freemsg(mp);
28896 		ipp_packet_free(pp);
28897 		return;
28898 	}
28899 	priv->proc = proc;
28900 	priv->ill_index = ill_index;
28901 	ipp_packet_set_private(pp, priv, ip_priv_free);
28902 	ipp_packet_set_data(pp, mp);
28903 
28904 	/* Invoke the classifier */
28905 	rc = ipp_packet_process(&pp);
28906 	if (pp != NULL) {
28907 		mp = ipp_packet_get_data(pp);
28908 		ipp_packet_free(pp);
28909 		if (rc != 0) {
28910 			freemsg(mp);
28911 			*mpp = NULL;
28912 		}
28913 	} else {
28914 		*mpp = NULL;
28915 	}
28916 #undef	IP_CLASS
28917 }
28918 
28919 /*
28920  * Propagate a multicast group membership operation (add/drop) on
28921  * all the interfaces crossed by the related multirt routes.
28922  * The call is considered successful if the operation succeeds
28923  * on at least one interface.
28924  */
28925 static int
28926 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28927     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28928     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28929     mblk_t *first_mp)
28930 {
28931 	ire_t		*ire_gw;
28932 	irb_t		*irb;
28933 	int		error = 0;
28934 	opt_restart_t	*or;
28935 	ip_stack_t	*ipst = ire->ire_ipst;
28936 
28937 	irb = ire->ire_bucket;
28938 	ASSERT(irb != NULL);
28939 
28940 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28941 
28942 	or = (opt_restart_t *)first_mp->b_rptr;
28943 	IRB_REFHOLD(irb);
28944 	for (; ire != NULL; ire = ire->ire_next) {
28945 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28946 			continue;
28947 		if (ire->ire_addr != group)
28948 			continue;
28949 
28950 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28951 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28952 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
28953 		/* No resolver exists for the gateway; skip this ire. */
28954 		if (ire_gw == NULL)
28955 			continue;
28956 
28957 		/*
28958 		 * This function can return EINPROGRESS. If so the operation
28959 		 * will be restarted from ip_restart_optmgmt which will
28960 		 * call ip_opt_set and option processing will restart for
28961 		 * this option. So we may end up calling 'fn' more than once.
28962 		 * This requires that 'fn' is idempotent except for the
28963 		 * return value. The operation is considered a success if
28964 		 * it succeeds at least once on any one interface.
28965 		 */
28966 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28967 		    NULL, fmode, src, first_mp);
28968 		if (error == 0)
28969 			or->or_private = CGTP_MCAST_SUCCESS;
28970 
28971 		if (ip_debug > 0) {
28972 			ulong_t	off;
28973 			char	*ksym;
28974 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28975 			ip2dbg(("ip_multirt_apply_membership: "
28976 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28977 			    "error %d [success %u]\n",
28978 			    ksym ? ksym : "?",
28979 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28980 			    error, or->or_private));
28981 		}
28982 
28983 		ire_refrele(ire_gw);
28984 		if (error == EINPROGRESS) {
28985 			IRB_REFRELE(irb);
28986 			return (error);
28987 		}
28988 	}
28989 	IRB_REFRELE(irb);
28990 	/*
28991 	 * Consider the call as successful if we succeeded on at least
28992 	 * one interface. Otherwise, return the last encountered error.
28993 	 */
28994 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28995 }
28996 
28997 
28998 /*
28999  * Issue a warning regarding a route crossing an interface with an
29000  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
29001  * amount of time is logged.
29002  */
29003 static void
29004 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
29005 {
29006 	hrtime_t	current = gethrtime();
29007 	char		buf[INET_ADDRSTRLEN];
29008 	ip_stack_t	*ipst = ire->ire_ipst;
29009 
29010 	/* Convert interval in ms to hrtime in ns */
29011 	if (ipst->ips_multirt_bad_mtu_last_time +
29012 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
29013 	    current) {
29014 		cmn_err(CE_WARN, "ip: ignoring multiroute "
29015 		    "to %s, incorrect MTU %u (expected %u)\n",
29016 		    ip_dot_addr(ire->ire_addr, buf),
29017 		    ire->ire_max_frag, max_frag);
29018 
29019 		ipst->ips_multirt_bad_mtu_last_time = current;
29020 	}
29021 }
29022 
29023 
29024 /*
29025  * Get the CGTP (multirouting) filtering status.
29026  * If 0, the CGTP hooks are transparent.
29027  */
29028 /* ARGSUSED */
29029 static int
29030 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
29031 {
29032 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29033 
29034 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
29035 	return (0);
29036 }
29037 
29038 
29039 /*
29040  * Set the CGTP (multirouting) filtering status.
29041  * If the status is changed from active to transparent
29042  * or from transparent to active, forward the new status
29043  * to the filtering module (if loaded).
29044  */
29045 /* ARGSUSED */
29046 static int
29047 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
29048     cred_t *ioc_cr)
29049 {
29050 	long		new_value;
29051 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29052 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29053 
29054 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
29055 		return (EPERM);
29056 
29057 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
29058 	    new_value < 0 || new_value > 1) {
29059 		return (EINVAL);
29060 	}
29061 
29062 	if ((!*ip_cgtp_filter_value) && new_value) {
29063 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
29064 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
29065 		    " (module not loaded)" : "");
29066 	}
29067 	if (*ip_cgtp_filter_value && (!new_value)) {
29068 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
29069 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
29070 		    " (module not loaded)" : "");
29071 	}
29072 
29073 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29074 		int	res;
29075 		netstackid_t stackid;
29076 
29077 		stackid = ipst->ips_netstack->netstack_stackid;
29078 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
29079 		    new_value);
29080 		if (res)
29081 			return (res);
29082 	}
29083 
29084 	*ip_cgtp_filter_value = (boolean_t)new_value;
29085 
29086 	return (0);
29087 }
29088 
29089 
29090 /*
29091  * Return the expected CGTP hooks version number.
29092  */
29093 int
29094 ip_cgtp_filter_supported(void)
29095 {
29096 	return (ip_cgtp_filter_rev);
29097 }
29098 
29099 
29100 /*
29101  * CGTP hooks can be registered by invoking this function.
29102  * Checks that the version number matches.
29103  */
29104 int
29105 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
29106 {
29107 	netstack_t *ns;
29108 	ip_stack_t *ipst;
29109 
29110 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
29111 		return (ENOTSUP);
29112 
29113 	ns = netstack_find_by_stackid(stackid);
29114 	if (ns == NULL)
29115 		return (EINVAL);
29116 	ipst = ns->netstack_ip;
29117 	ASSERT(ipst != NULL);
29118 
29119 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29120 		netstack_rele(ns);
29121 		return (EALREADY);
29122 	}
29123 
29124 	ipst->ips_ip_cgtp_filter_ops = ops;
29125 	netstack_rele(ns);
29126 	return (0);
29127 }
29128 
29129 /*
29130  * CGTP hooks can be unregistered by invoking this function.
29131  * Returns ENXIO if there was no registration.
29132  * Returns EBUSY if the ndd variable has not been turned off.
29133  */
29134 int
29135 ip_cgtp_filter_unregister(netstackid_t stackid)
29136 {
29137 	netstack_t *ns;
29138 	ip_stack_t *ipst;
29139 
29140 	ns = netstack_find_by_stackid(stackid);
29141 	if (ns == NULL)
29142 		return (EINVAL);
29143 	ipst = ns->netstack_ip;
29144 	ASSERT(ipst != NULL);
29145 
29146 	if (ipst->ips_ip_cgtp_filter) {
29147 		netstack_rele(ns);
29148 		return (EBUSY);
29149 	}
29150 
29151 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
29152 		netstack_rele(ns);
29153 		return (ENXIO);
29154 	}
29155 	ipst->ips_ip_cgtp_filter_ops = NULL;
29156 	netstack_rele(ns);
29157 	return (0);
29158 }
29159 
29160 /*
29161  * Check whether there is a CGTP filter registration.
29162  * Returns non-zero if there is a registration, otherwise returns zero.
29163  * Note: returns zero if bad stackid.
29164  */
29165 int
29166 ip_cgtp_filter_is_registered(netstackid_t stackid)
29167 {
29168 	netstack_t *ns;
29169 	ip_stack_t *ipst;
29170 	int ret;
29171 
29172 	ns = netstack_find_by_stackid(stackid);
29173 	if (ns == NULL)
29174 		return (0);
29175 	ipst = ns->netstack_ip;
29176 	ASSERT(ipst != NULL);
29177 
29178 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
29179 		ret = 1;
29180 	else
29181 		ret = 0;
29182 
29183 	netstack_rele(ns);
29184 	return (ret);
29185 }
29186 
29187 static squeue_func_t
29188 ip_squeue_switch(int val)
29189 {
29190 	squeue_func_t rval = squeue_fill;
29191 
29192 	switch (val) {
29193 	case IP_SQUEUE_ENTER_NODRAIN:
29194 		rval = squeue_enter_nodrain;
29195 		break;
29196 	case IP_SQUEUE_ENTER:
29197 		rval = squeue_enter;
29198 		break;
29199 	default:
29200 		break;
29201 	}
29202 	return (rval);
29203 }
29204 
29205 /* ARGSUSED */
29206 static int
29207 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29208     caddr_t addr, cred_t *cr)
29209 {
29210 	int *v = (int *)addr;
29211 	long new_value;
29212 
29213 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29214 		return (EPERM);
29215 
29216 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29217 		return (EINVAL);
29218 
29219 	ip_input_proc = ip_squeue_switch(new_value);
29220 	*v = new_value;
29221 	return (0);
29222 }
29223 
29224 /*
29225  * Handle ndd set of variables which require PRIV_SYS_NET_CONFIG such as
29226  * ip_debug.
29227  */
29228 /* ARGSUSED */
29229 static int
29230 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29231     caddr_t addr, cred_t *cr)
29232 {
29233 	int *v = (int *)addr;
29234 	long new_value;
29235 
29236 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29237 		return (EPERM);
29238 
29239 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29240 		return (EINVAL);
29241 
29242 	*v = new_value;
29243 	return (0);
29244 }
29245 
29246 /*
29247  * Handle changes to ipmp_hook_emulation ndd variable.
29248  * Need to update phyint_hook_ifindex.
29249  * Also generate a nic plumb event should a new ifidex be assigned to a group.
29250  */
29251 static void
29252 ipmp_hook_emulation_changed(ip_stack_t *ipst)
29253 {
29254 	phyint_t *phyi;
29255 	phyint_t *phyi_tmp;
29256 	char *groupname;
29257 	int namelen;
29258 	ill_t	*ill;
29259 	boolean_t new_group;
29260 
29261 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29262 	/*
29263 	 * Group indicies are stored in the phyint - a common structure
29264 	 * to both IPv4 and IPv6.
29265 	 */
29266 	phyi = avl_first(&ipst->ips_phyint_g_list->phyint_list_avl_by_index);
29267 	for (; phyi != NULL;
29268 	    phyi = avl_walk(&ipst->ips_phyint_g_list->phyint_list_avl_by_index,
29269 	    phyi, AVL_AFTER)) {
29270 		/* Ignore the ones that do not have a group */
29271 		if (phyi->phyint_groupname_len == 0)
29272 			continue;
29273 
29274 		/*
29275 		 * Look for other phyint in group.
29276 		 * Clear name/namelen so the lookup doesn't find ourselves.
29277 		 */
29278 		namelen = phyi->phyint_groupname_len;
29279 		groupname = phyi->phyint_groupname;
29280 		phyi->phyint_groupname_len = 0;
29281 		phyi->phyint_groupname = NULL;
29282 
29283 		phyi_tmp = phyint_lookup_group(groupname, B_FALSE, ipst);
29284 		/* Restore */
29285 		phyi->phyint_groupname_len = namelen;
29286 		phyi->phyint_groupname = groupname;
29287 
29288 		new_group = B_FALSE;
29289 		if (ipst->ips_ipmp_hook_emulation) {
29290 			/*
29291 			 * If the group already exists and has already
29292 			 * been assigned a group ifindex, we use the existing
29293 			 * group_ifindex, otherwise we pick a new group_ifindex
29294 			 * here.
29295 			 */
29296 			if (phyi_tmp != NULL &&
29297 			    phyi_tmp->phyint_group_ifindex != 0) {
29298 				phyi->phyint_group_ifindex =
29299 				    phyi_tmp->phyint_group_ifindex;
29300 			} else {
29301 				/* XXX We need a recovery strategy here. */
29302 				if (!ip_assign_ifindex(
29303 				    &phyi->phyint_group_ifindex, ipst))
29304 					cmn_err(CE_PANIC,
29305 					    "ip_assign_ifindex() failed");
29306 				new_group = B_TRUE;
29307 			}
29308 		} else {
29309 			phyi->phyint_group_ifindex = 0;
29310 		}
29311 		if (ipst->ips_ipmp_hook_emulation)
29312 			phyi->phyint_hook_ifindex = phyi->phyint_group_ifindex;
29313 		else
29314 			phyi->phyint_hook_ifindex = phyi->phyint_ifindex;
29315 
29316 		/*
29317 		 * For IP Filter to find out the relationship between
29318 		 * names and interface indicies, we need to generate
29319 		 * a NE_PLUMB event when a new group can appear.
29320 		 * We always generate events when a new interface appears
29321 		 * (even when ipmp_hook_emulation is set) so there
29322 		 * is no need to generate NE_PLUMB events when
29323 		 * ipmp_hook_emulation is turned off.
29324 		 * And since it isn't critical for IP Filter to get
29325 		 * the NE_UNPLUMB events we skip those here.
29326 		 */
29327 		if (new_group) {
29328 			/*
29329 			 * First phyint in group - generate group PLUMB event.
29330 			 * Since we are not running inside the ipsq we do
29331 			 * the dispatch immediately.
29332 			 */
29333 			if (phyi->phyint_illv4 != NULL)
29334 				ill = phyi->phyint_illv4;
29335 			else
29336 				ill = phyi->phyint_illv6;
29337 
29338 			if (ill != NULL) {
29339 				mutex_enter(&ill->ill_lock);
29340 				ill_nic_info_plumb(ill, B_TRUE);
29341 				ill_nic_info_dispatch(ill);
29342 				mutex_exit(&ill->ill_lock);
29343 			}
29344 		}
29345 	}
29346 	rw_exit(&ipst->ips_ill_g_lock);
29347 }
29348 
29349 /* ARGSUSED */
29350 static int
29351 ipmp_hook_emulation_set(queue_t *q, mblk_t *mp, char *value,
29352     caddr_t addr, cred_t *cr)
29353 {
29354 	int *v = (int *)addr;
29355 	long new_value;
29356 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29357 
29358 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29359 		return (EINVAL);
29360 
29361 	if (*v != new_value) {
29362 		*v = new_value;
29363 		ipmp_hook_emulation_changed(ipst);
29364 	}
29365 	return (0);
29366 }
29367 
29368 static void *
29369 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29370 {
29371 	kstat_t *ksp;
29372 
29373 	ip_stat_t template = {
29374 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29375 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29376 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29377 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29378 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29379 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29380 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29381 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29382 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29383 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29384 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29385 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29386 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29387 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29388 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29389 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29390 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29391 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29392 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29393 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29394 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29395 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29396 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29397 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29398 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29399 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29400 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29401 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29402 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29403 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29404 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29405 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29406 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29407 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29408 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29409 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29410 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29411 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29412 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29413 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29414 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29415 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29416 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29417 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29418 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29419 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29420 	};
29421 
29422 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29423 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29424 	    KSTAT_FLAG_VIRTUAL, stackid);
29425 
29426 	if (ksp == NULL)
29427 		return (NULL);
29428 
29429 	bcopy(&template, ip_statisticsp, sizeof (template));
29430 	ksp->ks_data = (void *)ip_statisticsp;
29431 	ksp->ks_private = (void *)(uintptr_t)stackid;
29432 
29433 	kstat_install(ksp);
29434 	return (ksp);
29435 }
29436 
29437 static void
29438 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29439 {
29440 	if (ksp != NULL) {
29441 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29442 		kstat_delete_netstack(ksp, stackid);
29443 	}
29444 }
29445 
29446 static void *
29447 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29448 {
29449 	kstat_t	*ksp;
29450 
29451 	ip_named_kstat_t template = {
29452 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29453 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29454 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29455 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29456 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29457 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29458 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29459 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29460 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29461 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29462 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29463 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29464 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29465 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29466 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29467 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29468 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29469 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29470 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29471 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29472 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29473 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29474 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29475 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29476 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29477 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29478 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29479 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29480 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29481 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29482 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29483 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29484 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29485 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29486 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29487 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29488 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29489 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29490 	};
29491 
29492 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29493 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29494 	if (ksp == NULL || ksp->ks_data == NULL)
29495 		return (NULL);
29496 
29497 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29498 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29499 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29500 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29501 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29502 
29503 	template.netToMediaEntrySize.value.i32 =
29504 	    sizeof (mib2_ipNetToMediaEntry_t);
29505 
29506 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29507 
29508 	bcopy(&template, ksp->ks_data, sizeof (template));
29509 	ksp->ks_update = ip_kstat_update;
29510 	ksp->ks_private = (void *)(uintptr_t)stackid;
29511 
29512 	kstat_install(ksp);
29513 	return (ksp);
29514 }
29515 
29516 static void
29517 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29518 {
29519 	if (ksp != NULL) {
29520 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29521 		kstat_delete_netstack(ksp, stackid);
29522 	}
29523 }
29524 
29525 static int
29526 ip_kstat_update(kstat_t *kp, int rw)
29527 {
29528 	ip_named_kstat_t *ipkp;
29529 	mib2_ipIfStatsEntry_t ipmib;
29530 	ill_walk_context_t ctx;
29531 	ill_t *ill;
29532 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29533 	netstack_t	*ns;
29534 	ip_stack_t	*ipst;
29535 
29536 	if (kp == NULL || kp->ks_data == NULL)
29537 		return (EIO);
29538 
29539 	if (rw == KSTAT_WRITE)
29540 		return (EACCES);
29541 
29542 	ns = netstack_find_by_stackid(stackid);
29543 	if (ns == NULL)
29544 		return (-1);
29545 	ipst = ns->netstack_ip;
29546 	if (ipst == NULL) {
29547 		netstack_rele(ns);
29548 		return (-1);
29549 	}
29550 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29551 
29552 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29553 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29554 	ill = ILL_START_WALK_V4(&ctx, ipst);
29555 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29556 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29557 	rw_exit(&ipst->ips_ill_g_lock);
29558 
29559 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29560 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29561 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29562 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29563 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29564 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29565 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29566 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29567 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29568 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29569 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29570 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29571 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29572 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29573 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29574 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29575 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29576 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29577 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29578 
29579 	ipkp->routingDiscards.value.ui32 =	0;
29580 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29581 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29582 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29583 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29584 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29585 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29586 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29587 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29588 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29589 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29590 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29591 
29592 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29593 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29594 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29595 
29596 	netstack_rele(ns);
29597 
29598 	return (0);
29599 }
29600 
29601 static void *
29602 icmp_kstat_init(netstackid_t stackid)
29603 {
29604 	kstat_t	*ksp;
29605 
29606 	icmp_named_kstat_t template = {
29607 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29608 		{ "inErrors",		KSTAT_DATA_UINT32 },
29609 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29610 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29611 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29612 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29613 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29614 		{ "inEchos",		KSTAT_DATA_UINT32 },
29615 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29616 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29617 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29618 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29619 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29620 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29621 		{ "outErrors",		KSTAT_DATA_UINT32 },
29622 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29623 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29624 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29625 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29626 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29627 		{ "outEchos",		KSTAT_DATA_UINT32 },
29628 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29629 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29630 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29631 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29632 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29633 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29634 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29635 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29636 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29637 		{ "outDrops",		KSTAT_DATA_UINT32 },
29638 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29639 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29640 	};
29641 
29642 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29643 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29644 	if (ksp == NULL || ksp->ks_data == NULL)
29645 		return (NULL);
29646 
29647 	bcopy(&template, ksp->ks_data, sizeof (template));
29648 
29649 	ksp->ks_update = icmp_kstat_update;
29650 	ksp->ks_private = (void *)(uintptr_t)stackid;
29651 
29652 	kstat_install(ksp);
29653 	return (ksp);
29654 }
29655 
29656 static void
29657 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29658 {
29659 	if (ksp != NULL) {
29660 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29661 		kstat_delete_netstack(ksp, stackid);
29662 	}
29663 }
29664 
29665 static int
29666 icmp_kstat_update(kstat_t *kp, int rw)
29667 {
29668 	icmp_named_kstat_t *icmpkp;
29669 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29670 	netstack_t	*ns;
29671 	ip_stack_t	*ipst;
29672 
29673 	if ((kp == NULL) || (kp->ks_data == NULL))
29674 		return (EIO);
29675 
29676 	if (rw == KSTAT_WRITE)
29677 		return (EACCES);
29678 
29679 	ns = netstack_find_by_stackid(stackid);
29680 	if (ns == NULL)
29681 		return (-1);
29682 	ipst = ns->netstack_ip;
29683 	if (ipst == NULL) {
29684 		netstack_rele(ns);
29685 		return (-1);
29686 	}
29687 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29688 
29689 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29690 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29691 	icmpkp->inDestUnreachs.value.ui32 =
29692 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29693 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29694 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29695 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29696 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29697 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29698 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29699 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29700 	icmpkp->inTimestampReps.value.ui32 =
29701 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29702 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29703 	icmpkp->inAddrMaskReps.value.ui32 =
29704 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29705 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29706 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29707 	icmpkp->outDestUnreachs.value.ui32 =
29708 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29709 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29710 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29711 	icmpkp->outSrcQuenchs.value.ui32 =
29712 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29713 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29714 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29715 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29716 	icmpkp->outTimestamps.value.ui32 =
29717 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29718 	icmpkp->outTimestampReps.value.ui32 =
29719 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29720 	icmpkp->outAddrMasks.value.ui32 =
29721 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29722 	icmpkp->outAddrMaskReps.value.ui32 =
29723 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29724 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29725 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29726 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29727 	icmpkp->outFragNeeded.value.ui32 =
29728 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29729 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29730 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29731 	icmpkp->inBadRedirects.value.ui32 =
29732 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29733 
29734 	netstack_rele(ns);
29735 	return (0);
29736 }
29737 
29738 /*
29739  * This is the fanout function for raw socket opened for SCTP.  Note
29740  * that it is called after SCTP checks that there is no socket which
29741  * wants a packet.  Then before SCTP handles this out of the blue packet,
29742  * this function is called to see if there is any raw socket for SCTP.
29743  * If there is and it is bound to the correct address, the packet will
29744  * be sent to that socket.  Note that only one raw socket can be bound to
29745  * a port.  This is assured in ipcl_sctp_hash_insert();
29746  */
29747 void
29748 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29749     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29750     zoneid_t zoneid)
29751 {
29752 	conn_t		*connp;
29753 	queue_t		*rq;
29754 	mblk_t		*first_mp;
29755 	boolean_t	secure;
29756 	ip6_t		*ip6h;
29757 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29758 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29759 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
29760 	boolean_t	sctp_csum_err = B_FALSE;
29761 
29762 	if (flags & IP_FF_SCTP_CSUM_ERR) {
29763 		sctp_csum_err = B_TRUE;
29764 		flags &= ~IP_FF_SCTP_CSUM_ERR;
29765 	}
29766 
29767 	first_mp = mp;
29768 	if (mctl_present) {
29769 		mp = first_mp->b_cont;
29770 		secure = ipsec_in_is_secure(first_mp);
29771 		ASSERT(mp != NULL);
29772 	} else {
29773 		secure = B_FALSE;
29774 	}
29775 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29776 
29777 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29778 	if (connp == NULL) {
29779 		/*
29780 		 * Although raw sctp is not summed, OOB chunks must be.
29781 		 * Drop the packet here if the sctp checksum failed.
29782 		 */
29783 		if (sctp_csum_err) {
29784 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
29785 			freemsg(first_mp);
29786 			return;
29787 		}
29788 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29789 		return;
29790 	}
29791 	rq = connp->conn_rq;
29792 	if (!canputnext(rq)) {
29793 		CONN_DEC_REF(connp);
29794 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29795 		freemsg(first_mp);
29796 		return;
29797 	}
29798 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29799 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29800 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29801 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29802 		if (first_mp == NULL) {
29803 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29804 			CONN_DEC_REF(connp);
29805 			return;
29806 		}
29807 	}
29808 	/*
29809 	 * We probably should not send M_CTL message up to
29810 	 * raw socket.
29811 	 */
29812 	if (mctl_present)
29813 		freeb(first_mp);
29814 
29815 	/* Initiate IPPF processing here if needed. */
29816 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29817 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29818 		ip_process(IPP_LOCAL_IN, &mp,
29819 		    recv_ill->ill_phyint->phyint_ifindex);
29820 		if (mp == NULL) {
29821 			CONN_DEC_REF(connp);
29822 			return;
29823 		}
29824 	}
29825 
29826 	if (connp->conn_recvif || connp->conn_recvslla ||
29827 	    ((connp->conn_ip_recvpktinfo ||
29828 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29829 	    (flags & IP_FF_IPINFO))) {
29830 		int in_flags = 0;
29831 
29832 		/*
29833 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29834 		 * IPF_RECVIF.
29835 		 */
29836 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29837 			in_flags = IPF_RECVIF;
29838 		}
29839 		if (connp->conn_recvslla) {
29840 			in_flags |= IPF_RECVSLLA;
29841 		}
29842 		if (isv4) {
29843 			mp = ip_add_info(mp, recv_ill, in_flags,
29844 			    IPCL_ZONEID(connp), ipst);
29845 		} else {
29846 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29847 			if (mp == NULL) {
29848 				BUMP_MIB(recv_ill->ill_ip_mib,
29849 				    ipIfStatsInDiscards);
29850 				CONN_DEC_REF(connp);
29851 				return;
29852 			}
29853 		}
29854 	}
29855 
29856 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29857 	/*
29858 	 * We are sending the IPSEC_IN message also up. Refer
29859 	 * to comments above this function.
29860 	 * This is the SOCK_RAW, IPPROTO_SCTP case.
29861 	 */
29862 	(connp->conn_recv)(connp, mp, NULL);
29863 	CONN_DEC_REF(connp);
29864 }
29865 
29866 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29867 {									\
29868 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29869 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29870 }
29871 /*
29872  * This function should be called only if all packet processing
29873  * including fragmentation is complete. Callers of this function
29874  * must set mp->b_prev to one of these values:
29875  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29876  * prior to handing over the mp as first argument to this function.
29877  *
29878  * If the ire passed by caller is incomplete, this function
29879  * queues the packet and if necessary, sends ARP request and bails.
29880  * If the ire passed is fully resolved, we simply prepend
29881  * the link-layer header to the packet, do ipsec hw acceleration
29882  * work if necessary, and send the packet out on the wire.
29883  *
29884  * NOTE: IPsec will only call this function with fully resolved
29885  * ires if hw acceleration is involved.
29886  * TODO list :
29887  * 	a Handle M_MULTIDATA so that
29888  *	  tcp_multisend->tcp_multisend_data can
29889  *	  call ip_xmit_v4 directly
29890  *	b Handle post-ARP work for fragments so that
29891  *	  ip_wput_frag can call this function.
29892  */
29893 ipxmit_state_t
29894 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
29895 {
29896 	nce_t		*arpce;
29897 	ipha_t		*ipha;
29898 	queue_t		*q;
29899 	int		ill_index;
29900 	mblk_t		*nxt_mp, *first_mp;
29901 	boolean_t	xmit_drop = B_FALSE;
29902 	ip_proc_t	proc;
29903 	ill_t		*out_ill;
29904 	int		pkt_len;
29905 
29906 	arpce = ire->ire_nce;
29907 	ASSERT(arpce != NULL);
29908 
29909 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29910 
29911 	mutex_enter(&arpce->nce_lock);
29912 	switch (arpce->nce_state) {
29913 	case ND_REACHABLE:
29914 		/* If there are other queued packets, queue this packet */
29915 		if (arpce->nce_qd_mp != NULL) {
29916 			if (mp != NULL)
29917 				nce_queue_mp_common(arpce, mp, B_FALSE);
29918 			mp = arpce->nce_qd_mp;
29919 		}
29920 		arpce->nce_qd_mp = NULL;
29921 		mutex_exit(&arpce->nce_lock);
29922 
29923 		/*
29924 		 * Flush the queue.  In the common case, where the
29925 		 * ARP is already resolved,  it will go through the
29926 		 * while loop only once.
29927 		 */
29928 		while (mp != NULL) {
29929 
29930 			nxt_mp = mp->b_next;
29931 			mp->b_next = NULL;
29932 			ASSERT(mp->b_datap->db_type != M_CTL);
29933 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29934 			/*
29935 			 * This info is needed for IPQOS to do COS marking
29936 			 * in ip_wput_attach_llhdr->ip_process.
29937 			 */
29938 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29939 			mp->b_prev = NULL;
29940 
29941 			/* set up ill index for outbound qos processing */
29942 			out_ill = ire_to_ill(ire);
29943 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29944 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29945 			    ill_index, &ipha);
29946 			if (first_mp == NULL) {
29947 				xmit_drop = B_TRUE;
29948 				BUMP_MIB(out_ill->ill_ip_mib,
29949 				    ipIfStatsOutDiscards);
29950 				goto next_mp;
29951 			}
29952 
29953 			/* non-ipsec hw accel case */
29954 			if (io == NULL || !io->ipsec_out_accelerated) {
29955 				/* send it */
29956 				q = ire->ire_stq;
29957 				if (proc == IPP_FWD_OUT) {
29958 					UPDATE_IB_PKT_COUNT(ire);
29959 				} else {
29960 					UPDATE_OB_PKT_COUNT(ire);
29961 				}
29962 				ire->ire_last_used_time = lbolt;
29963 
29964 				if (flow_ctl_enabled || canputnext(q)) {
29965 					if (proc == IPP_FWD_OUT) {
29966 
29967 					BUMP_MIB(out_ill->ill_ip_mib,
29968 					    ipIfStatsHCOutForwDatagrams);
29969 
29970 					}
29971 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29972 					    pkt_len);
29973 
29974 					DTRACE_IP7(send, mblk_t *, first_mp,
29975 					    conn_t *, NULL, void_ip_t *, ipha,
29976 					    __dtrace_ipsr_ill_t *, out_ill,
29977 					    ipha_t *, ipha, ip6_t *, NULL, int,
29978 					    0);
29979 
29980 					putnext(q, first_mp);
29981 				} else {
29982 					BUMP_MIB(out_ill->ill_ip_mib,
29983 					    ipIfStatsOutDiscards);
29984 					xmit_drop = B_TRUE;
29985 					freemsg(first_mp);
29986 				}
29987 			} else {
29988 				/*
29989 				 * Safety Pup says: make sure this
29990 				 *  is going to the right interface!
29991 				 */
29992 				ill_t *ill1 =
29993 				    (ill_t *)ire->ire_stq->q_ptr;
29994 				int ifindex =
29995 				    ill1->ill_phyint->phyint_ifindex;
29996 				if (ifindex !=
29997 				    io->ipsec_out_capab_ill_index) {
29998 					xmit_drop = B_TRUE;
29999 					freemsg(mp);
30000 				} else {
30001 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
30002 					    pkt_len);
30003 
30004 					DTRACE_IP7(send, mblk_t *, first_mp,
30005 					    conn_t *, NULL, void_ip_t *, ipha,
30006 					    __dtrace_ipsr_ill_t *, ill1,
30007 					    ipha_t *, ipha, ip6_t *, NULL,
30008 					    int, 0);
30009 
30010 					ipsec_hw_putnext(ire->ire_stq, mp);
30011 				}
30012 			}
30013 next_mp:
30014 			mp = nxt_mp;
30015 		} /* while (mp != NULL) */
30016 		if (xmit_drop)
30017 			return (SEND_FAILED);
30018 		else
30019 			return (SEND_PASSED);
30020 
30021 	case ND_INITIAL:
30022 	case ND_INCOMPLETE:
30023 
30024 		/*
30025 		 * While we do send off packets to dests that
30026 		 * use fully-resolved CGTP routes, we do not
30027 		 * handle unresolved CGTP routes.
30028 		 */
30029 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
30030 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
30031 
30032 		if (mp != NULL) {
30033 			/* queue the packet */
30034 			nce_queue_mp_common(arpce, mp, B_FALSE);
30035 		}
30036 
30037 		if (arpce->nce_state == ND_INCOMPLETE) {
30038 			mutex_exit(&arpce->nce_lock);
30039 			DTRACE_PROBE3(ip__xmit__incomplete,
30040 			    (ire_t *), ire, (mblk_t *), mp,
30041 			    (ipsec_out_t *), io);
30042 			return (LOOKUP_IN_PROGRESS);
30043 		}
30044 
30045 		arpce->nce_state = ND_INCOMPLETE;
30046 		mutex_exit(&arpce->nce_lock);
30047 		/*
30048 		 * Note that ire_add() (called from ire_forward())
30049 		 * holds a ref on the ire until ARP is completed.
30050 		 */
30051 
30052 		ire_arpresolve(ire, ire_to_ill(ire));
30053 		return (LOOKUP_IN_PROGRESS);
30054 	default:
30055 		ASSERT(0);
30056 		mutex_exit(&arpce->nce_lock);
30057 		return (LLHDR_RESLV_FAILED);
30058 	}
30059 }
30060 
30061 #undef	UPDATE_IP_MIB_OB_COUNTERS
30062 
30063 /*
30064  * Return B_TRUE if the buffers differ in length or content.
30065  * This is used for comparing extension header buffers.
30066  * Note that an extension header would be declared different
30067  * even if all that changed was the next header value in that header i.e.
30068  * what really changed is the next extension header.
30069  */
30070 boolean_t
30071 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
30072     uint_t blen)
30073 {
30074 	if (!b_valid)
30075 		blen = 0;
30076 
30077 	if (alen != blen)
30078 		return (B_TRUE);
30079 	if (alen == 0)
30080 		return (B_FALSE);	/* Both zero length */
30081 	return (bcmp(abuf, bbuf, alen));
30082 }
30083 
30084 /*
30085  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
30086  * Return B_FALSE if memory allocation fails - don't change any state!
30087  */
30088 boolean_t
30089 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30090     const void *src, uint_t srclen)
30091 {
30092 	void *dst;
30093 
30094 	if (!src_valid)
30095 		srclen = 0;
30096 
30097 	ASSERT(*dstlenp == 0);
30098 	if (src != NULL && srclen != 0) {
30099 		dst = mi_alloc(srclen, BPRI_MED);
30100 		if (dst == NULL)
30101 			return (B_FALSE);
30102 	} else {
30103 		dst = NULL;
30104 	}
30105 	if (*dstp != NULL)
30106 		mi_free(*dstp);
30107 	*dstp = dst;
30108 	*dstlenp = dst == NULL ? 0 : srclen;
30109 	return (B_TRUE);
30110 }
30111 
30112 /*
30113  * Replace what is in *dst, *dstlen with the source.
30114  * Assumes ip_allocbuf has already been called.
30115  */
30116 void
30117 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30118     const void *src, uint_t srclen)
30119 {
30120 	if (!src_valid)
30121 		srclen = 0;
30122 
30123 	ASSERT(*dstlenp == srclen);
30124 	if (src != NULL && srclen != 0)
30125 		bcopy(src, *dstp, srclen);
30126 }
30127 
30128 /*
30129  * Free the storage pointed to by the members of an ip6_pkt_t.
30130  */
30131 void
30132 ip6_pkt_free(ip6_pkt_t *ipp)
30133 {
30134 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
30135 
30136 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
30137 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
30138 		ipp->ipp_hopopts = NULL;
30139 		ipp->ipp_hopoptslen = 0;
30140 	}
30141 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
30142 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
30143 		ipp->ipp_rtdstopts = NULL;
30144 		ipp->ipp_rtdstoptslen = 0;
30145 	}
30146 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
30147 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
30148 		ipp->ipp_dstopts = NULL;
30149 		ipp->ipp_dstoptslen = 0;
30150 	}
30151 	if (ipp->ipp_fields & IPPF_RTHDR) {
30152 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
30153 		ipp->ipp_rthdr = NULL;
30154 		ipp->ipp_rthdrlen = 0;
30155 	}
30156 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
30157 	    IPPF_RTHDR);
30158 }
30159