xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision fada0503)
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 2007 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 <net/if.h>
60 #include <net/if_arp.h>
61 #include <net/route.h>
62 #include <sys/sockio.h>
63 #include <netinet/in.h>
64 #include <net/if_dl.h>
65 
66 #include <inet/common.h>
67 #include <inet/mi.h>
68 #include <inet/mib2.h>
69 #include <inet/nd.h>
70 #include <inet/arp.h>
71 #include <inet/snmpcom.h>
72 #include <inet/optcom.h>
73 #include <inet/kstatcom.h>
74 
75 #include <netinet/igmp_var.h>
76 #include <netinet/ip6.h>
77 #include <netinet/icmp6.h>
78 #include <netinet/sctp.h>
79 
80 #include <inet/ip.h>
81 #include <inet/ip_impl.h>
82 #include <inet/ip6.h>
83 #include <inet/ip6_asp.h>
84 #include <inet/tcp.h>
85 #include <inet/tcp_impl.h>
86 #include <inet/ip_multi.h>
87 #include <inet/ip_if.h>
88 #include <inet/ip_ire.h>
89 #include <inet/ip_ftable.h>
90 #include <inet/ip_rts.h>
91 #include <inet/ip_ndp.h>
92 #include <inet/ip_listutils.h>
93 #include <netinet/igmp.h>
94 #include <netinet/ip_mroute.h>
95 #include <inet/ipp_common.h>
96 
97 #include <net/pfkeyv2.h>
98 #include <inet/ipsec_info.h>
99 #include <inet/sadb.h>
100 #include <inet/ipsec_impl.h>
101 #include <sys/iphada.h>
102 #include <inet/tun.h>
103 #include <inet/ipdrop.h>
104 #include <inet/ip_netinfo.h>
105 
106 #include <sys/ethernet.h>
107 #include <net/if_types.h>
108 #include <sys/cpuvar.h>
109 
110 #include <ipp/ipp.h>
111 #include <ipp/ipp_impl.h>
112 #include <ipp/ipgpc/ipgpc.h>
113 
114 #include <sys/multidata.h>
115 #include <sys/pattr.h>
116 
117 #include <inet/ipclassifier.h>
118 #include <inet/sctp_ip.h>
119 #include <inet/sctp/sctp_impl.h>
120 #include <inet/udp_impl.h>
121 #include <inet/rawip_impl.h>
122 #include <inet/rts_impl.h>
123 #include <sys/sunddi.h>
124 
125 #include <sys/tsol/label.h>
126 #include <sys/tsol/tnet.h>
127 
128 #include <rpc/pmap_prot.h>
129 
130 /*
131  * Values for squeue switch:
132  * IP_SQUEUE_ENTER_NODRAIN: squeue_enter_nodrain
133  * IP_SQUEUE_ENTER: squeue_enter
134  * IP_SQUEUE_FILL: squeue_fill
135  */
136 int ip_squeue_enter = 2;	/* Setable in /etc/system */
137 
138 squeue_func_t ip_input_proc;
139 #define	SET_BPREV_FLAG(x)	((mblk_t *)(uintptr_t)(x))
140 
141 /*
142  * Setable in /etc/system
143  */
144 int ip_poll_normal_ms = 100;
145 int ip_poll_normal_ticks = 0;
146 int ip_modclose_ackwait_ms = 3000;
147 
148 /*
149  * It would be nice to have these present only in DEBUG systems, but the
150  * current design of the global symbol checking logic requires them to be
151  * unconditionally present.
152  */
153 uint_t ip_thread_data;			/* TSD key for debug support */
154 krwlock_t ip_thread_rwlock;
155 list_t	ip_thread_list;
156 
157 /*
158  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
159  */
160 
161 struct listptr_s {
162 	mblk_t	*lp_head;	/* pointer to the head of the list */
163 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
164 };
165 
166 typedef struct listptr_s listptr_t;
167 
168 /*
169  * This is used by ip_snmp_get_mib2_ip_route_media and
170  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
171  */
172 typedef struct iproutedata_s {
173 	uint_t		ird_idx;
174 	listptr_t	ird_route;	/* ipRouteEntryTable */
175 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
176 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
177 } iproutedata_t;
178 
179 /*
180  * Cluster specific hooks. These should be NULL when booted as a non-cluster
181  */
182 
183 /*
184  * Hook functions to enable cluster networking
185  * On non-clustered systems these vectors must always be NULL.
186  *
187  * Hook function to Check ip specified ip address is a shared ip address
188  * in the cluster
189  *
190  */
191 int (*cl_inet_isclusterwide)(uint8_t protocol,
192     sa_family_t addr_family, uint8_t *laddrp) = NULL;
193 
194 /*
195  * Hook function to generate cluster wide ip fragment identifier
196  */
197 uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
198     uint8_t *laddrp, uint8_t *faddrp) = NULL;
199 
200 /*
201  * Synchronization notes:
202  *
203  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
204  * MT level protection given by STREAMS. IP uses a combination of its own
205  * internal serialization mechanism and standard Solaris locking techniques.
206  * The internal serialization is per phyint (no IPMP) or per IPMP group.
207  * This is used to serialize plumbing operations, IPMP operations, certain
208  * multicast operations, most set ioctls, igmp/mld timers etc.
209  *
210  * Plumbing is a long sequence of operations involving message
211  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
212  * involved in plumbing operations. A natural model is to serialize these
213  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
214  * parallel without any interference. But various set ioctls on hme0 are best
215  * serialized. However if the system uses IPMP, the operations are easier if
216  * they are serialized on a per IPMP group basis since IPMP operations
217  * happen across ill's of a group. Thus the lowest common denominator is to
218  * serialize most set ioctls, multicast join/leave operations, IPMP operations
219  * igmp/mld timer operations, and processing of DLPI control messages received
220  * from drivers on a per IPMP group basis. If the system does not employ
221  * IPMP the serialization is on a per phyint basis. This serialization is
222  * provided by the ipsq_t and primitives operating on this. Details can
223  * be found in ip_if.c above the core primitives operating on ipsq_t.
224  *
225  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
226  * Simiarly lookup of an ire by a thread also returns a refheld ire.
227  * In addition ipif's and ill's referenced by the ire are also indirectly
228  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
229  * the ipif's address or netmask change as long as an ipif is refheld
230  * directly or indirectly. For example an SIOCLIFADDR ioctl that changes the
231  * address of an ipif has to go through the ipsq_t. This ensures that only
232  * 1 such exclusive operation proceeds at any time on the ipif. It then
233  * deletes all ires associated with this ipif, and waits for all refcnts
234  * associated with this ipif to come down to zero. The address is changed
235  * only after the ipif has been quiesced. Then the ipif is brought up again.
236  * More details are described above the comment in ip_sioctl_flags.
237  *
238  * Packet processing is based mostly on IREs and are fully multi-threaded
239  * using standard Solaris MT techniques.
240  *
241  * There are explicit locks in IP to handle:
242  * - The ip_g_head list maintained by mi_open_link() and friends.
243  *
244  * - The reassembly data structures (one lock per hash bucket)
245  *
246  * - conn_lock is meant to protect conn_t fields. The fields actually
247  *   protected by conn_lock are documented in the conn_t definition.
248  *
249  * - ire_lock to protect some of the fields of the ire, IRE tables
250  *   (one lock per hash bucket). Refer to ip_ire.c for details.
251  *
252  * - ndp_g_lock and nce_lock for protecting NCEs.
253  *
254  * - ill_lock protects fields of the ill and ipif. Details in ip.h
255  *
256  * - ill_g_lock: This is a global reader/writer lock. Protects the following
257  *	* The AVL tree based global multi list of all ills.
258  *	* The linked list of all ipifs of an ill
259  *	* The <ill-ipsq> mapping
260  *	* The ipsq->ipsq_phyint_list threaded by phyint_ipsq_next
261  *	* The illgroup list threaded by ill_group_next.
262  *	* <ill-phyint> association
263  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
264  *   into an ill, changing the <ill-ipsq> mapping of an ill, insertion/deletion
265  *   of an ill into the illgrp list, changing the <ill-phyint> assoc of an ill
266  *   will all have to hold the ill_g_lock as writer for the actual duration
267  *   of the insertion/deletion/change. More details about the <ill-ipsq> mapping
268  *   may be found in the IPMP section.
269  *
270  * - ill_lock:  This is a per ill mutex.
271  *   It protects some members of the ill and is documented below.
272  *   It also protects the <ill-ipsq> mapping
273  *   It also protects the illgroup list threaded by ill_group_next.
274  *   It also protects the <ill-phyint> assoc.
275  *   It also protects the list of ipifs hanging off the ill.
276  *
277  * - ipsq_lock: This is a per ipsq_t mutex lock.
278  *   This protects all the other members of the ipsq struct except
279  *   ipsq_refs and ipsq_phyint_list which are protected by ill_g_lock
280  *
281  * - illgrp_lock: This is a per ill_group mutex lock.
282  *   The only thing it protects is the illgrp_ill_schednext member of ill_group
283  *   which dictates which is the next ill in an ill_group that is to be chosen
284  *   for sending outgoing packets, through creation of an IRE_CACHE that
285  *   references this ill.
286  *
287  * - phyint_lock: This is a per phyint mutex lock. Protects just the
288  *   phyint_flags
289  *
290  * - ip_g_nd_lock: This is a global reader/writer lock.
291  *   Any call to nd_load to load a new parameter to the ND table must hold the
292  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
293  *   as reader.
294  *
295  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
296  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
297  *   uniqueness check also done atomically.
298  *
299  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
300  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
301  *   as a writer when adding or deleting elements from these lists, and
302  *   as a reader when walking these lists to send a SADB update to the
303  *   IPsec capable ills.
304  *
305  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
306  *   group list linked by ill_usesrc_grp_next. It also protects the
307  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
308  *   group is being added or deleted.  This lock is taken as a reader when
309  *   walking the list/group(eg: to get the number of members in a usesrc group).
310  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
311  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
312  *   example, it is not necessary to take this lock in the initial portion
313  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_groupname and
314  *   ip_sioctl_flags since the these operations are executed exclusively and
315  *   that ensures that the "usesrc group state" cannot change. The "usesrc
316  *   group state" change can happen only in the latter part of
317  *   ip_sioctl_slifusesrc and in ill_delete.
318  *
319  * Changing <ill-phyint>, <ill-ipsq>, <ill-illgroup> assocications.
320  *
321  * To change the <ill-phyint> association, the ill_g_lock must be held
322  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
323  * must be held.
324  *
325  * To change the <ill-ipsq> association the ill_g_lock must be held as writer
326  * and the ill_lock of the ill in question must be held.
327  *
328  * To change the <ill-illgroup> association the ill_g_lock must be held as
329  * writer and the ill_lock of the ill in question must be held.
330  *
331  * To add or delete an ipif from the list of ipifs hanging off the ill,
332  * ill_g_lock (writer) and ill_lock must be held and the thread must be
333  * a writer on the associated ipsq,.
334  *
335  * To add or delete an ill to the system, the ill_g_lock must be held as
336  * writer and the thread must be a writer on the associated ipsq.
337  *
338  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
339  * must be a writer on the associated ipsq.
340  *
341  * Lock hierarchy
342  *
343  * Some lock hierarchy scenarios are listed below.
344  *
345  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock
346  * ill_g_lock -> illgrp_lock -> ill_lock
347  * ill_g_lock -> ill_lock(s) -> phyint_lock
348  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
349  * ill_g_lock -> ip_addr_avail_lock
350  * conn_lock -> irb_lock -> ill_lock -> ire_lock
351  * ill_g_lock -> ip_g_nd_lock
352  *
353  * When more than 1 ill lock is needed to be held, all ill lock addresses
354  * are sorted on address and locked starting from highest addressed lock
355  * downward.
356  *
357  * IPsec scenarios
358  *
359  * ipsa_lock -> ill_g_lock -> ill_lock
360  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
361  * ipsec_capab_ills_lock -> ipsa_lock
362  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
363  *
364  * Trusted Solaris scenarios
365  *
366  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
367  * igsa_lock -> gcdb_lock
368  * gcgrp_rwlock -> ire_lock
369  * gcgrp_rwlock -> gcdb_lock
370  *
371  *
372  * Routing/forwarding table locking notes:
373  *
374  * Lock acquisition order: Radix tree lock, irb_lock.
375  * Requirements:
376  * i.  Walker must not hold any locks during the walker callback.
377  * ii  Walker must not see a truncated tree during the walk because of any node
378  *     deletion.
379  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
380  *     in many places in the code to walk the irb list. Thus even if all the
381  *     ires in a bucket have been deleted, we still can't free the radix node
382  *     until the ires have actually been inactive'd (freed).
383  *
384  * Tree traversal - Need to hold the global tree lock in read mode.
385  * Before dropping the global tree lock, need to either increment the ire_refcnt
386  * to ensure that the radix node can't be deleted.
387  *
388  * Tree add - Need to hold the global tree lock in write mode to add a
389  * radix node. To prevent the node from being deleted, increment the
390  * irb_refcnt, after the node is added to the tree. The ire itself is
391  * added later while holding the irb_lock, but not the tree lock.
392  *
393  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
394  * All associated ires must be inactive (i.e. freed), and irb_refcnt
395  * must be zero.
396  *
397  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
398  * global tree lock (read mode) for traversal.
399  *
400  * IPsec notes :
401  *
402  * IP interacts with the IPsec code (AH/ESP) by tagging a M_CTL message
403  * in front of the actual packet. For outbound datagrams, the M_CTL
404  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
405  * information used by the IPsec code for applying the right level of
406  * protection. The information initialized by IP in the ipsec_out_t
407  * is determined by the per-socket policy or global policy in the system.
408  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
409  * ipsec_info.h) which starts out with nothing in it. It gets filled
410  * with the right information if it goes through the AH/ESP code, which
411  * happens if the incoming packet is secure. The information initialized
412  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
413  * the policy requirements needed by per-socket policy or global policy
414  * is met or not.
415  *
416  * If there is both per-socket policy (set using setsockopt) and there
417  * is also global policy match for the 5 tuples of the socket,
418  * ipsec_override_policy() makes the decision of which one to use.
419  *
420  * For fully connected sockets i.e dst, src [addr, port] is known,
421  * conn_policy_cached is set indicating that policy has been cached.
422  * conn_in_enforce_policy may or may not be set depending on whether
423  * there is a global policy match or per-socket policy match.
424  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
425  * Once the right policy is set on the conn_t, policy cannot change for
426  * this socket. This makes life simpler for TCP (UDP ?) where
427  * re-transmissions go out with the same policy. For symmetry, policy
428  * is cached for fully connected UDP sockets also. Thus if policy is cached,
429  * it also implies that policy is latched i.e policy cannot change
430  * on these sockets. As we have the right policy on the conn, we don't
431  * have to lookup global policy for every outbound and inbound datagram
432  * and thus serving as an optimization. Note that a global policy change
433  * does not affect fully connected sockets if they have policy. If fully
434  * connected sockets did not have any policy associated with it, global
435  * policy change may affect them.
436  *
437  * IP Flow control notes:
438  *
439  * Non-TCP streams are flow controlled by IP. On the send side, if the packet
440  * cannot be sent down to the driver by IP, because of a canput failure, IP
441  * does a putq on the conn_wq. This will cause ip_wsrv to run on the conn_wq.
442  * ip_wsrv in turn, inserts the conn in a list of conn's that need to be drained
443  * when the flowcontrol condition subsides. Ultimately STREAMS backenables the
444  * ip_wsrv on the IP module, which in turn does a qenable of the conn_wq of the
445  * first conn in the list of conn's to be drained. ip_wsrv on this conn drains
446  * the queued messages, and removes the conn from the drain list, if all
447  * messages were drained. It also qenables the next conn in the drain list to
448  * continue the drain process.
449  *
450  * In reality the drain list is not a single list, but a configurable number
451  * of lists. The ip_wsrv on the IP module, qenables the first conn in each
452  * list. If the ip_wsrv of the next qenabled conn does not run, because the
453  * stream closes, ip_close takes responsibility to qenable the next conn in
454  * the drain list. The directly called ip_wput path always does a putq, if
455  * it cannot putnext. Thus synchronization problems are handled between
456  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
457  * functions that manipulate this drain list. Furthermore conn_drain_insert
458  * is called only from ip_wsrv, and there can be only 1 instance of ip_wsrv
459  * running on a queue at any time. conn_drain_tail can be simultaneously called
460  * from both ip_wsrv and ip_close.
461  *
462  * IPQOS notes:
463  *
464  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
465  * and IPQoS modules. IPPF includes hooks in IP at different control points
466  * (callout positions) which direct packets to IPQoS modules for policy
467  * processing. Policies, if present, are global.
468  *
469  * The callout positions are located in the following paths:
470  *		o local_in (packets destined for this host)
471  *		o local_out (packets orginating from this host )
472  *		o fwd_in  (packets forwarded by this m/c - inbound)
473  *		o fwd_out (packets forwarded by this m/c - outbound)
474  * Hooks at these callout points can be enabled/disabled using the ndd variable
475  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
476  * By default all the callout positions are enabled.
477  *
478  * Outbound (local_out)
479  * Hooks are placed in ip_wput_ire and ipsec_out_process.
480  *
481  * Inbound (local_in)
482  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
483  * TCP and UDP fanout routines.
484  *
485  * Forwarding (in and out)
486  * Hooks are placed in ip_rput_forward.
487  *
488  * IP Policy Framework processing (IPPF processing)
489  * Policy processing for a packet is initiated by ip_process, which ascertains
490  * that the classifier (ipgpc) is loaded and configured, failing which the
491  * packet resumes normal processing in IP. If the clasifier is present, the
492  * packet is acted upon by one or more IPQoS modules (action instances), per
493  * filters configured in ipgpc and resumes normal IP processing thereafter.
494  * An action instance can drop a packet in course of its processing.
495  *
496  * A boolean variable, ip_policy, is used in all the fanout routines that can
497  * invoke ip_process for a packet. This variable indicates if the packet should
498  * to be sent for policy processing. The variable is set to B_TRUE by default,
499  * i.e. when the routines are invoked in the normal ip procesing path for a
500  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
501  * ip_policy is set to B_FALSE for all the routines called in these two
502  * functions because, in the former case,  we don't process loopback traffic
503  * currently while in the latter, the packets have already been processed in
504  * icmp_inbound.
505  *
506  * Zones notes:
507  *
508  * The partitioning rules for networking are as follows:
509  * 1) Packets coming from a zone must have a source address belonging to that
510  * zone.
511  * 2) Packets coming from a zone can only be sent on a physical interface on
512  * which the zone has an IP address.
513  * 3) Between two zones on the same machine, packet delivery is only allowed if
514  * there's a matching route for the destination and zone in the forwarding
515  * table.
516  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
517  * different zones can bind to the same port with the wildcard address
518  * (INADDR_ANY).
519  *
520  * The granularity of interface partitioning is at the logical interface level.
521  * Therefore, every zone has its own IP addresses, and incoming packets can be
522  * attributed to a zone unambiguously. A logical interface is placed into a zone
523  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
524  * structure. Rule (1) is implemented by modifying the source address selection
525  * algorithm so that the list of eligible addresses is filtered based on the
526  * sending process zone.
527  *
528  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
529  * across all zones, depending on their type. Here is the break-up:
530  *
531  * IRE type				Shared/exclusive
532  * --------				----------------
533  * IRE_BROADCAST			Exclusive
534  * IRE_DEFAULT (default routes)		Shared (*)
535  * IRE_LOCAL				Exclusive (x)
536  * IRE_LOOPBACK				Exclusive
537  * IRE_PREFIX (net routes)		Shared (*)
538  * IRE_CACHE				Exclusive
539  * IRE_IF_NORESOLVER (interface routes)	Exclusive
540  * IRE_IF_RESOLVER (interface routes)	Exclusive
541  * IRE_HOST (host routes)		Shared (*)
542  *
543  * (*) A zone can only use a default or off-subnet route if the gateway is
544  * directly reachable from the zone, that is, if the gateway's address matches
545  * one of the zone's logical interfaces.
546  *
547  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
548  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
549  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
550  * address of the zone itself (the destination). Since IRE_LOCAL is used
551  * for communication between zones, ip_wput_ire has special logic to set
552  * the right source address when sending using an IRE_LOCAL.
553  *
554  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
555  * ire_cache_lookup restricts loopback using an IRE_LOCAL
556  * between zone to the case when L2 would have conceptually looped the packet
557  * back, i.e. the loopback which is required since neither Ethernet drivers
558  * nor Ethernet hardware loops them back. This is the case when the normal
559  * routes (ignoring IREs with different zoneids) would send out the packet on
560  * the same ill (or ill group) as the ill with which is IRE_LOCAL is
561  * associated.
562  *
563  * Multiple zones can share a common broadcast address; typically all zones
564  * share the 255.255.255.255 address. Incoming as well as locally originated
565  * broadcast packets must be dispatched to all the zones on the broadcast
566  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
567  * since some zones may not be on the 10.16.72/24 network. To handle this, each
568  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
569  * sent to every zone that has an IRE_BROADCAST entry for the destination
570  * address on the input ill, see conn_wantpacket().
571  *
572  * Applications in different zones can join the same multicast group address.
573  * For IPv4, group memberships are per-logical interface, so they're already
574  * inherently part of a zone. For IPv6, group memberships are per-physical
575  * interface, so we distinguish IPv6 group memberships based on group address,
576  * interface and zoneid. In both cases, received multicast packets are sent to
577  * every zone for which a group membership entry exists. On IPv6 we need to
578  * check that the target zone still has an address on the receiving physical
579  * interface; it could have been removed since the application issued the
580  * IPV6_JOIN_GROUP.
581  */
582 
583 /*
584  * Squeue Fanout flags:
585  *	0: No fanout.
586  *	1: Fanout across all squeues
587  */
588 boolean_t	ip_squeue_fanout = 0;
589 
590 /*
591  * Maximum dups allowed per packet.
592  */
593 uint_t ip_max_frag_dups = 10;
594 
595 #define	IS_SIMPLE_IPH(ipha)						\
596 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
597 
598 /* RFC1122 Conformance */
599 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
600 
601 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
602 
603 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
604 
605 static int	ip_open(queue_t *q, dev_t *devp, int flag, int sflag,
606 		    cred_t *credp, boolean_t isv6);
607 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t);
608 
609 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t,
610 		    ip_stack_t *);
611 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
612 		    uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
613 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
614 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
615 		    mblk_t *, int, ip_stack_t *);
616 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
617 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
618 		    ill_t *, zoneid_t);
619 static void	icmp_options_update(ipha_t *);
620 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t,
621 		    ip_stack_t *);
622 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
623 		    zoneid_t zoneid, ip_stack_t *);
624 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_stack_t *);
625 static void	icmp_redirect(ill_t *, mblk_t *);
626 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t,
627 		    ip_stack_t *);
628 
629 static void	ip_arp_news(queue_t *, mblk_t *);
630 static boolean_t ip_bind_insert_ire(mblk_t *, ire_t *, iulp_t *,
631 		    ip_stack_t *);
632 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
633 char		*ip_dot_addr(ipaddr_t, char *);
634 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
635 int		ip_close(queue_t *, int);
636 static char	*ip_dot_saddr(uchar_t *, char *);
637 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
638 		    boolean_t, boolean_t, ill_t *, zoneid_t);
639 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
640 		    boolean_t, boolean_t, zoneid_t);
641 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
642 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
643 static void	ip_lrput(queue_t *, mblk_t *);
644 ipaddr_t	ip_net_mask(ipaddr_t);
645 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, conn_t *, zoneid_t,
646 		    ip_stack_t *);
647 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
648 		    conn_t *, uint32_t, zoneid_t, ip_opt_info_t *);
649 char		*ip_nv_lookup(nv_t *, int);
650 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
651 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
652 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
653 static boolean_t	ip_param_register(IDP *ndp, ipparam_t *, size_t,
654     ipndp_t *, size_t);
655 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
656 void	ip_rput(queue_t *, mblk_t *);
657 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
658 		    void *dummy_arg);
659 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
660 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *,
661     ip_stack_t *);
662 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
663 			    ire_t *, ip_stack_t *);
664 static boolean_t	ip_rput_multimblk_ipoptions(queue_t *, ill_t *,
665 			    mblk_t *, ipha_t **, ipaddr_t *, ip_stack_t *);
666 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *,
667     ip_stack_t *);
668 static boolean_t ip_rput_fragment(queue_t *, mblk_t **, ipha_t *, uint32_t *,
669 		    uint16_t *);
670 int		ip_snmp_get(queue_t *, mblk_t *, int);
671 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
672 		    mib2_ipIfStatsEntry_t *, ip_stack_t *);
673 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
674 		    ip_stack_t *);
675 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *);
676 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
677 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
678 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
679 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
680 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
681 		    ip_stack_t *ipst);
682 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
683 		    ip_stack_t *ipst);
684 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
685 		    ip_stack_t *ipst);
686 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
687 		    ip_stack_t *ipst);
688 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
689 		    ip_stack_t *ipst);
690 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
691 		    ip_stack_t *ipst);
692 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
693 		    ip_stack_t *ipst);
694 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
695 		    ip_stack_t *ipst);
696 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *,
697 		    ip_stack_t *ipst);
698 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *,
699 		    ip_stack_t *ipst);
700 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
701 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
702 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
703 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
704 static boolean_t	ip_source_routed(ipha_t *, ip_stack_t *);
705 static boolean_t	ip_source_route_included(ipha_t *);
706 static void	ip_trash_ire_reclaim_stack(ip_stack_t *);
707 
708 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
709 		    zoneid_t, ip_stack_t *);
710 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int, ip_stack_t *);
711 static void	ip_wput_local_options(ipha_t *, ip_stack_t *);
712 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
713 		    zoneid_t, ip_stack_t *);
714 
715 static void	conn_drain_init(ip_stack_t *);
716 static void	conn_drain_fini(ip_stack_t *);
717 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
718 
719 static void	conn_walk_drain(ip_stack_t *);
720 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
721     zoneid_t);
722 
723 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
724 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
725 static void	ip_stack_fini(netstackid_t stackid, void *arg);
726 
727 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
728     zoneid_t);
729 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
730     void *dummy_arg);
731 
732 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
733 
734 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
735     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
736     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
737 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
738 
739 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
740 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
741     caddr_t, cred_t *);
742 extern int	ip_squeue_bind_set(queue_t *q, mblk_t *mp, char *value,
743     caddr_t cp, cred_t *cr);
744 extern int	ip_squeue_profile_set(queue_t *, mblk_t *, char *, caddr_t,
745     cred_t *);
746 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
747     caddr_t cp, cred_t *cr);
748 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
749     cred_t *);
750 static int	ipmp_hook_emulation_set(queue_t *, mblk_t *, char *, caddr_t,
751     cred_t *);
752 static squeue_func_t ip_squeue_switch(int);
753 
754 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
755 static void	ip_kstat_fini(netstackid_t, kstat_t *);
756 static int	ip_kstat_update(kstat_t *kp, int rw);
757 static void	*icmp_kstat_init(netstackid_t);
758 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
759 static int	icmp_kstat_update(kstat_t *kp, int rw);
760 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
761 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
762 
763 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
764 
765 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
766     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
767 
768 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
769     ipha_t *, ill_t *, boolean_t);
770 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
771 
772 /* How long, in seconds, we allow frags to hang around. */
773 #define	IP_FRAG_TIMEOUT	60
774 
775 /*
776  * Threshold which determines whether MDT should be used when
777  * generating IP fragments; payload size must be greater than
778  * this threshold for MDT to take place.
779  */
780 #define	IP_WPUT_FRAG_MDT_MIN	32768
781 
782 /* Setable in /etc/system only */
783 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
784 
785 static long ip_rput_pullups;
786 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
787 
788 vmem_t *ip_minor_arena;
789 
790 int	ip_debug;
791 
792 #ifdef DEBUG
793 uint32_t ipsechw_debug = 0;
794 #endif
795 
796 /*
797  * Multirouting/CGTP stuff
798  */
799 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
800 
801 /*
802  * XXX following really should only be in a header. Would need more
803  * header and .c clean up first.
804  */
805 extern optdb_obj_t	ip_opt_obj;
806 
807 ulong_t ip_squeue_enter_unbound = 0;
808 
809 /*
810  * Named Dispatch Parameter Table.
811  * All of these are alterable, within the min/max values given, at run time.
812  */
813 static ipparam_t	lcl_param_arr[] = {
814 	/* min	max	value	name */
815 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
816 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
817 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
818 	{  0,	1,	0,	"ip_respond_to_timestamp"},
819 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
820 	{  0,	1,	1,	"ip_send_redirects"},
821 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
822 	{  0,	10,	0,	"ip_debug"},
823 	{  0,	10,	0,	"ip_mrtdebug"},
824 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
825 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
826 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
827 	{  1,	255,	255,	"ip_def_ttl" },
828 	{  0,	1,	0,	"ip_forward_src_routed"},
829 	{  0,	256,	32,	"ip_wroff_extra" },
830 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
831 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
832 	{  0,	1,	1,	"ip_path_mtu_discovery" },
833 	{  0,	240,	30,	"ip_ignore_delete_time" },
834 	{  0,	1,	0,	"ip_ignore_redirect" },
835 	{  0,	1,	1,	"ip_output_queue" },
836 	{  1,	254,	1,	"ip_broadcast_ttl" },
837 	{  0,	99999,	100,	"ip_icmp_err_interval" },
838 	{  1,	99999,	10,	"ip_icmp_err_burst" },
839 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
840 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
841 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
842 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
843 	{  0,	1,	1,	"icmp_accept_clear_messages" },
844 	{  0,	1,	1,	"igmp_accept_clear_messages" },
845 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
846 				"ip_ndp_delay_first_probe_time"},
847 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
848 				"ip_ndp_max_unicast_solicit"},
849 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
850 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
851 	{  0,	1,	0,	"ip6_forward_src_routed"},
852 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
853 	{  0,	1,	1,	"ip6_send_redirects"},
854 	{  0,	1,	0,	"ip6_ignore_redirect" },
855 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
856 
857 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
858 
859 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
860 
861 	{  0,	1,	1,	"pim_accept_clear_messages" },
862 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
863 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
864 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
865 	{  0,	15,	0,	"ip_policy_mask" },
866 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
867 	{  0,	255,	1,	"ip_multirt_ttl" },
868 	{  0,	1,	1,	"ip_multidata_outbound" },
869 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
870 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
871 	{  0,	1000,	1,	"ip_max_temp_defend" },
872 	{  0,	1000,	3,	"ip_max_defend" },
873 	{  0,	999999,	30,	"ip_defend_interval" },
874 	{  0,	3600000, 300000, "ip_dup_recovery" },
875 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
876 	{  0,	1,	1,	"ip_lso_outbound" },
877 	{  IGMP_V1_ROUTER, IGMP_V3_ROUTER, IGMP_V3_ROUTER, "igmp_max_version" },
878 	{  MLD_V1_ROUTER, MLD_V2_ROUTER, MLD_V2_ROUTER, "mld_max_version" },
879 #ifdef DEBUG
880 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
881 #else
882 	{  0,	0,	0,	"" },
883 #endif
884 };
885 
886 /*
887  * Extended NDP table
888  * The addresses for the first two are filled in to be ips_ip_g_forward
889  * and ips_ipv6_forward at init time.
890  */
891 static ipndp_t	lcl_ndp_arr[] = {
892 	/* getf			setf		data			name */
893 #define	IPNDP_IP_FORWARDING_OFFSET	0
894 	{  ip_param_generic_get,	ip_forward_set,	NULL,
895 	    "ip_forwarding" },
896 #define	IPNDP_IP6_FORWARDING_OFFSET	1
897 	{  ip_param_generic_get,	ip_forward_set,	NULL,
898 	    "ip6_forwarding" },
899 	{  ip_ill_report,	NULL,		NULL,
900 	    "ip_ill_status" },
901 	{  ip_ipif_report,	NULL,		NULL,
902 	    "ip_ipif_status" },
903 	{  ip_ire_report,	NULL,		NULL,
904 	    "ipv4_ire_status" },
905 	{  ip_ire_report_v6,	NULL,		NULL,
906 	    "ipv6_ire_status" },
907 	{  ip_conn_report,	NULL,		NULL,
908 	    "ip_conn_status" },
909 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
910 	    "ip_rput_pullups" },
911 	{  ndp_report,		NULL,		NULL,
912 	    "ip_ndp_cache_report" },
913 	{  ip_srcid_report,	NULL,		NULL,
914 	    "ip_srcid_status" },
915 	{ ip_param_generic_get, ip_squeue_profile_set,
916 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
917 	{ ip_param_generic_get, ip_squeue_bind_set,
918 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
919 	{ ip_param_generic_get, ip_input_proc_set,
920 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
921 	{ ip_param_generic_get, ip_int_set,
922 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
923 #define	IPNDP_CGTP_FILTER_OFFSET	14
924 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
925 	    "ip_cgtp_filter" },
926 	{ ip_param_generic_get, ip_int_set,
927 	    (caddr_t)&ip_soft_rings_cnt, "ip_soft_rings_cnt" },
928 #define	IPNDP_IPMP_HOOK_OFFSET	16
929 	{  ip_param_generic_get, ipmp_hook_emulation_set, NULL,
930 	    "ipmp_hook_emulation" },
931 };
932 
933 /*
934  * Table of IP ioctls encoding the various properties of the ioctl and
935  * indexed based on the last byte of the ioctl command. Occasionally there
936  * is a clash, and there is more than 1 ioctl with the same last byte.
937  * In such a case 1 ioctl is encoded in the ndx table and the remaining
938  * ioctls are encoded in the misc table. An entry in the ndx table is
939  * retrieved by indexing on the last byte of the ioctl command and comparing
940  * the ioctl command with the value in the ndx table. In the event of a
941  * mismatch the misc table is then searched sequentially for the desired
942  * ioctl command.
943  *
944  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
945  */
946 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
947 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
948 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
949 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
950 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
951 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
952 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
953 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
954 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
955 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
956 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
957 
958 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
959 			MISC_CMD, ip_siocaddrt, NULL },
960 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
961 			MISC_CMD, ip_siocdelrt, NULL },
962 
963 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
964 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
965 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
966 			IF_CMD, ip_sioctl_get_addr, NULL },
967 
968 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
969 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
970 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
971 			IPI_GET_CMD | IPI_REPL,
972 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
973 
974 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
975 			IPI_PRIV | IPI_WR | IPI_REPL,
976 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
977 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
978 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
979 			IF_CMD, ip_sioctl_get_flags, NULL },
980 
981 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
982 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
983 
984 	/* copyin size cannot be coded for SIOCGIFCONF */
985 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
986 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
987 
988 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
989 			IF_CMD, ip_sioctl_mtu, NULL },
990 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
991 			IF_CMD, ip_sioctl_get_mtu, NULL },
992 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
993 			IPI_GET_CMD | IPI_REPL,
994 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
995 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
996 			IF_CMD, ip_sioctl_brdaddr, NULL },
997 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
998 			IPI_GET_CMD | IPI_REPL,
999 			IF_CMD, ip_sioctl_get_netmask, NULL },
1000 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1001 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1002 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1003 			IPI_GET_CMD | IPI_REPL,
1004 			IF_CMD, ip_sioctl_get_metric, NULL },
1005 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1006 			IF_CMD, ip_sioctl_metric, NULL },
1007 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1008 
1009 	/* See 166-168 below for extended SIOC*XARP ioctls */
1010 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1011 			ARP_CMD, ip_sioctl_arp, NULL },
1012 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1013 			ARP_CMD, ip_sioctl_arp, NULL },
1014 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1015 			ARP_CMD, ip_sioctl_arp, NULL },
1016 
1017 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1018 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1019 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1020 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1021 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1022 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1023 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1024 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1025 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1026 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1027 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1028 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1029 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1030 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1031 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1032 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1033 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1034 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1035 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1036 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1037 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1038 
1039 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1040 			MISC_CMD, if_unitsel, if_unitsel_restart },
1041 
1042 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1043 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1044 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1045 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1046 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1047 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1048 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1049 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1050 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1051 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1052 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1053 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1054 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1055 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1056 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1057 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1058 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1059 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1060 
1061 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1062 			IPI_PRIV | IPI_WR | IPI_MODOK,
1063 			IF_CMD, ip_sioctl_sifname, NULL },
1064 
1065 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1066 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1067 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1068 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1069 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1070 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1071 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1072 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1073 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1074 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1075 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1076 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1077 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1078 
1079 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1080 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1081 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1082 			IF_CMD, ip_sioctl_get_muxid, NULL },
1083 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1084 			IPI_PRIV | IPI_WR | IPI_REPL,
1085 			IF_CMD, ip_sioctl_muxid, NULL },
1086 
1087 	/* Both if and lif variants share same func */
1088 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1089 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1090 	/* Both if and lif variants share same func */
1091 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1092 			IPI_PRIV | IPI_WR | IPI_REPL,
1093 			IF_CMD, ip_sioctl_slifindex, NULL },
1094 
1095 	/* copyin size cannot be coded for SIOCGIFCONF */
1096 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
1097 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1098 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1099 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1100 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1101 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1102 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1103 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1104 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1105 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1106 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1109 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1110 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1111 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1112 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1113 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1114 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1115 
1116 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1117 			IPI_PRIV | IPI_WR | IPI_REPL,
1118 			LIF_CMD, ip_sioctl_removeif,
1119 			ip_sioctl_removeif_restart },
1120 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1121 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1122 			LIF_CMD, ip_sioctl_addif, NULL },
1123 #define	SIOCLIFADDR_NDX 112
1124 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1125 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1126 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1127 			IPI_GET_CMD | IPI_REPL,
1128 			LIF_CMD, ip_sioctl_get_addr, NULL },
1129 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1130 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1131 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1132 			IPI_GET_CMD | IPI_REPL,
1133 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1134 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1135 			IPI_PRIV | IPI_WR | IPI_REPL,
1136 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1137 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1138 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1139 			LIF_CMD, ip_sioctl_get_flags, NULL },
1140 
1141 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1142 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1143 
1144 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1145 			ip_sioctl_get_lifconf, NULL },
1146 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1147 			LIF_CMD, ip_sioctl_mtu, NULL },
1148 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1149 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1150 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1151 			IPI_GET_CMD | IPI_REPL,
1152 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1153 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1154 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1155 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1156 			IPI_GET_CMD | IPI_REPL,
1157 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1158 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1159 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1160 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1161 			IPI_GET_CMD | IPI_REPL,
1162 			LIF_CMD, ip_sioctl_get_metric, NULL },
1163 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1164 			LIF_CMD, ip_sioctl_metric, NULL },
1165 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1166 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1167 			LIF_CMD, ip_sioctl_slifname,
1168 			ip_sioctl_slifname_restart },
1169 
1170 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1171 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1172 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1173 			IPI_GET_CMD | IPI_REPL,
1174 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1175 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1176 			IPI_PRIV | IPI_WR | IPI_REPL,
1177 			LIF_CMD, ip_sioctl_muxid, NULL },
1178 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1179 			IPI_GET_CMD | IPI_REPL,
1180 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1181 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1182 			IPI_PRIV | IPI_WR | IPI_REPL,
1183 			LIF_CMD, ip_sioctl_slifindex, 0 },
1184 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1185 			LIF_CMD, ip_sioctl_token, NULL },
1186 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1187 			IPI_GET_CMD | IPI_REPL,
1188 			LIF_CMD, ip_sioctl_get_token, NULL },
1189 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1190 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1191 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1192 			IPI_GET_CMD | IPI_REPL,
1193 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1194 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1195 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1196 
1197 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1198 			IPI_GET_CMD | IPI_REPL,
1199 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1200 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1201 			LIF_CMD, ip_siocdelndp_v6, NULL },
1202 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1203 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1204 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1205 			LIF_CMD, ip_siocsetndp_v6, NULL },
1206 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1207 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1208 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1209 			MISC_CMD, ip_sioctl_tonlink, NULL },
1210 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1211 			MISC_CMD, ip_sioctl_tmysite, NULL },
1212 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1213 			TUN_CMD, ip_sioctl_tunparam, NULL },
1214 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1215 			IPI_PRIV | IPI_WR,
1216 			TUN_CMD, ip_sioctl_tunparam, NULL },
1217 
1218 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1219 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1220 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1221 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1222 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1223 
1224 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1225 			IPI_PRIV | IPI_WR | IPI_REPL,
1226 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1227 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1228 			IPI_PRIV | IPI_WR | IPI_REPL,
1229 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1230 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1231 			IPI_PRIV | IPI_WR,
1232 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1233 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1234 			IPI_GET_CMD | IPI_REPL,
1235 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1236 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1237 			IPI_GET_CMD | IPI_REPL,
1238 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1239 
1240 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1241 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1242 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1243 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1244 
1245 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1246 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1247 
1248 	/* These are handled in ip_sioctl_copyin_setup itself */
1249 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1250 			MISC_CMD, NULL, NULL },
1251 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1252 			MISC_CMD, NULL, NULL },
1253 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1254 
1255 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1256 			ip_sioctl_get_lifconf, NULL },
1257 
1258 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1259 			XARP_CMD, ip_sioctl_arp, NULL },
1260 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1261 			XARP_CMD, ip_sioctl_arp, NULL },
1262 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1263 			XARP_CMD, ip_sioctl_arp, NULL },
1264 
1265 	/* SIOCPOPSOCKFS is not handled by IP */
1266 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1267 
1268 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1269 			IPI_GET_CMD | IPI_REPL,
1270 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1271 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1272 			IPI_PRIV | IPI_WR | IPI_REPL,
1273 			LIF_CMD, ip_sioctl_slifzone,
1274 			ip_sioctl_slifzone_restart },
1275 	/* 172-174 are SCTP ioctls and not handled by IP */
1276 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1277 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1278 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1279 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1280 			IPI_GET_CMD, LIF_CMD,
1281 			ip_sioctl_get_lifusesrc, 0 },
1282 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1283 			IPI_PRIV | IPI_WR,
1284 			LIF_CMD, ip_sioctl_slifusesrc,
1285 			NULL },
1286 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1287 			ip_sioctl_get_lifsrcof, NULL },
1288 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1289 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1290 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1291 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1292 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1293 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1294 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1295 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1296 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1297 			ip_sioctl_set_ipmpfailback, 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 /* Defined in ip_netinfo.c */
1348 extern ddi_taskq_t	*eventq_queue_nic;
1349 
1350 /* Simple ICMP IP Header Template */
1351 static ipha_t icmp_ipha = {
1352 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1353 };
1354 
1355 struct module_info ip_mod_info = {
1356 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1357 };
1358 
1359 /*
1360  * Duplicate static symbols within a module confuses mdb; so we avoid the
1361  * problem by making the symbols here distinct from those in udp.c.
1362  */
1363 
1364 /*
1365  * Entry points for IP as a device and as a module.
1366  * FIXME: down the road we might want a separate module and driver qinit.
1367  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1368  */
1369 static struct qinit iprinitv4 = {
1370 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1371 	&ip_mod_info
1372 };
1373 
1374 struct qinit iprinitv6 = {
1375 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1376 	&ip_mod_info
1377 };
1378 
1379 static struct qinit ipwinitv4 = {
1380 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1381 	&ip_mod_info
1382 };
1383 
1384 struct qinit ipwinitv6 = {
1385 	(pfi_t)ip_wput_v6, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1386 	&ip_mod_info
1387 };
1388 
1389 static struct qinit iplrinit = {
1390 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1391 	&ip_mod_info
1392 };
1393 
1394 static struct qinit iplwinit = {
1395 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1396 	&ip_mod_info
1397 };
1398 
1399 /* For AF_INET aka /dev/ip */
1400 struct streamtab ipinfov4 = {
1401 	&iprinitv4, &ipwinitv4, &iplrinit, &iplwinit
1402 };
1403 
1404 /* For AF_INET6 aka /dev/ip6 */
1405 struct streamtab ipinfov6 = {
1406 	&iprinitv6, &ipwinitv6, &iplrinit, &iplwinit
1407 };
1408 
1409 #ifdef	DEBUG
1410 static boolean_t skip_sctp_cksum = B_FALSE;
1411 #endif
1412 
1413 /*
1414  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1415  * ip_rput_v6(), ip_output(), etc.  If the message
1416  * block already has a M_CTL at the front of it, then simply set the zoneid
1417  * appropriately.
1418  */
1419 mblk_t *
1420 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1421 {
1422 	mblk_t		*first_mp;
1423 	ipsec_out_t	*io;
1424 
1425 	ASSERT(zoneid != ALL_ZONES);
1426 	if (mp->b_datap->db_type == M_CTL) {
1427 		io = (ipsec_out_t *)mp->b_rptr;
1428 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1429 		io->ipsec_out_zoneid = zoneid;
1430 		return (mp);
1431 	}
1432 
1433 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1434 	if (first_mp == NULL)
1435 		return (NULL);
1436 	io = (ipsec_out_t *)first_mp->b_rptr;
1437 	/* This is not a secure packet */
1438 	io->ipsec_out_secure = B_FALSE;
1439 	io->ipsec_out_zoneid = zoneid;
1440 	first_mp->b_cont = mp;
1441 	return (first_mp);
1442 }
1443 
1444 /*
1445  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1446  */
1447 mblk_t *
1448 ip_copymsg(mblk_t *mp)
1449 {
1450 	mblk_t *nmp;
1451 	ipsec_info_t *in;
1452 
1453 	if (mp->b_datap->db_type != M_CTL)
1454 		return (copymsg(mp));
1455 
1456 	in = (ipsec_info_t *)mp->b_rptr;
1457 
1458 	/*
1459 	 * Note that M_CTL is also used for delivering ICMP error messages
1460 	 * upstream to transport layers.
1461 	 */
1462 	if (in->ipsec_info_type != IPSEC_OUT &&
1463 	    in->ipsec_info_type != IPSEC_IN)
1464 		return (copymsg(mp));
1465 
1466 	nmp = copymsg(mp->b_cont);
1467 
1468 	if (in->ipsec_info_type == IPSEC_OUT) {
1469 		return (ipsec_out_tag(mp, nmp,
1470 		    ((ipsec_out_t *)in)->ipsec_out_ns));
1471 	} else {
1472 		return (ipsec_in_tag(mp, nmp,
1473 		    ((ipsec_in_t *)in)->ipsec_in_ns));
1474 	}
1475 }
1476 
1477 /* Generate an ICMP fragmentation needed message. */
1478 static void
1479 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1480     ip_stack_t *ipst)
1481 {
1482 	icmph_t	icmph;
1483 	mblk_t *first_mp;
1484 	boolean_t mctl_present;
1485 
1486 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1487 
1488 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1489 		if (mctl_present)
1490 			freeb(first_mp);
1491 		return;
1492 	}
1493 
1494 	bzero(&icmph, sizeof (icmph_t));
1495 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1496 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1497 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1498 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1499 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1500 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1501 	    ipst);
1502 }
1503 
1504 /*
1505  * icmp_inbound deals with ICMP messages in the following ways.
1506  *
1507  * 1) It needs to send a reply back and possibly delivering it
1508  *    to the "interested" upper clients.
1509  * 2) It needs to send it to the upper clients only.
1510  * 3) It needs to change some values in IP only.
1511  * 4) It needs to change some values in IP and upper layers e.g TCP.
1512  *
1513  * We need to accomodate icmp messages coming in clear until we get
1514  * everything secure from the wire. If icmp_accept_clear_messages
1515  * is zero we check with the global policy and act accordingly. If
1516  * it is non-zero, we accept the message without any checks. But
1517  * *this does not mean* that this will be delivered to the upper
1518  * clients. By accepting we might send replies back, change our MTU
1519  * value etc. but delivery to the ULP/clients depends on their policy
1520  * dispositions.
1521  *
1522  * We handle the above 4 cases in the context of IPsec in the
1523  * following way :
1524  *
1525  * 1) Send the reply back in the same way as the request came in.
1526  *    If it came in encrypted, it goes out encrypted. If it came in
1527  *    clear, it goes out in clear. Thus, this will prevent chosen
1528  *    plain text attack.
1529  * 2) The client may or may not expect things to come in secure.
1530  *    If it comes in secure, the policy constraints are checked
1531  *    before delivering it to the upper layers. If it comes in
1532  *    clear, ipsec_inbound_accept_clear will decide whether to
1533  *    accept this in clear or not. In both the cases, if the returned
1534  *    message (IP header + 8 bytes) that caused the icmp message has
1535  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1536  *    sending up. If there are only 8 bytes of returned message, then
1537  *    upper client will not be notified.
1538  * 3) Check with global policy to see whether it matches the constaints.
1539  *    But this will be done only if icmp_accept_messages_in_clear is
1540  *    zero.
1541  * 4) If we need to change both in IP and ULP, then the decision taken
1542  *    while affecting the values in IP and while delivering up to TCP
1543  *    should be the same.
1544  *
1545  * 	There are two cases.
1546  *
1547  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1548  *	   failed), we will not deliver it to the ULP, even though they
1549  *	   are *willing* to accept in *clear*. This is fine as our global
1550  *	   disposition to icmp messages asks us reject the datagram.
1551  *
1552  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1553  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1554  *	   to deliver it to ULP (policy failed), it can lead to
1555  *	   consistency problems. The cases known at this time are
1556  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1557  *	   values :
1558  *
1559  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1560  *	     and Upper layer rejects. Then the communication will
1561  *	     come to a stop. This is solved by making similar decisions
1562  *	     at both levels. Currently, when we are unable to deliver
1563  *	     to the Upper Layer (due to policy failures) while IP has
1564  *	     adjusted ire_max_frag, the next outbound datagram would
1565  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1566  *	     will be with the right level of protection. Thus the right
1567  *	     value will be communicated even if we are not able to
1568  *	     communicate when we get from the wire initially. But this
1569  *	     assumes there would be at least one outbound datagram after
1570  *	     IP has adjusted its ire_max_frag value. To make things
1571  *	     simpler, we accept in clear after the validation of
1572  *	     AH/ESP headers.
1573  *
1574  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1575  *	     upper layer depending on the level of protection the upper
1576  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1577  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1578  *	     should be accepted in clear when the Upper layer expects secure.
1579  *	     Thus the communication may get aborted by some bad ICMP
1580  *	     packets.
1581  *
1582  * IPQoS Notes:
1583  * The only instance when a packet is sent for processing is when there
1584  * isn't an ICMP client and if we are interested in it.
1585  * If there is a client, IPPF processing will take place in the
1586  * ip_fanout_proto routine.
1587  *
1588  * Zones notes:
1589  * The packet is only processed in the context of the specified zone: typically
1590  * only this zone will reply to an echo request, and only interested clients in
1591  * this zone will receive a copy of the packet. This means that the caller must
1592  * call icmp_inbound() for each relevant zone.
1593  */
1594 static void
1595 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1596     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1597     ill_t *recv_ill, zoneid_t zoneid)
1598 {
1599 	icmph_t	*icmph;
1600 	ipha_t	*ipha;
1601 	int	iph_hdr_length;
1602 	int	hdr_length;
1603 	boolean_t	interested;
1604 	uint32_t	ts;
1605 	uchar_t	*wptr;
1606 	ipif_t	*ipif;
1607 	mblk_t *first_mp;
1608 	ipsec_in_t *ii;
1609 	ire_t *src_ire;
1610 	boolean_t onlink;
1611 	timestruc_t now;
1612 	uint32_t ill_index;
1613 	ip_stack_t *ipst;
1614 
1615 	ASSERT(ill != NULL);
1616 	ipst = ill->ill_ipst;
1617 
1618 	first_mp = mp;
1619 	if (mctl_present) {
1620 		mp = first_mp->b_cont;
1621 		ASSERT(mp != NULL);
1622 	}
1623 
1624 	ipha = (ipha_t *)mp->b_rptr;
1625 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1626 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1627 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1628 		if (first_mp == NULL)
1629 			return;
1630 	}
1631 
1632 	/*
1633 	 * On a labeled system, we have to check whether the zone itself is
1634 	 * permitted to receive raw traffic.
1635 	 */
1636 	if (is_system_labeled()) {
1637 		if (zoneid == ALL_ZONES)
1638 			zoneid = tsol_packet_to_zoneid(mp);
1639 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1640 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1641 			    zoneid));
1642 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1643 			freemsg(first_mp);
1644 			return;
1645 		}
1646 	}
1647 
1648 	/*
1649 	 * We have accepted the ICMP message. It means that we will
1650 	 * respond to the packet if needed. It may not be delivered
1651 	 * to the upper client depending on the policy constraints
1652 	 * and the disposition in ipsec_inbound_accept_clear.
1653 	 */
1654 
1655 	ASSERT(ill != NULL);
1656 
1657 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1658 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1659 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1660 		/* Last chance to get real. */
1661 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1662 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1663 			freemsg(first_mp);
1664 			return;
1665 		}
1666 		/* Refresh iph following the pullup. */
1667 		ipha = (ipha_t *)mp->b_rptr;
1668 	}
1669 	/* ICMP header checksum, including checksum field, should be zero. */
1670 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1671 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1672 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1673 		freemsg(first_mp);
1674 		return;
1675 	}
1676 	/* The IP header will always be a multiple of four bytes */
1677 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1678 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1679 	    icmph->icmph_code));
1680 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1681 	/* We will set "interested" to "true" if we want a copy */
1682 	interested = B_FALSE;
1683 	switch (icmph->icmph_type) {
1684 	case ICMP_ECHO_REPLY:
1685 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1686 		break;
1687 	case ICMP_DEST_UNREACHABLE:
1688 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1689 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1690 		interested = B_TRUE;	/* Pass up to transport */
1691 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1692 		break;
1693 	case ICMP_SOURCE_QUENCH:
1694 		interested = B_TRUE;	/* Pass up to transport */
1695 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1696 		break;
1697 	case ICMP_REDIRECT:
1698 		if (!ipst->ips_ip_ignore_redirect)
1699 			interested = B_TRUE;
1700 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1701 		break;
1702 	case ICMP_ECHO_REQUEST:
1703 		/*
1704 		 * Whether to respond to echo requests that come in as IP
1705 		 * broadcasts or as IP multicast is subject to debate
1706 		 * (what isn't?).  We aim to please, you pick it.
1707 		 * Default is do it.
1708 		 */
1709 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1710 			/* unicast: always respond */
1711 			interested = B_TRUE;
1712 		} else if (CLASSD(ipha->ipha_dst)) {
1713 			/* multicast: respond based on tunable */
1714 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1715 		} else if (broadcast) {
1716 			/* broadcast: respond based on tunable */
1717 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1718 		}
1719 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1720 		break;
1721 	case ICMP_ROUTER_ADVERTISEMENT:
1722 	case ICMP_ROUTER_SOLICITATION:
1723 		break;
1724 	case ICMP_TIME_EXCEEDED:
1725 		interested = B_TRUE;	/* Pass up to transport */
1726 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1727 		break;
1728 	case ICMP_PARAM_PROBLEM:
1729 		interested = B_TRUE;	/* Pass up to transport */
1730 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1731 		break;
1732 	case ICMP_TIME_STAMP_REQUEST:
1733 		/* Response to Time Stamp Requests is local policy. */
1734 		if (ipst->ips_ip_g_resp_to_timestamp &&
1735 		    /* So is whether to respond if it was an IP broadcast. */
1736 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1737 			int tstamp_len = 3 * sizeof (uint32_t);
1738 
1739 			if (wptr +  tstamp_len > mp->b_wptr) {
1740 				if (!pullupmsg(mp, wptr + tstamp_len -
1741 				    mp->b_rptr)) {
1742 					BUMP_MIB(ill->ill_ip_mib,
1743 					    ipIfStatsInDiscards);
1744 					freemsg(first_mp);
1745 					return;
1746 				}
1747 				/* Refresh ipha following the pullup. */
1748 				ipha = (ipha_t *)mp->b_rptr;
1749 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1750 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1751 			}
1752 			interested = B_TRUE;
1753 		}
1754 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1755 		break;
1756 	case ICMP_TIME_STAMP_REPLY:
1757 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1758 		break;
1759 	case ICMP_INFO_REQUEST:
1760 		/* Per RFC 1122 3.2.2.7, ignore this. */
1761 	case ICMP_INFO_REPLY:
1762 		break;
1763 	case ICMP_ADDRESS_MASK_REQUEST:
1764 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1765 		    !broadcast) &&
1766 		    /* TODO m_pullup of complete header? */
1767 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN) {
1768 			interested = B_TRUE;
1769 		}
1770 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1771 		break;
1772 	case ICMP_ADDRESS_MASK_REPLY:
1773 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1774 		break;
1775 	default:
1776 		interested = B_TRUE;	/* Pass up to transport */
1777 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1778 		break;
1779 	}
1780 	/* See if there is an ICMP client. */
1781 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1782 		/* If there is an ICMP client and we want one too, copy it. */
1783 		mblk_t *first_mp1;
1784 
1785 		if (!interested) {
1786 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1787 			    ip_policy, recv_ill, zoneid);
1788 			return;
1789 		}
1790 		first_mp1 = ip_copymsg(first_mp);
1791 		if (first_mp1 != NULL) {
1792 			ip_fanout_proto(q, first_mp1, ill, ipha,
1793 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1794 		}
1795 	} else if (!interested) {
1796 		freemsg(first_mp);
1797 		return;
1798 	} else {
1799 		/*
1800 		 * Initiate policy processing for this packet if ip_policy
1801 		 * is true.
1802 		 */
1803 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1804 			ill_index = ill->ill_phyint->phyint_ifindex;
1805 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1806 			if (mp == NULL) {
1807 				if (mctl_present) {
1808 					freeb(first_mp);
1809 				}
1810 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1811 				return;
1812 			}
1813 		}
1814 	}
1815 	/* We want to do something with it. */
1816 	/* Check db_ref to make sure we can modify the packet. */
1817 	if (mp->b_datap->db_ref > 1) {
1818 		mblk_t	*first_mp1;
1819 
1820 		first_mp1 = ip_copymsg(first_mp);
1821 		freemsg(first_mp);
1822 		if (!first_mp1) {
1823 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1824 			return;
1825 		}
1826 		first_mp = first_mp1;
1827 		if (mctl_present) {
1828 			mp = first_mp->b_cont;
1829 			ASSERT(mp != NULL);
1830 		} else {
1831 			mp = first_mp;
1832 		}
1833 		ipha = (ipha_t *)mp->b_rptr;
1834 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1835 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1836 	}
1837 	switch (icmph->icmph_type) {
1838 	case ICMP_ADDRESS_MASK_REQUEST:
1839 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1840 		if (ipif == NULL) {
1841 			freemsg(first_mp);
1842 			return;
1843 		}
1844 		/*
1845 		 * outging interface must be IPv4
1846 		 */
1847 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1848 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1849 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1850 		ipif_refrele(ipif);
1851 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1852 		break;
1853 	case ICMP_ECHO_REQUEST:
1854 		icmph->icmph_type = ICMP_ECHO_REPLY;
1855 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1856 		break;
1857 	case ICMP_TIME_STAMP_REQUEST: {
1858 		uint32_t *tsp;
1859 
1860 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1861 		tsp = (uint32_t *)wptr;
1862 		tsp++;		/* Skip past 'originate time' */
1863 		/* Compute # of milliseconds since midnight */
1864 		gethrestime(&now);
1865 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1866 		    now.tv_nsec / (NANOSEC / MILLISEC);
1867 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1868 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1869 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1870 		break;
1871 	}
1872 	default:
1873 		ipha = (ipha_t *)&icmph[1];
1874 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1875 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1876 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1877 				freemsg(first_mp);
1878 				return;
1879 			}
1880 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1881 			ipha = (ipha_t *)&icmph[1];
1882 		}
1883 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1884 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1885 			freemsg(first_mp);
1886 			return;
1887 		}
1888 		hdr_length = IPH_HDR_LENGTH(ipha);
1889 		if (hdr_length < sizeof (ipha_t)) {
1890 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1891 			freemsg(first_mp);
1892 			return;
1893 		}
1894 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1895 			if (!pullupmsg(mp,
1896 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1897 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1898 				freemsg(first_mp);
1899 				return;
1900 			}
1901 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1902 			ipha = (ipha_t *)&icmph[1];
1903 		}
1904 		switch (icmph->icmph_type) {
1905 		case ICMP_REDIRECT:
1906 			/*
1907 			 * As there is no upper client to deliver, we don't
1908 			 * need the first_mp any more.
1909 			 */
1910 			if (mctl_present) {
1911 				freeb(first_mp);
1912 			}
1913 			icmp_redirect(ill, mp);
1914 			return;
1915 		case ICMP_DEST_UNREACHABLE:
1916 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1917 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1918 				    zoneid, mp, iph_hdr_length, ipst)) {
1919 					freemsg(first_mp);
1920 					return;
1921 				}
1922 				/*
1923 				 * icmp_inbound_too_big() may alter mp.
1924 				 * Resynch ipha and icmph accordingly.
1925 				 */
1926 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1927 				ipha = (ipha_t *)&icmph[1];
1928 			}
1929 			/* FALLTHRU */
1930 		default :
1931 			/*
1932 			 * IPQoS notes: Since we have already done IPQoS
1933 			 * processing we don't want to do it again in
1934 			 * the fanout routines called by
1935 			 * icmp_inbound_error_fanout, hence the last
1936 			 * argument, ip_policy, is B_FALSE.
1937 			 */
1938 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1939 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1940 			    B_FALSE, recv_ill, zoneid);
1941 		}
1942 		return;
1943 	}
1944 	/* Send out an ICMP packet */
1945 	icmph->icmph_checksum = 0;
1946 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1947 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1948 		ipif_t	*ipif_chosen;
1949 		/*
1950 		 * Make it look like it was directed to us, so we don't look
1951 		 * like a fool with a broadcast or multicast source address.
1952 		 */
1953 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1954 		/*
1955 		 * Make sure that we haven't grabbed an interface that's DOWN.
1956 		 */
1957 		if (ipif != NULL) {
1958 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
1959 			    ipha->ipha_src, zoneid);
1960 			if (ipif_chosen != NULL) {
1961 				ipif_refrele(ipif);
1962 				ipif = ipif_chosen;
1963 			}
1964 		}
1965 		if (ipif == NULL) {
1966 			ip0dbg(("icmp_inbound: "
1967 			    "No source for broadcast/multicast:\n"
1968 			    "\tsrc 0x%x dst 0x%x ill %p "
1969 			    "ipif_lcl_addr 0x%x\n",
1970 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
1971 			    (void *)ill,
1972 			    ill->ill_ipif->ipif_lcl_addr));
1973 			freemsg(first_mp);
1974 			return;
1975 		}
1976 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1977 		ipha->ipha_dst = ipif->ipif_src_addr;
1978 		ipif_refrele(ipif);
1979 	}
1980 	/* Reset time to live. */
1981 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1982 	{
1983 		/* Swap source and destination addresses */
1984 		ipaddr_t tmp;
1985 
1986 		tmp = ipha->ipha_src;
1987 		ipha->ipha_src = ipha->ipha_dst;
1988 		ipha->ipha_dst = tmp;
1989 	}
1990 	ipha->ipha_ident = 0;
1991 	if (!IS_SIMPLE_IPH(ipha))
1992 		icmp_options_update(ipha);
1993 
1994 	/*
1995 	 * ICMP echo replies should go out on the same interface
1996 	 * the request came on as probes used by in.mpathd for detecting
1997 	 * NIC failures are ECHO packets. We turn-off load spreading
1998 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
1999 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
2000 	 * function. This is in turn handled by ip_wput and ip_newroute
2001 	 * to make sure that the packet goes out on the interface it came
2002 	 * in on. If we don't turnoff load spreading, the packets might get
2003 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
2004 	 * to go out and in.mpathd would wrongly detect a failure or
2005 	 * mis-detect a NIC failure for link failure. As load spreading
2006 	 * can happen only if ill_group is not NULL, we do only for
2007 	 * that case and this does not affect the normal case.
2008 	 *
2009 	 * We turn off load spreading only on echo packets that came from
2010 	 * on-link hosts. If the interface route has been deleted, this will
2011 	 * not be enforced as we can't do much. For off-link hosts, as the
2012 	 * default routes in IPv4 does not typically have an ire_ipif
2013 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2014 	 * Moreover, expecting a default route through this interface may
2015 	 * not be correct. We use ipha_dst because of the swap above.
2016 	 */
2017 	onlink = B_FALSE;
2018 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2019 		/*
2020 		 * First, we need to make sure that it is not one of our
2021 		 * local addresses. If we set onlink when it is one of
2022 		 * our local addresses, we will end up creating IRE_CACHES
2023 		 * for one of our local addresses. Then, we will never
2024 		 * accept packets for them afterwards.
2025 		 */
2026 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2027 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2028 		if (src_ire == NULL) {
2029 			ipif = ipif_get_next_ipif(NULL, ill);
2030 			if (ipif == NULL) {
2031 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2032 				freemsg(mp);
2033 				return;
2034 			}
2035 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2036 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2037 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE, ipst);
2038 			ipif_refrele(ipif);
2039 			if (src_ire != NULL) {
2040 				onlink = B_TRUE;
2041 				ire_refrele(src_ire);
2042 			}
2043 		} else {
2044 			ire_refrele(src_ire);
2045 		}
2046 	}
2047 	if (!mctl_present) {
2048 		/*
2049 		 * This packet should go out the same way as it
2050 		 * came in i.e in clear. To make sure that global
2051 		 * policy will not be applied to this in ip_wput_ire,
2052 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2053 		 */
2054 		ASSERT(first_mp == mp);
2055 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2056 		if (first_mp == NULL) {
2057 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2058 			freemsg(mp);
2059 			return;
2060 		}
2061 		ii = (ipsec_in_t *)first_mp->b_rptr;
2062 
2063 		/* This is not a secure packet */
2064 		ii->ipsec_in_secure = B_FALSE;
2065 		if (onlink) {
2066 			ii->ipsec_in_attach_if = B_TRUE;
2067 			ii->ipsec_in_ill_index =
2068 			    ill->ill_phyint->phyint_ifindex;
2069 			ii->ipsec_in_rill_index =
2070 			    recv_ill->ill_phyint->phyint_ifindex;
2071 		}
2072 		first_mp->b_cont = mp;
2073 	} else if (onlink) {
2074 		ii = (ipsec_in_t *)first_mp->b_rptr;
2075 		ii->ipsec_in_attach_if = B_TRUE;
2076 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2077 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2078 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2079 	} else {
2080 		ii = (ipsec_in_t *)first_mp->b_rptr;
2081 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2082 	}
2083 	ii->ipsec_in_zoneid = zoneid;
2084 	ASSERT(zoneid != ALL_ZONES);
2085 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2086 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2087 		return;
2088 	}
2089 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2090 	put(WR(q), first_mp);
2091 }
2092 
2093 static ipaddr_t
2094 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2095 {
2096 	conn_t *connp;
2097 	connf_t *connfp;
2098 	ipaddr_t nexthop_addr = INADDR_ANY;
2099 	int hdr_length = IPH_HDR_LENGTH(ipha);
2100 	uint16_t *up;
2101 	uint32_t ports;
2102 	ip_stack_t *ipst = ill->ill_ipst;
2103 
2104 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2105 	switch (ipha->ipha_protocol) {
2106 		case IPPROTO_TCP:
2107 		{
2108 			tcph_t *tcph;
2109 
2110 			/* do a reverse lookup */
2111 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2112 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2113 			    TCPS_LISTEN, ipst);
2114 			break;
2115 		}
2116 		case IPPROTO_UDP:
2117 		{
2118 			uint32_t dstport, srcport;
2119 
2120 			((uint16_t *)&ports)[0] = up[1];
2121 			((uint16_t *)&ports)[1] = up[0];
2122 
2123 			/* Extract ports in net byte order */
2124 			dstport = htons(ntohl(ports) & 0xFFFF);
2125 			srcport = htons(ntohl(ports) >> 16);
2126 
2127 			connfp = &ipst->ips_ipcl_udp_fanout[
2128 			    IPCL_UDP_HASH(dstport, ipst)];
2129 			mutex_enter(&connfp->connf_lock);
2130 			connp = connfp->connf_head;
2131 
2132 			/* do a reverse lookup */
2133 			while ((connp != NULL) &&
2134 			    (!IPCL_UDP_MATCH(connp, dstport,
2135 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2136 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2137 				connp = connp->conn_next;
2138 			}
2139 			if (connp != NULL)
2140 				CONN_INC_REF(connp);
2141 			mutex_exit(&connfp->connf_lock);
2142 			break;
2143 		}
2144 		case IPPROTO_SCTP:
2145 		{
2146 			in6_addr_t map_src, map_dst;
2147 
2148 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2149 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2150 			((uint16_t *)&ports)[0] = up[1];
2151 			((uint16_t *)&ports)[1] = up[0];
2152 
2153 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2154 			    zoneid, ipst->ips_netstack->netstack_sctp);
2155 			if (connp == NULL) {
2156 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2157 				    zoneid, ports, ipha, ipst);
2158 			} else {
2159 				CONN_INC_REF(connp);
2160 				SCTP_REFRELE(CONN2SCTP(connp));
2161 			}
2162 			break;
2163 		}
2164 		default:
2165 		{
2166 			ipha_t ripha;
2167 
2168 			ripha.ipha_src = ipha->ipha_dst;
2169 			ripha.ipha_dst = ipha->ipha_src;
2170 			ripha.ipha_protocol = ipha->ipha_protocol;
2171 
2172 			connfp = &ipst->ips_ipcl_proto_fanout[
2173 			    ipha->ipha_protocol];
2174 			mutex_enter(&connfp->connf_lock);
2175 			connp = connfp->connf_head;
2176 			for (connp = connfp->connf_head; connp != NULL;
2177 			    connp = connp->conn_next) {
2178 				if (IPCL_PROTO_MATCH(connp,
2179 				    ipha->ipha_protocol, &ripha, ill,
2180 				    0, zoneid)) {
2181 					CONN_INC_REF(connp);
2182 					break;
2183 				}
2184 			}
2185 			mutex_exit(&connfp->connf_lock);
2186 		}
2187 	}
2188 	if (connp != NULL) {
2189 		if (connp->conn_nexthop_set)
2190 			nexthop_addr = connp->conn_nexthop_v4;
2191 		CONN_DEC_REF(connp);
2192 	}
2193 	return (nexthop_addr);
2194 }
2195 
2196 /* Table from RFC 1191 */
2197 static int icmp_frag_size_table[] =
2198 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2199 
2200 /*
2201  * Process received ICMP Packet too big.
2202  * After updating any IRE it does the fanout to any matching transport streams.
2203  * Assumes the message has been pulled up till the IP header that caused
2204  * the error.
2205  *
2206  * Returns B_FALSE on failure and B_TRUE on success.
2207  */
2208 static boolean_t
2209 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2210     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2211     ip_stack_t *ipst)
2212 {
2213 	ire_t	*ire, *first_ire;
2214 	int	mtu;
2215 	int	hdr_length;
2216 	ipaddr_t nexthop_addr;
2217 
2218 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2219 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2220 	ASSERT(ill != NULL);
2221 
2222 	hdr_length = IPH_HDR_LENGTH(ipha);
2223 
2224 	/* Drop if the original packet contained a source route */
2225 	if (ip_source_route_included(ipha)) {
2226 		return (B_FALSE);
2227 	}
2228 	/*
2229 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2230 	 * header.
2231 	 */
2232 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2233 	    mp->b_wptr) {
2234 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2235 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2236 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2237 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2238 			return (B_FALSE);
2239 		}
2240 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2241 		ipha = (ipha_t *)&icmph[1];
2242 	}
2243 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2244 	if (nexthop_addr != INADDR_ANY) {
2245 		/* nexthop set */
2246 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2247 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2248 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2249 	} else {
2250 		/* nexthop not set */
2251 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2252 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2253 	}
2254 
2255 	if (!first_ire) {
2256 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2257 		    ntohl(ipha->ipha_dst)));
2258 		return (B_FALSE);
2259 	}
2260 	/* Check for MTU discovery advice as described in RFC 1191 */
2261 	mtu = ntohs(icmph->icmph_du_mtu);
2262 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2263 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2264 	    ire = ire->ire_next) {
2265 		/*
2266 		 * Look for the connection to which this ICMP message is
2267 		 * directed. If it has the IP_NEXTHOP option set, then the
2268 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2269 		 * option. Else the search is limited to regular IREs.
2270 		 */
2271 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2272 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2273 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2274 		    (nexthop_addr != INADDR_ANY)))
2275 			continue;
2276 
2277 		mutex_enter(&ire->ire_lock);
2278 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2279 			/* Reduce the IRE max frag value as advised. */
2280 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2281 			    mtu, ire->ire_max_frag));
2282 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2283 		} else {
2284 			uint32_t length;
2285 			int	i;
2286 
2287 			/*
2288 			 * Use the table from RFC 1191 to figure out
2289 			 * the next "plateau" based on the length in
2290 			 * the original IP packet.
2291 			 */
2292 			length = ntohs(ipha->ipha_length);
2293 			if (ire->ire_max_frag <= length &&
2294 			    ire->ire_max_frag >= length - hdr_length) {
2295 				/*
2296 				 * Handle broken BSD 4.2 systems that
2297 				 * return the wrong iph_length in ICMP
2298 				 * errors.
2299 				 */
2300 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2301 				    length, ire->ire_max_frag));
2302 				length -= hdr_length;
2303 			}
2304 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2305 				if (length > icmp_frag_size_table[i])
2306 					break;
2307 			}
2308 			if (i == A_CNT(icmp_frag_size_table)) {
2309 				/* Smaller than 68! */
2310 				ip1dbg(("Too big for packet size %d\n",
2311 				    length));
2312 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2313 				ire->ire_frag_flag = 0;
2314 			} else {
2315 				mtu = icmp_frag_size_table[i];
2316 				ip1dbg(("Calculated mtu %d, packet size %d, "
2317 				    "before %d", mtu, length,
2318 				    ire->ire_max_frag));
2319 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2320 				ip1dbg((", after %d\n", ire->ire_max_frag));
2321 			}
2322 			/* Record the new max frag size for the ULP. */
2323 			icmph->icmph_du_zero = 0;
2324 			icmph->icmph_du_mtu =
2325 			    htons((uint16_t)ire->ire_max_frag);
2326 		}
2327 		mutex_exit(&ire->ire_lock);
2328 	}
2329 	rw_exit(&first_ire->ire_bucket->irb_lock);
2330 	ire_refrele(first_ire);
2331 	return (B_TRUE);
2332 }
2333 
2334 /*
2335  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2336  * calls this function.
2337  */
2338 static mblk_t *
2339 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2340 {
2341 	ipha_t *ipha;
2342 	icmph_t *icmph;
2343 	ipha_t *in_ipha;
2344 	int length;
2345 
2346 	ASSERT(mp->b_datap->db_type == M_DATA);
2347 
2348 	/*
2349 	 * For Self-encapsulated packets, we added an extra IP header
2350 	 * without the options. Inner IP header is the one from which
2351 	 * the outer IP header was formed. Thus, we need to remove the
2352 	 * outer IP header. To do this, we pullup the whole message
2353 	 * and overlay whatever follows the outer IP header over the
2354 	 * outer IP header.
2355 	 */
2356 
2357 	if (!pullupmsg(mp, -1))
2358 		return (NULL);
2359 
2360 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2361 	ipha = (ipha_t *)&icmph[1];
2362 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2363 
2364 	/*
2365 	 * The length that we want to overlay is following the inner
2366 	 * IP header. Subtracting the IP header + icmp header + outer
2367 	 * IP header's length should give us the length that we want to
2368 	 * overlay.
2369 	 */
2370 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2371 	    hdr_length;
2372 	/*
2373 	 * Overlay whatever follows the inner header over the
2374 	 * outer header.
2375 	 */
2376 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2377 
2378 	/* Set the wptr to account for the outer header */
2379 	mp->b_wptr -= hdr_length;
2380 	return (mp);
2381 }
2382 
2383 /*
2384  * Try to pass the ICMP message upstream in case the ULP cares.
2385  *
2386  * If the packet that caused the ICMP error is secure, we send
2387  * it to AH/ESP to make sure that the attached packet has a
2388  * valid association. ipha in the code below points to the
2389  * IP header of the packet that caused the error.
2390  *
2391  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2392  * in the context of IPsec. Normally we tell the upper layer
2393  * whenever we send the ire (including ip_bind), the IPsec header
2394  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2395  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2396  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2397  * same thing. As TCP has the IPsec options size that needs to be
2398  * adjusted, we just pass the MTU unchanged.
2399  *
2400  * IFN could have been generated locally or by some router.
2401  *
2402  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2403  *	    This happens because IP adjusted its value of MTU on an
2404  *	    earlier IFN message and could not tell the upper layer,
2405  *	    the new adjusted value of MTU e.g. Packet was encrypted
2406  *	    or there was not enough information to fanout to upper
2407  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2408  *	    generates the IFN, where IPsec processing has *not* been
2409  *	    done.
2410  *
2411  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2412  *	    could have generated this. This happens because ire_max_frag
2413  *	    value in IP was set to a new value, while the IPsec processing
2414  *	    was being done and after we made the fragmentation check in
2415  *	    ip_wput_ire. Thus on return from IPsec processing,
2416  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2417  *	    and generates the IFN. As IPsec processing is over, we fanout
2418  *	    to AH/ESP to remove the header.
2419  *
2420  *	    In both these cases, ipsec_in_loopback will be set indicating
2421  *	    that IFN was generated locally.
2422  *
2423  * ROUTER : IFN could be secure or non-secure.
2424  *
2425  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2426  *	      packet in error has AH/ESP headers to validate the AH/ESP
2427  *	      headers. AH/ESP will verify whether there is a valid SA or
2428  *	      not and send it back. We will fanout again if we have more
2429  *	      data in the packet.
2430  *
2431  *	      If the packet in error does not have AH/ESP, we handle it
2432  *	      like any other case.
2433  *
2434  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2435  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2436  *	      for validation. AH/ESP will verify whether there is a
2437  *	      valid SA or not and send it back. We will fanout again if
2438  *	      we have more data in the packet.
2439  *
2440  *	      If the packet in error does not have AH/ESP, we handle it
2441  *	      like any other case.
2442  */
2443 static void
2444 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2445     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2446     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2447     zoneid_t zoneid)
2448 {
2449 	uint16_t *up;	/* Pointer to ports in ULP header */
2450 	uint32_t ports;	/* reversed ports for fanout */
2451 	ipha_t ripha;	/* With reversed addresses */
2452 	mblk_t *first_mp;
2453 	ipsec_in_t *ii;
2454 	tcph_t	*tcph;
2455 	conn_t	*connp;
2456 	ip_stack_t *ipst;
2457 
2458 	ASSERT(ill != NULL);
2459 
2460 	ASSERT(recv_ill != NULL);
2461 	ipst = recv_ill->ill_ipst;
2462 
2463 	first_mp = mp;
2464 	if (mctl_present) {
2465 		mp = first_mp->b_cont;
2466 		ASSERT(mp != NULL);
2467 
2468 		ii = (ipsec_in_t *)first_mp->b_rptr;
2469 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2470 	} else {
2471 		ii = NULL;
2472 	}
2473 
2474 	switch (ipha->ipha_protocol) {
2475 	case IPPROTO_UDP:
2476 		/*
2477 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2478 		 * transport header.
2479 		 */
2480 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2481 		    mp->b_wptr) {
2482 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2483 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2484 				goto discard_pkt;
2485 			}
2486 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2487 			ipha = (ipha_t *)&icmph[1];
2488 		}
2489 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2490 
2491 		/*
2492 		 * Attempt to find a client stream based on port.
2493 		 * Note that we do a reverse lookup since the header is
2494 		 * in the form we sent it out.
2495 		 * The ripha header is only used for the IP_UDP_MATCH and we
2496 		 * only set the src and dst addresses and protocol.
2497 		 */
2498 		ripha.ipha_src = ipha->ipha_dst;
2499 		ripha.ipha_dst = ipha->ipha_src;
2500 		ripha.ipha_protocol = ipha->ipha_protocol;
2501 		((uint16_t *)&ports)[0] = up[1];
2502 		((uint16_t *)&ports)[1] = up[0];
2503 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2504 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2505 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2506 		    icmph->icmph_type, icmph->icmph_code));
2507 
2508 		/* Have to change db_type after any pullupmsg */
2509 		DB_TYPE(mp) = M_CTL;
2510 
2511 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2512 		    mctl_present, ip_policy, recv_ill, zoneid);
2513 		return;
2514 
2515 	case IPPROTO_TCP:
2516 		/*
2517 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2518 		 * transport header.
2519 		 */
2520 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2521 		    mp->b_wptr) {
2522 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2523 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2524 				goto discard_pkt;
2525 			}
2526 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2527 			ipha = (ipha_t *)&icmph[1];
2528 		}
2529 		/*
2530 		 * Find a TCP client stream for this packet.
2531 		 * Note that we do a reverse lookup since the header is
2532 		 * in the form we sent it out.
2533 		 */
2534 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2535 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2536 		    ipst);
2537 		if (connp == NULL)
2538 			goto discard_pkt;
2539 
2540 		/* Have to change db_type after any pullupmsg */
2541 		DB_TYPE(mp) = M_CTL;
2542 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2543 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2544 		return;
2545 
2546 	case IPPROTO_SCTP:
2547 		/*
2548 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2549 		 * transport header.
2550 		 */
2551 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2552 		    mp->b_wptr) {
2553 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2554 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2555 				goto discard_pkt;
2556 			}
2557 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2558 			ipha = (ipha_t *)&icmph[1];
2559 		}
2560 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2561 		/*
2562 		 * Find a SCTP client stream for this packet.
2563 		 * Note that we do a reverse lookup since the header is
2564 		 * in the form we sent it out.
2565 		 * The ripha header is only used for the matching and we
2566 		 * only set the src and dst addresses, protocol, and version.
2567 		 */
2568 		ripha.ipha_src = ipha->ipha_dst;
2569 		ripha.ipha_dst = ipha->ipha_src;
2570 		ripha.ipha_protocol = ipha->ipha_protocol;
2571 		ripha.ipha_version_and_hdr_length =
2572 		    ipha->ipha_version_and_hdr_length;
2573 		((uint16_t *)&ports)[0] = up[1];
2574 		((uint16_t *)&ports)[1] = up[0];
2575 
2576 		/* Have to change db_type after any pullupmsg */
2577 		DB_TYPE(mp) = M_CTL;
2578 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2579 		    mctl_present, ip_policy, zoneid);
2580 		return;
2581 
2582 	case IPPROTO_ESP:
2583 	case IPPROTO_AH: {
2584 		int ipsec_rc;
2585 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2586 
2587 		/*
2588 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2589 		 * We will re-use the IPSEC_IN if it is already present as
2590 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2591 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2592 		 * one and attach it in the front.
2593 		 */
2594 		if (ii != NULL) {
2595 			/*
2596 			 * ip_fanout_proto_again converts the ICMP errors
2597 			 * that come back from AH/ESP to M_DATA so that
2598 			 * if it is non-AH/ESP and we do a pullupmsg in
2599 			 * this function, it would work. Convert it back
2600 			 * to M_CTL before we send up as this is a ICMP
2601 			 * error. This could have been generated locally or
2602 			 * by some router. Validate the inner IPsec
2603 			 * headers.
2604 			 *
2605 			 * NOTE : ill_index is used by ip_fanout_proto_again
2606 			 * to locate the ill.
2607 			 */
2608 			ASSERT(ill != NULL);
2609 			ii->ipsec_in_ill_index =
2610 			    ill->ill_phyint->phyint_ifindex;
2611 			ii->ipsec_in_rill_index =
2612 			    recv_ill->ill_phyint->phyint_ifindex;
2613 			DB_TYPE(first_mp->b_cont) = M_CTL;
2614 		} else {
2615 			/*
2616 			 * IPSEC_IN is not present. We attach a ipsec_in
2617 			 * message and send up to IPsec for validating
2618 			 * and removing the IPsec headers. Clear
2619 			 * ipsec_in_secure so that when we return
2620 			 * from IPsec, we don't mistakenly think that this
2621 			 * is a secure packet came from the network.
2622 			 *
2623 			 * NOTE : ill_index is used by ip_fanout_proto_again
2624 			 * to locate the ill.
2625 			 */
2626 			ASSERT(first_mp == mp);
2627 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2628 			if (first_mp == NULL) {
2629 				freemsg(mp);
2630 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2631 				return;
2632 			}
2633 			ii = (ipsec_in_t *)first_mp->b_rptr;
2634 
2635 			/* This is not a secure packet */
2636 			ii->ipsec_in_secure = B_FALSE;
2637 			first_mp->b_cont = mp;
2638 			DB_TYPE(mp) = M_CTL;
2639 			ASSERT(ill != NULL);
2640 			ii->ipsec_in_ill_index =
2641 			    ill->ill_phyint->phyint_ifindex;
2642 			ii->ipsec_in_rill_index =
2643 			    recv_ill->ill_phyint->phyint_ifindex;
2644 		}
2645 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2646 
2647 		if (!ipsec_loaded(ipss)) {
2648 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2649 			return;
2650 		}
2651 
2652 		if (ipha->ipha_protocol == IPPROTO_ESP)
2653 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2654 		else
2655 			ipsec_rc = ipsecah_icmp_error(first_mp);
2656 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2657 			return;
2658 
2659 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2660 		return;
2661 	}
2662 	default:
2663 		/*
2664 		 * The ripha header is only used for the lookup and we
2665 		 * only set the src and dst addresses and protocol.
2666 		 */
2667 		ripha.ipha_src = ipha->ipha_dst;
2668 		ripha.ipha_dst = ipha->ipha_src;
2669 		ripha.ipha_protocol = ipha->ipha_protocol;
2670 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2671 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2672 		    ntohl(ipha->ipha_dst),
2673 		    icmph->icmph_type, icmph->icmph_code));
2674 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2675 			ipha_t *in_ipha;
2676 
2677 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2678 			    mp->b_wptr) {
2679 				if (!pullupmsg(mp, (uchar_t *)ipha +
2680 				    hdr_length + sizeof (ipha_t) -
2681 				    mp->b_rptr)) {
2682 					goto discard_pkt;
2683 				}
2684 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2685 				ipha = (ipha_t *)&icmph[1];
2686 			}
2687 			/*
2688 			 * Caller has verified that length has to be
2689 			 * at least the size of IP header.
2690 			 */
2691 			ASSERT(hdr_length >= sizeof (ipha_t));
2692 			/*
2693 			 * Check the sanity of the inner IP header like
2694 			 * we did for the outer header.
2695 			 */
2696 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2697 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2698 				goto discard_pkt;
2699 			}
2700 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2701 				goto discard_pkt;
2702 			}
2703 			/* Check for Self-encapsulated tunnels */
2704 			if (in_ipha->ipha_src == ipha->ipha_src &&
2705 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2706 
2707 				mp = icmp_inbound_self_encap_error(mp,
2708 				    iph_hdr_length, hdr_length);
2709 				if (mp == NULL)
2710 					goto discard_pkt;
2711 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2712 				ipha = (ipha_t *)&icmph[1];
2713 				hdr_length = IPH_HDR_LENGTH(ipha);
2714 				/*
2715 				 * The packet in error is self-encapsualted.
2716 				 * And we are finding it further encapsulated
2717 				 * which we could not have possibly generated.
2718 				 */
2719 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2720 					goto discard_pkt;
2721 				}
2722 				icmp_inbound_error_fanout(q, ill, first_mp,
2723 				    icmph, ipha, iph_hdr_length, hdr_length,
2724 				    mctl_present, ip_policy, recv_ill, zoneid);
2725 				return;
2726 			}
2727 		}
2728 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2729 		    ipha->ipha_protocol == IPPROTO_IPV6) &&
2730 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2731 		    ii != NULL &&
2732 		    ii->ipsec_in_loopback &&
2733 		    ii->ipsec_in_secure) {
2734 			/*
2735 			 * For IP tunnels that get a looped-back
2736 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2737 			 * reported new MTU to take into account the IPsec
2738 			 * headers protecting this configured tunnel.
2739 			 *
2740 			 * This allows the tunnel module (tun.c) to blindly
2741 			 * accept the MTU reported in an ICMP "too big"
2742 			 * message.
2743 			 *
2744 			 * Non-looped back ICMP messages will just be
2745 			 * handled by the security protocols (if needed),
2746 			 * and the first subsequent packet will hit this
2747 			 * path.
2748 			 */
2749 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2750 			    ipsec_in_extra_length(first_mp));
2751 		}
2752 		/* Have to change db_type after any pullupmsg */
2753 		DB_TYPE(mp) = M_CTL;
2754 
2755 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2756 		    ip_policy, recv_ill, zoneid);
2757 		return;
2758 	}
2759 	/* NOTREACHED */
2760 discard_pkt:
2761 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2762 drop_pkt:;
2763 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2764 	freemsg(first_mp);
2765 }
2766 
2767 /*
2768  * Common IP options parser.
2769  *
2770  * Setup routine: fill in *optp with options-parsing state, then
2771  * tail-call ipoptp_next to return the first option.
2772  */
2773 uint8_t
2774 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2775 {
2776 	uint32_t totallen; /* total length of all options */
2777 
2778 	totallen = ipha->ipha_version_and_hdr_length -
2779 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2780 	totallen <<= 2;
2781 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2782 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2783 	optp->ipoptp_flags = 0;
2784 	return (ipoptp_next(optp));
2785 }
2786 
2787 /*
2788  * Common IP options parser: extract next option.
2789  */
2790 uint8_t
2791 ipoptp_next(ipoptp_t *optp)
2792 {
2793 	uint8_t *end = optp->ipoptp_end;
2794 	uint8_t *cur = optp->ipoptp_next;
2795 	uint8_t opt, len, pointer;
2796 
2797 	/*
2798 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2799 	 * has been corrupted.
2800 	 */
2801 	ASSERT(cur <= end);
2802 
2803 	if (cur == end)
2804 		return (IPOPT_EOL);
2805 
2806 	opt = cur[IPOPT_OPTVAL];
2807 
2808 	/*
2809 	 * Skip any NOP options.
2810 	 */
2811 	while (opt == IPOPT_NOP) {
2812 		cur++;
2813 		if (cur == end)
2814 			return (IPOPT_EOL);
2815 		opt = cur[IPOPT_OPTVAL];
2816 	}
2817 
2818 	if (opt == IPOPT_EOL)
2819 		return (IPOPT_EOL);
2820 
2821 	/*
2822 	 * Option requiring a length.
2823 	 */
2824 	if ((cur + 1) >= end) {
2825 		optp->ipoptp_flags |= IPOPTP_ERROR;
2826 		return (IPOPT_EOL);
2827 	}
2828 	len = cur[IPOPT_OLEN];
2829 	if (len < 2) {
2830 		optp->ipoptp_flags |= IPOPTP_ERROR;
2831 		return (IPOPT_EOL);
2832 	}
2833 	optp->ipoptp_cur = cur;
2834 	optp->ipoptp_len = len;
2835 	optp->ipoptp_next = cur + len;
2836 	if (cur + len > end) {
2837 		optp->ipoptp_flags |= IPOPTP_ERROR;
2838 		return (IPOPT_EOL);
2839 	}
2840 
2841 	/*
2842 	 * For the options which require a pointer field, make sure
2843 	 * its there, and make sure it points to either something
2844 	 * inside this option, or the end of the option.
2845 	 */
2846 	switch (opt) {
2847 	case IPOPT_RR:
2848 	case IPOPT_TS:
2849 	case IPOPT_LSRR:
2850 	case IPOPT_SSRR:
2851 		if (len <= IPOPT_OFFSET) {
2852 			optp->ipoptp_flags |= IPOPTP_ERROR;
2853 			return (opt);
2854 		}
2855 		pointer = cur[IPOPT_OFFSET];
2856 		if (pointer - 1 > len) {
2857 			optp->ipoptp_flags |= IPOPTP_ERROR;
2858 			return (opt);
2859 		}
2860 		break;
2861 	}
2862 
2863 	/*
2864 	 * Sanity check the pointer field based on the type of the
2865 	 * option.
2866 	 */
2867 	switch (opt) {
2868 	case IPOPT_RR:
2869 	case IPOPT_SSRR:
2870 	case IPOPT_LSRR:
2871 		if (pointer < IPOPT_MINOFF_SR)
2872 			optp->ipoptp_flags |= IPOPTP_ERROR;
2873 		break;
2874 	case IPOPT_TS:
2875 		if (pointer < IPOPT_MINOFF_IT)
2876 			optp->ipoptp_flags |= IPOPTP_ERROR;
2877 		/*
2878 		 * Note that the Internet Timestamp option also
2879 		 * contains two four bit fields (the Overflow field,
2880 		 * and the Flag field), which follow the pointer
2881 		 * field.  We don't need to check that these fields
2882 		 * fall within the length of the option because this
2883 		 * was implicitely done above.  We've checked that the
2884 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2885 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2886 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2887 		 */
2888 		ASSERT(len > IPOPT_POS_OV_FLG);
2889 		break;
2890 	}
2891 
2892 	return (opt);
2893 }
2894 
2895 /*
2896  * Use the outgoing IP header to create an IP_OPTIONS option the way
2897  * it was passed down from the application.
2898  */
2899 int
2900 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2901 {
2902 	ipoptp_t	opts;
2903 	const uchar_t	*opt;
2904 	uint8_t		optval;
2905 	uint8_t		optlen;
2906 	uint32_t	len = 0;
2907 	uchar_t	*buf1 = buf;
2908 
2909 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2910 	len += IP_ADDR_LEN;
2911 	bzero(buf1, IP_ADDR_LEN);
2912 
2913 	/*
2914 	 * OK to cast away const here, as we don't store through the returned
2915 	 * opts.ipoptp_cur pointer.
2916 	 */
2917 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2918 	    optval != IPOPT_EOL;
2919 	    optval = ipoptp_next(&opts)) {
2920 		int	off;
2921 
2922 		opt = opts.ipoptp_cur;
2923 		optlen = opts.ipoptp_len;
2924 		switch (optval) {
2925 		case IPOPT_SSRR:
2926 		case IPOPT_LSRR:
2927 
2928 			/*
2929 			 * Insert ipha_dst as the first entry in the source
2930 			 * route and move down the entries on step.
2931 			 * The last entry gets placed at buf1.
2932 			 */
2933 			buf[IPOPT_OPTVAL] = optval;
2934 			buf[IPOPT_OLEN] = optlen;
2935 			buf[IPOPT_OFFSET] = optlen;
2936 
2937 			off = optlen - IP_ADDR_LEN;
2938 			if (off < 0) {
2939 				/* No entries in source route */
2940 				break;
2941 			}
2942 			/* Last entry in source route */
2943 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2944 			off -= IP_ADDR_LEN;
2945 
2946 			while (off > 0) {
2947 				bcopy(opt + off,
2948 				    buf + off + IP_ADDR_LEN,
2949 				    IP_ADDR_LEN);
2950 				off -= IP_ADDR_LEN;
2951 			}
2952 			/* ipha_dst into first slot */
2953 			bcopy(&ipha->ipha_dst,
2954 			    buf + off + IP_ADDR_LEN,
2955 			    IP_ADDR_LEN);
2956 			buf += optlen;
2957 			len += optlen;
2958 			break;
2959 
2960 		case IPOPT_COMSEC:
2961 		case IPOPT_SECURITY:
2962 			/* if passing up a label is not ok, then remove */
2963 			if (is_system_labeled())
2964 				break;
2965 			/* FALLTHROUGH */
2966 		default:
2967 			bcopy(opt, buf, optlen);
2968 			buf += optlen;
2969 			len += optlen;
2970 			break;
2971 		}
2972 	}
2973 done:
2974 	/* Pad the resulting options */
2975 	while (len & 0x3) {
2976 		*buf++ = IPOPT_EOL;
2977 		len++;
2978 	}
2979 	return (len);
2980 }
2981 
2982 /*
2983  * Update any record route or timestamp options to include this host.
2984  * Reverse any source route option.
2985  * This routine assumes that the options are well formed i.e. that they
2986  * have already been checked.
2987  */
2988 static void
2989 icmp_options_update(ipha_t *ipha)
2990 {
2991 	ipoptp_t	opts;
2992 	uchar_t		*opt;
2993 	uint8_t		optval;
2994 	ipaddr_t	src;		/* Our local address */
2995 	ipaddr_t	dst;
2996 
2997 	ip2dbg(("icmp_options_update\n"));
2998 	src = ipha->ipha_src;
2999 	dst = ipha->ipha_dst;
3000 
3001 	for (optval = ipoptp_first(&opts, ipha);
3002 	    optval != IPOPT_EOL;
3003 	    optval = ipoptp_next(&opts)) {
3004 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
3005 		opt = opts.ipoptp_cur;
3006 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
3007 		    optval, opts.ipoptp_len));
3008 		switch (optval) {
3009 			int off1, off2;
3010 		case IPOPT_SSRR:
3011 		case IPOPT_LSRR:
3012 			/*
3013 			 * Reverse the source route.  The first entry
3014 			 * should be the next to last one in the current
3015 			 * source route (the last entry is our address).
3016 			 * The last entry should be the final destination.
3017 			 */
3018 			off1 = IPOPT_MINOFF_SR - 1;
3019 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3020 			if (off2 < 0) {
3021 				/* No entries in source route */
3022 				ip1dbg((
3023 				    "icmp_options_update: bad src route\n"));
3024 				break;
3025 			}
3026 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3027 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3028 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3029 			off2 -= IP_ADDR_LEN;
3030 
3031 			while (off1 < off2) {
3032 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3033 				bcopy((char *)opt + off2, (char *)opt + off1,
3034 				    IP_ADDR_LEN);
3035 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3036 				off1 += IP_ADDR_LEN;
3037 				off2 -= IP_ADDR_LEN;
3038 			}
3039 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3040 			break;
3041 		}
3042 	}
3043 }
3044 
3045 /*
3046  * Process received ICMP Redirect messages.
3047  */
3048 static void
3049 icmp_redirect(ill_t *ill, mblk_t *mp)
3050 {
3051 	ipha_t	*ipha;
3052 	int	iph_hdr_length;
3053 	icmph_t	*icmph;
3054 	ipha_t	*ipha_err;
3055 	ire_t	*ire;
3056 	ire_t	*prev_ire;
3057 	ire_t	*save_ire;
3058 	ipaddr_t  src, dst, gateway;
3059 	iulp_t	ulp_info = { 0 };
3060 	int	error;
3061 	ip_stack_t *ipst;
3062 
3063 	ASSERT(ill != NULL);
3064 	ipst = ill->ill_ipst;
3065 
3066 	ipha = (ipha_t *)mp->b_rptr;
3067 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3068 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3069 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3070 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3071 		freemsg(mp);
3072 		return;
3073 	}
3074 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3075 	ipha_err = (ipha_t *)&icmph[1];
3076 	src = ipha->ipha_src;
3077 	dst = ipha_err->ipha_dst;
3078 	gateway = icmph->icmph_rd_gateway;
3079 	/* Make sure the new gateway is reachable somehow. */
3080 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3081 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3082 	/*
3083 	 * Make sure we had a route for the dest in question and that
3084 	 * that route was pointing to the old gateway (the source of the
3085 	 * redirect packet.)
3086 	 */
3087 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3088 	    NULL, MATCH_IRE_GW, ipst);
3089 	/*
3090 	 * Check that
3091 	 *	the redirect was not from ourselves
3092 	 *	the new gateway and the old gateway are directly reachable
3093 	 */
3094 	if (!prev_ire ||
3095 	    !ire ||
3096 	    ire->ire_type == IRE_LOCAL) {
3097 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3098 		freemsg(mp);
3099 		if (ire != NULL)
3100 			ire_refrele(ire);
3101 		if (prev_ire != NULL)
3102 			ire_refrele(prev_ire);
3103 		return;
3104 	}
3105 
3106 	/*
3107 	 * Should we use the old ULP info to create the new gateway?  From
3108 	 * a user's perspective, we should inherit the info so that it
3109 	 * is a "smooth" transition.  If we do not do that, then new
3110 	 * connections going thru the new gateway will have no route metrics,
3111 	 * which is counter-intuitive to user.  From a network point of
3112 	 * view, this may or may not make sense even though the new gateway
3113 	 * is still directly connected to us so the route metrics should not
3114 	 * change much.
3115 	 *
3116 	 * But if the old ire_uinfo is not initialized, we do another
3117 	 * recursive lookup on the dest using the new gateway.  There may
3118 	 * be a route to that.  If so, use it to initialize the redirect
3119 	 * route.
3120 	 */
3121 	if (prev_ire->ire_uinfo.iulp_set) {
3122 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3123 	} else {
3124 		ire_t *tmp_ire;
3125 		ire_t *sire;
3126 
3127 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3128 		    ALL_ZONES, 0, NULL,
3129 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3130 		    ipst);
3131 		if (sire != NULL) {
3132 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3133 			/*
3134 			 * If sire != NULL, ire_ftable_lookup() should not
3135 			 * return a NULL value.
3136 			 */
3137 			ASSERT(tmp_ire != NULL);
3138 			ire_refrele(tmp_ire);
3139 			ire_refrele(sire);
3140 		} else if (tmp_ire != NULL) {
3141 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3142 			    sizeof (iulp_t));
3143 			ire_refrele(tmp_ire);
3144 		}
3145 	}
3146 	if (prev_ire->ire_type == IRE_CACHE)
3147 		ire_delete(prev_ire);
3148 	ire_refrele(prev_ire);
3149 	/*
3150 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3151 	 * require TOS routing
3152 	 */
3153 	switch (icmph->icmph_code) {
3154 	case 0:
3155 	case 1:
3156 		/* TODO: TOS specificity for cases 2 and 3 */
3157 	case 2:
3158 	case 3:
3159 		break;
3160 	default:
3161 		freemsg(mp);
3162 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3163 		ire_refrele(ire);
3164 		return;
3165 	}
3166 	/*
3167 	 * Create a Route Association.  This will allow us to remember that
3168 	 * someone we believe told us to use the particular gateway.
3169 	 */
3170 	save_ire = ire;
3171 	ire = ire_create(
3172 	    (uchar_t *)&dst,			/* dest addr */
3173 	    (uchar_t *)&ip_g_all_ones,		/* mask */
3174 	    (uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3175 	    (uchar_t *)&gateway,		/* gateway addr */
3176 	    &save_ire->ire_max_frag,		/* max frag */
3177 	    NULL,				/* no src nce */
3178 	    NULL,				/* no rfq */
3179 	    NULL,				/* no stq */
3180 	    IRE_HOST,
3181 	    NULL,				/* ipif */
3182 	    0,					/* cmask */
3183 	    0,					/* phandle */
3184 	    0,					/* ihandle */
3185 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3186 	    &ulp_info,
3187 	    NULL,				/* tsol_gc_t */
3188 	    NULL,				/* gcgrp */
3189 	    ipst);
3190 
3191 	if (ire == NULL) {
3192 		freemsg(mp);
3193 		ire_refrele(save_ire);
3194 		return;
3195 	}
3196 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3197 	ire_refrele(save_ire);
3198 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3199 
3200 	if (error == 0) {
3201 		ire_refrele(ire);		/* Held in ire_add_v4 */
3202 		/* tell routing sockets that we received a redirect */
3203 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3204 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3205 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3206 	}
3207 
3208 	/*
3209 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3210 	 * This together with the added IRE has the effect of
3211 	 * modifying an existing redirect.
3212 	 */
3213 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3214 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3215 	if (prev_ire != NULL) {
3216 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3217 			ire_delete(prev_ire);
3218 		ire_refrele(prev_ire);
3219 	}
3220 
3221 	freemsg(mp);
3222 }
3223 
3224 /*
3225  * Generate an ICMP parameter problem message.
3226  */
3227 static void
3228 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3229 	ip_stack_t *ipst)
3230 {
3231 	icmph_t	icmph;
3232 	boolean_t mctl_present;
3233 	mblk_t *first_mp;
3234 
3235 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3236 
3237 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3238 		if (mctl_present)
3239 			freeb(first_mp);
3240 		return;
3241 	}
3242 
3243 	bzero(&icmph, sizeof (icmph_t));
3244 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3245 	icmph.icmph_pp_ptr = ptr;
3246 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3247 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3248 	    ipst);
3249 }
3250 
3251 /*
3252  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3253  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3254  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3255  * an icmp error packet can be sent.
3256  * Assigns an appropriate source address to the packet. If ipha_dst is
3257  * one of our addresses use it for source. Otherwise pick a source based
3258  * on a route lookup back to ipha_src.
3259  * Note that ipha_src must be set here since the
3260  * packet is likely to arrive on an ill queue in ip_wput() which will
3261  * not set a source address.
3262  */
3263 static void
3264 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3265     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3266 {
3267 	ipaddr_t dst;
3268 	icmph_t	*icmph;
3269 	ipha_t	*ipha;
3270 	uint_t	len_needed;
3271 	size_t	msg_len;
3272 	mblk_t	*mp1;
3273 	ipaddr_t src;
3274 	ire_t	*ire;
3275 	mblk_t *ipsec_mp;
3276 	ipsec_out_t	*io = NULL;
3277 
3278 	if (mctl_present) {
3279 		/*
3280 		 * If it is :
3281 		 *
3282 		 * 1) a IPSEC_OUT, then this is caused by outbound
3283 		 *    datagram originating on this host. IPsec processing
3284 		 *    may or may not have been done. Refer to comments above
3285 		 *    icmp_inbound_error_fanout for details.
3286 		 *
3287 		 * 2) a IPSEC_IN if we are generating a icmp_message
3288 		 *    for an incoming datagram destined for us i.e called
3289 		 *    from ip_fanout_send_icmp.
3290 		 */
3291 		ipsec_info_t *in;
3292 		ipsec_mp = mp;
3293 		mp = ipsec_mp->b_cont;
3294 
3295 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3296 		ipha = (ipha_t *)mp->b_rptr;
3297 
3298 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3299 		    in->ipsec_info_type == IPSEC_IN);
3300 
3301 		if (in->ipsec_info_type == IPSEC_IN) {
3302 			/*
3303 			 * Convert the IPSEC_IN to IPSEC_OUT.
3304 			 */
3305 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3306 				BUMP_MIB(&ipst->ips_ip_mib,
3307 				    ipIfStatsOutDiscards);
3308 				return;
3309 			}
3310 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3311 		} else {
3312 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3313 			io = (ipsec_out_t *)in;
3314 			/*
3315 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3316 			 * ire lookup.
3317 			 */
3318 			io->ipsec_out_proc_begin = B_FALSE;
3319 		}
3320 		ASSERT(zoneid == io->ipsec_out_zoneid);
3321 		ASSERT(zoneid != ALL_ZONES);
3322 	} else {
3323 		/*
3324 		 * This is in clear. The icmp message we are building
3325 		 * here should go out in clear.
3326 		 *
3327 		 * Pardon the convolution of it all, but it's easier to
3328 		 * allocate a "use cleartext" IPSEC_IN message and convert
3329 		 * it than it is to allocate a new one.
3330 		 */
3331 		ipsec_in_t *ii;
3332 		ASSERT(DB_TYPE(mp) == M_DATA);
3333 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3334 		if (ipsec_mp == NULL) {
3335 			freemsg(mp);
3336 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3337 			return;
3338 		}
3339 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3340 
3341 		/* This is not a secure packet */
3342 		ii->ipsec_in_secure = B_FALSE;
3343 		/*
3344 		 * For trusted extensions using a shared IP address we can
3345 		 * send using any zoneid.
3346 		 */
3347 		if (zoneid == ALL_ZONES)
3348 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3349 		else
3350 			ii->ipsec_in_zoneid = zoneid;
3351 		ipsec_mp->b_cont = mp;
3352 		ipha = (ipha_t *)mp->b_rptr;
3353 		/*
3354 		 * Convert the IPSEC_IN to IPSEC_OUT.
3355 		 */
3356 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3357 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3358 			return;
3359 		}
3360 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3361 	}
3362 
3363 	/* Remember our eventual destination */
3364 	dst = ipha->ipha_src;
3365 
3366 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3367 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3368 	if (ire != NULL &&
3369 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3370 		src = ipha->ipha_dst;
3371 	} else {
3372 		if (ire != NULL)
3373 			ire_refrele(ire);
3374 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3375 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3376 		    ipst);
3377 		if (ire == NULL) {
3378 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3379 			freemsg(ipsec_mp);
3380 			return;
3381 		}
3382 		src = ire->ire_src_addr;
3383 	}
3384 
3385 	if (ire != NULL)
3386 		ire_refrele(ire);
3387 
3388 	/*
3389 	 * Check if we can send back more then 8 bytes in addition to
3390 	 * the IP header.  We try to send 64 bytes of data and the internal
3391 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3392 	 */
3393 	len_needed = IPH_HDR_LENGTH(ipha);
3394 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3395 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3396 
3397 		if (!pullupmsg(mp, -1)) {
3398 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3399 			freemsg(ipsec_mp);
3400 			return;
3401 		}
3402 		ipha = (ipha_t *)mp->b_rptr;
3403 
3404 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3405 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3406 			    len_needed));
3407 		} else {
3408 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3409 
3410 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3411 			len_needed += ip_hdr_length_v6(mp, ip6h);
3412 		}
3413 	}
3414 	len_needed += ipst->ips_ip_icmp_return;
3415 	msg_len = msgdsize(mp);
3416 	if (msg_len > len_needed) {
3417 		(void) adjmsg(mp, len_needed - msg_len);
3418 		msg_len = len_needed;
3419 	}
3420 	mp1 = allocb_tmpl(sizeof (icmp_ipha) + len, mp);
3421 	if (mp1 == NULL) {
3422 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3423 		freemsg(ipsec_mp);
3424 		return;
3425 	}
3426 	mp1->b_cont = mp;
3427 	mp = mp1;
3428 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3429 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3430 	    io->ipsec_out_type == IPSEC_OUT);
3431 	ipsec_mp->b_cont = mp;
3432 
3433 	/*
3434 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3435 	 * node generates be accepted in peace by all on-host destinations.
3436 	 * If we do NOT assume that all on-host destinations trust
3437 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3438 	 * (Look for ipsec_out_icmp_loopback).
3439 	 */
3440 	io->ipsec_out_icmp_loopback = B_TRUE;
3441 
3442 	ipha = (ipha_t *)mp->b_rptr;
3443 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3444 	*ipha = icmp_ipha;
3445 	ipha->ipha_src = src;
3446 	ipha->ipha_dst = dst;
3447 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3448 	msg_len += sizeof (icmp_ipha) + len;
3449 	if (msg_len > IP_MAXPACKET) {
3450 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3451 		msg_len = IP_MAXPACKET;
3452 	}
3453 	ipha->ipha_length = htons((uint16_t)msg_len);
3454 	icmph = (icmph_t *)&ipha[1];
3455 	bcopy(stuff, icmph, len);
3456 	icmph->icmph_checksum = 0;
3457 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3458 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3459 	put(q, ipsec_mp);
3460 }
3461 
3462 /*
3463  * Determine if an ICMP error packet can be sent given the rate limit.
3464  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3465  * in milliseconds) and a burst size. Burst size number of packets can
3466  * be sent arbitrarely closely spaced.
3467  * The state is tracked using two variables to implement an approximate
3468  * token bucket filter:
3469  *	icmp_pkt_err_last - lbolt value when the last burst started
3470  *	icmp_pkt_err_sent - number of packets sent in current burst
3471  */
3472 boolean_t
3473 icmp_err_rate_limit(ip_stack_t *ipst)
3474 {
3475 	clock_t now = TICK_TO_MSEC(lbolt);
3476 	uint_t refilled; /* Number of packets refilled in tbf since last */
3477 	/* Guard against changes by loading into local variable */
3478 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3479 
3480 	if (err_interval == 0)
3481 		return (B_FALSE);
3482 
3483 	if (ipst->ips_icmp_pkt_err_last > now) {
3484 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3485 		ipst->ips_icmp_pkt_err_last = 0;
3486 		ipst->ips_icmp_pkt_err_sent = 0;
3487 	}
3488 	/*
3489 	 * If we are in a burst update the token bucket filter.
3490 	 * Update the "last" time to be close to "now" but make sure
3491 	 * we don't loose precision.
3492 	 */
3493 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3494 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3495 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3496 			ipst->ips_icmp_pkt_err_sent = 0;
3497 		} else {
3498 			ipst->ips_icmp_pkt_err_sent -= refilled;
3499 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3500 		}
3501 	}
3502 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3503 		/* Start of new burst */
3504 		ipst->ips_icmp_pkt_err_last = now;
3505 	}
3506 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3507 		ipst->ips_icmp_pkt_err_sent++;
3508 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3509 		    ipst->ips_icmp_pkt_err_sent));
3510 		return (B_FALSE);
3511 	}
3512 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3513 	return (B_TRUE);
3514 }
3515 
3516 /*
3517  * Check if it is ok to send an IPv4 ICMP error packet in
3518  * response to the IPv4 packet in mp.
3519  * Free the message and return null if no
3520  * ICMP error packet should be sent.
3521  */
3522 static mblk_t *
3523 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3524 {
3525 	icmph_t	*icmph;
3526 	ipha_t	*ipha;
3527 	uint_t	len_needed;
3528 	ire_t	*src_ire;
3529 	ire_t	*dst_ire;
3530 
3531 	if (!mp)
3532 		return (NULL);
3533 	ipha = (ipha_t *)mp->b_rptr;
3534 	if (ip_csum_hdr(ipha)) {
3535 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3536 		freemsg(mp);
3537 		return (NULL);
3538 	}
3539 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3540 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3541 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3542 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3543 	if (src_ire != NULL || dst_ire != NULL ||
3544 	    CLASSD(ipha->ipha_dst) ||
3545 	    CLASSD(ipha->ipha_src) ||
3546 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3547 		/* Note: only errors to the fragment with offset 0 */
3548 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3549 		freemsg(mp);
3550 		if (src_ire != NULL)
3551 			ire_refrele(src_ire);
3552 		if (dst_ire != NULL)
3553 			ire_refrele(dst_ire);
3554 		return (NULL);
3555 	}
3556 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3557 		/*
3558 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3559 		 * errors in response to any ICMP errors.
3560 		 */
3561 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3562 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3563 			if (!pullupmsg(mp, len_needed)) {
3564 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3565 				freemsg(mp);
3566 				return (NULL);
3567 			}
3568 			ipha = (ipha_t *)mp->b_rptr;
3569 		}
3570 		icmph = (icmph_t *)
3571 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3572 		switch (icmph->icmph_type) {
3573 		case ICMP_DEST_UNREACHABLE:
3574 		case ICMP_SOURCE_QUENCH:
3575 		case ICMP_TIME_EXCEEDED:
3576 		case ICMP_PARAM_PROBLEM:
3577 		case ICMP_REDIRECT:
3578 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3579 			freemsg(mp);
3580 			return (NULL);
3581 		default:
3582 			break;
3583 		}
3584 	}
3585 	/*
3586 	 * If this is a labeled system, then check to see if we're allowed to
3587 	 * send a response to this particular sender.  If not, then just drop.
3588 	 */
3589 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3590 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3591 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3592 		freemsg(mp);
3593 		return (NULL);
3594 	}
3595 	if (icmp_err_rate_limit(ipst)) {
3596 		/*
3597 		 * Only send ICMP error packets every so often.
3598 		 * This should be done on a per port/source basis,
3599 		 * but for now this will suffice.
3600 		 */
3601 		freemsg(mp);
3602 		return (NULL);
3603 	}
3604 	return (mp);
3605 }
3606 
3607 /*
3608  * Generate an ICMP redirect message.
3609  */
3610 static void
3611 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3612 {
3613 	icmph_t	icmph;
3614 
3615 	/*
3616 	 * We are called from ip_rput where we could
3617 	 * not have attached an IPSEC_IN.
3618 	 */
3619 	ASSERT(mp->b_datap->db_type == M_DATA);
3620 
3621 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3622 		return;
3623 	}
3624 
3625 	bzero(&icmph, sizeof (icmph_t));
3626 	icmph.icmph_type = ICMP_REDIRECT;
3627 	icmph.icmph_code = 1;
3628 	icmph.icmph_rd_gateway = gateway;
3629 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3630 	/* Redirects sent by router, and router is global zone */
3631 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3632 }
3633 
3634 /*
3635  * Generate an ICMP time exceeded message.
3636  */
3637 void
3638 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3639     ip_stack_t *ipst)
3640 {
3641 	icmph_t	icmph;
3642 	boolean_t mctl_present;
3643 	mblk_t *first_mp;
3644 
3645 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3646 
3647 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3648 		if (mctl_present)
3649 			freeb(first_mp);
3650 		return;
3651 	}
3652 
3653 	bzero(&icmph, sizeof (icmph_t));
3654 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3655 	icmph.icmph_code = code;
3656 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3657 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3658 	    ipst);
3659 }
3660 
3661 /*
3662  * Generate an ICMP unreachable message.
3663  */
3664 void
3665 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3666     ip_stack_t *ipst)
3667 {
3668 	icmph_t	icmph;
3669 	mblk_t *first_mp;
3670 	boolean_t mctl_present;
3671 
3672 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3673 
3674 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3675 		if (mctl_present)
3676 			freeb(first_mp);
3677 		return;
3678 	}
3679 
3680 	bzero(&icmph, sizeof (icmph_t));
3681 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3682 	icmph.icmph_code = code;
3683 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3684 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3685 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3686 	    zoneid, ipst);
3687 }
3688 
3689 /*
3690  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3691  * duplicate.  As long as someone else holds the address, the interface will
3692  * stay down.  When that conflict goes away, the interface is brought back up.
3693  * This is done so that accidental shutdowns of addresses aren't made
3694  * permanent.  Your server will recover from a failure.
3695  *
3696  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3697  * user space process (dhcpagent).
3698  *
3699  * Recovery completes if ARP reports that the address is now ours (via
3700  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3701  *
3702  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3703  */
3704 static void
3705 ipif_dup_recovery(void *arg)
3706 {
3707 	ipif_t *ipif = arg;
3708 	ill_t *ill = ipif->ipif_ill;
3709 	mblk_t *arp_add_mp;
3710 	mblk_t *arp_del_mp;
3711 	area_t *area;
3712 	ip_stack_t *ipst = ill->ill_ipst;
3713 
3714 	ipif->ipif_recovery_id = 0;
3715 
3716 	/*
3717 	 * No lock needed for moving or condemned check, as this is just an
3718 	 * optimization.
3719 	 */
3720 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3721 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3722 	    (ipif->ipif_state_flags & (IPIF_MOVING | IPIF_CONDEMNED))) {
3723 		/* No reason to try to bring this address back. */
3724 		return;
3725 	}
3726 
3727 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3728 		goto alloc_fail;
3729 
3730 	if (ipif->ipif_arp_del_mp == NULL) {
3731 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3732 			goto alloc_fail;
3733 		ipif->ipif_arp_del_mp = arp_del_mp;
3734 	}
3735 
3736 	/* Setting the 'unverified' flag restarts DAD */
3737 	area = (area_t *)arp_add_mp->b_rptr;
3738 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3739 	    ACE_F_UNVERIFIED;
3740 	putnext(ill->ill_rq, arp_add_mp);
3741 	return;
3742 
3743 alloc_fail:
3744 	/*
3745 	 * On allocation failure, just restart the timer.  Note that the ipif
3746 	 * is down here, so no other thread could be trying to start a recovery
3747 	 * timer.  The ill_lock protects the condemned flag and the recovery
3748 	 * timer ID.
3749 	 */
3750 	freemsg(arp_add_mp);
3751 	mutex_enter(&ill->ill_lock);
3752 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3753 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3754 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3755 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3756 	}
3757 	mutex_exit(&ill->ill_lock);
3758 }
3759 
3760 /*
3761  * This is for exclusive changes due to ARP.  Either tear down an interface due
3762  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3763  */
3764 /* ARGSUSED */
3765 static void
3766 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3767 {
3768 	ill_t	*ill = rq->q_ptr;
3769 	arh_t *arh;
3770 	ipaddr_t src;
3771 	ipif_t	*ipif;
3772 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3773 	char hbuf[MAC_STR_LEN];
3774 	char sbuf[INET_ADDRSTRLEN];
3775 	const char *failtype;
3776 	boolean_t bring_up;
3777 	ip_stack_t *ipst = ill->ill_ipst;
3778 
3779 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3780 	case AR_CN_READY:
3781 		failtype = NULL;
3782 		bring_up = B_TRUE;
3783 		break;
3784 	case AR_CN_FAILED:
3785 		failtype = "in use";
3786 		bring_up = B_FALSE;
3787 		break;
3788 	default:
3789 		failtype = "claimed";
3790 		bring_up = B_FALSE;
3791 		break;
3792 	}
3793 
3794 	arh = (arh_t *)mp->b_cont->b_rptr;
3795 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3796 
3797 	/* Handle failures due to probes */
3798 	if (src == 0) {
3799 		bcopy((char *)&arh[1] + 2 * arh->arh_hlen + IP_ADDR_LEN, &src,
3800 		    IP_ADDR_LEN);
3801 	}
3802 
3803 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3804 	    sizeof (hbuf));
3805 	(void) ip_dot_addr(src, sbuf);
3806 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3807 
3808 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3809 		    ipif->ipif_lcl_addr != src) {
3810 			continue;
3811 		}
3812 
3813 		/*
3814 		 * If we failed on a recovery probe, then restart the timer to
3815 		 * try again later.
3816 		 */
3817 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3818 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3819 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3820 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3821 		    ipst->ips_ip_dup_recovery > 0 &&
3822 		    ipif->ipif_recovery_id == 0) {
3823 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3824 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3825 			continue;
3826 		}
3827 
3828 		/*
3829 		 * If what we're trying to do has already been done, then do
3830 		 * nothing.
3831 		 */
3832 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3833 			continue;
3834 
3835 		ipif_get_name(ipif, ibuf, sizeof (ibuf));
3836 
3837 		if (failtype == NULL) {
3838 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3839 			    ibuf);
3840 		} else {
3841 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3842 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3843 		}
3844 
3845 		if (bring_up) {
3846 			ASSERT(ill->ill_dl_up);
3847 			/*
3848 			 * Free up the ARP delete message so we can allocate
3849 			 * a fresh one through the normal path.
3850 			 */
3851 			freemsg(ipif->ipif_arp_del_mp);
3852 			ipif->ipif_arp_del_mp = NULL;
3853 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3854 			    EINPROGRESS) {
3855 				ipif->ipif_addr_ready = 1;
3856 				(void) ipif_up_done(ipif);
3857 			}
3858 			continue;
3859 		}
3860 
3861 		mutex_enter(&ill->ill_lock);
3862 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3863 		ipif->ipif_flags |= IPIF_DUPLICATE;
3864 		ill->ill_ipif_dup_count++;
3865 		mutex_exit(&ill->ill_lock);
3866 		/*
3867 		 * Already exclusive on the ill; no need to handle deferred
3868 		 * processing here.
3869 		 */
3870 		(void) ipif_down(ipif, NULL, NULL);
3871 		ipif_down_tail(ipif);
3872 		mutex_enter(&ill->ill_lock);
3873 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3874 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3875 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3876 		    ipst->ips_ip_dup_recovery > 0) {
3877 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3878 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3879 		}
3880 		mutex_exit(&ill->ill_lock);
3881 	}
3882 	freemsg(mp);
3883 }
3884 
3885 /* ARGSUSED */
3886 static void
3887 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3888 {
3889 	ill_t	*ill = rq->q_ptr;
3890 	arh_t *arh;
3891 	ipaddr_t src;
3892 	ipif_t	*ipif;
3893 
3894 	arh = (arh_t *)mp->b_cont->b_rptr;
3895 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3896 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3897 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3898 			(void) ipif_resolver_up(ipif, Res_act_defend);
3899 	}
3900 	freemsg(mp);
3901 }
3902 
3903 /*
3904  * News from ARP.  ARP sends notification of interesting events down
3905  * to its clients using M_CTL messages with the interesting ARP packet
3906  * attached via b_cont.
3907  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3908  * queue as opposed to ARP sending the message to all the clients, i.e. all
3909  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3910  * table if a cache IRE is found to delete all the entries for the address in
3911  * the packet.
3912  */
3913 static void
3914 ip_arp_news(queue_t *q, mblk_t *mp)
3915 {
3916 	arcn_t		*arcn;
3917 	arh_t		*arh;
3918 	ire_t		*ire = NULL;
3919 	char		hbuf[MAC_STR_LEN];
3920 	char		sbuf[INET_ADDRSTRLEN];
3921 	ipaddr_t	src;
3922 	in6_addr_t	v6src;
3923 	boolean_t	isv6 = B_FALSE;
3924 	ipif_t		*ipif;
3925 	ill_t		*ill;
3926 	ip_stack_t	*ipst;
3927 
3928 	if (CONN_Q(q)) {
3929 		conn_t *connp = Q_TO_CONN(q);
3930 
3931 		ipst = connp->conn_netstack->netstack_ip;
3932 	} else {
3933 		ill_t *ill = (ill_t *)q->q_ptr;
3934 
3935 		ipst = ill->ill_ipst;
3936 	}
3937 
3938 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3939 		if (q->q_next) {
3940 			putnext(q, mp);
3941 		} else
3942 			freemsg(mp);
3943 		return;
3944 	}
3945 	arh = (arh_t *)mp->b_cont->b_rptr;
3946 	/* Is it one we are interested in? */
3947 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3948 		isv6 = B_TRUE;
3949 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3950 		    IPV6_ADDR_LEN);
3951 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3952 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3953 		    IP_ADDR_LEN);
3954 	} else {
3955 		freemsg(mp);
3956 		return;
3957 	}
3958 
3959 	ill = q->q_ptr;
3960 
3961 	arcn = (arcn_t *)mp->b_rptr;
3962 	switch (arcn->arcn_code) {
3963 	case AR_CN_BOGON:
3964 		/*
3965 		 * Someone is sending ARP packets with a source protocol
3966 		 * address that we have published and for which we believe our
3967 		 * entry is authoritative and (when ill_arp_extend is set)
3968 		 * verified to be unique on the network.
3969 		 *
3970 		 * The ARP module internally handles the cases where the sender
3971 		 * is just probing (for DAD) and where the hardware address of
3972 		 * a non-authoritative entry has changed.  Thus, these are the
3973 		 * real conflicts, and we have to do resolution.
3974 		 *
3975 		 * We back away quickly from the address if it's from DHCP or
3976 		 * otherwise temporary and hasn't been used recently (or at
3977 		 * all).  We'd like to include "deprecated" addresses here as
3978 		 * well (as there's no real reason to defend something we're
3979 		 * discarding), but IPMP "reuses" this flag to mean something
3980 		 * other than the standard meaning.
3981 		 *
3982 		 * If the ARP module above is not extended (meaning that it
3983 		 * doesn't know how to defend the address), then we just log
3984 		 * the problem as we always did and continue on.  It's not
3985 		 * right, but there's little else we can do, and those old ATM
3986 		 * users are going away anyway.
3987 		 */
3988 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
3989 		    hbuf, sizeof (hbuf));
3990 		(void) ip_dot_addr(src, sbuf);
3991 		if (isv6) {
3992 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
3993 			    ipst);
3994 		} else {
3995 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
3996 		}
3997 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
3998 			uint32_t now;
3999 			uint32_t maxage;
4000 			clock_t lused;
4001 			uint_t maxdefense;
4002 			uint_t defs;
4003 
4004 			/*
4005 			 * First, figure out if this address hasn't been used
4006 			 * in a while.  If it hasn't, then it's a better
4007 			 * candidate for abandoning.
4008 			 */
4009 			ipif = ire->ire_ipif;
4010 			ASSERT(ipif != NULL);
4011 			now = gethrestime_sec();
4012 			maxage = now - ire->ire_create_time;
4013 			if (maxage > ipst->ips_ip_max_temp_idle)
4014 				maxage = ipst->ips_ip_max_temp_idle;
4015 			lused = drv_hztousec(ddi_get_lbolt() -
4016 			    ire->ire_last_used_time) / MICROSEC + 1;
4017 			if (lused >= maxage && (ipif->ipif_flags &
4018 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4019 				maxdefense = ipst->ips_ip_max_temp_defend;
4020 			else
4021 				maxdefense = ipst->ips_ip_max_defend;
4022 
4023 			/*
4024 			 * Now figure out how many times we've defended
4025 			 * ourselves.  Ignore defenses that happened long in
4026 			 * the past.
4027 			 */
4028 			mutex_enter(&ire->ire_lock);
4029 			if ((defs = ire->ire_defense_count) > 0 &&
4030 			    now - ire->ire_defense_time >
4031 			    ipst->ips_ip_defend_interval) {
4032 				ire->ire_defense_count = defs = 0;
4033 			}
4034 			ire->ire_defense_count++;
4035 			ire->ire_defense_time = now;
4036 			mutex_exit(&ire->ire_lock);
4037 			ill_refhold(ill);
4038 			ire_refrele(ire);
4039 
4040 			/*
4041 			 * If we've defended ourselves too many times already,
4042 			 * then give up and tear down the interface(s) using
4043 			 * this address.  Otherwise, defend by sending out a
4044 			 * gratuitous ARP.
4045 			 */
4046 			if (defs >= maxdefense && ill->ill_arp_extend) {
4047 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4048 				    B_FALSE);
4049 			} else {
4050 				cmn_err(CE_WARN,
4051 				    "node %s is using our IP address %s on %s",
4052 				    hbuf, sbuf, ill->ill_name);
4053 				/*
4054 				 * If this is an old (ATM) ARP module, then
4055 				 * don't try to defend the address.  Remain
4056 				 * compatible with the old behavior.  Defend
4057 				 * only with new ARP.
4058 				 */
4059 				if (ill->ill_arp_extend) {
4060 					qwriter_ip(ill, q, mp, ip_arp_defend,
4061 					    NEW_OP, B_FALSE);
4062 				} else {
4063 					ill_refrele(ill);
4064 				}
4065 			}
4066 			return;
4067 		}
4068 		cmn_err(CE_WARN,
4069 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4070 		    hbuf, sbuf, ill->ill_name);
4071 		if (ire != NULL)
4072 			ire_refrele(ire);
4073 		break;
4074 	case AR_CN_ANNOUNCE:
4075 		if (isv6) {
4076 			/*
4077 			 * For XRESOLV interfaces.
4078 			 * Delete the IRE cache entry and NCE for this
4079 			 * v6 address
4080 			 */
4081 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4082 			/*
4083 			 * If v6src is a non-zero, it's a router address
4084 			 * as below. Do the same sort of thing to clean
4085 			 * out off-net IRE_CACHE entries that go through
4086 			 * the router.
4087 			 */
4088 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4089 				ire_walk_v6(ire_delete_cache_gw_v6,
4090 				    (char *)&v6src, ALL_ZONES, ipst);
4091 			}
4092 		} else {
4093 			nce_hw_map_t hwm;
4094 
4095 			/*
4096 			 * ARP gives us a copy of any packet where it thinks
4097 			 * the address has changed, so that we can update our
4098 			 * caches.  We're responsible for caching known answers
4099 			 * in the current design.  We check whether the
4100 			 * hardware address really has changed in all of our
4101 			 * entries that have cached this mapping, and if so, we
4102 			 * blow them away.  This way we will immediately pick
4103 			 * up the rare case of a host changing hardware
4104 			 * address.
4105 			 */
4106 			if (src == 0)
4107 				break;
4108 			hwm.hwm_addr = src;
4109 			hwm.hwm_hwlen = arh->arh_hlen;
4110 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4111 			NDP_HW_CHANGE_INCR(ipst->ips_ndp4);
4112 			ndp_walk_common(ipst->ips_ndp4, NULL,
4113 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4114 			NDP_HW_CHANGE_DECR(ipst->ips_ndp4);
4115 		}
4116 		break;
4117 	case AR_CN_READY:
4118 		/* No external v6 resolver has a contract to use this */
4119 		if (isv6)
4120 			break;
4121 		/* If the link is down, we'll retry this later */
4122 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4123 			break;
4124 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4125 		    NULL, NULL, ipst);
4126 		if (ipif != NULL) {
4127 			/*
4128 			 * If this is a duplicate recovery, then we now need to
4129 			 * go exclusive to bring this thing back up.
4130 			 */
4131 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4132 			    IPIF_DUPLICATE) {
4133 				ipif_refrele(ipif);
4134 				ill_refhold(ill);
4135 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4136 				    B_FALSE);
4137 				return;
4138 			}
4139 			/*
4140 			 * If this is the first notice that this address is
4141 			 * ready, then let the user know now.
4142 			 */
4143 			if ((ipif->ipif_flags & IPIF_UP) &&
4144 			    !ipif->ipif_addr_ready) {
4145 				ipif_mask_reply(ipif);
4146 				ip_rts_ifmsg(ipif);
4147 				ip_rts_newaddrmsg(RTM_ADD, 0, ipif);
4148 				sctp_update_ipif(ipif, SCTP_IPIF_UP);
4149 			}
4150 			ipif->ipif_addr_ready = 1;
4151 			ipif_refrele(ipif);
4152 		}
4153 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp), ipst);
4154 		if (ire != NULL) {
4155 			ire->ire_defense_count = 0;
4156 			ire_refrele(ire);
4157 		}
4158 		break;
4159 	case AR_CN_FAILED:
4160 		/* No external v6 resolver has a contract to use this */
4161 		if (isv6)
4162 			break;
4163 		ill_refhold(ill);
4164 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, B_FALSE);
4165 		return;
4166 	}
4167 	freemsg(mp);
4168 }
4169 
4170 /*
4171  * Create a mblk suitable for carrying the interface index and/or source link
4172  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4173  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4174  * application.
4175  */
4176 mblk_t *
4177 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4178     ip_stack_t *ipst)
4179 {
4180 	mblk_t		*mp;
4181 	ip_pktinfo_t	*pinfo;
4182 	ipha_t *ipha;
4183 	struct ether_header *pether;
4184 
4185 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4186 	if (mp == NULL) {
4187 		ip1dbg(("ip_add_info: allocation failure.\n"));
4188 		return (data_mp);
4189 	}
4190 
4191 	ipha	= (ipha_t *)data_mp->b_rptr;
4192 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4193 	bzero(pinfo, sizeof (ip_pktinfo_t));
4194 	pinfo->ip_pkt_flags = (uchar_t)flags;
4195 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4196 
4197 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4198 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4199 	if (flags & IPF_RECVADDR) {
4200 		ipif_t	*ipif;
4201 		ire_t	*ire;
4202 
4203 		/*
4204 		 * Only valid for V4
4205 		 */
4206 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4207 		    (IPV4_VERSION << 4));
4208 
4209 		ipif = ipif_get_next_ipif(NULL, ill);
4210 		if (ipif != NULL) {
4211 			/*
4212 			 * Since a decision has already been made to deliver the
4213 			 * packet, there is no need to test for SECATTR and
4214 			 * ZONEONLY.
4215 			 * When a multicast packet is transmitted
4216 			 * a cache entry is created for the multicast address.
4217 			 * When delivering a copy of the packet or when new
4218 			 * packets are received we do not want to match on the
4219 			 * cached entry so explicitly match on
4220 			 * IRE_LOCAL and IRE_LOOPBACK
4221 			 */
4222 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4223 			    IRE_LOCAL | IRE_LOOPBACK,
4224 			    ipif, zoneid, NULL,
4225 			    MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP, ipst);
4226 			if (ire == NULL) {
4227 				/*
4228 				 * packet must have come on a different
4229 				 * interface.
4230 				 * Since a decision has already been made to
4231 				 * deliver the packet, there is no need to test
4232 				 * for SECATTR and ZONEONLY.
4233 				 * Only match on local and broadcast ire's.
4234 				 * See detailed comment above.
4235 				 */
4236 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4237 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4238 				    NULL, MATCH_IRE_TYPE, ipst);
4239 			}
4240 
4241 			if (ire == NULL) {
4242 				/*
4243 				 * This is either a multicast packet or
4244 				 * the address has been removed since
4245 				 * the packet was received.
4246 				 * Return INADDR_ANY so that normal source
4247 				 * selection occurs for the response.
4248 				 */
4249 
4250 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4251 			} else {
4252 				pinfo->ip_pkt_match_addr.s_addr =
4253 				    ire->ire_src_addr;
4254 				ire_refrele(ire);
4255 			}
4256 			ipif_refrele(ipif);
4257 		} else {
4258 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4259 		}
4260 	}
4261 
4262 	pether = (struct ether_header *)((char *)ipha
4263 	    - sizeof (struct ether_header));
4264 	/*
4265 	 * Make sure the interface is an ethernet type, since this option
4266 	 * is currently supported only on this type of interface. Also make
4267 	 * sure we are pointing correctly above db_base.
4268 	 */
4269 
4270 	if ((flags & IPF_RECVSLLA) &&
4271 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4272 	    (ill->ill_type == IFT_ETHER) &&
4273 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4274 
4275 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4276 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4277 		    (uchar_t *)pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4278 	} else {
4279 		/*
4280 		 * Clear the bit. Indicate to upper layer that IP is not
4281 		 * sending this ancillary info.
4282 		 */
4283 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4284 	}
4285 
4286 	mp->b_datap->db_type = M_CTL;
4287 	mp->b_wptr += sizeof (ip_pktinfo_t);
4288 	mp->b_cont = data_mp;
4289 
4290 	return (mp);
4291 }
4292 
4293 /*
4294  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4295  * part of the bind request.
4296  */
4297 
4298 boolean_t
4299 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4300 {
4301 	ipsec_in_t *ii;
4302 
4303 	ASSERT(policy_mp != NULL);
4304 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4305 
4306 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4307 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4308 
4309 	connp->conn_policy = ii->ipsec_in_policy;
4310 	ii->ipsec_in_policy = NULL;
4311 
4312 	if (ii->ipsec_in_action != NULL) {
4313 		if (connp->conn_latch == NULL) {
4314 			connp->conn_latch = iplatch_create();
4315 			if (connp->conn_latch == NULL)
4316 				return (B_FALSE);
4317 		}
4318 		ipsec_latch_inbound(connp->conn_latch, ii);
4319 	}
4320 	return (B_TRUE);
4321 }
4322 
4323 /*
4324  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4325  * and to arrange for power-fanout assist.  The ULP is identified by
4326  * adding a single byte at the end of the original bind message.
4327  * A ULP other than UDP or TCP that wishes to be recognized passes
4328  * down a bind with a zero length address.
4329  *
4330  * The binding works as follows:
4331  * - A zero byte address means just bind to the protocol.
4332  * - A four byte address is treated as a request to validate
4333  *   that the address is a valid local address, appropriate for
4334  *   an application to bind to. This does not affect any fanout
4335  *   information in IP.
4336  * - A sizeof sin_t byte address is used to bind to only the local address
4337  *   and port.
4338  * - A sizeof ipa_conn_t byte address contains complete fanout information
4339  *   consisting of local and remote addresses and ports.  In
4340  *   this case, the addresses are both validated as appropriate
4341  *   for this operation, and, if so, the information is retained
4342  *   for use in the inbound fanout.
4343  *
4344  * The ULP (except in the zero-length bind) can append an
4345  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4346  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4347  * a copy of the source or destination IRE (source for local bind;
4348  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4349  * policy information contained should be copied on to the conn.
4350  *
4351  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4352  */
4353 mblk_t *
4354 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4355 {
4356 	ssize_t		len;
4357 	struct T_bind_req	*tbr;
4358 	sin_t		*sin;
4359 	ipa_conn_t	*ac;
4360 	uchar_t		*ucp;
4361 	mblk_t		*mp1;
4362 	boolean_t	ire_requested;
4363 	boolean_t	ipsec_policy_set = B_FALSE;
4364 	int		error = 0;
4365 	int		protocol;
4366 	ipa_conn_x_t	*acx;
4367 
4368 	ASSERT(!connp->conn_af_isv6);
4369 	connp->conn_pkt_isv6 = B_FALSE;
4370 
4371 	len = MBLKL(mp);
4372 	if (len < (sizeof (*tbr) + 1)) {
4373 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4374 		    "ip_bind: bogus msg, len %ld", len);
4375 		/* XXX: Need to return something better */
4376 		goto bad_addr;
4377 	}
4378 	/* Back up and extract the protocol identifier. */
4379 	mp->b_wptr--;
4380 	protocol = *mp->b_wptr & 0xFF;
4381 	tbr = (struct T_bind_req *)mp->b_rptr;
4382 	/* Reset the message type in preparation for shipping it back. */
4383 	DB_TYPE(mp) = M_PCPROTO;
4384 
4385 	connp->conn_ulp = (uint8_t)protocol;
4386 
4387 	/*
4388 	 * Check for a zero length address.  This is from a protocol that
4389 	 * wants to register to receive all packets of its type.
4390 	 */
4391 	if (tbr->ADDR_length == 0) {
4392 		/*
4393 		 * These protocols are now intercepted in ip_bind_v6().
4394 		 * Reject protocol-level binds here for now.
4395 		 *
4396 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4397 		 * so that the protocol type cannot be SCTP.
4398 		 */
4399 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4400 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4401 			goto bad_addr;
4402 		}
4403 
4404 		/*
4405 		 *
4406 		 * The udp module never sends down a zero-length address,
4407 		 * and allowing this on a labeled system will break MLP
4408 		 * functionality.
4409 		 */
4410 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4411 			goto bad_addr;
4412 
4413 		if (connp->conn_mac_exempt)
4414 			goto bad_addr;
4415 
4416 		/* No hash here really.  The table is big enough. */
4417 		connp->conn_srcv6 = ipv6_all_zeros;
4418 
4419 		ipcl_proto_insert(connp, protocol);
4420 
4421 		tbr->PRIM_type = T_BIND_ACK;
4422 		return (mp);
4423 	}
4424 
4425 	/* Extract the address pointer from the message. */
4426 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4427 	    tbr->ADDR_length);
4428 	if (ucp == NULL) {
4429 		ip1dbg(("ip_bind: no address\n"));
4430 		goto bad_addr;
4431 	}
4432 	if (!OK_32PTR(ucp)) {
4433 		ip1dbg(("ip_bind: unaligned address\n"));
4434 		goto bad_addr;
4435 	}
4436 	/*
4437 	 * Check for trailing mps.
4438 	 */
4439 
4440 	mp1 = mp->b_cont;
4441 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4442 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4443 
4444 	switch (tbr->ADDR_length) {
4445 	default:
4446 		ip1dbg(("ip_bind: bad address length %d\n",
4447 		    (int)tbr->ADDR_length));
4448 		goto bad_addr;
4449 
4450 	case IP_ADDR_LEN:
4451 		/* Verification of local address only */
4452 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4453 		    ire_requested, ipsec_policy_set, B_FALSE);
4454 		break;
4455 
4456 	case sizeof (sin_t):
4457 		sin = (sin_t *)ucp;
4458 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4459 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4460 		break;
4461 
4462 	case sizeof (ipa_conn_t):
4463 		ac = (ipa_conn_t *)ucp;
4464 		/* For raw socket, the local port is not set. */
4465 		if (ac->ac_lport == 0)
4466 			ac->ac_lport = connp->conn_lport;
4467 		/* Always verify destination reachability. */
4468 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4469 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4470 		    ipsec_policy_set, B_TRUE, B_TRUE);
4471 		break;
4472 
4473 	case sizeof (ipa_conn_x_t):
4474 		acx = (ipa_conn_x_t *)ucp;
4475 		/*
4476 		 * Whether or not to verify destination reachability depends
4477 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4478 		 */
4479 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4480 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4481 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4482 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4483 		break;
4484 	}
4485 	if (error == EINPROGRESS)
4486 		return (NULL);
4487 	else if (error != 0)
4488 		goto bad_addr;
4489 	/*
4490 	 * Pass the IPsec headers size in ire_ipsec_overhead.
4491 	 * We can't do this in ip_bind_insert_ire because the policy
4492 	 * may not have been inherited at that point in time and hence
4493 	 * conn_out_enforce_policy may not be set.
4494 	 */
4495 	mp1 = mp->b_cont;
4496 	if (ire_requested && connp->conn_out_enforce_policy &&
4497 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4498 		ire_t *ire = (ire_t *)mp1->b_rptr;
4499 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4500 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4501 	}
4502 
4503 	/* Send it home. */
4504 	mp->b_datap->db_type = M_PCPROTO;
4505 	tbr->PRIM_type = T_BIND_ACK;
4506 	return (mp);
4507 
4508 bad_addr:
4509 	/*
4510 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4511 	 * a unix errno.
4512 	 */
4513 	if (error > 0)
4514 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4515 	else
4516 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4517 	return (mp);
4518 }
4519 
4520 /*
4521  * Here address is verified to be a valid local address.
4522  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4523  * address is also considered a valid local address.
4524  * In the case of a broadcast/multicast address, however, the
4525  * upper protocol is expected to reset the src address
4526  * to 0 if it sees a IRE_BROADCAST type returned so that
4527  * no packets are emitted with broadcast/multicast address as
4528  * source address (that violates hosts requirements RFC1122)
4529  * The addresses valid for bind are:
4530  *	(1) - INADDR_ANY (0)
4531  *	(2) - IP address of an UP interface
4532  *	(3) - IP address of a DOWN interface
4533  *	(4) - valid local IP broadcast addresses. In this case
4534  *	the conn will only receive packets destined to
4535  *	the specified broadcast address.
4536  *	(5) - a multicast address. In this case
4537  *	the conn will only receive packets destined to
4538  *	the specified multicast address. Note: the
4539  *	application still has to issue an
4540  *	IP_ADD_MEMBERSHIP socket option.
4541  *
4542  * On error, return -1 for TBADADDR otherwise pass the
4543  * errno with TSYSERR reply.
4544  *
4545  * In all the above cases, the bound address must be valid in the current zone.
4546  * When the address is loopback, multicast or broadcast, there might be many
4547  * matching IREs so bind has to look up based on the zone.
4548  *
4549  * Note: lport is in network byte order.
4550  */
4551 int
4552 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4553     boolean_t ire_requested, boolean_t ipsec_policy_set,
4554     boolean_t fanout_insert)
4555 {
4556 	int		error = 0;
4557 	ire_t		*src_ire;
4558 	mblk_t		*policy_mp;
4559 	ipif_t		*ipif;
4560 	zoneid_t	zoneid;
4561 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4562 
4563 	if (ipsec_policy_set) {
4564 		policy_mp = mp->b_cont;
4565 	}
4566 
4567 	/*
4568 	 * If it was previously connected, conn_fully_bound would have
4569 	 * been set.
4570 	 */
4571 	connp->conn_fully_bound = B_FALSE;
4572 
4573 	src_ire = NULL;
4574 	ipif = NULL;
4575 
4576 	zoneid = IPCL_ZONEID(connp);
4577 
4578 	if (src_addr) {
4579 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4580 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4581 		/*
4582 		 * If an address other than 0.0.0.0 is requested,
4583 		 * we verify that it is a valid address for bind
4584 		 * Note: Following code is in if-else-if form for
4585 		 * readability compared to a condition check.
4586 		 */
4587 		/* LINTED - statement has no consequent */
4588 		if (IRE_IS_LOCAL(src_ire)) {
4589 			/*
4590 			 * (2) Bind to address of local UP interface
4591 			 */
4592 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4593 			/*
4594 			 * (4) Bind to broadcast address
4595 			 * Note: permitted only from transports that
4596 			 * request IRE
4597 			 */
4598 			if (!ire_requested)
4599 				error = EADDRNOTAVAIL;
4600 		} else {
4601 			/*
4602 			 * (3) Bind to address of local DOWN interface
4603 			 * (ipif_lookup_addr() looks up all interfaces
4604 			 * but we do not get here for UP interfaces
4605 			 * - case (2) above)
4606 			 * We put the protocol byte back into the mblk
4607 			 * since we may come back via ip_wput_nondata()
4608 			 * later with this mblk if ipif_lookup_addr chooses
4609 			 * to defer processing.
4610 			 */
4611 			*mp->b_wptr++ = (char)connp->conn_ulp;
4612 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4613 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4614 			    &error, ipst)) != NULL) {
4615 				ipif_refrele(ipif);
4616 			} else if (error == EINPROGRESS) {
4617 				if (src_ire != NULL)
4618 					ire_refrele(src_ire);
4619 				return (EINPROGRESS);
4620 			} else if (CLASSD(src_addr)) {
4621 				error = 0;
4622 				if (src_ire != NULL)
4623 					ire_refrele(src_ire);
4624 				/*
4625 				 * (5) bind to multicast address.
4626 				 * Fake out the IRE returned to upper
4627 				 * layer to be a broadcast IRE.
4628 				 */
4629 				src_ire = ire_ctable_lookup(
4630 				    INADDR_BROADCAST, INADDR_ANY,
4631 				    IRE_BROADCAST, NULL, zoneid, NULL,
4632 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4633 				    ipst);
4634 				if (src_ire == NULL || !ire_requested)
4635 					error = EADDRNOTAVAIL;
4636 			} else {
4637 				/*
4638 				 * Not a valid address for bind
4639 				 */
4640 				error = EADDRNOTAVAIL;
4641 			}
4642 			/*
4643 			 * Just to keep it consistent with the processing in
4644 			 * ip_bind_v4()
4645 			 */
4646 			mp->b_wptr--;
4647 		}
4648 		if (error) {
4649 			/* Red Alert!  Attempting to be a bogon! */
4650 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4651 			    ntohl(src_addr)));
4652 			goto bad_addr;
4653 		}
4654 	}
4655 
4656 	/*
4657 	 * Allow setting new policies. For example, disconnects come
4658 	 * down as ipa_t bind. As we would have set conn_policy_cached
4659 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4660 	 * can change after the disconnect.
4661 	 */
4662 	connp->conn_policy_cached = B_FALSE;
4663 
4664 	/*
4665 	 * If not fanout_insert this was just an address verification
4666 	 */
4667 	if (fanout_insert) {
4668 		/*
4669 		 * The addresses have been verified. Time to insert in
4670 		 * the correct fanout list.
4671 		 */
4672 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4673 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4674 		connp->conn_lport = lport;
4675 		connp->conn_fport = 0;
4676 		/*
4677 		 * Do we need to add a check to reject Multicast packets
4678 		 */
4679 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4680 	}
4681 
4682 	if (error == 0) {
4683 		if (ire_requested) {
4684 			if (!ip_bind_insert_ire(mp, src_ire, NULL, ipst)) {
4685 				error = -1;
4686 				/* Falls through to bad_addr */
4687 			}
4688 		} else if (ipsec_policy_set) {
4689 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4690 				error = -1;
4691 				/* Falls through to bad_addr */
4692 			}
4693 		}
4694 	}
4695 bad_addr:
4696 	if (error != 0) {
4697 		if (connp->conn_anon_port) {
4698 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4699 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4700 			    B_FALSE);
4701 		}
4702 		connp->conn_mlp_type = mlptSingle;
4703 	}
4704 	if (src_ire != NULL)
4705 		IRE_REFRELE(src_ire);
4706 	if (ipsec_policy_set) {
4707 		ASSERT(policy_mp == mp->b_cont);
4708 		ASSERT(policy_mp != NULL);
4709 		freeb(policy_mp);
4710 		/*
4711 		 * As of now assume that nothing else accompanies
4712 		 * IPSEC_POLICY_SET.
4713 		 */
4714 		mp->b_cont = NULL;
4715 	}
4716 	return (error);
4717 }
4718 
4719 /*
4720  * Verify that both the source and destination addresses
4721  * are valid.  If verify_dst is false, then the destination address may be
4722  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4723  * destination reachability, while tunnels do not.
4724  * Note that we allow connect to broadcast and multicast
4725  * addresses when ire_requested is set. Thus the ULP
4726  * has to check for IRE_BROADCAST and multicast.
4727  *
4728  * Returns zero if ok.
4729  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4730  * (for use with TSYSERR reply).
4731  *
4732  * Note: lport and fport are in network byte order.
4733  */
4734 int
4735 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4736     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4737     boolean_t ire_requested, boolean_t ipsec_policy_set,
4738     boolean_t fanout_insert, boolean_t verify_dst)
4739 {
4740 	ire_t		*src_ire;
4741 	ire_t		*dst_ire;
4742 	int		error = 0;
4743 	int 		protocol;
4744 	mblk_t		*policy_mp;
4745 	ire_t		*sire = NULL;
4746 	ire_t		*md_dst_ire = NULL;
4747 	ire_t		*lso_dst_ire = NULL;
4748 	ill_t		*ill = NULL;
4749 	zoneid_t	zoneid;
4750 	ipaddr_t	src_addr = *src_addrp;
4751 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4752 
4753 	src_ire = dst_ire = NULL;
4754 	protocol = *mp->b_wptr & 0xFF;
4755 
4756 	/*
4757 	 * If we never got a disconnect before, clear it now.
4758 	 */
4759 	connp->conn_fully_bound = B_FALSE;
4760 
4761 	if (ipsec_policy_set) {
4762 		policy_mp = mp->b_cont;
4763 	}
4764 
4765 	zoneid = IPCL_ZONEID(connp);
4766 
4767 	if (CLASSD(dst_addr)) {
4768 		/* Pick up an IRE_BROADCAST */
4769 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4770 		    NULL, zoneid, MBLK_GETLABEL(mp),
4771 		    (MATCH_IRE_RECURSIVE |
4772 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4773 		    MATCH_IRE_SECATTR), ipst);
4774 	} else {
4775 		/*
4776 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4777 		 * and onlink ipif is not found set ENETUNREACH error.
4778 		 */
4779 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4780 			ipif_t *ipif;
4781 
4782 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4783 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4784 			if (ipif == NULL) {
4785 				error = ENETUNREACH;
4786 				goto bad_addr;
4787 			}
4788 			ipif_refrele(ipif);
4789 		}
4790 
4791 		if (connp->conn_nexthop_set) {
4792 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4793 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4794 			    MATCH_IRE_SECATTR, ipst);
4795 		} else {
4796 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4797 			    &sire, zoneid, MBLK_GETLABEL(mp),
4798 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4799 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4800 			    MATCH_IRE_SECATTR), ipst);
4801 		}
4802 	}
4803 	/*
4804 	 * dst_ire can't be a broadcast when not ire_requested.
4805 	 * We also prevent ire's with src address INADDR_ANY to
4806 	 * be used, which are created temporarily for
4807 	 * sending out packets from endpoints that have
4808 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4809 	 * reachable.  If verify_dst is false, the destination needn't be
4810 	 * reachable.
4811 	 *
4812 	 * If we match on a reject or black hole, then we've got a
4813 	 * local failure.  May as well fail out the connect() attempt,
4814 	 * since it's never going to succeed.
4815 	 */
4816 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4817 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4818 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4819 		/*
4820 		 * If we're verifying destination reachability, we always want
4821 		 * to complain here.
4822 		 *
4823 		 * If we're not verifying destination reachability but the
4824 		 * destination has a route, we still want to fail on the
4825 		 * temporary address and broadcast address tests.
4826 		 */
4827 		if (verify_dst || (dst_ire != NULL)) {
4828 			if (ip_debug > 2) {
4829 				pr_addr_dbg("ip_bind_connected: bad connected "
4830 				    "dst %s\n", AF_INET, &dst_addr);
4831 			}
4832 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4833 				error = ENETUNREACH;
4834 			else
4835 				error = EHOSTUNREACH;
4836 			goto bad_addr;
4837 		}
4838 	}
4839 
4840 	/*
4841 	 * We now know that routing will allow us to reach the destination.
4842 	 * Check whether Trusted Solaris policy allows communication with this
4843 	 * host, and pretend that the destination is unreachable if not.
4844 	 *
4845 	 * This is never a problem for TCP, since that transport is known to
4846 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4847 	 * handling.  If the remote is unreachable, it will be detected at that
4848 	 * point, so there's no reason to check it here.
4849 	 *
4850 	 * Note that for sendto (and other datagram-oriented friends), this
4851 	 * check is done as part of the data path label computation instead.
4852 	 * The check here is just to make non-TCP connect() report the right
4853 	 * error.
4854 	 */
4855 	if (dst_ire != NULL && is_system_labeled() &&
4856 	    !IPCL_IS_TCP(connp) &&
4857 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4858 	    connp->conn_mac_exempt, ipst) != 0) {
4859 		error = EHOSTUNREACH;
4860 		if (ip_debug > 2) {
4861 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4862 			    AF_INET, &dst_addr);
4863 		}
4864 		goto bad_addr;
4865 	}
4866 
4867 	/*
4868 	 * If the app does a connect(), it means that it will most likely
4869 	 * send more than 1 packet to the destination.  It makes sense
4870 	 * to clear the temporary flag.
4871 	 */
4872 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4873 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4874 		irb_t *irb = dst_ire->ire_bucket;
4875 
4876 		rw_enter(&irb->irb_lock, RW_WRITER);
4877 		dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4878 		irb->irb_tmp_ire_cnt--;
4879 		rw_exit(&irb->irb_lock);
4880 	}
4881 
4882 	/*
4883 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4884 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4885 	 * eligibility tests for passive connects are handled separately
4886 	 * through tcp_adapt_ire().  We do this before the source address
4887 	 * selection, because dst_ire may change after a call to
4888 	 * ipif_select_source().  This is a best-effort check, as the
4889 	 * packet for this connection may not actually go through
4890 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4891 	 * calling ip_newroute().  This is why we further check on the
4892 	 * IRE during LSO/Multidata packet transmission in
4893 	 * tcp_lsosend()/tcp_multisend().
4894 	 */
4895 	if (!ipsec_policy_set && dst_ire != NULL &&
4896 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4897 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4898 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4899 			lso_dst_ire = dst_ire;
4900 			IRE_REFHOLD(lso_dst_ire);
4901 		} else if (ipst->ips_ip_multidata_outbound &&
4902 		    ILL_MDT_CAPABLE(ill)) {
4903 			md_dst_ire = dst_ire;
4904 			IRE_REFHOLD(md_dst_ire);
4905 		}
4906 	}
4907 
4908 	if (dst_ire != NULL &&
4909 	    dst_ire->ire_type == IRE_LOCAL &&
4910 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4911 		/*
4912 		 * If the IRE belongs to a different zone, look for a matching
4913 		 * route in the forwarding table and use the source address from
4914 		 * that route.
4915 		 */
4916 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4917 		    zoneid, 0, NULL,
4918 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4919 		    MATCH_IRE_RJ_BHOLE, ipst);
4920 		if (src_ire == NULL) {
4921 			error = EHOSTUNREACH;
4922 			goto bad_addr;
4923 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4924 			if (!(src_ire->ire_type & IRE_HOST))
4925 				error = ENETUNREACH;
4926 			else
4927 				error = EHOSTUNREACH;
4928 			goto bad_addr;
4929 		}
4930 		if (src_addr == INADDR_ANY)
4931 			src_addr = src_ire->ire_src_addr;
4932 		ire_refrele(src_ire);
4933 		src_ire = NULL;
4934 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4935 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4936 			src_addr = sire->ire_src_addr;
4937 			ire_refrele(dst_ire);
4938 			dst_ire = sire;
4939 			sire = NULL;
4940 		} else {
4941 			/*
4942 			 * Pick a source address so that a proper inbound
4943 			 * load spreading would happen.
4944 			 */
4945 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4946 			ipif_t *src_ipif = NULL;
4947 			ire_t *ipif_ire;
4948 
4949 			/*
4950 			 * Supply a local source address such that inbound
4951 			 * load spreading happens.
4952 			 *
4953 			 * Determine the best source address on this ill for
4954 			 * the destination.
4955 			 *
4956 			 * 1) For broadcast, we should return a broadcast ire
4957 			 *    found above so that upper layers know that the
4958 			 *    destination address is a broadcast address.
4959 			 *
4960 			 * 2) If this is part of a group, select a better
4961 			 *    source address so that better inbound load
4962 			 *    balancing happens. Do the same if the ipif
4963 			 *    is DEPRECATED.
4964 			 *
4965 			 * 3) If the outgoing interface is part of a usesrc
4966 			 *    group, then try selecting a source address from
4967 			 *    the usesrc ILL.
4968 			 */
4969 			if ((dst_ire->ire_zoneid != zoneid &&
4970 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4971 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4972 			    ((dst_ill->ill_group != NULL) ||
4973 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4974 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4975 				/*
4976 				 * If the destination is reachable via a
4977 				 * given gateway, the selected source address
4978 				 * should be in the same subnet as the gateway.
4979 				 * Otherwise, the destination is not reachable.
4980 				 *
4981 				 * If there are no interfaces on the same subnet
4982 				 * as the destination, ipif_select_source gives
4983 				 * first non-deprecated interface which might be
4984 				 * on a different subnet than the gateway.
4985 				 * This is not desirable. Hence pass the dst_ire
4986 				 * source address to ipif_select_source.
4987 				 * It is sure that the destination is reachable
4988 				 * with the dst_ire source address subnet.
4989 				 * So passing dst_ire source address to
4990 				 * ipif_select_source will make sure that the
4991 				 * selected source will be on the same subnet
4992 				 * as dst_ire source address.
4993 				 */
4994 				ipaddr_t saddr =
4995 				    dst_ire->ire_ipif->ipif_src_addr;
4996 				src_ipif = ipif_select_source(dst_ill,
4997 				    saddr, zoneid);
4998 				if (src_ipif != NULL) {
4999 					if (IS_VNI(src_ipif->ipif_ill)) {
5000 						/*
5001 						 * For VNI there is no
5002 						 * interface route
5003 						 */
5004 						src_addr =
5005 						    src_ipif->ipif_src_addr;
5006 					} else {
5007 						ipif_ire =
5008 						    ipif_to_ire(src_ipif);
5009 						if (ipif_ire != NULL) {
5010 							IRE_REFRELE(dst_ire);
5011 							dst_ire = ipif_ire;
5012 						}
5013 						src_addr =
5014 						    dst_ire->ire_src_addr;
5015 					}
5016 					ipif_refrele(src_ipif);
5017 				} else {
5018 					src_addr = dst_ire->ire_src_addr;
5019 				}
5020 			} else {
5021 				src_addr = dst_ire->ire_src_addr;
5022 			}
5023 		}
5024 	}
5025 
5026 	/*
5027 	 * We do ire_route_lookup() here (and not
5028 	 * interface lookup as we assert that
5029 	 * src_addr should only come from an
5030 	 * UP interface for hard binding.
5031 	 */
5032 	ASSERT(src_ire == NULL);
5033 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5034 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5035 	/* src_ire must be a local|loopback */
5036 	if (!IRE_IS_LOCAL(src_ire)) {
5037 		if (ip_debug > 2) {
5038 			pr_addr_dbg("ip_bind_connected: bad connected "
5039 			    "src %s\n", AF_INET, &src_addr);
5040 		}
5041 		error = EADDRNOTAVAIL;
5042 		goto bad_addr;
5043 	}
5044 
5045 	/*
5046 	 * If the source address is a loopback address, the
5047 	 * destination had best be local or multicast.
5048 	 * The transports that can't handle multicast will reject
5049 	 * those addresses.
5050 	 */
5051 	if (src_ire->ire_type == IRE_LOOPBACK &&
5052 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5053 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5054 		error = -1;
5055 		goto bad_addr;
5056 	}
5057 
5058 	/*
5059 	 * Allow setting new policies. For example, disconnects come
5060 	 * down as ipa_t bind. As we would have set conn_policy_cached
5061 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5062 	 * can change after the disconnect.
5063 	 */
5064 	connp->conn_policy_cached = B_FALSE;
5065 
5066 	/*
5067 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5068 	 * can handle their passed-in conn's.
5069 	 */
5070 
5071 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5072 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5073 	connp->conn_lport = lport;
5074 	connp->conn_fport = fport;
5075 	*src_addrp = src_addr;
5076 
5077 	ASSERT(!(ipsec_policy_set && ire_requested));
5078 	if (ire_requested) {
5079 		iulp_t *ulp_info = NULL;
5080 
5081 		/*
5082 		 * Note that sire will not be NULL if this is an off-link
5083 		 * connection and there is not cache for that dest yet.
5084 		 *
5085 		 * XXX Because of an existing bug, if there are multiple
5086 		 * default routes, the IRE returned now may not be the actual
5087 		 * default route used (default routes are chosen in a
5088 		 * round robin fashion).  So if the metrics for different
5089 		 * default routes are different, we may return the wrong
5090 		 * metrics.  This will not be a problem if the existing
5091 		 * bug is fixed.
5092 		 */
5093 		if (sire != NULL) {
5094 			ulp_info = &(sire->ire_uinfo);
5095 		}
5096 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info, ipst)) {
5097 			error = -1;
5098 			goto bad_addr;
5099 		}
5100 	} else if (ipsec_policy_set) {
5101 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5102 			error = -1;
5103 			goto bad_addr;
5104 		}
5105 	}
5106 
5107 	/*
5108 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5109 	 * we'll cache that.  If we don't, we'll inherit global policy.
5110 	 *
5111 	 * We can't insert until the conn reflects the policy. Note that
5112 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5113 	 * connections where we don't have a policy. This is to prevent
5114 	 * global policy lookups in the inbound path.
5115 	 *
5116 	 * If we insert before we set conn_policy_cached,
5117 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5118 	 * because global policy cound be non-empty. We normally call
5119 	 * ipsec_check_policy() for conn_policy_cached connections only if
5120 	 * ipc_in_enforce_policy is set. But in this case,
5121 	 * conn_policy_cached can get set anytime since we made the
5122 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5123 	 * called, which will make the above assumption false.  Thus, we
5124 	 * need to insert after we set conn_policy_cached.
5125 	 */
5126 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5127 		goto bad_addr;
5128 
5129 	if (fanout_insert) {
5130 		/*
5131 		 * The addresses have been verified. Time to insert in
5132 		 * the correct fanout list.
5133 		 */
5134 		error = ipcl_conn_insert(connp, protocol, src_addr,
5135 		    dst_addr, connp->conn_ports);
5136 	}
5137 
5138 	if (error == 0) {
5139 		connp->conn_fully_bound = B_TRUE;
5140 		/*
5141 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5142 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5143 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5144 		 * ip_xxinfo_return(), which performs further checks
5145 		 * against them and upon success, returns the LSO/MDT info
5146 		 * mblk which we will attach to the bind acknowledgment.
5147 		 */
5148 		if (lso_dst_ire != NULL) {
5149 			mblk_t *lsoinfo_mp;
5150 
5151 			ASSERT(ill->ill_lso_capab != NULL);
5152 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5153 			    ill->ill_name, ill->ill_lso_capab)) != NULL)
5154 				linkb(mp, lsoinfo_mp);
5155 		} else if (md_dst_ire != NULL) {
5156 			mblk_t *mdinfo_mp;
5157 
5158 			ASSERT(ill->ill_mdt_capab != NULL);
5159 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5160 			    ill->ill_name, ill->ill_mdt_capab)) != NULL)
5161 				linkb(mp, mdinfo_mp);
5162 		}
5163 	}
5164 bad_addr:
5165 	if (ipsec_policy_set) {
5166 		ASSERT(policy_mp == mp->b_cont);
5167 		ASSERT(policy_mp != NULL);
5168 		freeb(policy_mp);
5169 		/*
5170 		 * As of now assume that nothing else accompanies
5171 		 * IPSEC_POLICY_SET.
5172 		 */
5173 		mp->b_cont = NULL;
5174 	}
5175 	if (src_ire != NULL)
5176 		IRE_REFRELE(src_ire);
5177 	if (dst_ire != NULL)
5178 		IRE_REFRELE(dst_ire);
5179 	if (sire != NULL)
5180 		IRE_REFRELE(sire);
5181 	if (md_dst_ire != NULL)
5182 		IRE_REFRELE(md_dst_ire);
5183 	if (lso_dst_ire != NULL)
5184 		IRE_REFRELE(lso_dst_ire);
5185 	return (error);
5186 }
5187 
5188 /*
5189  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5190  * Prefers dst_ire over src_ire.
5191  */
5192 static boolean_t
5193 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5194 {
5195 	mblk_t	*mp1;
5196 	ire_t *ret_ire = NULL;
5197 
5198 	mp1 = mp->b_cont;
5199 	ASSERT(mp1 != NULL);
5200 
5201 	if (ire != NULL) {
5202 		/*
5203 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5204 		 * appended mblk. Its <upper protocol>'s
5205 		 * job to make sure there is room.
5206 		 */
5207 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5208 			return (0);
5209 
5210 		mp1->b_datap->db_type = IRE_DB_TYPE;
5211 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5212 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5213 		ret_ire = (ire_t *)mp1->b_rptr;
5214 		/*
5215 		 * Pass the latest setting of the ip_path_mtu_discovery and
5216 		 * copy the ulp info if any.
5217 		 */
5218 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5219 		    IPH_DF : 0;
5220 		if (ulp_info != NULL) {
5221 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5222 			    sizeof (iulp_t));
5223 		}
5224 		ret_ire->ire_mp = mp1;
5225 	} else {
5226 		/*
5227 		 * No IRE was found. Remove IRE mblk.
5228 		 */
5229 		mp->b_cont = mp1->b_cont;
5230 		freeb(mp1);
5231 	}
5232 
5233 	return (1);
5234 }
5235 
5236 /*
5237  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5238  * the final piece where we don't.  Return a pointer to the first mblk in the
5239  * result, and update the pointer to the next mblk to chew on.  If anything
5240  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5241  * NULL pointer.
5242  */
5243 mblk_t *
5244 ip_carve_mp(mblk_t **mpp, ssize_t len)
5245 {
5246 	mblk_t	*mp0;
5247 	mblk_t	*mp1;
5248 	mblk_t	*mp2;
5249 
5250 	if (!len || !mpp || !(mp0 = *mpp))
5251 		return (NULL);
5252 	/* If we aren't going to consume the first mblk, we need a dup. */
5253 	if (mp0->b_wptr - mp0->b_rptr > len) {
5254 		mp1 = dupb(mp0);
5255 		if (mp1) {
5256 			/* Partition the data between the two mblks. */
5257 			mp1->b_wptr = mp1->b_rptr + len;
5258 			mp0->b_rptr = mp1->b_wptr;
5259 			/*
5260 			 * after adjustments if mblk not consumed is now
5261 			 * unaligned, try to align it. If this fails free
5262 			 * all messages and let upper layer recover.
5263 			 */
5264 			if (!OK_32PTR(mp0->b_rptr)) {
5265 				if (!pullupmsg(mp0, -1)) {
5266 					freemsg(mp0);
5267 					freemsg(mp1);
5268 					*mpp = NULL;
5269 					return (NULL);
5270 				}
5271 			}
5272 		}
5273 		return (mp1);
5274 	}
5275 	/* Eat through as many mblks as we need to get len bytes. */
5276 	len -= mp0->b_wptr - mp0->b_rptr;
5277 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5278 		if (mp2->b_wptr - mp2->b_rptr > len) {
5279 			/*
5280 			 * We won't consume the entire last mblk.  Like
5281 			 * above, dup and partition it.
5282 			 */
5283 			mp1->b_cont = dupb(mp2);
5284 			mp1 = mp1->b_cont;
5285 			if (!mp1) {
5286 				/*
5287 				 * Trouble.  Rather than go to a lot of
5288 				 * trouble to clean up, we free the messages.
5289 				 * This won't be any worse than losing it on
5290 				 * the wire.
5291 				 */
5292 				freemsg(mp0);
5293 				freemsg(mp2);
5294 				*mpp = NULL;
5295 				return (NULL);
5296 			}
5297 			mp1->b_wptr = mp1->b_rptr + len;
5298 			mp2->b_rptr = mp1->b_wptr;
5299 			/*
5300 			 * after adjustments if mblk not consumed is now
5301 			 * unaligned, try to align it. If this fails free
5302 			 * all messages and let upper layer recover.
5303 			 */
5304 			if (!OK_32PTR(mp2->b_rptr)) {
5305 				if (!pullupmsg(mp2, -1)) {
5306 					freemsg(mp0);
5307 					freemsg(mp2);
5308 					*mpp = NULL;
5309 					return (NULL);
5310 				}
5311 			}
5312 			*mpp = mp2;
5313 			return (mp0);
5314 		}
5315 		/* Decrement len by the amount we just got. */
5316 		len -= mp2->b_wptr - mp2->b_rptr;
5317 	}
5318 	/*
5319 	 * len should be reduced to zero now.  If not our caller has
5320 	 * screwed up.
5321 	 */
5322 	if (len) {
5323 		/* Shouldn't happen! */
5324 		freemsg(mp0);
5325 		*mpp = NULL;
5326 		return (NULL);
5327 	}
5328 	/*
5329 	 * We consumed up to exactly the end of an mblk.  Detach the part
5330 	 * we are returning from the rest of the chain.
5331 	 */
5332 	mp1->b_cont = NULL;
5333 	*mpp = mp2;
5334 	return (mp0);
5335 }
5336 
5337 /* The ill stream is being unplumbed. Called from ip_close */
5338 int
5339 ip_modclose(ill_t *ill)
5340 {
5341 	boolean_t success;
5342 	ipsq_t	*ipsq;
5343 	ipif_t	*ipif;
5344 	queue_t	*q = ill->ill_rq;
5345 	ip_stack_t	*ipst = ill->ill_ipst;
5346 	clock_t timeout;
5347 
5348 	/*
5349 	 * Wait for the ACKs of all deferred control messages to be processed.
5350 	 * In particular, we wait for a potential capability reset initiated
5351 	 * in ip_sioctl_plink() to complete before proceeding.
5352 	 *
5353 	 * Note: we wait for at most ip_modclose_ackwait_ms (by default 3000 ms)
5354 	 * in case the driver never replies.
5355 	 */
5356 	timeout = lbolt + MSEC_TO_TICK(ip_modclose_ackwait_ms);
5357 	mutex_enter(&ill->ill_lock);
5358 	while (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
5359 		if (cv_timedwait(&ill->ill_cv, &ill->ill_lock, timeout) < 0) {
5360 			/* Timeout */
5361 			break;
5362 		}
5363 	}
5364 	mutex_exit(&ill->ill_lock);
5365 
5366 	/*
5367 	 * Forcibly enter the ipsq after some delay. This is to take
5368 	 * care of the case when some ioctl does not complete because
5369 	 * we sent a control message to the driver and it did not
5370 	 * send us a reply. We want to be able to at least unplumb
5371 	 * and replumb rather than force the user to reboot the system.
5372 	 */
5373 	success = ipsq_enter(ill, B_FALSE);
5374 
5375 	/*
5376 	 * Open/close/push/pop is guaranteed to be single threaded
5377 	 * per stream by STREAMS. FS guarantees that all references
5378 	 * from top are gone before close is called. So there can't
5379 	 * be another close thread that has set CONDEMNED on this ill.
5380 	 * and cause ipsq_enter to return failure.
5381 	 */
5382 	ASSERT(success);
5383 	ipsq = ill->ill_phyint->phyint_ipsq;
5384 
5385 	/*
5386 	 * Mark it condemned. No new reference will be made to this ill.
5387 	 * Lookup functions will return an error. Threads that try to
5388 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5389 	 * that the refcnt will drop down to zero.
5390 	 */
5391 	mutex_enter(&ill->ill_lock);
5392 	ill->ill_state_flags |= ILL_CONDEMNED;
5393 	for (ipif = ill->ill_ipif; ipif != NULL;
5394 	    ipif = ipif->ipif_next) {
5395 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5396 	}
5397 	/*
5398 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5399 	 * returns  error if ILL_CONDEMNED is set
5400 	 */
5401 	cv_broadcast(&ill->ill_cv);
5402 	mutex_exit(&ill->ill_lock);
5403 
5404 	/*
5405 	 * Send all the deferred DLPI messages downstream which came in
5406 	 * during the small window right before ipsq_enter(). We do this
5407 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5408 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5409 	 */
5410 	ill_dlpi_send_deferred(ill);
5411 
5412 	/*
5413 	 * Shut down fragmentation reassembly.
5414 	 * ill_frag_timer won't start a timer again.
5415 	 * Now cancel any existing timer
5416 	 */
5417 	(void) untimeout(ill->ill_frag_timer_id);
5418 	(void) ill_frag_timeout(ill, 0);
5419 
5420 	/*
5421 	 * If MOVE was in progress, clear the
5422 	 * move_in_progress fields also.
5423 	 */
5424 	if (ill->ill_move_in_progress) {
5425 		ILL_CLEAR_MOVE(ill);
5426 	}
5427 
5428 	/*
5429 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5430 	 * this ill. Then wait for the refcnts to drop to zero.
5431 	 * ill_is_quiescent checks whether the ill is really quiescent.
5432 	 * Then make sure that threads that are waiting to enter the
5433 	 * ipsq have seen the error returned by ipsq_enter and have
5434 	 * gone away. Then we call ill_delete_tail which does the
5435 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5436 	 */
5437 	ill_delete(ill);
5438 	mutex_enter(&ill->ill_lock);
5439 	while (!ill_is_quiescent(ill))
5440 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5441 	while (ill->ill_waiters)
5442 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5443 
5444 	mutex_exit(&ill->ill_lock);
5445 
5446 	/*
5447 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5448 	 * it held until the end of the function since the cleanup
5449 	 * below needs to be able to use the ip_stack_t.
5450 	 */
5451 	netstack_hold(ipst->ips_netstack);
5452 
5453 	/* qprocsoff is called in ill_delete_tail */
5454 	ill_delete_tail(ill);
5455 	ASSERT(ill->ill_ipst == NULL);
5456 
5457 	/*
5458 	 * Walk through all upper (conn) streams and qenable
5459 	 * those that have queued data.
5460 	 * close synchronization needs this to
5461 	 * be done to ensure that all upper layers blocked
5462 	 * due to flow control to the closing device
5463 	 * get unblocked.
5464 	 */
5465 	ip1dbg(("ip_wsrv: walking\n"));
5466 	conn_walk_drain(ipst);
5467 
5468 	mutex_enter(&ipst->ips_ip_mi_lock);
5469 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5470 	mutex_exit(&ipst->ips_ip_mi_lock);
5471 
5472 	/*
5473 	 * credp could be null if the open didn't succeed and ip_modopen
5474 	 * itself calls ip_close.
5475 	 */
5476 	if (ill->ill_credp != NULL)
5477 		crfree(ill->ill_credp);
5478 
5479 	mutex_enter(&ill->ill_lock);
5480 	ill_nic_info_dispatch(ill);
5481 	mutex_exit(&ill->ill_lock);
5482 
5483 	/*
5484 	 * Now we are done with the module close pieces that
5485 	 * need the netstack_t.
5486 	 */
5487 	netstack_rele(ipst->ips_netstack);
5488 
5489 	mi_close_free((IDP)ill);
5490 	q->q_ptr = WR(q)->q_ptr = NULL;
5491 
5492 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5493 
5494 	return (0);
5495 }
5496 
5497 /*
5498  * This is called as part of close() for IP, UDP, ICMP, and RTS
5499  * in order to quiesce the conn.
5500  */
5501 void
5502 ip_quiesce_conn(conn_t *connp)
5503 {
5504 	boolean_t	drain_cleanup_reqd = B_FALSE;
5505 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5506 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5507 	ip_stack_t	*ipst;
5508 
5509 	ASSERT(!IPCL_IS_TCP(connp));
5510 	ipst = connp->conn_netstack->netstack_ip;
5511 
5512 	/*
5513 	 * Mark the conn as closing, and this conn must not be
5514 	 * inserted in future into any list. Eg. conn_drain_insert(),
5515 	 * won't insert this conn into the conn_drain_list.
5516 	 * Similarly ill_pending_mp_add() will not add any mp to
5517 	 * the pending mp list, after this conn has started closing.
5518 	 *
5519 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5520 	 * cannot get set henceforth.
5521 	 */
5522 	mutex_enter(&connp->conn_lock);
5523 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5524 	connp->conn_state_flags |= CONN_CLOSING;
5525 	if (connp->conn_idl != NULL)
5526 		drain_cleanup_reqd = B_TRUE;
5527 	if (connp->conn_oper_pending_ill != NULL)
5528 		conn_ioctl_cleanup_reqd = B_TRUE;
5529 	if (connp->conn_ilg_inuse != 0)
5530 		ilg_cleanup_reqd = B_TRUE;
5531 	mutex_exit(&connp->conn_lock);
5532 
5533 	if (conn_ioctl_cleanup_reqd)
5534 		conn_ioctl_cleanup(connp);
5535 
5536 	if (is_system_labeled() && connp->conn_anon_port) {
5537 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5538 		    connp->conn_mlp_type, connp->conn_ulp,
5539 		    ntohs(connp->conn_lport), B_FALSE);
5540 		connp->conn_anon_port = 0;
5541 	}
5542 	connp->conn_mlp_type = mlptSingle;
5543 
5544 	/*
5545 	 * Remove this conn from any fanout list it is on.
5546 	 * and then wait for any threads currently operating
5547 	 * on this endpoint to finish
5548 	 */
5549 	ipcl_hash_remove(connp);
5550 
5551 	/*
5552 	 * Remove this conn from the drain list, and do
5553 	 * any other cleanup that may be required.
5554 	 * (Only non-tcp streams may have a non-null conn_idl.
5555 	 * TCP streams are never flow controlled, and
5556 	 * conn_idl will be null)
5557 	 */
5558 	if (drain_cleanup_reqd)
5559 		conn_drain_tail(connp, B_TRUE);
5560 
5561 	if (connp == ipst->ips_ip_g_mrouter)
5562 		(void) ip_mrouter_done(NULL, ipst);
5563 
5564 	if (ilg_cleanup_reqd)
5565 		ilg_delete_all(connp);
5566 
5567 	conn_delete_ire(connp, NULL);
5568 
5569 	/*
5570 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5571 	 * callers from write side can't be there now because close
5572 	 * is in progress. The only other caller is ipcl_walk
5573 	 * which checks for the condemned flag.
5574 	 */
5575 	mutex_enter(&connp->conn_lock);
5576 	connp->conn_state_flags |= CONN_CONDEMNED;
5577 	while (connp->conn_ref != 1)
5578 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5579 	connp->conn_state_flags |= CONN_QUIESCED;
5580 	mutex_exit(&connp->conn_lock);
5581 }
5582 
5583 /* ARGSUSED */
5584 int
5585 ip_close(queue_t *q, int flags)
5586 {
5587 	conn_t		*connp;
5588 
5589 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5590 
5591 	/*
5592 	 * Call the appropriate delete routine depending on whether this is
5593 	 * a module or device.
5594 	 */
5595 	if (WR(q)->q_next != NULL) {
5596 		/* This is a module close */
5597 		return (ip_modclose((ill_t *)q->q_ptr));
5598 	}
5599 
5600 	connp = q->q_ptr;
5601 	ip_quiesce_conn(connp);
5602 
5603 	qprocsoff(q);
5604 
5605 	/*
5606 	 * Now we are truly single threaded on this stream, and can
5607 	 * delete the things hanging off the connp, and finally the connp.
5608 	 * We removed this connp from the fanout list, it cannot be
5609 	 * accessed thru the fanouts, and we already waited for the
5610 	 * conn_ref to drop to 0. We are already in close, so
5611 	 * there cannot be any other thread from the top. qprocsoff
5612 	 * has completed, and service has completed or won't run in
5613 	 * future.
5614 	 */
5615 	ASSERT(connp->conn_ref == 1);
5616 
5617 	inet_minor_free(ip_minor_arena, connp->conn_dev);
5618 
5619 	connp->conn_ref--;
5620 	ipcl_conn_destroy(connp);
5621 
5622 	q->q_ptr = WR(q)->q_ptr = NULL;
5623 	return (0);
5624 }
5625 
5626 /* Return the IP checksum for the IP header at "iph". */
5627 uint16_t
5628 ip_csum_hdr(ipha_t *ipha)
5629 {
5630 	uint16_t	*uph;
5631 	uint32_t	sum;
5632 	int		opt_len;
5633 
5634 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5635 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5636 	uph = (uint16_t *)ipha;
5637 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5638 	    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5639 	if (opt_len > 0) {
5640 		do {
5641 			sum += uph[10];
5642 			sum += uph[11];
5643 			uph += 2;
5644 		} while (--opt_len);
5645 	}
5646 	sum = (sum & 0xFFFF) + (sum >> 16);
5647 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5648 	if (sum == 0xffff)
5649 		sum = 0;
5650 	return ((uint16_t)sum);
5651 }
5652 
5653 /*
5654  * Called when the module is about to be unloaded
5655  */
5656 void
5657 ip_ddi_destroy(void)
5658 {
5659 	tnet_fini();
5660 
5661 	icmp_ddi_destroy();
5662 	rts_ddi_destroy();
5663 	udp_ddi_destroy();
5664 	sctp_ddi_g_destroy();
5665 	tcp_ddi_g_destroy();
5666 	ipsec_policy_g_destroy();
5667 	ipcl_g_destroy();
5668 	ip_net_g_destroy();
5669 	ip_ire_g_fini();
5670 	inet_minor_destroy(ip_minor_arena);
5671 
5672 #ifdef DEBUG
5673 	list_destroy(&ip_thread_list);
5674 	rw_destroy(&ip_thread_rwlock);
5675 	tsd_destroy(&ip_thread_data);
5676 #endif
5677 
5678 	netstack_unregister(NS_IP);
5679 }
5680 
5681 /*
5682  * First step in cleanup.
5683  */
5684 /* ARGSUSED */
5685 static void
5686 ip_stack_shutdown(netstackid_t stackid, void *arg)
5687 {
5688 	ip_stack_t *ipst = (ip_stack_t *)arg;
5689 
5690 #ifdef NS_DEBUG
5691 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5692 #endif
5693 
5694 	/* Get rid of loopback interfaces and their IREs */
5695 	ip_loopback_cleanup(ipst);
5696 }
5697 
5698 /*
5699  * Free the IP stack instance.
5700  */
5701 static void
5702 ip_stack_fini(netstackid_t stackid, void *arg)
5703 {
5704 	ip_stack_t *ipst = (ip_stack_t *)arg;
5705 	int ret;
5706 
5707 #ifdef NS_DEBUG
5708 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5709 #endif
5710 	ipv4_hook_destroy(ipst);
5711 	ipv6_hook_destroy(ipst);
5712 	ip_net_destroy(ipst);
5713 
5714 	rw_destroy(&ipst->ips_srcid_lock);
5715 
5716 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5717 	ipst->ips_ip_mibkp = NULL;
5718 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5719 	ipst->ips_icmp_mibkp = NULL;
5720 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5721 	ipst->ips_ip_kstat = NULL;
5722 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5723 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5724 	ipst->ips_ip6_kstat = NULL;
5725 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5726 
5727 	nd_free(&ipst->ips_ip_g_nd);
5728 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5729 	ipst->ips_param_arr = NULL;
5730 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5731 	ipst->ips_ndp_arr = NULL;
5732 
5733 	ip_mrouter_stack_destroy(ipst);
5734 
5735 	mutex_destroy(&ipst->ips_ip_mi_lock);
5736 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5737 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5738 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5739 
5740 	ret = untimeout(ipst->ips_igmp_timeout_id);
5741 	if (ret == -1) {
5742 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5743 	} else {
5744 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5745 		ipst->ips_igmp_timeout_id = 0;
5746 	}
5747 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5748 	if (ret == -1) {
5749 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5750 	} else {
5751 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5752 		ipst->ips_igmp_slowtimeout_id = 0;
5753 	}
5754 	ret = untimeout(ipst->ips_mld_timeout_id);
5755 	if (ret == -1) {
5756 		ASSERT(ipst->ips_mld_timeout_id == 0);
5757 	} else {
5758 		ASSERT(ipst->ips_mld_timeout_id != 0);
5759 		ipst->ips_mld_timeout_id = 0;
5760 	}
5761 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5762 	if (ret == -1) {
5763 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5764 	} else {
5765 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5766 		ipst->ips_mld_slowtimeout_id = 0;
5767 	}
5768 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5769 	if (ret == -1) {
5770 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5771 	} else {
5772 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5773 		ipst->ips_ip_ire_expire_id = 0;
5774 	}
5775 
5776 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5777 	mutex_destroy(&ipst->ips_mld_timer_lock);
5778 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5779 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5780 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5781 	rw_destroy(&ipst->ips_ill_g_lock);
5782 
5783 	ip_ire_fini(ipst);
5784 	ip6_asp_free(ipst);
5785 	conn_drain_fini(ipst);
5786 	ipcl_destroy(ipst);
5787 
5788 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5789 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5790 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5791 	ipst->ips_ndp4 = NULL;
5792 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5793 	ipst->ips_ndp6 = NULL;
5794 
5795 	if (ipst->ips_loopback_ksp != NULL) {
5796 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5797 		ipst->ips_loopback_ksp = NULL;
5798 	}
5799 
5800 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5801 	ipst->ips_phyint_g_list = NULL;
5802 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5803 	ipst->ips_ill_g_heads = NULL;
5804 
5805 	kmem_free(ipst, sizeof (*ipst));
5806 }
5807 
5808 /*
5809  * This function is called from the TSD destructor, and is used to debug
5810  * reference count issues in IP. See block comment in <inet/ip_if.h> for
5811  * details.
5812  */
5813 static void
5814 ip_thread_exit(void *phash)
5815 {
5816 	th_hash_t *thh = phash;
5817 
5818 	rw_enter(&ip_thread_rwlock, RW_WRITER);
5819 	list_remove(&ip_thread_list, thh);
5820 	rw_exit(&ip_thread_rwlock);
5821 	mod_hash_destroy_hash(thh->thh_hash);
5822 	kmem_free(thh, sizeof (*thh));
5823 }
5824 
5825 /*
5826  * Called when the IP kernel module is loaded into the kernel
5827  */
5828 void
5829 ip_ddi_init(void)
5830 {
5831 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5832 
5833 	/*
5834 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5835 	 * initial devices: ip, ip6, tcp, tcp6.
5836 	 */
5837 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
5838 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
5839 		cmn_err(CE_PANIC,
5840 		    "ip_ddi_init: ip_minor_arena creation failed\n");
5841 	}
5842 
5843 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5844 
5845 	ipcl_g_init();
5846 	ip_ire_g_init();
5847 	ip_net_g_init();
5848 
5849 #ifdef DEBUG
5850 	tsd_create(&ip_thread_data, ip_thread_exit);
5851 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
5852 	list_create(&ip_thread_list, sizeof (th_hash_t),
5853 	    offsetof(th_hash_t, thh_link));
5854 #endif
5855 
5856 	/*
5857 	 * We want to be informed each time a stack is created or
5858 	 * destroyed in the kernel, so we can maintain the
5859 	 * set of udp_stack_t's.
5860 	 */
5861 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5862 	    ip_stack_fini);
5863 
5864 	ipsec_policy_g_init();
5865 	tcp_ddi_g_init();
5866 	sctp_ddi_g_init();
5867 
5868 	tnet_init();
5869 
5870 	udp_ddi_init();
5871 	rts_ddi_init();
5872 	icmp_ddi_init();
5873 }
5874 
5875 /*
5876  * Initialize the IP stack instance.
5877  */
5878 static void *
5879 ip_stack_init(netstackid_t stackid, netstack_t *ns)
5880 {
5881 	ip_stack_t	*ipst;
5882 	ipparam_t	*pa;
5883 	ipndp_t		*na;
5884 
5885 #ifdef NS_DEBUG
5886 	printf("ip_stack_init(stack %d)\n", stackid);
5887 #endif
5888 
5889 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
5890 	ipst->ips_netstack = ns;
5891 
5892 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
5893 	    KM_SLEEP);
5894 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
5895 	    KM_SLEEP);
5896 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5897 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5898 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5899 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5900 
5901 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5902 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5903 	ipst->ips_igmp_deferred_next = INFINITY;
5904 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5905 	ipst->ips_mld_deferred_next = INFINITY;
5906 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5907 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5908 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5909 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5910 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
5911 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5912 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5913 
5914 	ipcl_init(ipst);
5915 	ip_ire_init(ipst);
5916 	ip6_asp_init(ipst);
5917 	ipif_init(ipst);
5918 	conn_drain_init(ipst);
5919 	ip_mrouter_stack_init(ipst);
5920 
5921 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
5922 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
5923 
5924 	ipst->ips_ip_multirt_log_interval = 1000;
5925 
5926 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
5927 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
5928 	ipst->ips_ill_index = 1;
5929 
5930 	ipst->ips_saved_ip_g_forward = -1;
5931 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
5932 
5933 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
5934 	ipst->ips_param_arr = pa;
5935 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
5936 
5937 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
5938 	ipst->ips_ndp_arr = na;
5939 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5940 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
5941 	    (caddr_t)&ipst->ips_ip_g_forward;
5942 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
5943 	    (caddr_t)&ipst->ips_ipv6_forward;
5944 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
5945 	    "ip_cgtp_filter") == 0);
5946 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
5947 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
5948 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_name,
5949 	    "ipmp_hook_emulation") == 0);
5950 	ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_data =
5951 	    (caddr_t)&ipst->ips_ipmp_hook_emulation;
5952 
5953 	(void) ip_param_register(&ipst->ips_ip_g_nd,
5954 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
5955 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
5956 
5957 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
5958 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
5959 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
5960 	ipst->ips_ip6_kstat =
5961 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
5962 
5963 	ipst->ips_ipmp_enable_failback = B_TRUE;
5964 
5965 	ipst->ips_ip_src_id = 1;
5966 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
5967 
5968 	ip_net_init(ipst, ns);
5969 	ipv4_hook_init(ipst);
5970 	ipv6_hook_init(ipst);
5971 
5972 	return (ipst);
5973 }
5974 
5975 /*
5976  * Allocate and initialize a DLPI template of the specified length.  (May be
5977  * called as writer.)
5978  */
5979 mblk_t *
5980 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
5981 {
5982 	mblk_t	*mp;
5983 
5984 	mp = allocb(len, BPRI_MED);
5985 	if (!mp)
5986 		return (NULL);
5987 
5988 	/*
5989 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
5990 	 * of which we don't seem to use) are sent with M_PCPROTO, and
5991 	 * that other DLPI are M_PROTO.
5992 	 */
5993 	if (prim == DL_INFO_REQ) {
5994 		mp->b_datap->db_type = M_PCPROTO;
5995 	} else {
5996 		mp->b_datap->db_type = M_PROTO;
5997 	}
5998 
5999 	mp->b_wptr = mp->b_rptr + len;
6000 	bzero(mp->b_rptr, len);
6001 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6002 	return (mp);
6003 }
6004 
6005 const char *
6006 dlpi_prim_str(int prim)
6007 {
6008 	switch (prim) {
6009 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
6010 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
6011 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
6012 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
6013 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
6014 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
6015 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
6016 	case DL_OK_ACK:		return ("DL_OK_ACK");
6017 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
6018 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
6019 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
6020 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
6021 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
6022 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
6023 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
6024 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
6025 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
6026 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
6027 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
6028 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
6029 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
6030 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
6031 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
6032 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
6033 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
6034 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
6035 	default:		return ("<unknown primitive>");
6036 	}
6037 }
6038 
6039 const char *
6040 dlpi_err_str(int err)
6041 {
6042 	switch (err) {
6043 	case DL_ACCESS:		return ("DL_ACCESS");
6044 	case DL_BADADDR:	return ("DL_BADADDR");
6045 	case DL_BADCORR:	return ("DL_BADCORR");
6046 	case DL_BADDATA:	return ("DL_BADDATA");
6047 	case DL_BADPPA:		return ("DL_BADPPA");
6048 	case DL_BADPRIM:	return ("DL_BADPRIM");
6049 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
6050 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
6051 	case DL_BADSAP:		return ("DL_BADSAP");
6052 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
6053 	case DL_BOUND:		return ("DL_BOUND");
6054 	case DL_INITFAILED:	return ("DL_INITFAILED");
6055 	case DL_NOADDR:		return ("DL_NOADDR");
6056 	case DL_NOTINIT:	return ("DL_NOTINIT");
6057 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
6058 	case DL_SYSERR:		return ("DL_SYSERR");
6059 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
6060 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
6061 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
6062 	case DL_TOOMANY:	return ("DL_TOOMANY");
6063 	case DL_NOTENAB:	return ("DL_NOTENAB");
6064 	case DL_BUSY:		return ("DL_BUSY");
6065 	case DL_NOAUTO:		return ("DL_NOAUTO");
6066 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
6067 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
6068 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
6069 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
6070 	case DL_PENDING:	return ("DL_PENDING");
6071 	default:		return ("<unknown error>");
6072 	}
6073 }
6074 
6075 /*
6076  * Debug formatting routine.  Returns a character string representation of the
6077  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6078  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6079  *
6080  * Once the ndd table-printing interfaces are removed, this can be changed to
6081  * standard dotted-decimal form.
6082  */
6083 char *
6084 ip_dot_addr(ipaddr_t addr, char *buf)
6085 {
6086 	uint8_t *ap = (uint8_t *)&addr;
6087 
6088 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6089 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6090 	return (buf);
6091 }
6092 
6093 /*
6094  * Write the given MAC address as a printable string in the usual colon-
6095  * separated format.
6096  */
6097 const char *
6098 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6099 {
6100 	char *bp;
6101 
6102 	if (alen == 0 || buflen < 4)
6103 		return ("?");
6104 	bp = buf;
6105 	for (;;) {
6106 		/*
6107 		 * If there are more MAC address bytes available, but we won't
6108 		 * have any room to print them, then add "..." to the string
6109 		 * instead.  See below for the 'magic number' explanation.
6110 		 */
6111 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6112 			(void) strcpy(bp, "...");
6113 			break;
6114 		}
6115 		(void) sprintf(bp, "%02x", *addr++);
6116 		bp += 2;
6117 		if (--alen == 0)
6118 			break;
6119 		*bp++ = ':';
6120 		buflen -= 3;
6121 		/*
6122 		 * At this point, based on the first 'if' statement above,
6123 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6124 		 * buflen >= 4.  The first case leaves room for the final "xx"
6125 		 * number and trailing NUL byte.  The second leaves room for at
6126 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6127 		 * that statement.
6128 		 */
6129 	}
6130 	return (buf);
6131 }
6132 
6133 /*
6134  * Send an ICMP error after patching up the packet appropriately.  Returns
6135  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6136  */
6137 static boolean_t
6138 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6139     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6140     zoneid_t zoneid, ip_stack_t *ipst)
6141 {
6142 	ipha_t *ipha;
6143 	mblk_t *first_mp;
6144 	boolean_t secure;
6145 	unsigned char db_type;
6146 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6147 
6148 	first_mp = mp;
6149 	if (mctl_present) {
6150 		mp = mp->b_cont;
6151 		secure = ipsec_in_is_secure(first_mp);
6152 		ASSERT(mp != NULL);
6153 	} else {
6154 		/*
6155 		 * If this is an ICMP error being reported - which goes
6156 		 * up as M_CTLs, we need to convert them to M_DATA till
6157 		 * we finish checking with global policy because
6158 		 * ipsec_check_global_policy() assumes M_DATA as clear
6159 		 * and M_CTL as secure.
6160 		 */
6161 		db_type = DB_TYPE(mp);
6162 		DB_TYPE(mp) = M_DATA;
6163 		secure = B_FALSE;
6164 	}
6165 	/*
6166 	 * We are generating an icmp error for some inbound packet.
6167 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6168 	 * Before we generate an error, check with global policy
6169 	 * to see whether this is allowed to enter the system. As
6170 	 * there is no "conn", we are checking with global policy.
6171 	 */
6172 	ipha = (ipha_t *)mp->b_rptr;
6173 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6174 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6175 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6176 		if (first_mp == NULL)
6177 			return (B_FALSE);
6178 	}
6179 
6180 	if (!mctl_present)
6181 		DB_TYPE(mp) = db_type;
6182 
6183 	if (flags & IP_FF_SEND_ICMP) {
6184 		if (flags & IP_FF_HDR_COMPLETE) {
6185 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6186 				freemsg(first_mp);
6187 				return (B_TRUE);
6188 			}
6189 		}
6190 		if (flags & IP_FF_CKSUM) {
6191 			/*
6192 			 * Have to correct checksum since
6193 			 * the packet might have been
6194 			 * fragmented and the reassembly code in ip_rput
6195 			 * does not restore the IP checksum.
6196 			 */
6197 			ipha->ipha_hdr_checksum = 0;
6198 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6199 		}
6200 		switch (icmp_type) {
6201 		case ICMP_DEST_UNREACHABLE:
6202 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6203 			    ipst);
6204 			break;
6205 		default:
6206 			freemsg(first_mp);
6207 			break;
6208 		}
6209 	} else {
6210 		freemsg(first_mp);
6211 		return (B_FALSE);
6212 	}
6213 
6214 	return (B_TRUE);
6215 }
6216 
6217 /*
6218  * Used to send an ICMP error message when a packet is received for
6219  * a protocol that is not supported. The mblk passed as argument
6220  * is consumed by this function.
6221  */
6222 void
6223 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6224     ip_stack_t *ipst)
6225 {
6226 	mblk_t *mp;
6227 	ipha_t *ipha;
6228 	ill_t *ill;
6229 	ipsec_in_t *ii;
6230 
6231 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6232 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6233 
6234 	mp = ipsec_mp->b_cont;
6235 	ipsec_mp->b_cont = NULL;
6236 	ipha = (ipha_t *)mp->b_rptr;
6237 	/* Get ill from index in ipsec_in_t. */
6238 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6239 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6240 	    ipst);
6241 	if (ill != NULL) {
6242 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6243 			if (ip_fanout_send_icmp(q, mp, flags,
6244 			    ICMP_DEST_UNREACHABLE,
6245 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6246 				BUMP_MIB(ill->ill_ip_mib,
6247 				    ipIfStatsInUnknownProtos);
6248 			}
6249 		} else {
6250 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6251 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6252 			    0, B_FALSE, zoneid, ipst)) {
6253 				BUMP_MIB(ill->ill_ip_mib,
6254 				    ipIfStatsInUnknownProtos);
6255 			}
6256 		}
6257 		ill_refrele(ill);
6258 	} else { /* re-link for the freemsg() below. */
6259 		ipsec_mp->b_cont = mp;
6260 	}
6261 
6262 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6263 	freemsg(ipsec_mp);
6264 }
6265 
6266 /*
6267  * See if the inbound datagram has had IPsec processing applied to it.
6268  */
6269 boolean_t
6270 ipsec_in_is_secure(mblk_t *ipsec_mp)
6271 {
6272 	ipsec_in_t *ii;
6273 
6274 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6275 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6276 
6277 	if (ii->ipsec_in_loopback) {
6278 		return (ii->ipsec_in_secure);
6279 	} else {
6280 		return (ii->ipsec_in_ah_sa != NULL ||
6281 		    ii->ipsec_in_esp_sa != NULL ||
6282 		    ii->ipsec_in_decaps);
6283 	}
6284 }
6285 
6286 /*
6287  * Handle protocols with which IP is less intimate.  There
6288  * can be more than one stream bound to a particular
6289  * protocol.  When this is the case, normally each one gets a copy
6290  * of any incoming packets.
6291  *
6292  * IPsec NOTE :
6293  *
6294  * Don't allow a secure packet going up a non-secure connection.
6295  * We don't allow this because
6296  *
6297  * 1) Reply might go out in clear which will be dropped at
6298  *    the sending side.
6299  * 2) If the reply goes out in clear it will give the
6300  *    adversary enough information for getting the key in
6301  *    most of the cases.
6302  *
6303  * Moreover getting a secure packet when we expect clear
6304  * implies that SA's were added without checking for
6305  * policy on both ends. This should not happen once ISAKMP
6306  * is used to negotiate SAs as SAs will be added only after
6307  * verifying the policy.
6308  *
6309  * NOTE : If the packet was tunneled and not multicast we only send
6310  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6311  * back to delivering packets to AF_INET6 raw sockets.
6312  *
6313  * IPQoS Notes:
6314  * Once we have determined the client, invoke IPPF processing.
6315  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6316  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6317  * ip_policy will be false.
6318  *
6319  * Zones notes:
6320  * Currently only applications in the global zone can create raw sockets for
6321  * protocols other than ICMP. So unlike the broadcast / multicast case of
6322  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6323  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6324  */
6325 static void
6326 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6327     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6328     zoneid_t zoneid)
6329 {
6330 	queue_t	*rq;
6331 	mblk_t	*mp1, *first_mp1;
6332 	uint_t	protocol = ipha->ipha_protocol;
6333 	ipaddr_t dst;
6334 	boolean_t one_only;
6335 	mblk_t *first_mp = mp;
6336 	boolean_t secure;
6337 	uint32_t ill_index;
6338 	conn_t	*connp, *first_connp, *next_connp;
6339 	connf_t	*connfp;
6340 	boolean_t shared_addr;
6341 	mib2_ipIfStatsEntry_t *mibptr;
6342 	ip_stack_t *ipst = recv_ill->ill_ipst;
6343 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6344 
6345 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6346 	if (mctl_present) {
6347 		mp = first_mp->b_cont;
6348 		secure = ipsec_in_is_secure(first_mp);
6349 		ASSERT(mp != NULL);
6350 	} else {
6351 		secure = B_FALSE;
6352 	}
6353 	dst = ipha->ipha_dst;
6354 	/*
6355 	 * If the packet was tunneled and not multicast we only send to it
6356 	 * the first match.
6357 	 */
6358 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6359 	    !CLASSD(dst));
6360 
6361 	shared_addr = (zoneid == ALL_ZONES);
6362 	if (shared_addr) {
6363 		/*
6364 		 * We don't allow multilevel ports for raw IP, so no need to
6365 		 * check for that here.
6366 		 */
6367 		zoneid = tsol_packet_to_zoneid(mp);
6368 	}
6369 
6370 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6371 	mutex_enter(&connfp->connf_lock);
6372 	connp = connfp->connf_head;
6373 	for (connp = connfp->connf_head; connp != NULL;
6374 	    connp = connp->conn_next) {
6375 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6376 		    zoneid) &&
6377 		    (!is_system_labeled() ||
6378 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6379 		    connp))) {
6380 			break;
6381 		}
6382 	}
6383 
6384 	if (connp == NULL || connp->conn_upq == NULL) {
6385 		/*
6386 		 * No one bound to these addresses.  Is
6387 		 * there a client that wants all
6388 		 * unclaimed datagrams?
6389 		 */
6390 		mutex_exit(&connfp->connf_lock);
6391 		/*
6392 		 * Check for IPPROTO_ENCAP...
6393 		 */
6394 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6395 			/*
6396 			 * If an IPsec mblk is here on a multicast
6397 			 * tunnel (using ip_mroute stuff), check policy here,
6398 			 * THEN ship off to ip_mroute_decap().
6399 			 *
6400 			 * BTW,  If I match a configured IP-in-IP
6401 			 * tunnel, this path will not be reached, and
6402 			 * ip_mroute_decap will never be called.
6403 			 */
6404 			first_mp = ipsec_check_global_policy(first_mp, connp,
6405 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6406 			if (first_mp != NULL) {
6407 				if (mctl_present)
6408 					freeb(first_mp);
6409 				ip_mroute_decap(q, mp, ill);
6410 			} /* Else we already freed everything! */
6411 		} else {
6412 			/*
6413 			 * Otherwise send an ICMP protocol unreachable.
6414 			 */
6415 			if (ip_fanout_send_icmp(q, first_mp, flags,
6416 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6417 			    mctl_present, zoneid, ipst)) {
6418 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6419 			}
6420 		}
6421 		return;
6422 	}
6423 	CONN_INC_REF(connp);
6424 	first_connp = connp;
6425 
6426 	/*
6427 	 * Only send message to one tunnel driver by immediately
6428 	 * terminating the loop.
6429 	 */
6430 	connp = one_only ? NULL : connp->conn_next;
6431 
6432 	for (;;) {
6433 		while (connp != NULL) {
6434 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6435 			    flags, zoneid) &&
6436 			    (!is_system_labeled() ||
6437 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6438 			    shared_addr, connp)))
6439 				break;
6440 			connp = connp->conn_next;
6441 		}
6442 
6443 		/*
6444 		 * Copy the packet.
6445 		 */
6446 		if (connp == NULL || connp->conn_upq == NULL ||
6447 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6448 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6449 			/*
6450 			 * No more interested clients or memory
6451 			 * allocation failed
6452 			 */
6453 			connp = first_connp;
6454 			break;
6455 		}
6456 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6457 		CONN_INC_REF(connp);
6458 		mutex_exit(&connfp->connf_lock);
6459 		rq = connp->conn_rq;
6460 		if (!canputnext(rq)) {
6461 			if (flags & IP_FF_RAWIP) {
6462 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6463 			} else {
6464 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6465 			}
6466 
6467 			freemsg(first_mp1);
6468 		} else {
6469 			/*
6470 			 * Don't enforce here if we're an actual tunnel -
6471 			 * let "tun" do it instead.
6472 			 */
6473 			if (!IPCL_IS_IPTUN(connp) &&
6474 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6475 			    secure)) {
6476 				first_mp1 = ipsec_check_inbound_policy
6477 				    (first_mp1, connp, ipha, NULL,
6478 				    mctl_present);
6479 			}
6480 			if (first_mp1 != NULL) {
6481 				int in_flags = 0;
6482 				/*
6483 				 * ip_fanout_proto also gets called from
6484 				 * icmp_inbound_error_fanout, in which case
6485 				 * the msg type is M_CTL.  Don't add info
6486 				 * in this case for the time being. In future
6487 				 * when there is a need for knowing the
6488 				 * inbound iface index for ICMP error msgs,
6489 				 * then this can be changed.
6490 				 */
6491 				if (connp->conn_recvif)
6492 					in_flags = IPF_RECVIF;
6493 				/*
6494 				 * The ULP may support IP_RECVPKTINFO for both
6495 				 * IP v4 and v6 so pass the appropriate argument
6496 				 * based on conn IP version.
6497 				 */
6498 				if (connp->conn_ip_recvpktinfo) {
6499 					if (connp->conn_af_isv6) {
6500 						/*
6501 						 * V6 only needs index
6502 						 */
6503 						in_flags |= IPF_RECVIF;
6504 					} else {
6505 						/*
6506 						 * V4 needs index +
6507 						 * matching address.
6508 						 */
6509 						in_flags |= IPF_RECVADDR;
6510 					}
6511 				}
6512 				if ((in_flags != 0) &&
6513 				    (mp->b_datap->db_type != M_CTL)) {
6514 					/*
6515 					 * the actual data will be
6516 					 * contained in b_cont upon
6517 					 * successful return of the
6518 					 * following call else
6519 					 * original mblk is returned
6520 					 */
6521 					ASSERT(recv_ill != NULL);
6522 					mp1 = ip_add_info(mp1, recv_ill,
6523 					    in_flags, IPCL_ZONEID(connp), ipst);
6524 				}
6525 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6526 				if (mctl_present)
6527 					freeb(first_mp1);
6528 				(connp->conn_recv)(connp, mp1, NULL);
6529 			}
6530 		}
6531 		mutex_enter(&connfp->connf_lock);
6532 		/* Follow the next pointer before releasing the conn. */
6533 		next_connp = connp->conn_next;
6534 		CONN_DEC_REF(connp);
6535 		connp = next_connp;
6536 	}
6537 
6538 	/* Last one.  Send it upstream. */
6539 	mutex_exit(&connfp->connf_lock);
6540 
6541 	/*
6542 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6543 	 * will be set to false.
6544 	 */
6545 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6546 		ill_index = ill->ill_phyint->phyint_ifindex;
6547 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6548 		if (mp == NULL) {
6549 			CONN_DEC_REF(connp);
6550 			if (mctl_present) {
6551 				freeb(first_mp);
6552 			}
6553 			return;
6554 		}
6555 	}
6556 
6557 	rq = connp->conn_rq;
6558 	if (!canputnext(rq)) {
6559 		if (flags & IP_FF_RAWIP) {
6560 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6561 		} else {
6562 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6563 		}
6564 
6565 		freemsg(first_mp);
6566 	} else {
6567 		if (IPCL_IS_IPTUN(connp)) {
6568 			/*
6569 			 * Tunneled packet.  We enforce policy in the tunnel
6570 			 * module itself.
6571 			 *
6572 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6573 			 * a policy check.
6574 			 * FIXME to use conn_recv for tun later.
6575 			 */
6576 			putnext(rq, first_mp);
6577 			CONN_DEC_REF(connp);
6578 			return;
6579 		}
6580 
6581 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6582 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6583 			    ipha, NULL, mctl_present);
6584 		}
6585 
6586 		if (first_mp != NULL) {
6587 			int in_flags = 0;
6588 
6589 			/*
6590 			 * ip_fanout_proto also gets called
6591 			 * from icmp_inbound_error_fanout, in
6592 			 * which case the msg type is M_CTL.
6593 			 * Don't add info in this case for time
6594 			 * being. In future when there is a
6595 			 * need for knowing the inbound iface
6596 			 * index for ICMP error msgs, then this
6597 			 * can be changed
6598 			 */
6599 			if (connp->conn_recvif)
6600 				in_flags = IPF_RECVIF;
6601 			if (connp->conn_ip_recvpktinfo) {
6602 				if (connp->conn_af_isv6) {
6603 					/*
6604 					 * V6 only needs index
6605 					 */
6606 					in_flags |= IPF_RECVIF;
6607 				} else {
6608 					/*
6609 					 * V4 needs index +
6610 					 * matching address.
6611 					 */
6612 					in_flags |= IPF_RECVADDR;
6613 				}
6614 			}
6615 			if ((in_flags != 0) &&
6616 			    (mp->b_datap->db_type != M_CTL)) {
6617 
6618 				/*
6619 				 * the actual data will be contained in
6620 				 * b_cont upon successful return
6621 				 * of the following call else original
6622 				 * mblk is returned
6623 				 */
6624 				ASSERT(recv_ill != NULL);
6625 				mp = ip_add_info(mp, recv_ill,
6626 				    in_flags, IPCL_ZONEID(connp), ipst);
6627 			}
6628 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6629 			(connp->conn_recv)(connp, mp, NULL);
6630 			if (mctl_present)
6631 				freeb(first_mp);
6632 		}
6633 	}
6634 	CONN_DEC_REF(connp);
6635 }
6636 
6637 /*
6638  * Fanout for TCP packets
6639  * The caller puts <fport, lport> in the ports parameter.
6640  *
6641  * IPQoS Notes
6642  * Before sending it to the client, invoke IPPF processing.
6643  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6644  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6645  * ip_policy is false.
6646  */
6647 static void
6648 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6649     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6650 {
6651 	mblk_t  *first_mp;
6652 	boolean_t secure;
6653 	uint32_t ill_index;
6654 	int	ip_hdr_len;
6655 	tcph_t	*tcph;
6656 	boolean_t syn_present = B_FALSE;
6657 	conn_t	*connp;
6658 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6659 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6660 
6661 	ASSERT(recv_ill != NULL);
6662 
6663 	first_mp = mp;
6664 	if (mctl_present) {
6665 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6666 		mp = first_mp->b_cont;
6667 		secure = ipsec_in_is_secure(first_mp);
6668 		ASSERT(mp != NULL);
6669 	} else {
6670 		secure = B_FALSE;
6671 	}
6672 
6673 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6674 
6675 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6676 	    zoneid, ipst)) == NULL) {
6677 		/*
6678 		 * No connected connection or listener. Send a
6679 		 * TH_RST via tcp_xmit_listeners_reset.
6680 		 */
6681 
6682 		/* Initiate IPPf processing, if needed. */
6683 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6684 			uint32_t ill_index;
6685 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6686 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6687 			if (first_mp == NULL)
6688 				return;
6689 		}
6690 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6691 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6692 		    zoneid));
6693 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6694 		    ipst->ips_netstack->netstack_tcp, NULL);
6695 		return;
6696 	}
6697 
6698 	/*
6699 	 * Allocate the SYN for the TCP connection here itself
6700 	 */
6701 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6702 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6703 		if (IPCL_IS_TCP(connp)) {
6704 			squeue_t *sqp;
6705 
6706 			/*
6707 			 * For fused tcp loopback, assign the eager's
6708 			 * squeue to be that of the active connect's.
6709 			 * Note that we don't check for IP_FF_LOOPBACK
6710 			 * here since this routine gets called only
6711 			 * for loopback (unlike the IPv6 counterpart).
6712 			 */
6713 			ASSERT(Q_TO_CONN(q) != NULL);
6714 			if (do_tcp_fusion &&
6715 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6716 			    !secure &&
6717 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6718 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6719 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6720 				sqp = Q_TO_CONN(q)->conn_sqp;
6721 			} else {
6722 				sqp = IP_SQUEUE_GET(lbolt);
6723 			}
6724 
6725 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6726 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6727 			syn_present = B_TRUE;
6728 		}
6729 	}
6730 
6731 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6732 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6733 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6734 		if ((flags & TH_RST) || (flags & TH_URG)) {
6735 			CONN_DEC_REF(connp);
6736 			freemsg(first_mp);
6737 			return;
6738 		}
6739 		if (flags & TH_ACK) {
6740 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6741 			    ipst->ips_netstack->netstack_tcp, connp);
6742 			CONN_DEC_REF(connp);
6743 			return;
6744 		}
6745 
6746 		CONN_DEC_REF(connp);
6747 		freemsg(first_mp);
6748 		return;
6749 	}
6750 
6751 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6752 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6753 		    NULL, mctl_present);
6754 		if (first_mp == NULL) {
6755 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6756 			CONN_DEC_REF(connp);
6757 			return;
6758 		}
6759 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6760 			ASSERT(syn_present);
6761 			if (mctl_present) {
6762 				ASSERT(first_mp != mp);
6763 				first_mp->b_datap->db_struioflag |=
6764 				    STRUIO_POLICY;
6765 			} else {
6766 				ASSERT(first_mp == mp);
6767 				mp->b_datap->db_struioflag &=
6768 				    ~STRUIO_EAGER;
6769 				mp->b_datap->db_struioflag |=
6770 				    STRUIO_POLICY;
6771 			}
6772 		} else {
6773 			/*
6774 			 * Discard first_mp early since we're dealing with a
6775 			 * fully-connected conn_t and tcp doesn't do policy in
6776 			 * this case.
6777 			 */
6778 			if (mctl_present) {
6779 				freeb(first_mp);
6780 				mctl_present = B_FALSE;
6781 			}
6782 			first_mp = mp;
6783 		}
6784 	}
6785 
6786 	/*
6787 	 * Initiate policy processing here if needed. If we get here from
6788 	 * icmp_inbound_error_fanout, ip_policy is false.
6789 	 */
6790 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6791 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6792 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6793 		if (mp == NULL) {
6794 			CONN_DEC_REF(connp);
6795 			if (mctl_present)
6796 				freeb(first_mp);
6797 			return;
6798 		} else if (mctl_present) {
6799 			ASSERT(first_mp != mp);
6800 			first_mp->b_cont = mp;
6801 		} else {
6802 			first_mp = mp;
6803 		}
6804 	}
6805 
6806 
6807 
6808 	/* Handle socket options. */
6809 	if (!syn_present &&
6810 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6811 		/* Add header */
6812 		ASSERT(recv_ill != NULL);
6813 		/*
6814 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6815 		 * IPF_RECVIF.
6816 		 */
6817 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6818 		    ipst);
6819 		if (mp == NULL) {
6820 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6821 			CONN_DEC_REF(connp);
6822 			if (mctl_present)
6823 				freeb(first_mp);
6824 			return;
6825 		} else if (mctl_present) {
6826 			/*
6827 			 * ip_add_info might return a new mp.
6828 			 */
6829 			ASSERT(first_mp != mp);
6830 			first_mp->b_cont = mp;
6831 		} else {
6832 			first_mp = mp;
6833 		}
6834 	}
6835 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6836 	if (IPCL_IS_TCP(connp)) {
6837 		/* do not drain, certain use cases can blow the stack */
6838 		squeue_enter_nodrain(connp->conn_sqp, first_mp,
6839 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6840 	} else {
6841 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
6842 		(connp->conn_recv)(connp, first_mp, NULL);
6843 		CONN_DEC_REF(connp);
6844 	}
6845 }
6846 
6847 /*
6848  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
6849  * pass it along to ESP if the SPI is non-zero.  Returns TRUE if the mblk
6850  * is not consumed.
6851  *
6852  * One of four things can happen, all of which affect the passed-in mblk:
6853  *
6854  * 1.) ICMP messages that go through here just get returned TRUE.
6855  *
6856  * 2.) The packet is stock UDP and gets its zero-SPI stripped.  Return TRUE.
6857  *
6858  * 3.) The packet is ESP-in-UDP, gets transformed into an equivalent
6859  *     ESP packet, and is passed along to ESP for consumption.  Return FALSE.
6860  *
6861  * 4.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
6862  */
6863 static boolean_t
6864 zero_spi_check(queue_t *q, mblk_t *mp, ire_t *ire, ill_t *recv_ill,
6865     ipsec_stack_t *ipss)
6866 {
6867 	int shift, plen, iph_len;
6868 	ipha_t *ipha;
6869 	udpha_t *udpha;
6870 	uint32_t *spi;
6871 	uint8_t *orptr;
6872 	boolean_t udp_pkt, free_ire;
6873 
6874 	if (DB_TYPE(mp) == M_CTL) {
6875 		/*
6876 		 * ICMP message with UDP inside.  Don't bother stripping, just
6877 		 * send it up.
6878 		 *
6879 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
6880 		 * to ignore errors set by ICMP anyway ('cause they might be
6881 		 * forged), but that's the app's decision, not ours.
6882 		 */
6883 
6884 		/* Bunch of reality checks for DEBUG kernels... */
6885 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
6886 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
6887 
6888 		return (B_TRUE);
6889 	}
6890 
6891 	ipha = (ipha_t *)mp->b_rptr;
6892 	iph_len = IPH_HDR_LENGTH(ipha);
6893 	plen = ntohs(ipha->ipha_length);
6894 
6895 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
6896 		/*
6897 		 * Most likely a keepalive for the benefit of an intervening
6898 		 * NAT.  These aren't for us, per se, so drop it.
6899 		 *
6900 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
6901 		 * byte packets (keepalives are 1-byte), but we'll drop them
6902 		 * also.
6903 		 */
6904 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6905 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
6906 		return (B_FALSE);
6907 	}
6908 
6909 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
6910 		/* might as well pull it all up - it might be ESP. */
6911 		if (!pullupmsg(mp, -1)) {
6912 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6913 			    DROPPER(ipss, ipds_esp_nomem),
6914 			    &ipss->ipsec_dropper);
6915 			return (B_FALSE);
6916 		}
6917 
6918 		ipha = (ipha_t *)mp->b_rptr;
6919 	}
6920 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
6921 	if (*spi == 0) {
6922 		/* UDP packet - remove 0-spi. */
6923 		shift = sizeof (uint32_t);
6924 	} else {
6925 		/* ESP-in-UDP packet - reduce to ESP. */
6926 		ipha->ipha_protocol = IPPROTO_ESP;
6927 		shift = sizeof (udpha_t);
6928 	}
6929 
6930 	/* Fix IP header */
6931 	ipha->ipha_length = htons(plen - shift);
6932 	ipha->ipha_hdr_checksum = 0;
6933 
6934 	orptr = mp->b_rptr;
6935 	mp->b_rptr += shift;
6936 
6937 	if (*spi == 0) {
6938 		ASSERT((uint8_t *)ipha == orptr);
6939 		udpha = (udpha_t *)(orptr + iph_len);
6940 		udpha->uha_length = htons(plen - shift - iph_len);
6941 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
6942 		udp_pkt = B_TRUE;
6943 	} else {
6944 		udp_pkt = B_FALSE;
6945 	}
6946 	ovbcopy(orptr, orptr + shift, iph_len);
6947 	if (!udp_pkt) /* Punt up for ESP processing. */ {
6948 		ipha = (ipha_t *)(orptr + shift);
6949 
6950 		free_ire = (ire == NULL);
6951 		if (free_ire) {
6952 			/* Re-acquire ire. */
6953 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
6954 			    ipss->ipsec_netstack->netstack_ip);
6955 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
6956 				if (ire != NULL)
6957 					ire_refrele(ire);
6958 				/*
6959 				 * Do a regular freemsg(), as this is an IP
6960 				 * error (no local route) not an IPsec one.
6961 				 */
6962 				freemsg(mp);
6963 			}
6964 		}
6965 
6966 		ip_proto_input(q, mp, ipha, ire, recv_ill, B_TRUE);
6967 		if (free_ire)
6968 			ire_refrele(ire);
6969 	}
6970 
6971 	return (udp_pkt);
6972 }
6973 
6974 /*
6975  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6976  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6977  * Caller is responsible for dropping references to the conn, and freeing
6978  * first_mp.
6979  *
6980  * IPQoS Notes
6981  * Before sending it to the client, invoke IPPF processing. Policy processing
6982  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6983  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6984  * ip_wput_local, ip_policy is false.
6985  */
6986 static void
6987 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
6988     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
6989     boolean_t ip_policy)
6990 {
6991 	boolean_t	mctl_present = (first_mp != NULL);
6992 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
6993 	uint32_t	ill_index;
6994 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6995 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6996 
6997 	ASSERT(ill != NULL);
6998 
6999 	if (mctl_present)
7000 		first_mp->b_cont = mp;
7001 	else
7002 		first_mp = mp;
7003 
7004 	if (CONN_UDP_FLOWCTLD(connp)) {
7005 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
7006 		freemsg(first_mp);
7007 		return;
7008 	}
7009 
7010 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
7011 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
7012 		    NULL, mctl_present);
7013 		if (first_mp == NULL) {
7014 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7015 			return;	/* Freed by ipsec_check_inbound_policy(). */
7016 		}
7017 	}
7018 	if (mctl_present)
7019 		freeb(first_mp);
7020 
7021 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
7022 	if (connp->conn_udp->udp_nat_t_endpoint) {
7023 		if (mctl_present) {
7024 			/* mctl_present *shouldn't* happen. */
7025 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
7026 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
7027 			    &ipss->ipsec_dropper);
7028 			return;
7029 		}
7030 
7031 		if (!zero_spi_check(ill->ill_rq, mp, NULL, recv_ill, ipss))
7032 			return;
7033 	}
7034 
7035 	/* Handle options. */
7036 	if (connp->conn_recvif)
7037 		in_flags = IPF_RECVIF;
7038 	/*
7039 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7040 	 * passed to ip_add_info is based on IP version of connp.
7041 	 */
7042 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7043 		if (connp->conn_af_isv6) {
7044 			/*
7045 			 * V6 only needs index
7046 			 */
7047 			in_flags |= IPF_RECVIF;
7048 		} else {
7049 			/*
7050 			 * V4 needs index + matching address.
7051 			 */
7052 			in_flags |= IPF_RECVADDR;
7053 		}
7054 	}
7055 
7056 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7057 		in_flags |= IPF_RECVSLLA;
7058 
7059 	/*
7060 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7061 	 * freed if the packet is dropped. The caller will do so.
7062 	 */
7063 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7064 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7065 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7066 		if (mp == NULL) {
7067 			return;
7068 		}
7069 	}
7070 	if ((in_flags != 0) &&
7071 	    (mp->b_datap->db_type != M_CTL)) {
7072 		/*
7073 		 * The actual data will be contained in b_cont
7074 		 * upon successful return of the following call
7075 		 * else original mblk is returned
7076 		 */
7077 		ASSERT(recv_ill != NULL);
7078 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7079 		    ipst);
7080 	}
7081 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7082 	/* Send it upstream */
7083 	(connp->conn_recv)(connp, mp, NULL);
7084 }
7085 
7086 /*
7087  * Fanout for UDP packets.
7088  * The caller puts <fport, lport> in the ports parameter.
7089  *
7090  * If SO_REUSEADDR is set all multicast and broadcast packets
7091  * will be delivered to all streams bound to the same port.
7092  *
7093  * Zones notes:
7094  * Multicast and broadcast packets will be distributed to streams in all zones.
7095  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7096  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7097  * packets. To maintain this behavior with multiple zones, the conns are grouped
7098  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7099  * each zone. If unset, all the following conns in the same zone are skipped.
7100  */
7101 static void
7102 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7103     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7104     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7105 {
7106 	uint32_t	dstport, srcport;
7107 	ipaddr_t	dst;
7108 	mblk_t		*first_mp;
7109 	boolean_t	secure;
7110 	in6_addr_t	v6src;
7111 	conn_t		*connp;
7112 	connf_t		*connfp;
7113 	conn_t		*first_connp;
7114 	conn_t		*next_connp;
7115 	mblk_t		*mp1, *first_mp1;
7116 	ipaddr_t	src;
7117 	zoneid_t	last_zoneid;
7118 	boolean_t	reuseaddr;
7119 	boolean_t	shared_addr;
7120 	ip_stack_t	*ipst;
7121 
7122 	ASSERT(recv_ill != NULL);
7123 	ipst = recv_ill->ill_ipst;
7124 
7125 	first_mp = mp;
7126 	if (mctl_present) {
7127 		mp = first_mp->b_cont;
7128 		first_mp->b_cont = NULL;
7129 		secure = ipsec_in_is_secure(first_mp);
7130 		ASSERT(mp != NULL);
7131 	} else {
7132 		first_mp = NULL;
7133 		secure = B_FALSE;
7134 	}
7135 
7136 	/* Extract ports in net byte order */
7137 	dstport = htons(ntohl(ports) & 0xFFFF);
7138 	srcport = htons(ntohl(ports) >> 16);
7139 	dst = ipha->ipha_dst;
7140 	src = ipha->ipha_src;
7141 
7142 	shared_addr = (zoneid == ALL_ZONES);
7143 	if (shared_addr) {
7144 		/*
7145 		 * No need to handle exclusive-stack zones since ALL_ZONES
7146 		 * only applies to the shared stack.
7147 		 */
7148 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7149 		if (zoneid == ALL_ZONES)
7150 			zoneid = tsol_packet_to_zoneid(mp);
7151 	}
7152 
7153 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7154 	mutex_enter(&connfp->connf_lock);
7155 	connp = connfp->connf_head;
7156 	if (!broadcast && !CLASSD(dst)) {
7157 		/*
7158 		 * Not broadcast or multicast. Send to the one (first)
7159 		 * client we find. No need to check conn_wantpacket()
7160 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7161 		 * IPv4 unicast packets.
7162 		 */
7163 		while ((connp != NULL) &&
7164 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7165 		    !IPCL_ZONE_MATCH(connp, zoneid))) {
7166 			connp = connp->conn_next;
7167 		}
7168 
7169 		if (connp == NULL || connp->conn_upq == NULL)
7170 			goto notfound;
7171 
7172 		if (is_system_labeled() &&
7173 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7174 		    connp))
7175 			goto notfound;
7176 
7177 		CONN_INC_REF(connp);
7178 		mutex_exit(&connfp->connf_lock);
7179 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7180 		    flags, recv_ill, ip_policy);
7181 		IP_STAT(ipst, ip_udp_fannorm);
7182 		CONN_DEC_REF(connp);
7183 		return;
7184 	}
7185 
7186 	/*
7187 	 * Broadcast and multicast case
7188 	 *
7189 	 * Need to check conn_wantpacket().
7190 	 * If SO_REUSEADDR has been set on the first we send the
7191 	 * packet to all clients that have joined the group and
7192 	 * match the port.
7193 	 */
7194 
7195 	while (connp != NULL) {
7196 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7197 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7198 		    (!is_system_labeled() ||
7199 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7200 		    connp)))
7201 			break;
7202 		connp = connp->conn_next;
7203 	}
7204 
7205 	if (connp == NULL || connp->conn_upq == NULL)
7206 		goto notfound;
7207 
7208 	first_connp = connp;
7209 	/*
7210 	 * When SO_REUSEADDR is not set, send the packet only to the first
7211 	 * matching connection in its zone by keeping track of the zoneid.
7212 	 */
7213 	reuseaddr = first_connp->conn_reuseaddr;
7214 	last_zoneid = first_connp->conn_zoneid;
7215 
7216 	CONN_INC_REF(connp);
7217 	connp = connp->conn_next;
7218 	for (;;) {
7219 		while (connp != NULL) {
7220 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7221 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7222 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7223 			    (!is_system_labeled() ||
7224 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7225 			    shared_addr, connp)))
7226 				break;
7227 			connp = connp->conn_next;
7228 		}
7229 		/*
7230 		 * Just copy the data part alone. The mctl part is
7231 		 * needed just for verifying policy and it is never
7232 		 * sent up.
7233 		 */
7234 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7235 		    ((mp1 = copymsg(mp)) == NULL))) {
7236 			/*
7237 			 * No more interested clients or memory
7238 			 * allocation failed
7239 			 */
7240 			connp = first_connp;
7241 			break;
7242 		}
7243 		if (connp->conn_zoneid != last_zoneid) {
7244 			/*
7245 			 * Update the zoneid so that the packet isn't sent to
7246 			 * any more conns in the same zone unless SO_REUSEADDR
7247 			 * is set.
7248 			 */
7249 			reuseaddr = connp->conn_reuseaddr;
7250 			last_zoneid = connp->conn_zoneid;
7251 		}
7252 		if (first_mp != NULL) {
7253 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7254 			    ipsec_info_type == IPSEC_IN);
7255 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7256 			    ipst->ips_netstack);
7257 			if (first_mp1 == NULL) {
7258 				freemsg(mp1);
7259 				connp = first_connp;
7260 				break;
7261 			}
7262 		} else {
7263 			first_mp1 = NULL;
7264 		}
7265 		CONN_INC_REF(connp);
7266 		mutex_exit(&connfp->connf_lock);
7267 		/*
7268 		 * IPQoS notes: We don't send the packet for policy
7269 		 * processing here, will do it for the last one (below).
7270 		 * i.e. we do it per-packet now, but if we do policy
7271 		 * processing per-conn, then we would need to do it
7272 		 * here too.
7273 		 */
7274 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7275 		    ipha, flags, recv_ill, B_FALSE);
7276 		mutex_enter(&connfp->connf_lock);
7277 		/* Follow the next pointer before releasing the conn. */
7278 		next_connp = connp->conn_next;
7279 		IP_STAT(ipst, ip_udp_fanmb);
7280 		CONN_DEC_REF(connp);
7281 		connp = next_connp;
7282 	}
7283 
7284 	/* Last one.  Send it upstream. */
7285 	mutex_exit(&connfp->connf_lock);
7286 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7287 	    recv_ill, ip_policy);
7288 	IP_STAT(ipst, ip_udp_fanmb);
7289 	CONN_DEC_REF(connp);
7290 	return;
7291 
7292 notfound:
7293 
7294 	mutex_exit(&connfp->connf_lock);
7295 	IP_STAT(ipst, ip_udp_fanothers);
7296 	/*
7297 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7298 	 * have already been matched above, since they live in the IPv4
7299 	 * fanout tables. This implies we only need to
7300 	 * check for IPv6 in6addr_any endpoints here.
7301 	 * Thus we compare using ipv6_all_zeros instead of the destination
7302 	 * address, except for the multicast group membership lookup which
7303 	 * uses the IPv4 destination.
7304 	 */
7305 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7306 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7307 	mutex_enter(&connfp->connf_lock);
7308 	connp = connfp->connf_head;
7309 	if (!broadcast && !CLASSD(dst)) {
7310 		while (connp != NULL) {
7311 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7312 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7313 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7314 			    !connp->conn_ipv6_v6only)
7315 				break;
7316 			connp = connp->conn_next;
7317 		}
7318 
7319 		if (connp != NULL && is_system_labeled() &&
7320 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7321 		    connp))
7322 			connp = NULL;
7323 
7324 		if (connp == NULL || connp->conn_upq == NULL) {
7325 			/*
7326 			 * No one bound to this port.  Is
7327 			 * there a client that wants all
7328 			 * unclaimed datagrams?
7329 			 */
7330 			mutex_exit(&connfp->connf_lock);
7331 
7332 			if (mctl_present)
7333 				first_mp->b_cont = mp;
7334 			else
7335 				first_mp = mp;
7336 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7337 			    connf_head != NULL) {
7338 				ip_fanout_proto(q, first_mp, ill, ipha,
7339 				    flags | IP_FF_RAWIP, mctl_present,
7340 				    ip_policy, recv_ill, zoneid);
7341 			} else {
7342 				if (ip_fanout_send_icmp(q, first_mp, flags,
7343 				    ICMP_DEST_UNREACHABLE,
7344 				    ICMP_PORT_UNREACHABLE,
7345 				    mctl_present, zoneid, ipst)) {
7346 					BUMP_MIB(ill->ill_ip_mib,
7347 					    udpIfStatsNoPorts);
7348 				}
7349 			}
7350 			return;
7351 		}
7352 
7353 		CONN_INC_REF(connp);
7354 		mutex_exit(&connfp->connf_lock);
7355 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7356 		    flags, recv_ill, ip_policy);
7357 		CONN_DEC_REF(connp);
7358 		return;
7359 	}
7360 	/*
7361 	 * IPv4 multicast packet being delivered to an AF_INET6
7362 	 * in6addr_any endpoint.
7363 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7364 	 * and not conn_wantpacket_v6() since any multicast membership is
7365 	 * for an IPv4-mapped multicast address.
7366 	 * The packet is sent to all clients in all zones that have joined the
7367 	 * group and match the port.
7368 	 */
7369 	while (connp != NULL) {
7370 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7371 		    srcport, v6src) &&
7372 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7373 		    (!is_system_labeled() ||
7374 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7375 		    connp)))
7376 			break;
7377 		connp = connp->conn_next;
7378 	}
7379 
7380 	if (connp == NULL || connp->conn_upq == NULL) {
7381 		/*
7382 		 * No one bound to this port.  Is
7383 		 * there a client that wants all
7384 		 * unclaimed datagrams?
7385 		 */
7386 		mutex_exit(&connfp->connf_lock);
7387 
7388 		if (mctl_present)
7389 			first_mp->b_cont = mp;
7390 		else
7391 			first_mp = mp;
7392 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7393 		    NULL) {
7394 			ip_fanout_proto(q, first_mp, ill, ipha,
7395 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7396 			    recv_ill, zoneid);
7397 		} else {
7398 			/*
7399 			 * We used to attempt to send an icmp error here, but
7400 			 * since this is known to be a multicast packet
7401 			 * and we don't send icmp errors in response to
7402 			 * multicast, just drop the packet and give up sooner.
7403 			 */
7404 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7405 			freemsg(first_mp);
7406 		}
7407 		return;
7408 	}
7409 
7410 	first_connp = connp;
7411 
7412 	CONN_INC_REF(connp);
7413 	connp = connp->conn_next;
7414 	for (;;) {
7415 		while (connp != NULL) {
7416 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7417 			    ipv6_all_zeros, srcport, v6src) &&
7418 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7419 			    (!is_system_labeled() ||
7420 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7421 			    shared_addr, connp)))
7422 				break;
7423 			connp = connp->conn_next;
7424 		}
7425 		/*
7426 		 * Just copy the data part alone. The mctl part is
7427 		 * needed just for verifying policy and it is never
7428 		 * sent up.
7429 		 */
7430 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7431 		    ((mp1 = copymsg(mp)) == NULL))) {
7432 			/*
7433 			 * No more intested clients or memory
7434 			 * allocation failed
7435 			 */
7436 			connp = first_connp;
7437 			break;
7438 		}
7439 		if (first_mp != NULL) {
7440 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7441 			    ipsec_info_type == IPSEC_IN);
7442 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7443 			    ipst->ips_netstack);
7444 			if (first_mp1 == NULL) {
7445 				freemsg(mp1);
7446 				connp = first_connp;
7447 				break;
7448 			}
7449 		} else {
7450 			first_mp1 = NULL;
7451 		}
7452 		CONN_INC_REF(connp);
7453 		mutex_exit(&connfp->connf_lock);
7454 		/*
7455 		 * IPQoS notes: We don't send the packet for policy
7456 		 * processing here, will do it for the last one (below).
7457 		 * i.e. we do it per-packet now, but if we do policy
7458 		 * processing per-conn, then we would need to do it
7459 		 * here too.
7460 		 */
7461 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7462 		    ipha, flags, recv_ill, B_FALSE);
7463 		mutex_enter(&connfp->connf_lock);
7464 		/* Follow the next pointer before releasing the conn. */
7465 		next_connp = connp->conn_next;
7466 		CONN_DEC_REF(connp);
7467 		connp = next_connp;
7468 	}
7469 
7470 	/* Last one.  Send it upstream. */
7471 	mutex_exit(&connfp->connf_lock);
7472 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7473 	    recv_ill, ip_policy);
7474 	CONN_DEC_REF(connp);
7475 }
7476 
7477 /*
7478  * Complete the ip_wput header so that it
7479  * is possible to generate ICMP
7480  * errors.
7481  */
7482 int
7483 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7484 {
7485 	ire_t *ire;
7486 
7487 	if (ipha->ipha_src == INADDR_ANY) {
7488 		ire = ire_lookup_local(zoneid, ipst);
7489 		if (ire == NULL) {
7490 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7491 			return (1);
7492 		}
7493 		ipha->ipha_src = ire->ire_addr;
7494 		ire_refrele(ire);
7495 	}
7496 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7497 	ipha->ipha_hdr_checksum = 0;
7498 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7499 	return (0);
7500 }
7501 
7502 /*
7503  * Nobody should be sending
7504  * packets up this stream
7505  */
7506 static void
7507 ip_lrput(queue_t *q, mblk_t *mp)
7508 {
7509 	mblk_t *mp1;
7510 
7511 	switch (mp->b_datap->db_type) {
7512 	case M_FLUSH:
7513 		/* Turn around */
7514 		if (*mp->b_rptr & FLUSHW) {
7515 			*mp->b_rptr &= ~FLUSHR;
7516 			qreply(q, mp);
7517 			return;
7518 		}
7519 		break;
7520 	}
7521 	/* Could receive messages that passed through ar_rput */
7522 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7523 		mp1->b_prev = mp1->b_next = NULL;
7524 	freemsg(mp);
7525 }
7526 
7527 /* Nobody should be sending packets down this stream */
7528 /* ARGSUSED */
7529 void
7530 ip_lwput(queue_t *q, mblk_t *mp)
7531 {
7532 	freemsg(mp);
7533 }
7534 
7535 /*
7536  * Move the first hop in any source route to ipha_dst and remove that part of
7537  * the source route.  Called by other protocols.  Errors in option formatting
7538  * are ignored - will be handled by ip_wput_options Return the final
7539  * destination (either ipha_dst or the last entry in a source route.)
7540  */
7541 ipaddr_t
7542 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7543 {
7544 	ipoptp_t	opts;
7545 	uchar_t		*opt;
7546 	uint8_t		optval;
7547 	uint8_t		optlen;
7548 	ipaddr_t	dst;
7549 	int		i;
7550 	ire_t		*ire;
7551 	ip_stack_t	*ipst = ns->netstack_ip;
7552 
7553 	ip2dbg(("ip_massage_options\n"));
7554 	dst = ipha->ipha_dst;
7555 	for (optval = ipoptp_first(&opts, ipha);
7556 	    optval != IPOPT_EOL;
7557 	    optval = ipoptp_next(&opts)) {
7558 		opt = opts.ipoptp_cur;
7559 		switch (optval) {
7560 			uint8_t off;
7561 		case IPOPT_SSRR:
7562 		case IPOPT_LSRR:
7563 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7564 				ip1dbg(("ip_massage_options: bad src route\n"));
7565 				break;
7566 			}
7567 			optlen = opts.ipoptp_len;
7568 			off = opt[IPOPT_OFFSET];
7569 			off--;
7570 		redo_srr:
7571 			if (optlen < IP_ADDR_LEN ||
7572 			    off > optlen - IP_ADDR_LEN) {
7573 				/* End of source route */
7574 				ip1dbg(("ip_massage_options: end of SR\n"));
7575 				break;
7576 			}
7577 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7578 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7579 			    ntohl(dst)));
7580 			/*
7581 			 * Check if our address is present more than
7582 			 * once as consecutive hops in source route.
7583 			 * XXX verify per-interface ip_forwarding
7584 			 * for source route?
7585 			 */
7586 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7587 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7588 			if (ire != NULL) {
7589 				ire_refrele(ire);
7590 				off += IP_ADDR_LEN;
7591 				goto redo_srr;
7592 			}
7593 			if (dst == htonl(INADDR_LOOPBACK)) {
7594 				ip1dbg(("ip_massage_options: loopback addr in "
7595 				    "source route!\n"));
7596 				break;
7597 			}
7598 			/*
7599 			 * Update ipha_dst to be the first hop and remove the
7600 			 * first hop from the source route (by overwriting
7601 			 * part of the option with NOP options).
7602 			 */
7603 			ipha->ipha_dst = dst;
7604 			/* Put the last entry in dst */
7605 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7606 			    3;
7607 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7608 
7609 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7610 			    ntohl(dst)));
7611 			/* Move down and overwrite */
7612 			opt[IP_ADDR_LEN] = opt[0];
7613 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7614 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7615 			for (i = 0; i < IP_ADDR_LEN; i++)
7616 				opt[i] = IPOPT_NOP;
7617 			break;
7618 		}
7619 	}
7620 	return (dst);
7621 }
7622 
7623 /*
7624  * Return the network mask
7625  * associated with the specified address.
7626  */
7627 ipaddr_t
7628 ip_net_mask(ipaddr_t addr)
7629 {
7630 	uchar_t	*up = (uchar_t *)&addr;
7631 	ipaddr_t mask = 0;
7632 	uchar_t	*maskp = (uchar_t *)&mask;
7633 
7634 #if defined(__i386) || defined(__amd64)
7635 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7636 #endif
7637 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7638 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7639 #endif
7640 	if (CLASSD(addr)) {
7641 		maskp[0] = 0xF0;
7642 		return (mask);
7643 	}
7644 	if (addr == 0)
7645 		return (0);
7646 	maskp[0] = 0xFF;
7647 	if ((up[0] & 0x80) == 0)
7648 		return (mask);
7649 
7650 	maskp[1] = 0xFF;
7651 	if ((up[0] & 0xC0) == 0x80)
7652 		return (mask);
7653 
7654 	maskp[2] = 0xFF;
7655 	if ((up[0] & 0xE0) == 0xC0)
7656 		return (mask);
7657 
7658 	/* Must be experimental or multicast, indicate as much */
7659 	return ((ipaddr_t)0);
7660 }
7661 
7662 /*
7663  * Select an ill for the packet by considering load spreading across
7664  * a different ill in the group if dst_ill is part of some group.
7665  */
7666 ill_t *
7667 ip_newroute_get_dst_ill(ill_t *dst_ill)
7668 {
7669 	ill_t *ill;
7670 
7671 	/*
7672 	 * We schedule irrespective of whether the source address is
7673 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7674 	 */
7675 	ill = illgrp_scheduler(dst_ill);
7676 	if (ill == NULL)
7677 		return (NULL);
7678 
7679 	/*
7680 	 * For groups with names ip_sioctl_groupname ensures that all
7681 	 * ills are of same type. For groups without names, ifgrp_insert
7682 	 * ensures this.
7683 	 */
7684 	ASSERT(dst_ill->ill_type == ill->ill_type);
7685 
7686 	return (ill);
7687 }
7688 
7689 /*
7690  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7691  */
7692 ill_t *
7693 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6,
7694     ip_stack_t *ipst)
7695 {
7696 	ill_t *ret_ill;
7697 
7698 	ASSERT(ifindex != 0);
7699 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7700 	    ipst);
7701 	if (ret_ill == NULL ||
7702 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7703 		if (isv6) {
7704 			if (ill != NULL) {
7705 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7706 			} else {
7707 				BUMP_MIB(&ipst->ips_ip6_mib,
7708 				    ipIfStatsOutDiscards);
7709 			}
7710 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7711 			    "bad ifindex %d.\n", ifindex));
7712 		} else {
7713 			if (ill != NULL) {
7714 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7715 			} else {
7716 				BUMP_MIB(&ipst->ips_ip_mib,
7717 				    ipIfStatsOutDiscards);
7718 			}
7719 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7720 			    "bad ifindex %d.\n", ifindex));
7721 		}
7722 		if (ret_ill != NULL)
7723 			ill_refrele(ret_ill);
7724 		freemsg(first_mp);
7725 		return (NULL);
7726 	}
7727 
7728 	return (ret_ill);
7729 }
7730 
7731 /*
7732  * IPv4 -
7733  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7734  * out a packet to a destination address for which we do not have specific
7735  * (or sufficient) routing information.
7736  *
7737  * NOTE : These are the scopes of some of the variables that point at IRE,
7738  *	  which needs to be followed while making any future modifications
7739  *	  to avoid memory leaks.
7740  *
7741  *	- ire and sire are the entries looked up initially by
7742  *	  ire_ftable_lookup.
7743  *	- ipif_ire is used to hold the interface ire associated with
7744  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7745  *	  it before branching out to error paths.
7746  *	- save_ire is initialized before ire_create, so that ire returned
7747  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7748  *	  before breaking out of the switch.
7749  *
7750  *	Thus on failures, we have to REFRELE only ire and sire, if they
7751  *	are not NULL.
7752  */
7753 void
7754 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7755     zoneid_t zoneid, ip_stack_t *ipst)
7756 {
7757 	areq_t	*areq;
7758 	ipaddr_t gw = 0;
7759 	ire_t	*ire = NULL;
7760 	mblk_t	*res_mp;
7761 	ipaddr_t *addrp;
7762 	ipaddr_t nexthop_addr;
7763 	ipif_t  *src_ipif = NULL;
7764 	ill_t	*dst_ill = NULL;
7765 	ipha_t  *ipha;
7766 	ire_t	*sire = NULL;
7767 	mblk_t	*first_mp;
7768 	ire_t	*save_ire;
7769 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7770 	ushort_t ire_marks = 0;
7771 	boolean_t mctl_present;
7772 	ipsec_out_t *io;
7773 	mblk_t	*saved_mp;
7774 	ire_t	*first_sire = NULL;
7775 	mblk_t	*copy_mp = NULL;
7776 	mblk_t	*xmit_mp = NULL;
7777 	ipaddr_t save_dst;
7778 	uint32_t multirt_flags =
7779 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7780 	boolean_t multirt_is_resolvable;
7781 	boolean_t multirt_resolve_next;
7782 	boolean_t do_attach_ill = B_FALSE;
7783 	boolean_t ip_nexthop = B_FALSE;
7784 	tsol_ire_gw_secattr_t *attrp = NULL;
7785 	tsol_gcgrp_t *gcgrp = NULL;
7786 	tsol_gcgrp_addr_t ga;
7787 
7788 	if (ip_debug > 2) {
7789 		/* ip1dbg */
7790 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7791 	}
7792 
7793 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7794 	if (mctl_present) {
7795 		io = (ipsec_out_t *)first_mp->b_rptr;
7796 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7797 		ASSERT(zoneid == io->ipsec_out_zoneid);
7798 		ASSERT(zoneid != ALL_ZONES);
7799 	}
7800 
7801 	ipha = (ipha_t *)mp->b_rptr;
7802 
7803 	/* All multicast lookups come through ip_newroute_ipif() */
7804 	if (CLASSD(dst)) {
7805 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7806 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7807 		freemsg(first_mp);
7808 		return;
7809 	}
7810 
7811 	if (mctl_present && io->ipsec_out_attach_if) {
7812 		/* ip_grab_attach_ill returns a held ill */
7813 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7814 		    io->ipsec_out_ill_index, B_FALSE, ipst);
7815 
7816 		/* Failure case frees things for us. */
7817 		if (attach_ill == NULL)
7818 			return;
7819 
7820 		/*
7821 		 * Check if we need an ire that will not be
7822 		 * looked up by anybody else i.e. HIDDEN.
7823 		 */
7824 		if (ill_is_probeonly(attach_ill))
7825 			ire_marks = IRE_MARK_HIDDEN;
7826 	}
7827 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7828 		ip_nexthop = B_TRUE;
7829 		nexthop_addr = io->ipsec_out_nexthop_addr;
7830 	}
7831 	/*
7832 	 * If this IRE is created for forwarding or it is not for
7833 	 * traffic for congestion controlled protocols, mark it as temporary.
7834 	 */
7835 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7836 		ire_marks |= IRE_MARK_TEMPORARY;
7837 
7838 	/*
7839 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7840 	 * chain until it gets the most specific information available.
7841 	 * For example, we know that there is no IRE_CACHE for this dest,
7842 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7843 	 * ire_ftable_lookup will look up the gateway, etc.
7844 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7845 	 * to the destination, of equal netmask length in the forward table,
7846 	 * will be recursively explored. If no information is available
7847 	 * for the final gateway of that route, we force the returned ire
7848 	 * to be equal to sire using MATCH_IRE_PARENT.
7849 	 * At least, in this case we have a starting point (in the buckets)
7850 	 * to look for other routes to the destination in the forward table.
7851 	 * This is actually used only for multirouting, where a list
7852 	 * of routes has to be processed in sequence.
7853 	 *
7854 	 * In the process of coming up with the most specific information,
7855 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7856 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7857 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7858 	 * Two caveats when handling incomplete ire's in ip_newroute:
7859 	 * - we should be careful when accessing its ire_nce (specifically
7860 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7861 	 * - not all legacy code path callers are prepared to handle
7862 	 *   incomplete ire's, so we should not create/add incomplete
7863 	 *   ire_cache entries here. (See discussion about temporary solution
7864 	 *   further below).
7865 	 *
7866 	 * In order to minimize packet dropping, and to preserve existing
7867 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7868 	 * gateway, and instead use the IF_RESOLVER ire to send out
7869 	 * another request to ARP (this is achieved by passing the
7870 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7871 	 * arp response comes back in ip_wput_nondata, we will create
7872 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7873 	 *
7874 	 * Note that this is a temporary solution; the correct solution is
7875 	 * to create an incomplete  per-dst ire_cache entry, and send the
7876 	 * packet out when the gw's nce is resolved. In order to achieve this,
7877 	 * all packet processing must have been completed prior to calling
7878 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7879 	 * to be modified to accomodate this solution.
7880 	 */
7881 	if (ip_nexthop) {
7882 		/*
7883 		 * The first time we come here, we look for an IRE_INTERFACE
7884 		 * entry for the specified nexthop, set the dst to be the
7885 		 * nexthop address and create an IRE_CACHE entry for the
7886 		 * nexthop. The next time around, we are able to find an
7887 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7888 		 * nexthop address and create an IRE_CACHE entry for the
7889 		 * destination address via the specified nexthop.
7890 		 */
7891 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7892 		    MBLK_GETLABEL(mp), ipst);
7893 		if (ire != NULL) {
7894 			gw = nexthop_addr;
7895 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7896 		} else {
7897 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7898 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7899 			    MBLK_GETLABEL(mp),
7900 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
7901 			    ipst);
7902 			if (ire != NULL) {
7903 				dst = nexthop_addr;
7904 			}
7905 		}
7906 	} else if (attach_ill == NULL) {
7907 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7908 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
7909 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7910 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7911 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
7912 		    ipst);
7913 	} else {
7914 		/*
7915 		 * attach_ill is set only for communicating with
7916 		 * on-link hosts. So, don't look for DEFAULT.
7917 		 */
7918 		ipif_t	*attach_ipif;
7919 
7920 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
7921 		if (attach_ipif == NULL) {
7922 			ill_refrele(attach_ill);
7923 			goto icmp_err_ret;
7924 		}
7925 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
7926 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
7927 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
7928 		    MATCH_IRE_SECATTR, ipst);
7929 		ipif_refrele(attach_ipif);
7930 	}
7931 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7932 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7933 
7934 	/*
7935 	 * This loop is run only once in most cases.
7936 	 * We loop to resolve further routes only when the destination
7937 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7938 	 */
7939 	do {
7940 		/* Clear the previous iteration's values */
7941 		if (src_ipif != NULL) {
7942 			ipif_refrele(src_ipif);
7943 			src_ipif = NULL;
7944 		}
7945 		if (dst_ill != NULL) {
7946 			ill_refrele(dst_ill);
7947 			dst_ill = NULL;
7948 		}
7949 
7950 		multirt_resolve_next = B_FALSE;
7951 		/*
7952 		 * We check if packets have to be multirouted.
7953 		 * In this case, given the current <ire, sire> couple,
7954 		 * we look for the next suitable <ire, sire>.
7955 		 * This check is done in ire_multirt_lookup(),
7956 		 * which applies various criteria to find the next route
7957 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7958 		 * unchanged if it detects it has not been tried yet.
7959 		 */
7960 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7961 			ip3dbg(("ip_newroute: starting next_resolution "
7962 			    "with first_mp %p, tag %d\n",
7963 			    (void *)first_mp,
7964 			    MULTIRT_DEBUG_TAGGED(first_mp)));
7965 
7966 			ASSERT(sire != NULL);
7967 			multirt_is_resolvable =
7968 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
7969 			    MBLK_GETLABEL(mp), ipst);
7970 
7971 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
7972 			    "ire %p, sire %p\n",
7973 			    multirt_is_resolvable,
7974 			    (void *)ire, (void *)sire));
7975 
7976 			if (!multirt_is_resolvable) {
7977 				/*
7978 				 * No more multirt route to resolve; give up
7979 				 * (all routes resolved or no more
7980 				 * resolvable routes).
7981 				 */
7982 				if (ire != NULL) {
7983 					ire_refrele(ire);
7984 					ire = NULL;
7985 				}
7986 			} else {
7987 				ASSERT(sire != NULL);
7988 				ASSERT(ire != NULL);
7989 				/*
7990 				 * We simply use first_sire as a flag that
7991 				 * indicates if a resolvable multirt route
7992 				 * has already been found.
7993 				 * If it is not the case, we may have to send
7994 				 * an ICMP error to report that the
7995 				 * destination is unreachable.
7996 				 * We do not IRE_REFHOLD first_sire.
7997 				 */
7998 				if (first_sire == NULL) {
7999 					first_sire = sire;
8000 				}
8001 			}
8002 		}
8003 		if (ire == NULL) {
8004 			if (ip_debug > 3) {
8005 				/* ip2dbg */
8006 				pr_addr_dbg("ip_newroute: "
8007 				    "can't resolve %s\n", AF_INET, &dst);
8008 			}
8009 			ip3dbg(("ip_newroute: "
8010 			    "ire %p, sire %p, first_sire %p\n",
8011 			    (void *)ire, (void *)sire, (void *)first_sire));
8012 
8013 			if (sire != NULL) {
8014 				ire_refrele(sire);
8015 				sire = NULL;
8016 			}
8017 
8018 			if (first_sire != NULL) {
8019 				/*
8020 				 * At least one multirt route has been found
8021 				 * in the same call to ip_newroute();
8022 				 * there is no need to report an ICMP error.
8023 				 * first_sire was not IRE_REFHOLDed.
8024 				 */
8025 				MULTIRT_DEBUG_UNTAG(first_mp);
8026 				freemsg(first_mp);
8027 				return;
8028 			}
8029 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8030 			    RTA_DST, ipst);
8031 			if (attach_ill != NULL)
8032 				ill_refrele(attach_ill);
8033 			goto icmp_err_ret;
8034 		}
8035 
8036 		/*
8037 		 * Verify that the returned IRE does not have either
8038 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8039 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8040 		 */
8041 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8042 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8043 			if (attach_ill != NULL)
8044 				ill_refrele(attach_ill);
8045 			goto icmp_err_ret;
8046 		}
8047 		/*
8048 		 * Increment the ire_ob_pkt_count field for ire if it is an
8049 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8050 		 * increment the same for the parent IRE, sire, if it is some
8051 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8052 		 */
8053 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8054 			UPDATE_OB_PKT_COUNT(ire);
8055 			ire->ire_last_used_time = lbolt;
8056 		}
8057 
8058 		if (sire != NULL) {
8059 			gw = sire->ire_gateway_addr;
8060 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8061 			    IRE_INTERFACE)) == 0);
8062 			UPDATE_OB_PKT_COUNT(sire);
8063 			sire->ire_last_used_time = lbolt;
8064 		}
8065 		/*
8066 		 * We have a route to reach the destination.
8067 		 *
8068 		 * 1) If the interface is part of ill group, try to get a new
8069 		 *    ill taking load spreading into account.
8070 		 *
8071 		 * 2) After selecting the ill, get a source address that
8072 		 *    might create good inbound load spreading.
8073 		 *    ipif_select_source does this for us.
8074 		 *
8075 		 * If the application specified the ill (ifindex), we still
8076 		 * load spread. Only if the packets needs to go out
8077 		 * specifically on a given ill e.g. binding to
8078 		 * IPIF_NOFAILOVER address, then we don't try to use a
8079 		 * different ill for load spreading.
8080 		 */
8081 		if (attach_ill == NULL) {
8082 			/*
8083 			 * Don't perform outbound load spreading in the
8084 			 * case of an RTF_MULTIRT route, as we actually
8085 			 * typically want to replicate outgoing packets
8086 			 * through particular interfaces.
8087 			 */
8088 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8089 				dst_ill = ire->ire_ipif->ipif_ill;
8090 				/* for uniformity */
8091 				ill_refhold(dst_ill);
8092 			} else {
8093 				/*
8094 				 * If we are here trying to create an IRE_CACHE
8095 				 * for an offlink destination and have the
8096 				 * IRE_CACHE for the next hop and the latter is
8097 				 * using virtual IP source address selection i.e
8098 				 * it's ire->ire_ipif is pointing to a virtual
8099 				 * network interface (vni) then
8100 				 * ip_newroute_get_dst_ll() will return the vni
8101 				 * interface as the dst_ill. Since the vni is
8102 				 * virtual i.e not associated with any physical
8103 				 * interface, it cannot be the dst_ill, hence
8104 				 * in such a case call ip_newroute_get_dst_ll()
8105 				 * with the stq_ill instead of the ire_ipif ILL.
8106 				 * The function returns a refheld ill.
8107 				 */
8108 				if ((ire->ire_type == IRE_CACHE) &&
8109 				    IS_VNI(ire->ire_ipif->ipif_ill))
8110 					dst_ill = ip_newroute_get_dst_ill(
8111 					    ire->ire_stq->q_ptr);
8112 				else
8113 					dst_ill = ip_newroute_get_dst_ill(
8114 					    ire->ire_ipif->ipif_ill);
8115 			}
8116 			if (dst_ill == NULL) {
8117 				if (ip_debug > 2) {
8118 					pr_addr_dbg("ip_newroute: "
8119 					    "no dst ill for dst"
8120 					    " %s\n", AF_INET, &dst);
8121 				}
8122 				goto icmp_err_ret;
8123 			}
8124 		} else {
8125 			dst_ill = ire->ire_ipif->ipif_ill;
8126 			/* for uniformity */
8127 			ill_refhold(dst_ill);
8128 			/*
8129 			 * We should have found a route matching ill as we
8130 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
8131 			 * Rather than asserting, when there is a mismatch,
8132 			 * we just drop the packet.
8133 			 */
8134 			if (dst_ill != attach_ill) {
8135 				ip0dbg(("ip_newroute: Packet dropped as "
8136 				    "IPIF_NOFAILOVER ill is %s, "
8137 				    "ire->ire_ipif->ipif_ill is %s\n",
8138 				    attach_ill->ill_name,
8139 				    dst_ill->ill_name));
8140 				ill_refrele(attach_ill);
8141 				goto icmp_err_ret;
8142 			}
8143 		}
8144 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
8145 		if (attach_ill != NULL) {
8146 			ill_refrele(attach_ill);
8147 			attach_ill = NULL;
8148 			do_attach_ill = B_TRUE;
8149 		}
8150 		ASSERT(dst_ill != NULL);
8151 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8152 
8153 		/*
8154 		 * Pick the best source address from dst_ill.
8155 		 *
8156 		 * 1) If it is part of a multipathing group, we would
8157 		 *    like to spread the inbound packets across different
8158 		 *    interfaces. ipif_select_source picks a random source
8159 		 *    across the different ills in the group.
8160 		 *
8161 		 * 2) If it is not part of a multipathing group, we try
8162 		 *    to pick the source address from the destination
8163 		 *    route. Clustering assumes that when we have multiple
8164 		 *    prefixes hosted on an interface, the prefix of the
8165 		 *    source address matches the prefix of the destination
8166 		 *    route. We do this only if the address is not
8167 		 *    DEPRECATED.
8168 		 *
8169 		 * 3) If the conn is in a different zone than the ire, we
8170 		 *    need to pick a source address from the right zone.
8171 		 *
8172 		 * NOTE : If we hit case (1) above, the prefix of the source
8173 		 *	  address picked may not match the prefix of the
8174 		 *	  destination routes prefix as ipif_select_source
8175 		 *	  does not look at "dst" while picking a source
8176 		 *	  address.
8177 		 *	  If we want the same behavior as (2), we will need
8178 		 *	  to change the behavior of ipif_select_source.
8179 		 */
8180 		ASSERT(src_ipif == NULL);
8181 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8182 			/*
8183 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8184 			 * Check that the ipif matching the requested source
8185 			 * address still exists.
8186 			 */
8187 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8188 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8189 		}
8190 		if (src_ipif == NULL) {
8191 			ire_marks |= IRE_MARK_USESRC_CHECK;
8192 			if ((dst_ill->ill_group != NULL) ||
8193 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8194 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8195 			    ire->ire_zoneid != ALL_ZONES) ||
8196 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8197 				/*
8198 				 * If the destination is reachable via a
8199 				 * given gateway, the selected source address
8200 				 * should be in the same subnet as the gateway.
8201 				 * Otherwise, the destination is not reachable.
8202 				 *
8203 				 * If there are no interfaces on the same subnet
8204 				 * as the destination, ipif_select_source gives
8205 				 * first non-deprecated interface which might be
8206 				 * on a different subnet than the gateway.
8207 				 * This is not desirable. Hence pass the dst_ire
8208 				 * source address to ipif_select_source.
8209 				 * It is sure that the destination is reachable
8210 				 * with the dst_ire source address subnet.
8211 				 * So passing dst_ire source address to
8212 				 * ipif_select_source will make sure that the
8213 				 * selected source will be on the same subnet
8214 				 * as dst_ire source address.
8215 				 */
8216 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8217 				src_ipif = ipif_select_source(dst_ill, saddr,
8218 				    zoneid);
8219 				if (src_ipif == NULL) {
8220 					if (ip_debug > 2) {
8221 						pr_addr_dbg("ip_newroute: "
8222 						    "no src for dst %s ",
8223 						    AF_INET, &dst);
8224 						printf("through interface %s\n",
8225 						    dst_ill->ill_name);
8226 					}
8227 					goto icmp_err_ret;
8228 				}
8229 			} else {
8230 				src_ipif = ire->ire_ipif;
8231 				ASSERT(src_ipif != NULL);
8232 				/* hold src_ipif for uniformity */
8233 				ipif_refhold(src_ipif);
8234 			}
8235 		}
8236 
8237 		/*
8238 		 * Assign a source address while we have the conn.
8239 		 * We can't have ip_wput_ire pick a source address when the
8240 		 * packet returns from arp since we need to look at
8241 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8242 		 * going through arp.
8243 		 *
8244 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8245 		 *	  it uses ip6i to store this information.
8246 		 */
8247 		if (ipha->ipha_src == INADDR_ANY &&
8248 		    (connp == NULL || !connp->conn_unspec_src)) {
8249 			ipha->ipha_src = src_ipif->ipif_src_addr;
8250 		}
8251 		if (ip_debug > 3) {
8252 			/* ip2dbg */
8253 			pr_addr_dbg("ip_newroute: first hop %s\n",
8254 			    AF_INET, &gw);
8255 		}
8256 		ip2dbg(("\tire type %s (%d)\n",
8257 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8258 
8259 		/*
8260 		 * The TTL of multirouted packets is bounded by the
8261 		 * ip_multirt_ttl ndd variable.
8262 		 */
8263 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8264 			/* Force TTL of multirouted packets */
8265 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8266 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8267 				ip2dbg(("ip_newroute: forcing multirt TTL "
8268 				    "to %d (was %d), dst 0x%08x\n",
8269 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8270 				    ntohl(sire->ire_addr)));
8271 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8272 			}
8273 		}
8274 		/*
8275 		 * At this point in ip_newroute(), ire is either the
8276 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8277 		 * destination or an IRE_INTERFACE type that should be used
8278 		 * to resolve an on-subnet destination or an on-subnet
8279 		 * next-hop gateway.
8280 		 *
8281 		 * In the IRE_CACHE case, we have the following :
8282 		 *
8283 		 * 1) src_ipif - used for getting a source address.
8284 		 *
8285 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8286 		 *    means packets using this IRE_CACHE will go out on
8287 		 *    dst_ill.
8288 		 *
8289 		 * 3) The IRE sire will point to the prefix that is the
8290 		 *    longest  matching route for the destination. These
8291 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8292 		 *
8293 		 *    The newly created IRE_CACHE entry for the off-subnet
8294 		 *    destination is tied to both the prefix route and the
8295 		 *    interface route used to resolve the next-hop gateway
8296 		 *    via the ire_phandle and ire_ihandle fields,
8297 		 *    respectively.
8298 		 *
8299 		 * In the IRE_INTERFACE case, we have the following :
8300 		 *
8301 		 * 1) src_ipif - used for getting a source address.
8302 		 *
8303 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8304 		 *    means packets using the IRE_CACHE that we will build
8305 		 *    here will go out on dst_ill.
8306 		 *
8307 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8308 		 *    to be created will only be tied to the IRE_INTERFACE
8309 		 *    that was derived from the ire_ihandle field.
8310 		 *
8311 		 *    If sire is non-NULL, it means the destination is
8312 		 *    off-link and we will first create the IRE_CACHE for the
8313 		 *    gateway. Next time through ip_newroute, we will create
8314 		 *    the IRE_CACHE for the final destination as described
8315 		 *    above.
8316 		 *
8317 		 * In both cases, after the current resolution has been
8318 		 * completed (or possibly initialised, in the IRE_INTERFACE
8319 		 * case), the loop may be re-entered to attempt the resolution
8320 		 * of another RTF_MULTIRT route.
8321 		 *
8322 		 * When an IRE_CACHE entry for the off-subnet destination is
8323 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8324 		 * for further processing in emission loops.
8325 		 */
8326 		save_ire = ire;
8327 		switch (ire->ire_type) {
8328 		case IRE_CACHE: {
8329 			ire_t	*ipif_ire;
8330 
8331 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8332 			if (gw == 0)
8333 				gw = ire->ire_gateway_addr;
8334 			/*
8335 			 * We need 3 ire's to create a new cache ire for an
8336 			 * off-link destination from the cache ire of the
8337 			 * gateway.
8338 			 *
8339 			 *	1. The prefix ire 'sire' (Note that this does
8340 			 *	   not apply to the conn_nexthop_set case)
8341 			 *	2. The cache ire of the gateway 'ire'
8342 			 *	3. The interface ire 'ipif_ire'
8343 			 *
8344 			 * We have (1) and (2). We lookup (3) below.
8345 			 *
8346 			 * If there is no interface route to the gateway,
8347 			 * it is a race condition, where we found the cache
8348 			 * but the interface route has been deleted.
8349 			 */
8350 			if (ip_nexthop) {
8351 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8352 			} else {
8353 				ipif_ire =
8354 				    ire_ihandle_lookup_offlink(ire, sire);
8355 			}
8356 			if (ipif_ire == NULL) {
8357 				ip1dbg(("ip_newroute: "
8358 				    "ire_ihandle_lookup_offlink failed\n"));
8359 				goto icmp_err_ret;
8360 			}
8361 
8362 			/*
8363 			 * Check cached gateway IRE for any security
8364 			 * attributes; if found, associate the gateway
8365 			 * credentials group to the destination IRE.
8366 			 */
8367 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8368 				mutex_enter(&attrp->igsa_lock);
8369 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8370 					GCGRP_REFHOLD(gcgrp);
8371 				mutex_exit(&attrp->igsa_lock);
8372 			}
8373 
8374 			/*
8375 			 * XXX For the source of the resolver mp,
8376 			 * we are using the same DL_UNITDATA_REQ
8377 			 * (from save_ire->ire_nce->nce_res_mp)
8378 			 * though the save_ire is not pointing at the same ill.
8379 			 * This is incorrect. We need to send it up to the
8380 			 * resolver to get the right res_mp. For ethernets
8381 			 * this may be okay (ill_type == DL_ETHER).
8382 			 */
8383 
8384 			ire = ire_create(
8385 			    (uchar_t *)&dst,		/* dest address */
8386 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8387 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8388 			    (uchar_t *)&gw,		/* gateway address */
8389 			    &save_ire->ire_max_frag,
8390 			    save_ire->ire_nce,		/* src nce */
8391 			    dst_ill->ill_rq,		/* recv-from queue */
8392 			    dst_ill->ill_wq,		/* send-to queue */
8393 			    IRE_CACHE,			/* IRE type */
8394 			    src_ipif,
8395 			    (sire != NULL) ?
8396 			    sire->ire_mask : 0, 	/* Parent mask */
8397 			    (sire != NULL) ?
8398 			    sire->ire_phandle : 0,	/* Parent handle */
8399 			    ipif_ire->ire_ihandle,	/* Interface handle */
8400 			    (sire != NULL) ? (sire->ire_flags &
8401 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8402 			    (sire != NULL) ?
8403 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8404 			    NULL,
8405 			    gcgrp,
8406 			    ipst);
8407 
8408 			if (ire == NULL) {
8409 				if (gcgrp != NULL) {
8410 					GCGRP_REFRELE(gcgrp);
8411 					gcgrp = NULL;
8412 				}
8413 				ire_refrele(ipif_ire);
8414 				ire_refrele(save_ire);
8415 				break;
8416 			}
8417 
8418 			/* reference now held by IRE */
8419 			gcgrp = NULL;
8420 
8421 			ire->ire_marks |= ire_marks;
8422 
8423 			/*
8424 			 * Prevent sire and ipif_ire from getting deleted.
8425 			 * The newly created ire is tied to both of them via
8426 			 * the phandle and ihandle respectively.
8427 			 */
8428 			if (sire != NULL) {
8429 				IRB_REFHOLD(sire->ire_bucket);
8430 				/* Has it been removed already ? */
8431 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8432 					IRB_REFRELE(sire->ire_bucket);
8433 					ire_refrele(ipif_ire);
8434 					ire_refrele(save_ire);
8435 					break;
8436 				}
8437 			}
8438 
8439 			IRB_REFHOLD(ipif_ire->ire_bucket);
8440 			/* Has it been removed already ? */
8441 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8442 				IRB_REFRELE(ipif_ire->ire_bucket);
8443 				if (sire != NULL)
8444 					IRB_REFRELE(sire->ire_bucket);
8445 				ire_refrele(ipif_ire);
8446 				ire_refrele(save_ire);
8447 				break;
8448 			}
8449 
8450 			xmit_mp = first_mp;
8451 			/*
8452 			 * In the case of multirouting, a copy
8453 			 * of the packet is done before its sending.
8454 			 * The copy is used to attempt another
8455 			 * route resolution, in a next loop.
8456 			 */
8457 			if (ire->ire_flags & RTF_MULTIRT) {
8458 				copy_mp = copymsg(first_mp);
8459 				if (copy_mp != NULL) {
8460 					xmit_mp = copy_mp;
8461 					MULTIRT_DEBUG_TAG(first_mp);
8462 				}
8463 			}
8464 			ire_add_then_send(q, ire, xmit_mp);
8465 			ire_refrele(save_ire);
8466 
8467 			/* Assert that sire is not deleted yet. */
8468 			if (sire != NULL) {
8469 				ASSERT(sire->ire_ptpn != NULL);
8470 				IRB_REFRELE(sire->ire_bucket);
8471 			}
8472 
8473 			/* Assert that ipif_ire is not deleted yet. */
8474 			ASSERT(ipif_ire->ire_ptpn != NULL);
8475 			IRB_REFRELE(ipif_ire->ire_bucket);
8476 			ire_refrele(ipif_ire);
8477 
8478 			/*
8479 			 * If copy_mp is not NULL, multirouting was
8480 			 * requested. We loop to initiate a next
8481 			 * route resolution attempt, starting from sire.
8482 			 */
8483 			if (copy_mp != NULL) {
8484 				/*
8485 				 * Search for the next unresolved
8486 				 * multirt route.
8487 				 */
8488 				copy_mp = NULL;
8489 				ipif_ire = NULL;
8490 				ire = NULL;
8491 				multirt_resolve_next = B_TRUE;
8492 				continue;
8493 			}
8494 			if (sire != NULL)
8495 				ire_refrele(sire);
8496 			ipif_refrele(src_ipif);
8497 			ill_refrele(dst_ill);
8498 			return;
8499 		}
8500 		case IRE_IF_NORESOLVER: {
8501 
8502 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8503 			    dst_ill->ill_resolver_mp == NULL) {
8504 				ip1dbg(("ip_newroute: dst_ill %p "
8505 				    "for IRE_IF_NORESOLVER ire %p has "
8506 				    "no ill_resolver_mp\n",
8507 				    (void *)dst_ill, (void *)ire));
8508 				break;
8509 			}
8510 
8511 			/*
8512 			 * TSol note: We are creating the ire cache for the
8513 			 * destination 'dst'. If 'dst' is offlink, going
8514 			 * through the first hop 'gw', the security attributes
8515 			 * of 'dst' must be set to point to the gateway
8516 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8517 			 * is possible that 'dst' is a potential gateway that is
8518 			 * referenced by some route that has some security
8519 			 * attributes. Thus in the former case, we need to do a
8520 			 * gcgrp_lookup of 'gw' while in the latter case we
8521 			 * need to do gcgrp_lookup of 'dst' itself.
8522 			 */
8523 			ga.ga_af = AF_INET;
8524 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8525 			    &ga.ga_addr);
8526 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8527 
8528 			ire = ire_create(
8529 			    (uchar_t *)&dst,		/* dest address */
8530 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8531 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8532 			    (uchar_t *)&gw,		/* gateway address */
8533 			    &save_ire->ire_max_frag,
8534 			    NULL,			/* no src nce */
8535 			    dst_ill->ill_rq,		/* recv-from queue */
8536 			    dst_ill->ill_wq,		/* send-to queue */
8537 			    IRE_CACHE,
8538 			    src_ipif,
8539 			    save_ire->ire_mask,		/* Parent mask */
8540 			    (sire != NULL) ?		/* Parent handle */
8541 			    sire->ire_phandle : 0,
8542 			    save_ire->ire_ihandle,	/* Interface handle */
8543 			    (sire != NULL) ? sire->ire_flags &
8544 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8545 			    &(save_ire->ire_uinfo),
8546 			    NULL,
8547 			    gcgrp,
8548 			    ipst);
8549 
8550 			if (ire == NULL) {
8551 				if (gcgrp != NULL) {
8552 					GCGRP_REFRELE(gcgrp);
8553 					gcgrp = NULL;
8554 				}
8555 				ire_refrele(save_ire);
8556 				break;
8557 			}
8558 
8559 			/* reference now held by IRE */
8560 			gcgrp = NULL;
8561 
8562 			ire->ire_marks |= ire_marks;
8563 
8564 			/* Prevent save_ire from getting deleted */
8565 			IRB_REFHOLD(save_ire->ire_bucket);
8566 			/* Has it been removed already ? */
8567 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8568 				IRB_REFRELE(save_ire->ire_bucket);
8569 				ire_refrele(save_ire);
8570 				break;
8571 			}
8572 
8573 			/*
8574 			 * In the case of multirouting, a copy
8575 			 * of the packet is made before it is sent.
8576 			 * The copy is used in the next
8577 			 * loop to attempt another resolution.
8578 			 */
8579 			xmit_mp = first_mp;
8580 			if ((sire != NULL) &&
8581 			    (sire->ire_flags & RTF_MULTIRT)) {
8582 				copy_mp = copymsg(first_mp);
8583 				if (copy_mp != NULL) {
8584 					xmit_mp = copy_mp;
8585 					MULTIRT_DEBUG_TAG(first_mp);
8586 				}
8587 			}
8588 			ire_add_then_send(q, ire, xmit_mp);
8589 
8590 			/* Assert that it is not deleted yet. */
8591 			ASSERT(save_ire->ire_ptpn != NULL);
8592 			IRB_REFRELE(save_ire->ire_bucket);
8593 			ire_refrele(save_ire);
8594 
8595 			if (copy_mp != NULL) {
8596 				/*
8597 				 * If we found a (no)resolver, we ignore any
8598 				 * trailing top priority IRE_CACHE in further
8599 				 * loops. This ensures that we do not omit any
8600 				 * (no)resolver.
8601 				 * This IRE_CACHE, if any, will be processed
8602 				 * by another thread entering ip_newroute().
8603 				 * IRE_CACHE entries, if any, will be processed
8604 				 * by another thread entering ip_newroute(),
8605 				 * (upon resolver response, for instance).
8606 				 * This aims to force parallel multirt
8607 				 * resolutions as soon as a packet must be sent.
8608 				 * In the best case, after the tx of only one
8609 				 * packet, all reachable routes are resolved.
8610 				 * Otherwise, the resolution of all RTF_MULTIRT
8611 				 * routes would require several emissions.
8612 				 */
8613 				multirt_flags &= ~MULTIRT_CACHEGW;
8614 
8615 				/*
8616 				 * Search for the next unresolved multirt
8617 				 * route.
8618 				 */
8619 				copy_mp = NULL;
8620 				save_ire = NULL;
8621 				ire = NULL;
8622 				multirt_resolve_next = B_TRUE;
8623 				continue;
8624 			}
8625 
8626 			/*
8627 			 * Don't need sire anymore
8628 			 */
8629 			if (sire != NULL)
8630 				ire_refrele(sire);
8631 
8632 			ipif_refrele(src_ipif);
8633 			ill_refrele(dst_ill);
8634 			return;
8635 		}
8636 		case IRE_IF_RESOLVER:
8637 			/*
8638 			 * We can't build an IRE_CACHE yet, but at least we
8639 			 * found a resolver that can help.
8640 			 */
8641 			res_mp = dst_ill->ill_resolver_mp;
8642 			if (!OK_RESOLVER_MP(res_mp))
8643 				break;
8644 
8645 			/*
8646 			 * To be at this point in the code with a non-zero gw
8647 			 * means that dst is reachable through a gateway that
8648 			 * we have never resolved.  By changing dst to the gw
8649 			 * addr we resolve the gateway first.
8650 			 * When ire_add_then_send() tries to put the IP dg
8651 			 * to dst, it will reenter ip_newroute() at which
8652 			 * time we will find the IRE_CACHE for the gw and
8653 			 * create another IRE_CACHE in case IRE_CACHE above.
8654 			 */
8655 			if (gw != INADDR_ANY) {
8656 				/*
8657 				 * The source ipif that was determined above was
8658 				 * relative to the destination address, not the
8659 				 * gateway's. If src_ipif was not taken out of
8660 				 * the IRE_IF_RESOLVER entry, we'll need to call
8661 				 * ipif_select_source() again.
8662 				 */
8663 				if (src_ipif != ire->ire_ipif) {
8664 					ipif_refrele(src_ipif);
8665 					src_ipif = ipif_select_source(dst_ill,
8666 					    gw, zoneid);
8667 					if (src_ipif == NULL) {
8668 						if (ip_debug > 2) {
8669 							pr_addr_dbg(
8670 							    "ip_newroute: no "
8671 							    "src for gw %s ",
8672 							    AF_INET, &gw);
8673 							printf("through "
8674 							    "interface %s\n",
8675 							    dst_ill->ill_name);
8676 						}
8677 						goto icmp_err_ret;
8678 					}
8679 				}
8680 				save_dst = dst;
8681 				dst = gw;
8682 				gw = INADDR_ANY;
8683 			}
8684 
8685 			/*
8686 			 * We obtain a partial IRE_CACHE which we will pass
8687 			 * along with the resolver query.  When the response
8688 			 * comes back it will be there ready for us to add.
8689 			 * The ire_max_frag is atomically set under the
8690 			 * irebucket lock in ire_add_v[46].
8691 			 */
8692 
8693 			ire = ire_create_mp(
8694 			    (uchar_t *)&dst,		/* dest address */
8695 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8696 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8697 			    (uchar_t *)&gw,		/* gateway address */
8698 			    NULL,			/* ire_max_frag */
8699 			    NULL,			/* no src nce */
8700 			    dst_ill->ill_rq,		/* recv-from queue */
8701 			    dst_ill->ill_wq,		/* send-to queue */
8702 			    IRE_CACHE,
8703 			    src_ipif,			/* Interface ipif */
8704 			    save_ire->ire_mask,		/* Parent mask */
8705 			    0,
8706 			    save_ire->ire_ihandle,	/* Interface handle */
8707 			    0,				/* flags if any */
8708 			    &(save_ire->ire_uinfo),
8709 			    NULL,
8710 			    NULL,
8711 			    ipst);
8712 
8713 			if (ire == NULL) {
8714 				ire_refrele(save_ire);
8715 				break;
8716 			}
8717 
8718 			if ((sire != NULL) &&
8719 			    (sire->ire_flags & RTF_MULTIRT)) {
8720 				copy_mp = copymsg(first_mp);
8721 				if (copy_mp != NULL)
8722 					MULTIRT_DEBUG_TAG(copy_mp);
8723 			}
8724 
8725 			ire->ire_marks |= ire_marks;
8726 
8727 			/*
8728 			 * Construct message chain for the resolver
8729 			 * of the form:
8730 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8731 			 * Packet could contain a IPSEC_OUT mp.
8732 			 *
8733 			 * NOTE : ire will be added later when the response
8734 			 * comes back from ARP. If the response does not
8735 			 * come back, ARP frees the packet. For this reason,
8736 			 * we can't REFHOLD the bucket of save_ire to prevent
8737 			 * deletions. We may not be able to REFRELE the bucket
8738 			 * if the response never comes back. Thus, before
8739 			 * adding the ire, ire_add_v4 will make sure that the
8740 			 * interface route does not get deleted. This is the
8741 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8742 			 * where we can always prevent deletions because of
8743 			 * the synchronous nature of adding IRES i.e
8744 			 * ire_add_then_send is called after creating the IRE.
8745 			 */
8746 			ASSERT(ire->ire_mp != NULL);
8747 			ire->ire_mp->b_cont = first_mp;
8748 			/* Have saved_mp handy, for cleanup if canput fails */
8749 			saved_mp = mp;
8750 			mp = copyb(res_mp);
8751 			if (mp == NULL) {
8752 				/* Prepare for cleanup */
8753 				mp = saved_mp; /* pkt */
8754 				ire_delete(ire); /* ire_mp */
8755 				ire = NULL;
8756 				ire_refrele(save_ire);
8757 				if (copy_mp != NULL) {
8758 					MULTIRT_DEBUG_UNTAG(copy_mp);
8759 					freemsg(copy_mp);
8760 					copy_mp = NULL;
8761 				}
8762 				break;
8763 			}
8764 			linkb(mp, ire->ire_mp);
8765 
8766 			/*
8767 			 * Fill in the source and dest addrs for the resolver.
8768 			 * NOTE: this depends on memory layouts imposed by
8769 			 * ill_init().
8770 			 */
8771 			areq = (areq_t *)mp->b_rptr;
8772 			addrp = (ipaddr_t *)((char *)areq +
8773 			    areq->areq_sender_addr_offset);
8774 			if (do_attach_ill) {
8775 				/*
8776 				 * This is bind to no failover case.
8777 				 * arp packet also must go out on attach_ill.
8778 				 */
8779 				ASSERT(ipha->ipha_src != NULL);
8780 				*addrp = ipha->ipha_src;
8781 			} else {
8782 				*addrp = save_ire->ire_src_addr;
8783 			}
8784 
8785 			ire_refrele(save_ire);
8786 			addrp = (ipaddr_t *)((char *)areq +
8787 			    areq->areq_target_addr_offset);
8788 			*addrp = dst;
8789 			/* Up to the resolver. */
8790 			if (canputnext(dst_ill->ill_rq) &&
8791 			    !(dst_ill->ill_arp_closing)) {
8792 				putnext(dst_ill->ill_rq, mp);
8793 				ire = NULL;
8794 				if (copy_mp != NULL) {
8795 					/*
8796 					 * If we found a resolver, we ignore
8797 					 * any trailing top priority IRE_CACHE
8798 					 * in the further loops. This ensures
8799 					 * that we do not omit any resolver.
8800 					 * IRE_CACHE entries, if any, will be
8801 					 * processed next time we enter
8802 					 * ip_newroute().
8803 					 */
8804 					multirt_flags &= ~MULTIRT_CACHEGW;
8805 					/*
8806 					 * Search for the next unresolved
8807 					 * multirt route.
8808 					 */
8809 					first_mp = copy_mp;
8810 					copy_mp = NULL;
8811 					/* Prepare the next resolution loop. */
8812 					mp = first_mp;
8813 					EXTRACT_PKT_MP(mp, first_mp,
8814 					    mctl_present);
8815 					if (mctl_present)
8816 						io = (ipsec_out_t *)
8817 						    first_mp->b_rptr;
8818 					ipha = (ipha_t *)mp->b_rptr;
8819 
8820 					ASSERT(sire != NULL);
8821 
8822 					dst = save_dst;
8823 					multirt_resolve_next = B_TRUE;
8824 					continue;
8825 				}
8826 
8827 				if (sire != NULL)
8828 					ire_refrele(sire);
8829 
8830 				/*
8831 				 * The response will come back in ip_wput
8832 				 * with db_type IRE_DB_TYPE.
8833 				 */
8834 				ipif_refrele(src_ipif);
8835 				ill_refrele(dst_ill);
8836 				return;
8837 			} else {
8838 				/* Prepare for cleanup */
8839 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8840 				    mp);
8841 				mp->b_cont = NULL;
8842 				freeb(mp); /* areq */
8843 				/*
8844 				 * this is an ire that is not added to the
8845 				 * cache. ire_freemblk will handle the release
8846 				 * of any resources associated with the ire.
8847 				 */
8848 				ire_delete(ire); /* ire_mp */
8849 				mp = saved_mp; /* pkt */
8850 				ire = NULL;
8851 				if (copy_mp != NULL) {
8852 					MULTIRT_DEBUG_UNTAG(copy_mp);
8853 					freemsg(copy_mp);
8854 					copy_mp = NULL;
8855 				}
8856 				break;
8857 			}
8858 		default:
8859 			break;
8860 		}
8861 	} while (multirt_resolve_next);
8862 
8863 	ip1dbg(("ip_newroute: dropped\n"));
8864 	/* Did this packet originate externally? */
8865 	if (mp->b_prev) {
8866 		mp->b_next = NULL;
8867 		mp->b_prev = NULL;
8868 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8869 	} else {
8870 		if (dst_ill != NULL) {
8871 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8872 		} else {
8873 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8874 		}
8875 	}
8876 	ASSERT(copy_mp == NULL);
8877 	MULTIRT_DEBUG_UNTAG(first_mp);
8878 	freemsg(first_mp);
8879 	if (ire != NULL)
8880 		ire_refrele(ire);
8881 	if (sire != NULL)
8882 		ire_refrele(sire);
8883 	if (src_ipif != NULL)
8884 		ipif_refrele(src_ipif);
8885 	if (dst_ill != NULL)
8886 		ill_refrele(dst_ill);
8887 	return;
8888 
8889 icmp_err_ret:
8890 	ip1dbg(("ip_newroute: no route\n"));
8891 	if (src_ipif != NULL)
8892 		ipif_refrele(src_ipif);
8893 	if (dst_ill != NULL)
8894 		ill_refrele(dst_ill);
8895 	if (sire != NULL)
8896 		ire_refrele(sire);
8897 	/* Did this packet originate externally? */
8898 	if (mp->b_prev) {
8899 		mp->b_next = NULL;
8900 		mp->b_prev = NULL;
8901 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8902 		q = WR(q);
8903 	} else {
8904 		/*
8905 		 * There is no outgoing ill, so just increment the
8906 		 * system MIB.
8907 		 */
8908 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
8909 		/*
8910 		 * Since ip_wput() isn't close to finished, we fill
8911 		 * in enough of the header for credible error reporting.
8912 		 */
8913 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
8914 			/* Failed */
8915 			MULTIRT_DEBUG_UNTAG(first_mp);
8916 			freemsg(first_mp);
8917 			if (ire != NULL)
8918 				ire_refrele(ire);
8919 			return;
8920 		}
8921 	}
8922 
8923 	/*
8924 	 * At this point we will have ire only if RTF_BLACKHOLE
8925 	 * or RTF_REJECT flags are set on the IRE. It will not
8926 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8927 	 */
8928 	if (ire != NULL) {
8929 		if (ire->ire_flags & RTF_BLACKHOLE) {
8930 			ire_refrele(ire);
8931 			MULTIRT_DEBUG_UNTAG(first_mp);
8932 			freemsg(first_mp);
8933 			return;
8934 		}
8935 		ire_refrele(ire);
8936 	}
8937 	if (ip_source_routed(ipha, ipst)) {
8938 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8939 		    zoneid, ipst);
8940 		return;
8941 	}
8942 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
8943 }
8944 
8945 ip_opt_info_t zero_info;
8946 
8947 /*
8948  * IPv4 -
8949  * ip_newroute_ipif is called by ip_wput_multicast and
8950  * ip_rput_forward_multicast whenever we need to send
8951  * out a packet to a destination address for which we do not have specific
8952  * routing information. It is used when the packet will be sent out
8953  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
8954  * socket option is set or icmp error message wants to go out on a particular
8955  * interface for a unicast packet.
8956  *
8957  * In most cases, the destination address is resolved thanks to the ipif
8958  * intrinsic resolver. However, there are some cases where the call to
8959  * ip_newroute_ipif must take into account the potential presence of
8960  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8961  * that uses the interface. This is specified through flags,
8962  * which can be a combination of:
8963  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8964  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
8965  *   and flags. Additionally, the packet source address has to be set to
8966  *   the specified address. The caller is thus expected to set this flag
8967  *   if the packet has no specific source address yet.
8968  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
8969  *   flag, the resulting ire will inherit the flag. All unresolved routes
8970  *   to the destination must be explored in the same call to
8971  *   ip_newroute_ipif().
8972  */
8973 static void
8974 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
8975     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
8976 {
8977 	areq_t	*areq;
8978 	ire_t	*ire = NULL;
8979 	mblk_t	*res_mp;
8980 	ipaddr_t *addrp;
8981 	mblk_t *first_mp;
8982 	ire_t	*save_ire = NULL;
8983 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
8984 	ipif_t	*src_ipif = NULL;
8985 	ushort_t ire_marks = 0;
8986 	ill_t	*dst_ill = NULL;
8987 	boolean_t mctl_present;
8988 	ipsec_out_t *io;
8989 	ipha_t *ipha;
8990 	int	ihandle = 0;
8991 	mblk_t	*saved_mp;
8992 	ire_t   *fire = NULL;
8993 	mblk_t  *copy_mp = NULL;
8994 	boolean_t multirt_resolve_next;
8995 	ipaddr_t ipha_dst;
8996 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
8997 
8998 	/*
8999 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9000 	 * here for uniformity
9001 	 */
9002 	ipif_refhold(ipif);
9003 
9004 	/*
9005 	 * This loop is run only once in most cases.
9006 	 * We loop to resolve further routes only when the destination
9007 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9008 	 */
9009 	do {
9010 		if (dst_ill != NULL) {
9011 			ill_refrele(dst_ill);
9012 			dst_ill = NULL;
9013 		}
9014 		if (src_ipif != NULL) {
9015 			ipif_refrele(src_ipif);
9016 			src_ipif = NULL;
9017 		}
9018 		multirt_resolve_next = B_FALSE;
9019 
9020 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9021 		    ipif->ipif_ill->ill_name));
9022 
9023 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
9024 		if (mctl_present)
9025 			io = (ipsec_out_t *)first_mp->b_rptr;
9026 
9027 		ipha = (ipha_t *)mp->b_rptr;
9028 
9029 		/*
9030 		 * Save the packet destination address, we may need it after
9031 		 * the packet has been consumed.
9032 		 */
9033 		ipha_dst = ipha->ipha_dst;
9034 
9035 		/*
9036 		 * If the interface is a pt-pt interface we look for an
9037 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9038 		 * local_address and the pt-pt destination address. Otherwise
9039 		 * we just match the local address.
9040 		 * NOTE: dst could be different than ipha->ipha_dst in case
9041 		 * of sending igmp multicast packets over a point-to-point
9042 		 * connection.
9043 		 * Thus we must be careful enough to check ipha_dst to be a
9044 		 * multicast address, otherwise it will take xmit_if path for
9045 		 * multicast packets resulting into kernel stack overflow by
9046 		 * repeated calls to ip_newroute_ipif from ire_send().
9047 		 */
9048 		if (CLASSD(ipha_dst) &&
9049 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9050 			goto err_ret;
9051 		}
9052 
9053 		/*
9054 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9055 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9056 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9057 		 * propagate its flags to the new ire.
9058 		 */
9059 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9060 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9061 			ip2dbg(("ip_newroute_ipif: "
9062 			    "ipif_lookup_multi_ire("
9063 			    "ipif %p, dst %08x) = fire %p\n",
9064 			    (void *)ipif, ntohl(dst), (void *)fire));
9065 		}
9066 
9067 		if (mctl_present && io->ipsec_out_attach_if) {
9068 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
9069 			    io->ipsec_out_ill_index, B_FALSE, ipst);
9070 
9071 			/* Failure case frees things for us. */
9072 			if (attach_ill == NULL) {
9073 				ipif_refrele(ipif);
9074 				if (fire != NULL)
9075 					ire_refrele(fire);
9076 				return;
9077 			}
9078 
9079 			/*
9080 			 * Check if we need an ire that will not be
9081 			 * looked up by anybody else i.e. HIDDEN.
9082 			 */
9083 			if (ill_is_probeonly(attach_ill)) {
9084 				ire_marks = IRE_MARK_HIDDEN;
9085 			}
9086 			/*
9087 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
9088 			 * case.
9089 			 */
9090 			dst_ill = ipif->ipif_ill;
9091 			/* attach_ill has been refheld by ip_grab_attach_ill */
9092 			ASSERT(dst_ill == attach_ill);
9093 		} else {
9094 			/*
9095 			 * If this is set by IP_XMIT_IF, then make sure that
9096 			 * ipif is pointing to the same ill as the IP_XMIT_IF
9097 			 * specified ill.
9098 			 */
9099 			ASSERT((connp == NULL) ||
9100 			    (connp->conn_xmit_if_ill == NULL) ||
9101 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
9102 			/*
9103 			 * If the interface belongs to an interface group,
9104 			 * make sure the next possible interface in the group
9105 			 * is used.  This encourages load spreading among
9106 			 * peers in an interface group.
9107 			 * Note: load spreading is disabled for RTF_MULTIRT
9108 			 * routes.
9109 			 */
9110 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9111 			    (fire->ire_flags & RTF_MULTIRT)) {
9112 				/*
9113 				 * Don't perform outbound load spreading
9114 				 * in the case of an RTF_MULTIRT issued route,
9115 				 * we actually typically want to replicate
9116 				 * outgoing packets through particular
9117 				 * interfaces.
9118 				 */
9119 				dst_ill = ipif->ipif_ill;
9120 				ill_refhold(dst_ill);
9121 			} else {
9122 				dst_ill = ip_newroute_get_dst_ill(
9123 				    ipif->ipif_ill);
9124 			}
9125 			if (dst_ill == NULL) {
9126 				if (ip_debug > 2) {
9127 					pr_addr_dbg("ip_newroute_ipif: "
9128 					    "no dst ill for dst %s\n",
9129 					    AF_INET, &dst);
9130 				}
9131 				goto err_ret;
9132 			}
9133 		}
9134 
9135 		/*
9136 		 * Pick a source address preferring non-deprecated ones.
9137 		 * Unlike ip_newroute, we don't do any source address
9138 		 * selection here since for multicast it really does not help
9139 		 * in inbound load spreading as in the unicast case.
9140 		 */
9141 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9142 		    (fire->ire_flags & RTF_SETSRC)) {
9143 			/*
9144 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9145 			 * on that interface. This ire has RTF_SETSRC flag, so
9146 			 * the source address of the packet must be changed.
9147 			 * Check that the ipif matching the requested source
9148 			 * address still exists.
9149 			 */
9150 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9151 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9152 		}
9153 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
9154 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9155 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9156 		    (src_ipif == NULL)) {
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 loose the conn when going through arp.
9183 		 */
9184 		if (ipha->ipha_src == INADDR_ANY &&
9185 		    (connp == NULL || !connp->conn_unspec_src)) {
9186 			ipha->ipha_src = src_ipif->ipif_src_addr;
9187 		}
9188 
9189 		/*
9190 		 * In the case of IP_XMIT_IF, it is possible that the
9191 		 * outgoing interface does not have an interface ire.
9192 		 */
9193 		if (CLASSD(ipha_dst) && (connp == NULL ||
9194 		    connp->conn_xmit_if_ill == NULL) &&
9195 		    infop->ip_opt_ill_index == 0) {
9196 			/* ipif_to_ire returns an held ire */
9197 			ire = ipif_to_ire(ipif);
9198 			if (ire == NULL)
9199 				goto err_ret;
9200 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9201 				goto err_ret;
9202 			/*
9203 			 * ihandle is needed when the ire is added to
9204 			 * cache table.
9205 			 */
9206 			save_ire = ire;
9207 			ihandle = save_ire->ire_ihandle;
9208 
9209 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9210 			    "flags %04x\n",
9211 			    (void *)ire, (void *)ipif, flags));
9212 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9213 			    (fire->ire_flags & RTF_MULTIRT)) {
9214 				/*
9215 				 * As requested by flags, an IRE_OFFSUBNET was
9216 				 * looked up on that interface. This ire has
9217 				 * RTF_MULTIRT flag, so the resolution loop will
9218 				 * be re-entered to resolve additional routes on
9219 				 * other interfaces. For that purpose, a copy of
9220 				 * the packet is performed at this point.
9221 				 */
9222 				fire->ire_last_used_time = lbolt;
9223 				copy_mp = copymsg(first_mp);
9224 				if (copy_mp) {
9225 					MULTIRT_DEBUG_TAG(copy_mp);
9226 				}
9227 			}
9228 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9229 			    (fire->ire_flags & RTF_SETSRC)) {
9230 				/*
9231 				 * As requested by flags, an IRE_OFFSUBET was
9232 				 * looked up on that interface. This ire has
9233 				 * RTF_SETSRC flag, so the source address of the
9234 				 * packet must be changed.
9235 				 */
9236 				ipha->ipha_src = fire->ire_src_addr;
9237 			}
9238 		} else {
9239 			ASSERT((connp == NULL) ||
9240 			    (connp->conn_xmit_if_ill != NULL) ||
9241 			    (connp->conn_dontroute) ||
9242 			    infop->ip_opt_ill_index != 0);
9243 			/*
9244 			 * The only ways we can come here are:
9245 			 * 1) IP_XMIT_IF socket option is set
9246 			 * 2) SO_DONTROUTE socket option is set
9247 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9248 			 * In all cases, the new ire will not be added
9249 			 * into cache table.
9250 			 */
9251 			ire_marks |= IRE_MARK_NOADD;
9252 		}
9253 
9254 		switch (ipif->ipif_net_type) {
9255 		case IRE_IF_NORESOLVER: {
9256 			/* We have what we need to build an IRE_CACHE. */
9257 
9258 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9259 			    (dst_ill->ill_resolver_mp == NULL)) {
9260 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9261 				    "for IRE_IF_NORESOLVER ire %p has "
9262 				    "no ill_resolver_mp\n",
9263 				    (void *)dst_ill, (void *)ire));
9264 				break;
9265 			}
9266 
9267 			/*
9268 			 * The new ire inherits the IRE_OFFSUBNET flags
9269 			 * and source address, if this was requested.
9270 			 */
9271 			ire = ire_create(
9272 			    (uchar_t *)&dst,		/* dest address */
9273 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9274 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9275 			    NULL,			/* gateway address */
9276 			    &ipif->ipif_mtu,
9277 			    NULL,			/* no src nce */
9278 			    dst_ill->ill_rq,		/* recv-from queue */
9279 			    dst_ill->ill_wq,		/* send-to queue */
9280 			    IRE_CACHE,
9281 			    src_ipif,
9282 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9283 			    (fire != NULL) ?		/* Parent handle */
9284 			    fire->ire_phandle : 0,
9285 			    ihandle,			/* Interface handle */
9286 			    (fire != NULL) ?
9287 			    (fire->ire_flags &
9288 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9289 			    (save_ire == NULL ? &ire_uinfo_null :
9290 			    &save_ire->ire_uinfo),
9291 			    NULL,
9292 			    NULL,
9293 			    ipst);
9294 
9295 			if (ire == NULL) {
9296 				if (save_ire != NULL)
9297 					ire_refrele(save_ire);
9298 				break;
9299 			}
9300 
9301 			ire->ire_marks |= ire_marks;
9302 
9303 			/*
9304 			 * If IRE_MARK_NOADD is set then we need to convert
9305 			 * the max_fragp to a useable value now. This is
9306 			 * normally done in ire_add_v[46]. We also need to
9307 			 * associate the ire with an nce (normally would be
9308 			 * done in ip_wput_nondata()).
9309 			 *
9310 			 * Note that IRE_MARK_NOADD packets created here
9311 			 * do not have a non-null ire_mp pointer. The null
9312 			 * value of ire_bucket indicates that they were
9313 			 * never added.
9314 			 */
9315 			if (ire->ire_marks & IRE_MARK_NOADD) {
9316 				uint_t  max_frag;
9317 
9318 				max_frag = *ire->ire_max_fragp;
9319 				ire->ire_max_fragp = NULL;
9320 				ire->ire_max_frag = max_frag;
9321 
9322 				if ((ire->ire_nce = ndp_lookup_v4(
9323 				    ire_to_ill(ire),
9324 				    (ire->ire_gateway_addr != INADDR_ANY ?
9325 				    &ire->ire_gateway_addr : &ire->ire_addr),
9326 				    B_FALSE)) == NULL) {
9327 					if (save_ire != NULL)
9328 						ire_refrele(save_ire);
9329 					break;
9330 				}
9331 				ASSERT(ire->ire_nce->nce_state ==
9332 				    ND_REACHABLE);
9333 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9334 			}
9335 
9336 			/* Prevent save_ire from getting deleted */
9337 			if (save_ire != NULL) {
9338 				IRB_REFHOLD(save_ire->ire_bucket);
9339 				/* Has it been removed already ? */
9340 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9341 					IRB_REFRELE(save_ire->ire_bucket);
9342 					ire_refrele(save_ire);
9343 					break;
9344 				}
9345 			}
9346 
9347 			ire_add_then_send(q, ire, first_mp);
9348 
9349 			/* Assert that save_ire is not deleted yet. */
9350 			if (save_ire != NULL) {
9351 				ASSERT(save_ire->ire_ptpn != NULL);
9352 				IRB_REFRELE(save_ire->ire_bucket);
9353 				ire_refrele(save_ire);
9354 				save_ire = NULL;
9355 			}
9356 			if (fire != NULL) {
9357 				ire_refrele(fire);
9358 				fire = NULL;
9359 			}
9360 
9361 			/*
9362 			 * the resolution loop is re-entered if this
9363 			 * was requested through flags and if we
9364 			 * actually are in a multirouting case.
9365 			 */
9366 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9367 				boolean_t need_resolve =
9368 				    ire_multirt_need_resolve(ipha_dst,
9369 				    MBLK_GETLABEL(copy_mp), ipst);
9370 				if (!need_resolve) {
9371 					MULTIRT_DEBUG_UNTAG(copy_mp);
9372 					freemsg(copy_mp);
9373 					copy_mp = NULL;
9374 				} else {
9375 					/*
9376 					 * ipif_lookup_group() calls
9377 					 * ire_lookup_multi() that uses
9378 					 * ire_ftable_lookup() to find
9379 					 * an IRE_INTERFACE for the group.
9380 					 * In the multirt case,
9381 					 * ire_lookup_multi() then invokes
9382 					 * ire_multirt_lookup() to find
9383 					 * the next resolvable ire.
9384 					 * As a result, we obtain an new
9385 					 * interface, derived from the
9386 					 * next ire.
9387 					 */
9388 					ipif_refrele(ipif);
9389 					ipif = ipif_lookup_group(ipha_dst,
9390 					    zoneid, ipst);
9391 					ip2dbg(("ip_newroute_ipif: "
9392 					    "multirt dst %08x, ipif %p\n",
9393 					    htonl(dst), (void *)ipif));
9394 					if (ipif != NULL) {
9395 						mp = copy_mp;
9396 						copy_mp = NULL;
9397 						multirt_resolve_next = B_TRUE;
9398 						continue;
9399 					} else {
9400 						freemsg(copy_mp);
9401 					}
9402 				}
9403 			}
9404 			if (ipif != NULL)
9405 				ipif_refrele(ipif);
9406 			ill_refrele(dst_ill);
9407 			ipif_refrele(src_ipif);
9408 			return;
9409 		}
9410 		case IRE_IF_RESOLVER:
9411 			/*
9412 			 * We can't build an IRE_CACHE yet, but at least
9413 			 * we found a resolver that can help.
9414 			 */
9415 			res_mp = dst_ill->ill_resolver_mp;
9416 			if (!OK_RESOLVER_MP(res_mp))
9417 				break;
9418 
9419 			/*
9420 			 * We obtain a partial IRE_CACHE which we will pass
9421 			 * along with the resolver query.  When the response
9422 			 * comes back it will be there ready for us to add.
9423 			 * The new ire inherits the IRE_OFFSUBNET flags
9424 			 * and source address, if this was requested.
9425 			 * The ire_max_frag is atomically set under the
9426 			 * irebucket lock in ire_add_v[46]. Only in the
9427 			 * case of IRE_MARK_NOADD, we set it here itself.
9428 			 */
9429 			ire = ire_create_mp(
9430 			    (uchar_t *)&dst,		/* dest address */
9431 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9432 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9433 			    NULL,			/* gateway address */
9434 			    (ire_marks & IRE_MARK_NOADD) ?
9435 			    ipif->ipif_mtu : 0,		/* max_frag */
9436 			    NULL,			/* no src nce */
9437 			    dst_ill->ill_rq,		/* recv-from queue */
9438 			    dst_ill->ill_wq,		/* send-to queue */
9439 			    IRE_CACHE,
9440 			    src_ipif,
9441 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9442 			    (fire != NULL) ?		/* Parent handle */
9443 			    fire->ire_phandle : 0,
9444 			    ihandle,			/* Interface handle */
9445 			    (fire != NULL) ?		/* flags if any */
9446 			    (fire->ire_flags &
9447 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9448 			    (save_ire == NULL ? &ire_uinfo_null :
9449 			    &save_ire->ire_uinfo),
9450 			    NULL,
9451 			    NULL,
9452 			    ipst);
9453 
9454 			if (save_ire != NULL) {
9455 				ire_refrele(save_ire);
9456 				save_ire = NULL;
9457 			}
9458 			if (ire == NULL)
9459 				break;
9460 
9461 			ire->ire_marks |= ire_marks;
9462 			/*
9463 			 * Construct message chain for the resolver of the
9464 			 * form:
9465 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9466 			 *
9467 			 * NOTE : ire will be added later when the response
9468 			 * comes back from ARP. If the response does not
9469 			 * come back, ARP frees the packet. For this reason,
9470 			 * we can't REFHOLD the bucket of save_ire to prevent
9471 			 * deletions. We may not be able to REFRELE the
9472 			 * bucket if the response never comes back.
9473 			 * Thus, before adding the ire, ire_add_v4 will make
9474 			 * sure that the interface route does not get deleted.
9475 			 * This is the only case unlike ip_newroute_v6,
9476 			 * ip_newroute_ipif_v6 where we can always prevent
9477 			 * deletions because ire_add_then_send is called after
9478 			 * creating the IRE.
9479 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9480 			 * does not add this IRE into the IRE CACHE.
9481 			 */
9482 			ASSERT(ire->ire_mp != NULL);
9483 			ire->ire_mp->b_cont = first_mp;
9484 			/* Have saved_mp handy, for cleanup if canput fails */
9485 			saved_mp = mp;
9486 			mp = copyb(res_mp);
9487 			if (mp == NULL) {
9488 				/* Prepare for cleanup */
9489 				mp = saved_mp; /* pkt */
9490 				ire_delete(ire); /* ire_mp */
9491 				ire = NULL;
9492 				if (copy_mp != NULL) {
9493 					MULTIRT_DEBUG_UNTAG(copy_mp);
9494 					freemsg(copy_mp);
9495 					copy_mp = NULL;
9496 				}
9497 				break;
9498 			}
9499 			linkb(mp, ire->ire_mp);
9500 
9501 			/*
9502 			 * Fill in the source and dest addrs for the resolver.
9503 			 * NOTE: this depends on memory layouts imposed by
9504 			 * ill_init().
9505 			 */
9506 			areq = (areq_t *)mp->b_rptr;
9507 			addrp = (ipaddr_t *)((char *)areq +
9508 			    areq->areq_sender_addr_offset);
9509 			*addrp = ire->ire_src_addr;
9510 			addrp = (ipaddr_t *)((char *)areq +
9511 			    areq->areq_target_addr_offset);
9512 			*addrp = dst;
9513 			/* Up to the resolver. */
9514 			if (canputnext(dst_ill->ill_rq) &&
9515 			    !(dst_ill->ill_arp_closing)) {
9516 				putnext(dst_ill->ill_rq, mp);
9517 				/*
9518 				 * The response will come back in ip_wput
9519 				 * with db_type IRE_DB_TYPE.
9520 				 */
9521 			} else {
9522 				mp->b_cont = NULL;
9523 				freeb(mp); /* areq */
9524 				ire_delete(ire); /* ire_mp */
9525 				saved_mp->b_next = NULL;
9526 				saved_mp->b_prev = NULL;
9527 				freemsg(first_mp); /* pkt */
9528 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9529 			}
9530 
9531 			if (fire != NULL) {
9532 				ire_refrele(fire);
9533 				fire = NULL;
9534 			}
9535 
9536 
9537 			/*
9538 			 * The resolution loop is re-entered if this was
9539 			 * requested through flags and we actually are
9540 			 * in a multirouting case.
9541 			 */
9542 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9543 				boolean_t need_resolve =
9544 				    ire_multirt_need_resolve(ipha_dst,
9545 				    MBLK_GETLABEL(copy_mp), ipst);
9546 				if (!need_resolve) {
9547 					MULTIRT_DEBUG_UNTAG(copy_mp);
9548 					freemsg(copy_mp);
9549 					copy_mp = NULL;
9550 				} else {
9551 					/*
9552 					 * ipif_lookup_group() calls
9553 					 * ire_lookup_multi() that uses
9554 					 * ire_ftable_lookup() to find
9555 					 * an IRE_INTERFACE for the group.
9556 					 * In the multirt case,
9557 					 * ire_lookup_multi() then invokes
9558 					 * ire_multirt_lookup() to find
9559 					 * the next resolvable ire.
9560 					 * As a result, we obtain an new
9561 					 * interface, derived from the
9562 					 * next ire.
9563 					 */
9564 					ipif_refrele(ipif);
9565 					ipif = ipif_lookup_group(ipha_dst,
9566 					    zoneid, ipst);
9567 					if (ipif != NULL) {
9568 						mp = copy_mp;
9569 						copy_mp = NULL;
9570 						multirt_resolve_next = B_TRUE;
9571 						continue;
9572 					} else {
9573 						freemsg(copy_mp);
9574 					}
9575 				}
9576 			}
9577 			if (ipif != NULL)
9578 				ipif_refrele(ipif);
9579 			ill_refrele(dst_ill);
9580 			ipif_refrele(src_ipif);
9581 			return;
9582 		default:
9583 			break;
9584 		}
9585 	} while (multirt_resolve_next);
9586 
9587 err_ret:
9588 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9589 	if (fire != NULL)
9590 		ire_refrele(fire);
9591 	ipif_refrele(ipif);
9592 	/* Did this packet originate externally? */
9593 	if (dst_ill != NULL)
9594 		ill_refrele(dst_ill);
9595 	if (src_ipif != NULL)
9596 		ipif_refrele(src_ipif);
9597 	if (mp->b_prev || mp->b_next) {
9598 		mp->b_next = NULL;
9599 		mp->b_prev = NULL;
9600 	} else {
9601 		/*
9602 		 * Since ip_wput() isn't close to finished, we fill
9603 		 * in enough of the header for credible error reporting.
9604 		 */
9605 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9606 			/* Failed */
9607 			freemsg(first_mp);
9608 			if (ire != NULL)
9609 				ire_refrele(ire);
9610 			return;
9611 		}
9612 	}
9613 	/*
9614 	 * At this point we will have ire only if RTF_BLACKHOLE
9615 	 * or RTF_REJECT flags are set on the IRE. It will not
9616 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9617 	 */
9618 	if (ire != NULL) {
9619 		if (ire->ire_flags & RTF_BLACKHOLE) {
9620 			ire_refrele(ire);
9621 			freemsg(first_mp);
9622 			return;
9623 		}
9624 		ire_refrele(ire);
9625 	}
9626 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9627 }
9628 
9629 /* Name/Value Table Lookup Routine */
9630 char *
9631 ip_nv_lookup(nv_t *nv, int value)
9632 {
9633 	if (!nv)
9634 		return (NULL);
9635 	for (; nv->nv_name; nv++) {
9636 		if (nv->nv_value == value)
9637 			return (nv->nv_name);
9638 	}
9639 	return ("unknown");
9640 }
9641 
9642 /*
9643  * This is a module open, i.e. this is a control stream for access
9644  * to a DLPI device.  We allocate an ill_t as the instance data in
9645  * this case.
9646  */
9647 int
9648 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9649 {
9650 	ill_t	*ill;
9651 	int	err;
9652 	zoneid_t zoneid;
9653 	netstack_t *ns;
9654 	ip_stack_t *ipst;
9655 
9656 	/*
9657 	 * Prevent unprivileged processes from pushing IP so that
9658 	 * they can't send raw IP.
9659 	 */
9660 	if (secpolicy_net_rawaccess(credp) != 0)
9661 		return (EPERM);
9662 
9663 	ns = netstack_find_by_cred(credp);
9664 	ASSERT(ns != NULL);
9665 	ipst = ns->netstack_ip;
9666 	ASSERT(ipst != NULL);
9667 
9668 	/*
9669 	 * For exclusive stacks we set the zoneid to zero
9670 	 * to make IP operate as if in the global zone.
9671 	 */
9672 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9673 		zoneid = GLOBAL_ZONEID;
9674 	else
9675 		zoneid = crgetzoneid(credp);
9676 
9677 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9678 	q->q_ptr = WR(q)->q_ptr = ill;
9679 	ill->ill_ipst = ipst;
9680 	ill->ill_zoneid = zoneid;
9681 
9682 	/*
9683 	 * ill_init initializes the ill fields and then sends down
9684 	 * down a DL_INFO_REQ after calling qprocson.
9685 	 */
9686 	err = ill_init(q, ill);
9687 	if (err != 0) {
9688 		mi_free(ill);
9689 		netstack_rele(ipst->ips_netstack);
9690 		q->q_ptr = NULL;
9691 		WR(q)->q_ptr = NULL;
9692 		return (err);
9693 	}
9694 
9695 	/* ill_init initializes the ipsq marking this thread as writer */
9696 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9697 	/* Wait for the DL_INFO_ACK */
9698 	mutex_enter(&ill->ill_lock);
9699 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9700 		/*
9701 		 * Return value of 0 indicates a pending signal.
9702 		 */
9703 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9704 		if (err == 0) {
9705 			mutex_exit(&ill->ill_lock);
9706 			(void) ip_close(q, 0);
9707 			return (EINTR);
9708 		}
9709 	}
9710 	mutex_exit(&ill->ill_lock);
9711 
9712 	/*
9713 	 * ip_rput_other could have set an error  in ill_error on
9714 	 * receipt of M_ERROR.
9715 	 */
9716 
9717 	err = ill->ill_error;
9718 	if (err != 0) {
9719 		(void) ip_close(q, 0);
9720 		return (err);
9721 	}
9722 
9723 	ill->ill_credp = credp;
9724 	crhold(credp);
9725 
9726 	mutex_enter(&ipst->ips_ip_mi_lock);
9727 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9728 	    credp);
9729 	mutex_exit(&ipst->ips_ip_mi_lock);
9730 	if (err) {
9731 		(void) ip_close(q, 0);
9732 		return (err);
9733 	}
9734 	return (0);
9735 }
9736 
9737 /* For /dev/ip aka AF_INET open */
9738 int
9739 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9740 {
9741 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
9742 }
9743 
9744 /* For /dev/ip6 aka AF_INET6 open */
9745 int
9746 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9747 {
9748 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
9749 }
9750 
9751 /* IP open routine. */
9752 int
9753 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9754     boolean_t isv6)
9755 {
9756 	conn_t 		*connp;
9757 	major_t		maj;
9758 	zoneid_t	zoneid;
9759 	netstack_t	*ns;
9760 	ip_stack_t	*ipst;
9761 
9762 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9763 
9764 	/* Allow reopen. */
9765 	if (q->q_ptr != NULL)
9766 		return (0);
9767 
9768 	if (sflag & MODOPEN) {
9769 		/* This is a module open */
9770 		return (ip_modopen(q, devp, flag, sflag, credp));
9771 	}
9772 
9773 	ns = netstack_find_by_cred(credp);
9774 	ASSERT(ns != NULL);
9775 	ipst = ns->netstack_ip;
9776 	ASSERT(ipst != NULL);
9777 
9778 	/*
9779 	 * For exclusive stacks we set the zoneid to zero
9780 	 * to make IP operate as if in the global zone.
9781 	 */
9782 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9783 		zoneid = GLOBAL_ZONEID;
9784 	else
9785 		zoneid = crgetzoneid(credp);
9786 
9787 	/*
9788 	 * We are opening as a device. This is an IP client stream, and we
9789 	 * allocate an conn_t as the instance data.
9790 	 */
9791 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9792 
9793 	/*
9794 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9795 	 * done by netstack_find_by_cred()
9796 	 */
9797 	netstack_rele(ipst->ips_netstack);
9798 
9799 	connp->conn_zoneid = zoneid;
9800 
9801 	connp->conn_upq = q;
9802 	q->q_ptr = WR(q)->q_ptr = connp;
9803 
9804 	if (flag & SO_SOCKSTR)
9805 		connp->conn_flags |= IPCL_SOCKET;
9806 
9807 	/* Minor tells us which /dev entry was opened */
9808 	if (isv6) {
9809 		connp->conn_flags |= IPCL_ISV6;
9810 		connp->conn_af_isv6 = B_TRUE;
9811 		ip_setpktversion(connp, isv6, B_FALSE, ipst);
9812 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9813 	} else {
9814 		connp->conn_af_isv6 = B_FALSE;
9815 		connp->conn_pkt_isv6 = B_FALSE;
9816 	}
9817 
9818 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
9819 		/* CONN_DEC_REF takes care of netstack_rele() */
9820 		q->q_ptr = WR(q)->q_ptr = NULL;
9821 		CONN_DEC_REF(connp);
9822 		return (EBUSY);
9823 	}
9824 
9825 	maj = getemajor(*devp);
9826 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9827 
9828 	/*
9829 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9830 	 */
9831 	connp->conn_cred = credp;
9832 	crhold(connp->conn_cred);
9833 
9834 	/*
9835 	 * If the caller has the process-wide flag set, then default to MAC
9836 	 * exempt mode.  This allows read-down to unlabeled hosts.
9837 	 */
9838 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9839 		connp->conn_mac_exempt = B_TRUE;
9840 
9841 	connp->conn_rq = q;
9842 	connp->conn_wq = WR(q);
9843 
9844 	/* Non-zero default values */
9845 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9846 
9847 	/*
9848 	 * Make the conn globally visible to walkers
9849 	 */
9850 	ASSERT(connp->conn_ref == 1);
9851 	mutex_enter(&connp->conn_lock);
9852 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9853 	mutex_exit(&connp->conn_lock);
9854 
9855 	qprocson(q);
9856 
9857 	return (0);
9858 }
9859 
9860 /*
9861  * Change the output format (IPv4 vs. IPv6) for a conn_t.
9862  * Note that there is no race since either ip_output function works - it
9863  * is just an optimization to enter the best ip_output routine directly.
9864  */
9865 void
9866 ip_setpktversion(conn_t *connp, boolean_t isv6, boolean_t bump_mib,
9867     ip_stack_t *ipst)
9868 {
9869 	if (isv6)  {
9870 		if (bump_mib) {
9871 			BUMP_MIB(&ipst->ips_ip6_mib,
9872 			    ipIfStatsOutSwitchIPVersion);
9873 		}
9874 		connp->conn_send = ip_output_v6;
9875 		connp->conn_pkt_isv6 = B_TRUE;
9876 	} else {
9877 		if (bump_mib) {
9878 			BUMP_MIB(&ipst->ips_ip_mib,
9879 			    ipIfStatsOutSwitchIPVersion);
9880 		}
9881 		connp->conn_send = ip_output;
9882 		connp->conn_pkt_isv6 = B_FALSE;
9883 	}
9884 
9885 }
9886 
9887 /*
9888  * See if IPsec needs loading because of the options in mp.
9889  */
9890 static boolean_t
9891 ipsec_opt_present(mblk_t *mp)
9892 {
9893 	uint8_t *optcp, *next_optcp, *opt_endcp;
9894 	struct opthdr *opt;
9895 	struct T_opthdr *topt;
9896 	int opthdr_len;
9897 	t_uscalar_t optname, optlevel;
9898 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9899 	ipsec_req_t *ipsr;
9900 
9901 	/*
9902 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9903 	 * return TRUE.
9904 	 */
9905 
9906 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9907 	opt_endcp = optcp + tor->OPT_length;
9908 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9909 		opthdr_len = sizeof (struct T_opthdr);
9910 	} else {		/* O_OPTMGMT_REQ */
9911 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9912 		opthdr_len = sizeof (struct opthdr);
9913 	}
9914 	for (; optcp < opt_endcp; optcp = next_optcp) {
9915 		if (optcp + opthdr_len > opt_endcp)
9916 			return (B_FALSE);	/* Not enough option header. */
9917 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9918 			topt = (struct T_opthdr *)optcp;
9919 			optlevel = topt->level;
9920 			optname = topt->name;
9921 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9922 		} else {
9923 			opt = (struct opthdr *)optcp;
9924 			optlevel = opt->level;
9925 			optname = opt->name;
9926 			next_optcp = optcp + opthdr_len +
9927 			    _TPI_ALIGN_OPT(opt->len);
9928 		}
9929 		if ((next_optcp < optcp) || /* wraparound pointer space */
9930 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9931 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9932 			return (B_FALSE); /* bad option buffer */
9933 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9934 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9935 			/*
9936 			 * Check to see if it's an all-bypass or all-zeroes
9937 			 * IPsec request.  Don't bother loading IPsec if
9938 			 * the socket doesn't want to use it.  (A good example
9939 			 * is a bypass request.)
9940 			 *
9941 			 * Basically, if any of the non-NEVER bits are set,
9942 			 * load IPsec.
9943 			 */
9944 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9945 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9946 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9947 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9948 			    != 0)
9949 				return (B_TRUE);
9950 		}
9951 	}
9952 	return (B_FALSE);
9953 }
9954 
9955 /*
9956  * If conn is is waiting for ipsec to finish loading, kick it.
9957  */
9958 /* ARGSUSED */
9959 static void
9960 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9961 {
9962 	t_scalar_t	optreq_prim;
9963 	mblk_t		*mp;
9964 	cred_t		*cr;
9965 	int		err = 0;
9966 
9967 	/*
9968 	 * This function is called, after ipsec loading is complete.
9969 	 * Since IP checks exclusively and atomically (i.e it prevents
9970 	 * ipsec load from completing until ip_optcom_req completes)
9971 	 * whether ipsec load is complete, there cannot be a race with IP
9972 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
9973 	 */
9974 	mutex_enter(&connp->conn_lock);
9975 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
9976 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
9977 		mp = connp->conn_ipsec_opt_mp;
9978 		connp->conn_ipsec_opt_mp = NULL;
9979 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
9980 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
9981 		mutex_exit(&connp->conn_lock);
9982 
9983 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
9984 
9985 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
9986 		if (optreq_prim == T_OPTMGMT_REQ) {
9987 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9988 			    &ip_opt_obj, B_FALSE);
9989 		} else {
9990 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
9991 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9992 			    &ip_opt_obj, B_FALSE);
9993 		}
9994 		if (err != EINPROGRESS)
9995 			CONN_OPER_PENDING_DONE(connp);
9996 		return;
9997 	}
9998 	mutex_exit(&connp->conn_lock);
9999 }
10000 
10001 /*
10002  * Called from the ipsec_loader thread, outside any perimeter, to tell
10003  * ip qenable any of the queues waiting for the ipsec loader to
10004  * complete.
10005  */
10006 void
10007 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10008 {
10009 	netstack_t *ns = ipss->ipsec_netstack;
10010 
10011 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10012 }
10013 
10014 /*
10015  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10016  * determines the grp on which it has to become exclusive, queues the mp
10017  * and sq draining restarts the optmgmt
10018  */
10019 static boolean_t
10020 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10021 {
10022 	conn_t *connp = Q_TO_CONN(q);
10023 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10024 
10025 	/*
10026 	 * Take IPsec requests and treat them special.
10027 	 */
10028 	if (ipsec_opt_present(mp)) {
10029 		/* First check if IPsec is loaded. */
10030 		mutex_enter(&ipss->ipsec_loader_lock);
10031 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10032 			mutex_exit(&ipss->ipsec_loader_lock);
10033 			return (B_FALSE);
10034 		}
10035 		mutex_enter(&connp->conn_lock);
10036 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10037 
10038 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10039 		connp->conn_ipsec_opt_mp = mp;
10040 		mutex_exit(&connp->conn_lock);
10041 		mutex_exit(&ipss->ipsec_loader_lock);
10042 
10043 		ipsec_loader_loadnow(ipss);
10044 		return (B_TRUE);
10045 	}
10046 	return (B_FALSE);
10047 }
10048 
10049 /*
10050  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10051  * all of them are copied to the conn_t. If the req is "zero", the policy is
10052  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10053  * fields.
10054  * We keep only the latest setting of the policy and thus policy setting
10055  * is not incremental/cumulative.
10056  *
10057  * Requests to set policies with multiple alternative actions will
10058  * go through a different API.
10059  */
10060 int
10061 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10062 {
10063 	uint_t ah_req = 0;
10064 	uint_t esp_req = 0;
10065 	uint_t se_req = 0;
10066 	ipsec_selkey_t sel;
10067 	ipsec_act_t *actp = NULL;
10068 	uint_t nact;
10069 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10070 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10071 	ipsec_policy_root_t *pr;
10072 	ipsec_policy_head_t *ph;
10073 	int fam;
10074 	boolean_t is_pol_reset;
10075 	int error = 0;
10076 	netstack_t	*ns = connp->conn_netstack;
10077 	ip_stack_t	*ipst = ns->netstack_ip;
10078 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10079 
10080 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10081 
10082 	/*
10083 	 * The IP_SEC_OPT option does not allow variable length parameters,
10084 	 * hence a request cannot be NULL.
10085 	 */
10086 	if (req == NULL)
10087 		return (EINVAL);
10088 
10089 	ah_req = req->ipsr_ah_req;
10090 	esp_req = req->ipsr_esp_req;
10091 	se_req = req->ipsr_self_encap_req;
10092 
10093 	/*
10094 	 * Are we dealing with a request to reset the policy (i.e.
10095 	 * zero requests).
10096 	 */
10097 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10098 	    (esp_req & REQ_MASK) == 0 &&
10099 	    (se_req & REQ_MASK) == 0);
10100 
10101 	if (!is_pol_reset) {
10102 		/*
10103 		 * If we couldn't load IPsec, fail with "protocol
10104 		 * not supported".
10105 		 * IPsec may not have been loaded for a request with zero
10106 		 * policies, so we don't fail in this case.
10107 		 */
10108 		mutex_enter(&ipss->ipsec_loader_lock);
10109 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10110 			mutex_exit(&ipss->ipsec_loader_lock);
10111 			return (EPROTONOSUPPORT);
10112 		}
10113 		mutex_exit(&ipss->ipsec_loader_lock);
10114 
10115 		/*
10116 		 * Test for valid requests. Invalid algorithms
10117 		 * need to be tested by IPsec code because new
10118 		 * algorithms can be added dynamically.
10119 		 */
10120 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10121 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10122 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10123 			return (EINVAL);
10124 		}
10125 
10126 		/*
10127 		 * Only privileged users can issue these
10128 		 * requests.
10129 		 */
10130 		if (((ah_req & IPSEC_PREF_NEVER) ||
10131 		    (esp_req & IPSEC_PREF_NEVER) ||
10132 		    (se_req & IPSEC_PREF_NEVER)) &&
10133 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10134 			return (EPERM);
10135 		}
10136 
10137 		/*
10138 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10139 		 * are mutually exclusive.
10140 		 */
10141 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10142 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10143 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10144 			/* Both of them are set */
10145 			return (EINVAL);
10146 		}
10147 	}
10148 
10149 	mutex_enter(&connp->conn_lock);
10150 
10151 	/*
10152 	 * If we have already cached policies in ip_bind_connected*(), don't
10153 	 * let them change now. We cache policies for connections
10154 	 * whose src,dst [addr, port] is known.
10155 	 */
10156 	if (connp->conn_policy_cached) {
10157 		mutex_exit(&connp->conn_lock);
10158 		return (EINVAL);
10159 	}
10160 
10161 	/*
10162 	 * We have a zero policies, reset the connection policy if already
10163 	 * set. This will cause the connection to inherit the
10164 	 * global policy, if any.
10165 	 */
10166 	if (is_pol_reset) {
10167 		if (connp->conn_policy != NULL) {
10168 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10169 			connp->conn_policy = NULL;
10170 		}
10171 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10172 		connp->conn_in_enforce_policy = B_FALSE;
10173 		connp->conn_out_enforce_policy = B_FALSE;
10174 		mutex_exit(&connp->conn_lock);
10175 		return (0);
10176 	}
10177 
10178 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10179 	    ipst->ips_netstack);
10180 	if (ph == NULL)
10181 		goto enomem;
10182 
10183 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10184 	if (actp == NULL)
10185 		goto enomem;
10186 
10187 	/*
10188 	 * Always allocate IPv4 policy entries, since they can also
10189 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10190 	 */
10191 	bzero(&sel, sizeof (sel));
10192 	sel.ipsl_valid = IPSL_IPV4;
10193 
10194 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10195 	    ipst->ips_netstack);
10196 	if (pin4 == NULL)
10197 		goto enomem;
10198 
10199 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10200 	    ipst->ips_netstack);
10201 	if (pout4 == NULL)
10202 		goto enomem;
10203 
10204 	if (connp->conn_pkt_isv6) {
10205 		/*
10206 		 * We're looking at a v6 socket, also allocate the
10207 		 * v6-specific entries...
10208 		 */
10209 		sel.ipsl_valid = IPSL_IPV6;
10210 		pin6 = ipsec_policy_create(&sel, actp, nact,
10211 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10212 		if (pin6 == NULL)
10213 			goto enomem;
10214 
10215 		pout6 = ipsec_policy_create(&sel, actp, nact,
10216 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10217 		if (pout6 == NULL)
10218 			goto enomem;
10219 
10220 		/*
10221 		 * .. and file them away in the right place.
10222 		 */
10223 		fam = IPSEC_AF_V6;
10224 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10225 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10226 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10227 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10228 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10229 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10230 	}
10231 
10232 	ipsec_actvec_free(actp, nact);
10233 
10234 	/*
10235 	 * File the v4 policies.
10236 	 */
10237 	fam = IPSEC_AF_V4;
10238 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10239 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10240 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10241 
10242 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10243 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10244 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10245 
10246 	/*
10247 	 * If the requests need security, set enforce_policy.
10248 	 * If the requests are IPSEC_PREF_NEVER, one should
10249 	 * still set conn_out_enforce_policy so that an ipsec_out
10250 	 * gets attached in ip_wput. This is needed so that
10251 	 * for connections that we don't cache policy in ip_bind,
10252 	 * if global policy matches in ip_wput_attach_policy, we
10253 	 * don't wrongly inherit global policy. Similarly, we need
10254 	 * to set conn_in_enforce_policy also so that we don't verify
10255 	 * policy wrongly.
10256 	 */
10257 	if ((ah_req & REQ_MASK) != 0 ||
10258 	    (esp_req & REQ_MASK) != 0 ||
10259 	    (se_req & REQ_MASK) != 0) {
10260 		connp->conn_in_enforce_policy = B_TRUE;
10261 		connp->conn_out_enforce_policy = B_TRUE;
10262 		connp->conn_flags |= IPCL_CHECK_POLICY;
10263 	}
10264 
10265 	mutex_exit(&connp->conn_lock);
10266 	return (error);
10267 #undef REQ_MASK
10268 
10269 	/*
10270 	 * Common memory-allocation-failure exit path.
10271 	 */
10272 enomem:
10273 	mutex_exit(&connp->conn_lock);
10274 	if (actp != NULL)
10275 		ipsec_actvec_free(actp, nact);
10276 	if (pin4 != NULL)
10277 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10278 	if (pout4 != NULL)
10279 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10280 	if (pin6 != NULL)
10281 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10282 	if (pout6 != NULL)
10283 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10284 	return (ENOMEM);
10285 }
10286 
10287 /*
10288  * Only for options that pass in an IP addr. Currently only V4 options
10289  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10290  * So this function assumes level is IPPROTO_IP
10291  */
10292 int
10293 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10294     mblk_t *first_mp)
10295 {
10296 	ipif_t *ipif = NULL;
10297 	int error;
10298 	ill_t *ill;
10299 	int zoneid;
10300 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10301 
10302 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10303 
10304 	if (addr != INADDR_ANY || checkonly) {
10305 		ASSERT(connp != NULL);
10306 		zoneid = IPCL_ZONEID(connp);
10307 		if (option == IP_NEXTHOP) {
10308 			ipif = ipif_lookup_onlink_addr(addr,
10309 			    connp->conn_zoneid, ipst);
10310 		} else {
10311 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10312 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10313 			    &error, ipst);
10314 		}
10315 		if (ipif == NULL) {
10316 			if (error == EINPROGRESS)
10317 				return (error);
10318 			else if ((option == IP_MULTICAST_IF) ||
10319 			    (option == IP_NEXTHOP))
10320 				return (EHOSTUNREACH);
10321 			else
10322 				return (EINVAL);
10323 		} else if (checkonly) {
10324 			if (option == IP_MULTICAST_IF) {
10325 				ill = ipif->ipif_ill;
10326 				/* not supported by the virtual network iface */
10327 				if (IS_VNI(ill)) {
10328 					ipif_refrele(ipif);
10329 					return (EINVAL);
10330 				}
10331 			}
10332 			ipif_refrele(ipif);
10333 			return (0);
10334 		}
10335 		ill = ipif->ipif_ill;
10336 		mutex_enter(&connp->conn_lock);
10337 		mutex_enter(&ill->ill_lock);
10338 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10339 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10340 			mutex_exit(&ill->ill_lock);
10341 			mutex_exit(&connp->conn_lock);
10342 			ipif_refrele(ipif);
10343 			return (option == IP_MULTICAST_IF ?
10344 			    EHOSTUNREACH : EINVAL);
10345 		}
10346 	} else {
10347 		mutex_enter(&connp->conn_lock);
10348 	}
10349 
10350 	/* None of the options below are supported on the VNI */
10351 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10352 		mutex_exit(&ill->ill_lock);
10353 		mutex_exit(&connp->conn_lock);
10354 		ipif_refrele(ipif);
10355 		return (EINVAL);
10356 	}
10357 
10358 	switch (option) {
10359 	case IP_DONTFAILOVER_IF:
10360 		/*
10361 		 * This option is used by in.mpathd to ensure
10362 		 * that IPMP probe packets only go out on the
10363 		 * test interfaces. in.mpathd sets this option
10364 		 * on the non-failover interfaces.
10365 		 * For backward compatibility, this option
10366 		 * implicitly sets IP_MULTICAST_IF, as used
10367 		 * be done in bind(), so that ip_wput gets
10368 		 * this ipif to send mcast packets.
10369 		 */
10370 		if (ipif != NULL) {
10371 			ASSERT(addr != INADDR_ANY);
10372 			connp->conn_nofailover_ill = ipif->ipif_ill;
10373 			connp->conn_multicast_ipif = ipif;
10374 		} else {
10375 			ASSERT(addr == INADDR_ANY);
10376 			connp->conn_nofailover_ill = NULL;
10377 			connp->conn_multicast_ipif = NULL;
10378 		}
10379 		break;
10380 
10381 	case IP_MULTICAST_IF:
10382 		connp->conn_multicast_ipif = ipif;
10383 		break;
10384 	case IP_NEXTHOP:
10385 		connp->conn_nexthop_v4 = addr;
10386 		connp->conn_nexthop_set = B_TRUE;
10387 		break;
10388 	}
10389 
10390 	if (ipif != NULL) {
10391 		mutex_exit(&ill->ill_lock);
10392 		mutex_exit(&connp->conn_lock);
10393 		ipif_refrele(ipif);
10394 		return (0);
10395 	}
10396 	mutex_exit(&connp->conn_lock);
10397 	/* We succeded in cleared the option */
10398 	return (0);
10399 }
10400 
10401 /*
10402  * For options that pass in an ifindex specifying the ill. V6 options always
10403  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10404  */
10405 int
10406 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10407     int level, int option, mblk_t *first_mp)
10408 {
10409 	ill_t *ill = NULL;
10410 	int error = 0;
10411 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10412 
10413 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10414 	if (ifindex != 0) {
10415 		ASSERT(connp != NULL);
10416 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10417 		    first_mp, ip_restart_optmgmt, &error, ipst);
10418 		if (ill != NULL) {
10419 			if (checkonly) {
10420 				/* not supported by the virtual network iface */
10421 				if (IS_VNI(ill)) {
10422 					ill_refrele(ill);
10423 					return (EINVAL);
10424 				}
10425 				ill_refrele(ill);
10426 				return (0);
10427 			}
10428 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10429 			    0, NULL)) {
10430 				ill_refrele(ill);
10431 				ill = NULL;
10432 				mutex_enter(&connp->conn_lock);
10433 				goto setit;
10434 			}
10435 			mutex_enter(&connp->conn_lock);
10436 			mutex_enter(&ill->ill_lock);
10437 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10438 				mutex_exit(&ill->ill_lock);
10439 				mutex_exit(&connp->conn_lock);
10440 				ill_refrele(ill);
10441 				ill = NULL;
10442 				mutex_enter(&connp->conn_lock);
10443 			}
10444 			goto setit;
10445 		} else if (error == EINPROGRESS) {
10446 			return (error);
10447 		} else {
10448 			error = 0;
10449 		}
10450 	}
10451 	mutex_enter(&connp->conn_lock);
10452 setit:
10453 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10454 
10455 	/*
10456 	 * The options below assume that the ILL (if any) transmits and/or
10457 	 * receives traffic. Neither of which is true for the virtual network
10458 	 * interface, so fail setting these on a VNI.
10459 	 */
10460 	if (IS_VNI(ill)) {
10461 		ASSERT(ill != NULL);
10462 		mutex_exit(&ill->ill_lock);
10463 		mutex_exit(&connp->conn_lock);
10464 		ill_refrele(ill);
10465 		return (EINVAL);
10466 	}
10467 
10468 	if (level == IPPROTO_IP) {
10469 		switch (option) {
10470 		case IP_BOUND_IF:
10471 			connp->conn_incoming_ill = ill;
10472 			connp->conn_outgoing_ill = ill;
10473 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10474 			    0 : ifindex;
10475 			break;
10476 
10477 		case IP_XMIT_IF:
10478 			/*
10479 			 * Similar to IP_BOUND_IF, but this only
10480 			 * determines the outgoing interface for
10481 			 * unicast packets. Also no IRE_CACHE entry
10482 			 * is added for the destination of the
10483 			 * outgoing packets.
10484 			 */
10485 			connp->conn_xmit_if_ill = ill;
10486 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
10487 			    0 : ifindex;
10488 			break;
10489 
10490 		case IP_MULTICAST_IF:
10491 			/*
10492 			 * This option is an internal special. The socket
10493 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10494 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10495 			 * specifies an ifindex and we try first on V6 ill's.
10496 			 * If we don't find one, we they try using on v4 ill's
10497 			 * intenally and we come here.
10498 			 */
10499 			if (!checkonly && ill != NULL) {
10500 				ipif_t	*ipif;
10501 				ipif = ill->ill_ipif;
10502 
10503 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10504 					mutex_exit(&ill->ill_lock);
10505 					mutex_exit(&connp->conn_lock);
10506 					ill_refrele(ill);
10507 					ill = NULL;
10508 					mutex_enter(&connp->conn_lock);
10509 				} else {
10510 					connp->conn_multicast_ipif = ipif;
10511 				}
10512 			}
10513 			break;
10514 		}
10515 	} else {
10516 		switch (option) {
10517 		case IPV6_BOUND_IF:
10518 			connp->conn_incoming_ill = ill;
10519 			connp->conn_outgoing_ill = ill;
10520 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10521 			    0 : ifindex;
10522 			break;
10523 
10524 		case IPV6_BOUND_PIF:
10525 			/*
10526 			 * Limit all transmit to this ill.
10527 			 * Unlike IPV6_BOUND_IF, using this option
10528 			 * prevents load spreading and failover from
10529 			 * happening when the interface is part of the
10530 			 * group. That's why we don't need to remember
10531 			 * the ifindex in orig_bound_ifindex as in
10532 			 * IPV6_BOUND_IF.
10533 			 */
10534 			connp->conn_outgoing_pill = ill;
10535 			break;
10536 
10537 		case IPV6_DONTFAILOVER_IF:
10538 			/*
10539 			 * This option is used by in.mpathd to ensure
10540 			 * that IPMP probe packets only go out on the
10541 			 * test interfaces. in.mpathd sets this option
10542 			 * on the non-failover interfaces.
10543 			 */
10544 			connp->conn_nofailover_ill = ill;
10545 			/*
10546 			 * For backward compatibility, this option
10547 			 * implicitly sets ip_multicast_ill as used in
10548 			 * IPV6_MULTICAST_IF so that ip_wput gets
10549 			 * this ill to send mcast packets.
10550 			 */
10551 			connp->conn_multicast_ill = ill;
10552 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10553 			    0 : ifindex;
10554 			break;
10555 
10556 		case IPV6_MULTICAST_IF:
10557 			/*
10558 			 * Set conn_multicast_ill to be the IPv6 ill.
10559 			 * Set conn_multicast_ipif to be an IPv4 ipif
10560 			 * for ifindex to make IPv4 mapped addresses
10561 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10562 			 * Even if no IPv6 ill exists for the ifindex
10563 			 * we need to check for an IPv4 ifindex in order
10564 			 * for this to work with mapped addresses. In that
10565 			 * case only set conn_multicast_ipif.
10566 			 */
10567 			if (!checkonly) {
10568 				if (ifindex == 0) {
10569 					connp->conn_multicast_ill = NULL;
10570 					connp->conn_orig_multicast_ifindex = 0;
10571 					connp->conn_multicast_ipif = NULL;
10572 				} else if (ill != NULL) {
10573 					connp->conn_multicast_ill = ill;
10574 					connp->conn_orig_multicast_ifindex =
10575 					    ifindex;
10576 				}
10577 			}
10578 			break;
10579 		}
10580 	}
10581 
10582 	if (ill != NULL) {
10583 		mutex_exit(&ill->ill_lock);
10584 		mutex_exit(&connp->conn_lock);
10585 		ill_refrele(ill);
10586 		return (0);
10587 	}
10588 	mutex_exit(&connp->conn_lock);
10589 	/*
10590 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10591 	 * locate the ill and could not set the option (ifindex != 0)
10592 	 */
10593 	return (ifindex == 0 ? 0 : EINVAL);
10594 }
10595 
10596 /* This routine sets socket options. */
10597 /* ARGSUSED */
10598 int
10599 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10600     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10601     void *dummy, cred_t *cr, mblk_t *first_mp)
10602 {
10603 	int		*i1 = (int *)invalp;
10604 	conn_t		*connp = Q_TO_CONN(q);
10605 	int		error = 0;
10606 	boolean_t	checkonly;
10607 	ire_t		*ire;
10608 	boolean_t	found;
10609 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10610 
10611 	switch (optset_context) {
10612 
10613 	case SETFN_OPTCOM_CHECKONLY:
10614 		checkonly = B_TRUE;
10615 		/*
10616 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10617 		 * inlen != 0 implies value supplied and
10618 		 * 	we have to "pretend" to set it.
10619 		 * inlen == 0 implies that there is no
10620 		 * 	value part in T_CHECK request and just validation
10621 		 * done elsewhere should be enough, we just return here.
10622 		 */
10623 		if (inlen == 0) {
10624 			*outlenp = 0;
10625 			return (0);
10626 		}
10627 		break;
10628 	case SETFN_OPTCOM_NEGOTIATE:
10629 	case SETFN_UD_NEGOTIATE:
10630 	case SETFN_CONN_NEGOTIATE:
10631 		checkonly = B_FALSE;
10632 		break;
10633 	default:
10634 		/*
10635 		 * We should never get here
10636 		 */
10637 		*outlenp = 0;
10638 		return (EINVAL);
10639 	}
10640 
10641 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10642 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10643 
10644 	/*
10645 	 * For fixed length options, no sanity check
10646 	 * of passed in length is done. It is assumed *_optcom_req()
10647 	 * routines do the right thing.
10648 	 */
10649 
10650 	switch (level) {
10651 	case SOL_SOCKET:
10652 		/*
10653 		 * conn_lock protects the bitfields, and is used to
10654 		 * set the fields atomically.
10655 		 */
10656 		switch (name) {
10657 		case SO_BROADCAST:
10658 			if (!checkonly) {
10659 				/* TODO: use value someplace? */
10660 				mutex_enter(&connp->conn_lock);
10661 				connp->conn_broadcast = *i1 ? 1 : 0;
10662 				mutex_exit(&connp->conn_lock);
10663 			}
10664 			break;	/* goto sizeof (int) option return */
10665 		case SO_USELOOPBACK:
10666 			if (!checkonly) {
10667 				/* TODO: use value someplace? */
10668 				mutex_enter(&connp->conn_lock);
10669 				connp->conn_loopback = *i1 ? 1 : 0;
10670 				mutex_exit(&connp->conn_lock);
10671 			}
10672 			break;	/* goto sizeof (int) option return */
10673 		case SO_DONTROUTE:
10674 			if (!checkonly) {
10675 				mutex_enter(&connp->conn_lock);
10676 				connp->conn_dontroute = *i1 ? 1 : 0;
10677 				mutex_exit(&connp->conn_lock);
10678 			}
10679 			break;	/* goto sizeof (int) option return */
10680 		case SO_REUSEADDR:
10681 			if (!checkonly) {
10682 				mutex_enter(&connp->conn_lock);
10683 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10684 				mutex_exit(&connp->conn_lock);
10685 			}
10686 			break;	/* goto sizeof (int) option return */
10687 		case SO_PROTOTYPE:
10688 			if (!checkonly) {
10689 				mutex_enter(&connp->conn_lock);
10690 				connp->conn_proto = *i1;
10691 				mutex_exit(&connp->conn_lock);
10692 			}
10693 			break;	/* goto sizeof (int) option return */
10694 		case SO_ALLZONES:
10695 			if (!checkonly) {
10696 				mutex_enter(&connp->conn_lock);
10697 				if (IPCL_IS_BOUND(connp)) {
10698 					mutex_exit(&connp->conn_lock);
10699 					return (EINVAL);
10700 				}
10701 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10702 				mutex_exit(&connp->conn_lock);
10703 			}
10704 			break;	/* goto sizeof (int) option return */
10705 		case SO_ANON_MLP:
10706 			if (!checkonly) {
10707 				mutex_enter(&connp->conn_lock);
10708 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10709 				mutex_exit(&connp->conn_lock);
10710 			}
10711 			break;	/* goto sizeof (int) option return */
10712 		case SO_MAC_EXEMPT:
10713 			if (secpolicy_net_mac_aware(cr) != 0 ||
10714 			    IPCL_IS_BOUND(connp))
10715 				return (EACCES);
10716 			if (!checkonly) {
10717 				mutex_enter(&connp->conn_lock);
10718 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10719 				mutex_exit(&connp->conn_lock);
10720 			}
10721 			break;	/* goto sizeof (int) option return */
10722 		default:
10723 			/*
10724 			 * "soft" error (negative)
10725 			 * option not handled at this level
10726 			 * Note: Do not modify *outlenp
10727 			 */
10728 			return (-EINVAL);
10729 		}
10730 		break;
10731 	case IPPROTO_IP:
10732 		switch (name) {
10733 		case IP_NEXTHOP:
10734 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10735 				return (EPERM);
10736 			/* FALLTHRU */
10737 		case IP_MULTICAST_IF:
10738 		case IP_DONTFAILOVER_IF: {
10739 			ipaddr_t addr = *i1;
10740 
10741 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10742 			    first_mp);
10743 			if (error != 0)
10744 				return (error);
10745 			break;	/* goto sizeof (int) option return */
10746 		}
10747 
10748 		case IP_MULTICAST_TTL:
10749 			/* Recorded in transport above IP */
10750 			*outvalp = *invalp;
10751 			*outlenp = sizeof (uchar_t);
10752 			return (0);
10753 		case IP_MULTICAST_LOOP:
10754 			if (!checkonly) {
10755 				mutex_enter(&connp->conn_lock);
10756 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10757 				mutex_exit(&connp->conn_lock);
10758 			}
10759 			*outvalp = *invalp;
10760 			*outlenp = sizeof (uchar_t);
10761 			return (0);
10762 		case IP_ADD_MEMBERSHIP:
10763 		case MCAST_JOIN_GROUP:
10764 		case IP_DROP_MEMBERSHIP:
10765 		case MCAST_LEAVE_GROUP: {
10766 			struct ip_mreq *mreqp;
10767 			struct group_req *greqp;
10768 			ire_t *ire;
10769 			boolean_t done = B_FALSE;
10770 			ipaddr_t group, ifaddr;
10771 			struct sockaddr_in *sin;
10772 			uint32_t *ifindexp;
10773 			boolean_t mcast_opt = B_TRUE;
10774 			mcast_record_t fmode;
10775 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10776 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10777 
10778 			switch (name) {
10779 			case IP_ADD_MEMBERSHIP:
10780 				mcast_opt = B_FALSE;
10781 				/* FALLTHRU */
10782 			case MCAST_JOIN_GROUP:
10783 				fmode = MODE_IS_EXCLUDE;
10784 				optfn = ip_opt_add_group;
10785 				break;
10786 
10787 			case IP_DROP_MEMBERSHIP:
10788 				mcast_opt = B_FALSE;
10789 				/* FALLTHRU */
10790 			case MCAST_LEAVE_GROUP:
10791 				fmode = MODE_IS_INCLUDE;
10792 				optfn = ip_opt_delete_group;
10793 				break;
10794 			}
10795 
10796 			if (mcast_opt) {
10797 				greqp = (struct group_req *)i1;
10798 				sin = (struct sockaddr_in *)&greqp->gr_group;
10799 				if (sin->sin_family != AF_INET) {
10800 					*outlenp = 0;
10801 					return (ENOPROTOOPT);
10802 				}
10803 				group = (ipaddr_t)sin->sin_addr.s_addr;
10804 				ifaddr = INADDR_ANY;
10805 				ifindexp = &greqp->gr_interface;
10806 			} else {
10807 				mreqp = (struct ip_mreq *)i1;
10808 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10809 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10810 				ifindexp = NULL;
10811 			}
10812 
10813 			/*
10814 			 * In the multirouting case, we need to replicate
10815 			 * the request on all interfaces that will take part
10816 			 * in replication.  We do so because multirouting is
10817 			 * reflective, thus we will probably receive multi-
10818 			 * casts on those interfaces.
10819 			 * The ip_multirt_apply_membership() succeeds if the
10820 			 * operation succeeds on at least one interface.
10821 			 */
10822 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10823 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10824 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10825 			if (ire != NULL) {
10826 				if (ire->ire_flags & RTF_MULTIRT) {
10827 					error = ip_multirt_apply_membership(
10828 					    optfn, ire, connp, checkonly, group,
10829 					    fmode, INADDR_ANY, first_mp);
10830 					done = B_TRUE;
10831 				}
10832 				ire_refrele(ire);
10833 			}
10834 			if (!done) {
10835 				error = optfn(connp, checkonly, group, ifaddr,
10836 				    ifindexp, fmode, INADDR_ANY, first_mp);
10837 			}
10838 			if (error) {
10839 				/*
10840 				 * EINPROGRESS is a soft error, needs retry
10841 				 * so don't make *outlenp zero.
10842 				 */
10843 				if (error != EINPROGRESS)
10844 					*outlenp = 0;
10845 				return (error);
10846 			}
10847 			/* OK return - copy input buffer into output buffer */
10848 			if (invalp != outvalp) {
10849 				/* don't trust bcopy for identical src/dst */
10850 				bcopy(invalp, outvalp, inlen);
10851 			}
10852 			*outlenp = inlen;
10853 			return (0);
10854 		}
10855 		case IP_BLOCK_SOURCE:
10856 		case IP_UNBLOCK_SOURCE:
10857 		case IP_ADD_SOURCE_MEMBERSHIP:
10858 		case IP_DROP_SOURCE_MEMBERSHIP:
10859 		case MCAST_BLOCK_SOURCE:
10860 		case MCAST_UNBLOCK_SOURCE:
10861 		case MCAST_JOIN_SOURCE_GROUP:
10862 		case MCAST_LEAVE_SOURCE_GROUP: {
10863 			struct ip_mreq_source *imreqp;
10864 			struct group_source_req *gsreqp;
10865 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10866 			uint32_t ifindex = 0;
10867 			mcast_record_t fmode;
10868 			struct sockaddr_in *sin;
10869 			ire_t *ire;
10870 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10871 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10872 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10873 
10874 			switch (name) {
10875 			case IP_BLOCK_SOURCE:
10876 				mcast_opt = B_FALSE;
10877 				/* FALLTHRU */
10878 			case MCAST_BLOCK_SOURCE:
10879 				fmode = MODE_IS_EXCLUDE;
10880 				optfn = ip_opt_add_group;
10881 				break;
10882 
10883 			case IP_UNBLOCK_SOURCE:
10884 				mcast_opt = B_FALSE;
10885 				/* FALLTHRU */
10886 			case MCAST_UNBLOCK_SOURCE:
10887 				fmode = MODE_IS_EXCLUDE;
10888 				optfn = ip_opt_delete_group;
10889 				break;
10890 
10891 			case IP_ADD_SOURCE_MEMBERSHIP:
10892 				mcast_opt = B_FALSE;
10893 				/* FALLTHRU */
10894 			case MCAST_JOIN_SOURCE_GROUP:
10895 				fmode = MODE_IS_INCLUDE;
10896 				optfn = ip_opt_add_group;
10897 				break;
10898 
10899 			case IP_DROP_SOURCE_MEMBERSHIP:
10900 				mcast_opt = B_FALSE;
10901 				/* FALLTHRU */
10902 			case MCAST_LEAVE_SOURCE_GROUP:
10903 				fmode = MODE_IS_INCLUDE;
10904 				optfn = ip_opt_delete_group;
10905 				break;
10906 			}
10907 
10908 			if (mcast_opt) {
10909 				gsreqp = (struct group_source_req *)i1;
10910 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10911 					*outlenp = 0;
10912 					return (ENOPROTOOPT);
10913 				}
10914 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10915 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10916 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10917 				src = (ipaddr_t)sin->sin_addr.s_addr;
10918 				ifindex = gsreqp->gsr_interface;
10919 			} else {
10920 				imreqp = (struct ip_mreq_source *)i1;
10921 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10922 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10923 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10924 			}
10925 
10926 			/*
10927 			 * In the multirouting case, we need to replicate
10928 			 * the request as noted in the mcast cases above.
10929 			 */
10930 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10931 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10932 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10933 			if (ire != NULL) {
10934 				if (ire->ire_flags & RTF_MULTIRT) {
10935 					error = ip_multirt_apply_membership(
10936 					    optfn, ire, connp, checkonly, grp,
10937 					    fmode, src, first_mp);
10938 					done = B_TRUE;
10939 				}
10940 				ire_refrele(ire);
10941 			}
10942 			if (!done) {
10943 				error = optfn(connp, checkonly, grp, ifaddr,
10944 				    &ifindex, fmode, src, first_mp);
10945 			}
10946 			if (error != 0) {
10947 				/*
10948 				 * EINPROGRESS is a soft error, needs retry
10949 				 * so don't make *outlenp zero.
10950 				 */
10951 				if (error != EINPROGRESS)
10952 					*outlenp = 0;
10953 				return (error);
10954 			}
10955 			/* OK return - copy input buffer into output buffer */
10956 			if (invalp != outvalp) {
10957 				bcopy(invalp, outvalp, inlen);
10958 			}
10959 			*outlenp = inlen;
10960 			return (0);
10961 		}
10962 		case IP_SEC_OPT:
10963 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10964 			if (error != 0) {
10965 				*outlenp = 0;
10966 				return (error);
10967 			}
10968 			break;
10969 		case IP_HDRINCL:
10970 		case IP_OPTIONS:
10971 		case T_IP_OPTIONS:
10972 		case IP_TOS:
10973 		case T_IP_TOS:
10974 		case IP_TTL:
10975 		case IP_RECVDSTADDR:
10976 		case IP_RECVOPTS:
10977 			/* OK return - copy input buffer into output buffer */
10978 			if (invalp != outvalp) {
10979 				/* don't trust bcopy for identical src/dst */
10980 				bcopy(invalp, outvalp, inlen);
10981 			}
10982 			*outlenp = inlen;
10983 			return (0);
10984 		case IP_RECVIF:
10985 			/* Retrieve the inbound interface index */
10986 			if (!checkonly) {
10987 				mutex_enter(&connp->conn_lock);
10988 				connp->conn_recvif = *i1 ? 1 : 0;
10989 				mutex_exit(&connp->conn_lock);
10990 			}
10991 			break;	/* goto sizeof (int) option return */
10992 		case IP_RECVPKTINFO:
10993 			if (!checkonly) {
10994 				mutex_enter(&connp->conn_lock);
10995 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
10996 				mutex_exit(&connp->conn_lock);
10997 			}
10998 			break;	/* goto sizeof (int) option return */
10999 		case IP_RECVSLLA:
11000 			/* Retrieve the source link layer address */
11001 			if (!checkonly) {
11002 				mutex_enter(&connp->conn_lock);
11003 				connp->conn_recvslla = *i1 ? 1 : 0;
11004 				mutex_exit(&connp->conn_lock);
11005 			}
11006 			break;	/* goto sizeof (int) option return */
11007 		case MRT_INIT:
11008 		case MRT_DONE:
11009 		case MRT_ADD_VIF:
11010 		case MRT_DEL_VIF:
11011 		case MRT_ADD_MFC:
11012 		case MRT_DEL_MFC:
11013 		case MRT_ASSERT:
11014 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11015 				*outlenp = 0;
11016 				return (error);
11017 			}
11018 			error = ip_mrouter_set((int)name, q, checkonly,
11019 			    (uchar_t *)invalp, inlen, first_mp);
11020 			if (error) {
11021 				*outlenp = 0;
11022 				return (error);
11023 			}
11024 			/* OK return - copy input buffer into output buffer */
11025 			if (invalp != outvalp) {
11026 				/* don't trust bcopy for identical src/dst */
11027 				bcopy(invalp, outvalp, inlen);
11028 			}
11029 			*outlenp = inlen;
11030 			return (0);
11031 		case IP_BOUND_IF:
11032 		case IP_XMIT_IF:
11033 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11034 			    level, name, first_mp);
11035 			if (error != 0)
11036 				return (error);
11037 			break; 		/* goto sizeof (int) option return */
11038 
11039 		case IP_UNSPEC_SRC:
11040 			/* Allow sending with a zero source address */
11041 			if (!checkonly) {
11042 				mutex_enter(&connp->conn_lock);
11043 				connp->conn_unspec_src = *i1 ? 1 : 0;
11044 				mutex_exit(&connp->conn_lock);
11045 			}
11046 			break;	/* goto sizeof (int) option return */
11047 		default:
11048 			/*
11049 			 * "soft" error (negative)
11050 			 * option not handled at this level
11051 			 * Note: Do not modify *outlenp
11052 			 */
11053 			return (-EINVAL);
11054 		}
11055 		break;
11056 	case IPPROTO_IPV6:
11057 		switch (name) {
11058 		case IPV6_BOUND_IF:
11059 		case IPV6_BOUND_PIF:
11060 		case IPV6_DONTFAILOVER_IF:
11061 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11062 			    level, name, first_mp);
11063 			if (error != 0)
11064 				return (error);
11065 			break; 		/* goto sizeof (int) option return */
11066 
11067 		case IPV6_MULTICAST_IF:
11068 			/*
11069 			 * The only possible errors are EINPROGRESS and
11070 			 * EINVAL. EINPROGRESS will be restarted and is not
11071 			 * a hard error. We call this option on both V4 and V6
11072 			 * If both return EINVAL, then this call returns
11073 			 * EINVAL. If at least one of them succeeds we
11074 			 * return success.
11075 			 */
11076 			found = B_FALSE;
11077 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11078 			    level, name, first_mp);
11079 			if (error == EINPROGRESS)
11080 				return (error);
11081 			if (error == 0)
11082 				found = B_TRUE;
11083 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11084 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11085 			if (error == 0)
11086 				found = B_TRUE;
11087 			if (!found)
11088 				return (error);
11089 			break; 		/* goto sizeof (int) option return */
11090 
11091 		case IPV6_MULTICAST_HOPS:
11092 			/* Recorded in transport above IP */
11093 			break;	/* goto sizeof (int) option return */
11094 		case IPV6_MULTICAST_LOOP:
11095 			if (!checkonly) {
11096 				mutex_enter(&connp->conn_lock);
11097 				connp->conn_multicast_loop = *i1;
11098 				mutex_exit(&connp->conn_lock);
11099 			}
11100 			break;	/* goto sizeof (int) option return */
11101 		case IPV6_JOIN_GROUP:
11102 		case MCAST_JOIN_GROUP:
11103 		case IPV6_LEAVE_GROUP:
11104 		case MCAST_LEAVE_GROUP: {
11105 			struct ipv6_mreq *ip_mreqp;
11106 			struct group_req *greqp;
11107 			ire_t *ire;
11108 			boolean_t done = B_FALSE;
11109 			in6_addr_t groupv6;
11110 			uint32_t ifindex;
11111 			boolean_t mcast_opt = B_TRUE;
11112 			mcast_record_t fmode;
11113 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11114 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11115 
11116 			switch (name) {
11117 			case IPV6_JOIN_GROUP:
11118 				mcast_opt = B_FALSE;
11119 				/* FALLTHRU */
11120 			case MCAST_JOIN_GROUP:
11121 				fmode = MODE_IS_EXCLUDE;
11122 				optfn = ip_opt_add_group_v6;
11123 				break;
11124 
11125 			case IPV6_LEAVE_GROUP:
11126 				mcast_opt = B_FALSE;
11127 				/* FALLTHRU */
11128 			case MCAST_LEAVE_GROUP:
11129 				fmode = MODE_IS_INCLUDE;
11130 				optfn = ip_opt_delete_group_v6;
11131 				break;
11132 			}
11133 
11134 			if (mcast_opt) {
11135 				struct sockaddr_in *sin;
11136 				struct sockaddr_in6 *sin6;
11137 				greqp = (struct group_req *)i1;
11138 				if (greqp->gr_group.ss_family == AF_INET) {
11139 					sin = (struct sockaddr_in *)
11140 					    &(greqp->gr_group);
11141 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11142 					    &groupv6);
11143 				} else {
11144 					sin6 = (struct sockaddr_in6 *)
11145 					    &(greqp->gr_group);
11146 					groupv6 = sin6->sin6_addr;
11147 				}
11148 				ifindex = greqp->gr_interface;
11149 			} else {
11150 				ip_mreqp = (struct ipv6_mreq *)i1;
11151 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11152 				ifindex = ip_mreqp->ipv6mr_interface;
11153 			}
11154 			/*
11155 			 * In the multirouting case, we need to replicate
11156 			 * the request on all interfaces that will take part
11157 			 * in replication.  We do so because multirouting is
11158 			 * reflective, thus we will probably receive multi-
11159 			 * casts on those interfaces.
11160 			 * The ip_multirt_apply_membership_v6() succeeds if
11161 			 * the operation succeeds on at least one interface.
11162 			 */
11163 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11164 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11165 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11166 			if (ire != NULL) {
11167 				if (ire->ire_flags & RTF_MULTIRT) {
11168 					error = ip_multirt_apply_membership_v6(
11169 					    optfn, ire, connp, checkonly,
11170 					    &groupv6, fmode, &ipv6_all_zeros,
11171 					    first_mp);
11172 					done = B_TRUE;
11173 				}
11174 				ire_refrele(ire);
11175 			}
11176 			if (!done) {
11177 				error = optfn(connp, checkonly, &groupv6,
11178 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11179 			}
11180 			if (error) {
11181 				/*
11182 				 * EINPROGRESS is a soft error, needs retry
11183 				 * so don't make *outlenp zero.
11184 				 */
11185 				if (error != EINPROGRESS)
11186 					*outlenp = 0;
11187 				return (error);
11188 			}
11189 			/* OK return - copy input buffer into output buffer */
11190 			if (invalp != outvalp) {
11191 				/* don't trust bcopy for identical src/dst */
11192 				bcopy(invalp, outvalp, inlen);
11193 			}
11194 			*outlenp = inlen;
11195 			return (0);
11196 		}
11197 		case MCAST_BLOCK_SOURCE:
11198 		case MCAST_UNBLOCK_SOURCE:
11199 		case MCAST_JOIN_SOURCE_GROUP:
11200 		case MCAST_LEAVE_SOURCE_GROUP: {
11201 			struct group_source_req *gsreqp;
11202 			in6_addr_t v6grp, v6src;
11203 			uint32_t ifindex;
11204 			mcast_record_t fmode;
11205 			ire_t *ire;
11206 			boolean_t done = B_FALSE;
11207 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11208 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11209 
11210 			switch (name) {
11211 			case MCAST_BLOCK_SOURCE:
11212 				fmode = MODE_IS_EXCLUDE;
11213 				optfn = ip_opt_add_group_v6;
11214 				break;
11215 			case MCAST_UNBLOCK_SOURCE:
11216 				fmode = MODE_IS_EXCLUDE;
11217 				optfn = ip_opt_delete_group_v6;
11218 				break;
11219 			case MCAST_JOIN_SOURCE_GROUP:
11220 				fmode = MODE_IS_INCLUDE;
11221 				optfn = ip_opt_add_group_v6;
11222 				break;
11223 			case MCAST_LEAVE_SOURCE_GROUP:
11224 				fmode = MODE_IS_INCLUDE;
11225 				optfn = ip_opt_delete_group_v6;
11226 				break;
11227 			}
11228 
11229 			gsreqp = (struct group_source_req *)i1;
11230 			ifindex = gsreqp->gsr_interface;
11231 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11232 				struct sockaddr_in *s;
11233 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11234 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11235 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11236 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11237 			} else {
11238 				struct sockaddr_in6 *s6;
11239 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11240 				v6grp = s6->sin6_addr;
11241 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11242 				v6src = s6->sin6_addr;
11243 			}
11244 
11245 			/*
11246 			 * In the multirouting case, we need to replicate
11247 			 * the request as noted in the mcast cases above.
11248 			 */
11249 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11250 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11251 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11252 			if (ire != NULL) {
11253 				if (ire->ire_flags & RTF_MULTIRT) {
11254 					error = ip_multirt_apply_membership_v6(
11255 					    optfn, ire, connp, checkonly,
11256 					    &v6grp, fmode, &v6src, first_mp);
11257 					done = B_TRUE;
11258 				}
11259 				ire_refrele(ire);
11260 			}
11261 			if (!done) {
11262 				error = optfn(connp, checkonly, &v6grp,
11263 				    ifindex, fmode, &v6src, first_mp);
11264 			}
11265 			if (error != 0) {
11266 				/*
11267 				 * EINPROGRESS is a soft error, needs retry
11268 				 * so don't make *outlenp zero.
11269 				 */
11270 				if (error != EINPROGRESS)
11271 					*outlenp = 0;
11272 				return (error);
11273 			}
11274 			/* OK return - copy input buffer into output buffer */
11275 			if (invalp != outvalp) {
11276 				bcopy(invalp, outvalp, inlen);
11277 			}
11278 			*outlenp = inlen;
11279 			return (0);
11280 		}
11281 		case IPV6_UNICAST_HOPS:
11282 			/* Recorded in transport above IP */
11283 			break;	/* goto sizeof (int) option return */
11284 		case IPV6_UNSPEC_SRC:
11285 			/* Allow sending with a zero source address */
11286 			if (!checkonly) {
11287 				mutex_enter(&connp->conn_lock);
11288 				connp->conn_unspec_src = *i1 ? 1 : 0;
11289 				mutex_exit(&connp->conn_lock);
11290 			}
11291 			break;	/* goto sizeof (int) option return */
11292 		case IPV6_RECVPKTINFO:
11293 			if (!checkonly) {
11294 				mutex_enter(&connp->conn_lock);
11295 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11296 				mutex_exit(&connp->conn_lock);
11297 			}
11298 			break;	/* goto sizeof (int) option return */
11299 		case IPV6_RECVTCLASS:
11300 			if (!checkonly) {
11301 				if (*i1 < 0 || *i1 > 1) {
11302 					return (EINVAL);
11303 				}
11304 				mutex_enter(&connp->conn_lock);
11305 				connp->conn_ipv6_recvtclass = *i1;
11306 				mutex_exit(&connp->conn_lock);
11307 			}
11308 			break;
11309 		case IPV6_RECVPATHMTU:
11310 			if (!checkonly) {
11311 				if (*i1 < 0 || *i1 > 1) {
11312 					return (EINVAL);
11313 				}
11314 				mutex_enter(&connp->conn_lock);
11315 				connp->conn_ipv6_recvpathmtu = *i1;
11316 				mutex_exit(&connp->conn_lock);
11317 			}
11318 			break;
11319 		case IPV6_RECVHOPLIMIT:
11320 			if (!checkonly) {
11321 				mutex_enter(&connp->conn_lock);
11322 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11323 				mutex_exit(&connp->conn_lock);
11324 			}
11325 			break;	/* goto sizeof (int) option return */
11326 		case IPV6_RECVHOPOPTS:
11327 			if (!checkonly) {
11328 				mutex_enter(&connp->conn_lock);
11329 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11330 				mutex_exit(&connp->conn_lock);
11331 			}
11332 			break;	/* goto sizeof (int) option return */
11333 		case IPV6_RECVDSTOPTS:
11334 			if (!checkonly) {
11335 				mutex_enter(&connp->conn_lock);
11336 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11337 				mutex_exit(&connp->conn_lock);
11338 			}
11339 			break;	/* goto sizeof (int) option return */
11340 		case IPV6_RECVRTHDR:
11341 			if (!checkonly) {
11342 				mutex_enter(&connp->conn_lock);
11343 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11344 				mutex_exit(&connp->conn_lock);
11345 			}
11346 			break;	/* goto sizeof (int) option return */
11347 		case IPV6_RECVRTHDRDSTOPTS:
11348 			if (!checkonly) {
11349 				mutex_enter(&connp->conn_lock);
11350 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11351 				mutex_exit(&connp->conn_lock);
11352 			}
11353 			break;	/* goto sizeof (int) option return */
11354 		case IPV6_PKTINFO:
11355 			if (inlen == 0)
11356 				return (-EINVAL);	/* clearing option */
11357 			error = ip6_set_pktinfo(cr, connp,
11358 			    (struct in6_pktinfo *)invalp, first_mp);
11359 			if (error != 0)
11360 				*outlenp = 0;
11361 			else
11362 				*outlenp = inlen;
11363 			return (error);
11364 		case IPV6_NEXTHOP: {
11365 			struct sockaddr_in6 *sin6;
11366 
11367 			/* Verify that the nexthop is reachable */
11368 			if (inlen == 0)
11369 				return (-EINVAL);	/* clearing option */
11370 
11371 			sin6 = (struct sockaddr_in6 *)invalp;
11372 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11373 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11374 			    NULL, MATCH_IRE_DEFAULT, ipst);
11375 
11376 			if (ire == NULL) {
11377 				*outlenp = 0;
11378 				return (EHOSTUNREACH);
11379 			}
11380 			ire_refrele(ire);
11381 			return (-EINVAL);
11382 		}
11383 		case IPV6_SEC_OPT:
11384 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11385 			if (error != 0) {
11386 				*outlenp = 0;
11387 				return (error);
11388 			}
11389 			break;
11390 		case IPV6_SRC_PREFERENCES: {
11391 			/*
11392 			 * This is implemented strictly in the ip module
11393 			 * (here and in tcp_opt_*() to accomodate tcp
11394 			 * sockets).  Modules above ip pass this option
11395 			 * down here since ip is the only one that needs to
11396 			 * be aware of source address preferences.
11397 			 *
11398 			 * This socket option only affects connected
11399 			 * sockets that haven't already bound to a specific
11400 			 * IPv6 address.  In other words, sockets that
11401 			 * don't call bind() with an address other than the
11402 			 * unspecified address and that call connect().
11403 			 * ip_bind_connected_v6() passes these preferences
11404 			 * to the ipif_select_source_v6() function.
11405 			 */
11406 			if (inlen != sizeof (uint32_t))
11407 				return (EINVAL);
11408 			error = ip6_set_src_preferences(connp,
11409 			    *(uint32_t *)invalp);
11410 			if (error != 0) {
11411 				*outlenp = 0;
11412 				return (error);
11413 			} else {
11414 				*outlenp = sizeof (uint32_t);
11415 			}
11416 			break;
11417 		}
11418 		case IPV6_V6ONLY:
11419 			if (*i1 < 0 || *i1 > 1) {
11420 				return (EINVAL);
11421 			}
11422 			mutex_enter(&connp->conn_lock);
11423 			connp->conn_ipv6_v6only = *i1;
11424 			mutex_exit(&connp->conn_lock);
11425 			break;
11426 		default:
11427 			return (-EINVAL);
11428 		}
11429 		break;
11430 	default:
11431 		/*
11432 		 * "soft" error (negative)
11433 		 * option not handled at this level
11434 		 * Note: Do not modify *outlenp
11435 		 */
11436 		return (-EINVAL);
11437 	}
11438 	/*
11439 	 * Common case of return from an option that is sizeof (int)
11440 	 */
11441 	*(int *)outvalp = *i1;
11442 	*outlenp = sizeof (int);
11443 	return (0);
11444 }
11445 
11446 /*
11447  * This routine gets default values of certain options whose default
11448  * values are maintained by protocol specific code
11449  */
11450 /* ARGSUSED */
11451 int
11452 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11453 {
11454 	int *i1 = (int *)ptr;
11455 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11456 
11457 	switch (level) {
11458 	case IPPROTO_IP:
11459 		switch (name) {
11460 		case IP_MULTICAST_TTL:
11461 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11462 			return (sizeof (uchar_t));
11463 		case IP_MULTICAST_LOOP:
11464 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11465 			return (sizeof (uchar_t));
11466 		default:
11467 			return (-1);
11468 		}
11469 	case IPPROTO_IPV6:
11470 		switch (name) {
11471 		case IPV6_UNICAST_HOPS:
11472 			*i1 = ipst->ips_ipv6_def_hops;
11473 			return (sizeof (int));
11474 		case IPV6_MULTICAST_HOPS:
11475 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11476 			return (sizeof (int));
11477 		case IPV6_MULTICAST_LOOP:
11478 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11479 			return (sizeof (int));
11480 		case IPV6_V6ONLY:
11481 			*i1 = 1;
11482 			return (sizeof (int));
11483 		default:
11484 			return (-1);
11485 		}
11486 	default:
11487 		return (-1);
11488 	}
11489 	/* NOTREACHED */
11490 }
11491 
11492 /*
11493  * Given a destination address and a pointer to where to put the information
11494  * this routine fills in the mtuinfo.
11495  */
11496 int
11497 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11498     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11499 {
11500 	ire_t *ire;
11501 	ip_stack_t	*ipst = ns->netstack_ip;
11502 
11503 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11504 		return (-1);
11505 
11506 	bzero(mtuinfo, sizeof (*mtuinfo));
11507 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11508 	mtuinfo->ip6m_addr.sin6_port = port;
11509 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11510 
11511 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11512 	if (ire != NULL) {
11513 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11514 		ire_refrele(ire);
11515 	} else {
11516 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11517 	}
11518 	return (sizeof (struct ip6_mtuinfo));
11519 }
11520 
11521 /*
11522  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11523  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11524  * isn't.  This doesn't matter as the error checking is done properly for the
11525  * other MRT options coming in through ip_opt_set.
11526  */
11527 int
11528 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11529 {
11530 	conn_t		*connp = Q_TO_CONN(q);
11531 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11532 
11533 	switch (level) {
11534 	case IPPROTO_IP:
11535 		switch (name) {
11536 		case MRT_VERSION:
11537 		case MRT_ASSERT:
11538 			(void) ip_mrouter_get(name, q, ptr);
11539 			return (sizeof (int));
11540 		case IP_SEC_OPT:
11541 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11542 		case IP_NEXTHOP:
11543 			if (connp->conn_nexthop_set) {
11544 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11545 				return (sizeof (ipaddr_t));
11546 			} else
11547 				return (0);
11548 		case IP_RECVPKTINFO:
11549 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11550 			return (sizeof (int));
11551 		default:
11552 			break;
11553 		}
11554 		break;
11555 	case IPPROTO_IPV6:
11556 		switch (name) {
11557 		case IPV6_SEC_OPT:
11558 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11559 		case IPV6_SRC_PREFERENCES: {
11560 			return (ip6_get_src_preferences(connp,
11561 			    (uint32_t *)ptr));
11562 		}
11563 		case IPV6_V6ONLY:
11564 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11565 			return (sizeof (int));
11566 		case IPV6_PATHMTU:
11567 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11568 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11569 		default:
11570 			break;
11571 		}
11572 		break;
11573 	default:
11574 		break;
11575 	}
11576 	return (-1);
11577 }
11578 
11579 /* Named Dispatch routine to get a current value out of our parameter table. */
11580 /* ARGSUSED */
11581 static int
11582 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11583 {
11584 	ipparam_t *ippa = (ipparam_t *)cp;
11585 
11586 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11587 	return (0);
11588 }
11589 
11590 /* ARGSUSED */
11591 static int
11592 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11593 {
11594 
11595 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11596 	return (0);
11597 }
11598 
11599 /*
11600  * Set ip{,6}_forwarding values.  This means walking through all of the
11601  * ill's and toggling their forwarding values.
11602  */
11603 /* ARGSUSED */
11604 static int
11605 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11606 {
11607 	long new_value;
11608 	int *forwarding_value = (int *)cp;
11609 	ill_t *ill;
11610 	boolean_t isv6;
11611 	ill_walk_context_t ctx;
11612 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11613 
11614 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11615 
11616 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11617 	    new_value < 0 || new_value > 1) {
11618 		return (EINVAL);
11619 	}
11620 
11621 	*forwarding_value = new_value;
11622 
11623 	/*
11624 	 * Regardless of the current value of ip_forwarding, set all per-ill
11625 	 * values of ip_forwarding to the value being set.
11626 	 *
11627 	 * Bring all the ill's up to date with the new global value.
11628 	 */
11629 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11630 
11631 	if (isv6)
11632 		ill = ILL_START_WALK_V6(&ctx, ipst);
11633 	else
11634 		ill = ILL_START_WALK_V4(&ctx, ipst);
11635 
11636 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11637 		(void) ill_forward_set(ill, new_value != 0);
11638 
11639 	rw_exit(&ipst->ips_ill_g_lock);
11640 	return (0);
11641 }
11642 
11643 /*
11644  * Walk through the param array specified registering each element with the
11645  * Named Dispatch handler. This is called only during init. So it is ok
11646  * not to acquire any locks
11647  */
11648 static boolean_t
11649 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11650     ipndp_t *ipnd, size_t ipnd_cnt)
11651 {
11652 	for (; ippa_cnt-- > 0; ippa++) {
11653 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11654 			if (!nd_load(ndp, ippa->ip_param_name,
11655 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11656 				nd_free(ndp);
11657 				return (B_FALSE);
11658 			}
11659 		}
11660 	}
11661 
11662 	for (; ipnd_cnt-- > 0; ipnd++) {
11663 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11664 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11665 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11666 			    ipnd->ip_ndp_data)) {
11667 				nd_free(ndp);
11668 				return (B_FALSE);
11669 			}
11670 		}
11671 	}
11672 
11673 	return (B_TRUE);
11674 }
11675 
11676 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11677 /* ARGSUSED */
11678 static int
11679 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11680 {
11681 	long		new_value;
11682 	ipparam_t	*ippa = (ipparam_t *)cp;
11683 
11684 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11685 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11686 		return (EINVAL);
11687 	}
11688 	ippa->ip_param_value = new_value;
11689 	return (0);
11690 }
11691 
11692 /*
11693  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11694  * When an ipf is passed here for the first time, if
11695  * we already have in-order fragments on the queue, we convert from the fast-
11696  * path reassembly scheme to the hard-case scheme.  From then on, additional
11697  * fragments are reassembled here.  We keep track of the start and end offsets
11698  * of each piece, and the number of holes in the chain.  When the hole count
11699  * goes to zero, we are done!
11700  *
11701  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11702  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11703  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11704  * after the call to ip_reassemble().
11705  */
11706 int
11707 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11708     size_t msg_len)
11709 {
11710 	uint_t	end;
11711 	mblk_t	*next_mp;
11712 	mblk_t	*mp1;
11713 	uint_t	offset;
11714 	boolean_t incr_dups = B_TRUE;
11715 	boolean_t offset_zero_seen = B_FALSE;
11716 	boolean_t pkt_boundary_checked = B_FALSE;
11717 
11718 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11719 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11720 
11721 	/* Add in byte count */
11722 	ipf->ipf_count += msg_len;
11723 	if (ipf->ipf_end) {
11724 		/*
11725 		 * We were part way through in-order reassembly, but now there
11726 		 * is a hole.  We walk through messages already queued, and
11727 		 * mark them for hard case reassembly.  We know that up till
11728 		 * now they were in order starting from offset zero.
11729 		 */
11730 		offset = 0;
11731 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11732 			IP_REASS_SET_START(mp1, offset);
11733 			if (offset == 0) {
11734 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11735 				offset = -ipf->ipf_nf_hdr_len;
11736 			}
11737 			offset += mp1->b_wptr - mp1->b_rptr;
11738 			IP_REASS_SET_END(mp1, offset);
11739 		}
11740 		/* One hole at the end. */
11741 		ipf->ipf_hole_cnt = 1;
11742 		/* Brand it as a hard case, forever. */
11743 		ipf->ipf_end = 0;
11744 	}
11745 	/* Walk through all the new pieces. */
11746 	do {
11747 		end = start + (mp->b_wptr - mp->b_rptr);
11748 		/*
11749 		 * If start is 0, decrease 'end' only for the first mblk of
11750 		 * the fragment. Otherwise 'end' can get wrong value in the
11751 		 * second pass of the loop if first mblk is exactly the
11752 		 * size of ipf_nf_hdr_len.
11753 		 */
11754 		if (start == 0 && !offset_zero_seen) {
11755 			/* First segment */
11756 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11757 			end -= ipf->ipf_nf_hdr_len;
11758 			offset_zero_seen = B_TRUE;
11759 		}
11760 		next_mp = mp->b_cont;
11761 		/*
11762 		 * We are checking to see if there is any interesing data
11763 		 * to process.  If there isn't and the mblk isn't the
11764 		 * one which carries the unfragmentable header then we
11765 		 * drop it.  It's possible to have just the unfragmentable
11766 		 * header come through without any data.  That needs to be
11767 		 * saved.
11768 		 *
11769 		 * If the assert at the top of this function holds then the
11770 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11771 		 * is infrequently traveled enough that the test is left in
11772 		 * to protect against future code changes which break that
11773 		 * invariant.
11774 		 */
11775 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11776 			/* Empty.  Blast it. */
11777 			IP_REASS_SET_START(mp, 0);
11778 			IP_REASS_SET_END(mp, 0);
11779 			/*
11780 			 * If the ipf points to the mblk we are about to free,
11781 			 * update ipf to point to the next mblk (or NULL
11782 			 * if none).
11783 			 */
11784 			if (ipf->ipf_mp->b_cont == mp)
11785 				ipf->ipf_mp->b_cont = next_mp;
11786 			freeb(mp);
11787 			continue;
11788 		}
11789 		mp->b_cont = NULL;
11790 		IP_REASS_SET_START(mp, start);
11791 		IP_REASS_SET_END(mp, end);
11792 		if (!ipf->ipf_tail_mp) {
11793 			ipf->ipf_tail_mp = mp;
11794 			ipf->ipf_mp->b_cont = mp;
11795 			if (start == 0 || !more) {
11796 				ipf->ipf_hole_cnt = 1;
11797 				/*
11798 				 * if the first fragment comes in more than one
11799 				 * mblk, this loop will be executed for each
11800 				 * mblk. Need to adjust hole count so exiting
11801 				 * this routine will leave hole count at 1.
11802 				 */
11803 				if (next_mp)
11804 					ipf->ipf_hole_cnt++;
11805 			} else
11806 				ipf->ipf_hole_cnt = 2;
11807 			continue;
11808 		} else if (ipf->ipf_last_frag_seen && !more &&
11809 		    !pkt_boundary_checked) {
11810 			/*
11811 			 * We check datagram boundary only if this fragment
11812 			 * claims to be the last fragment and we have seen a
11813 			 * last fragment in the past too. We do this only
11814 			 * once for a given fragment.
11815 			 *
11816 			 * start cannot be 0 here as fragments with start=0
11817 			 * and MF=0 gets handled as a complete packet. These
11818 			 * fragments should not reach here.
11819 			 */
11820 
11821 			if (start + msgdsize(mp) !=
11822 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11823 				/*
11824 				 * We have two fragments both of which claim
11825 				 * to be the last fragment but gives conflicting
11826 				 * information about the whole datagram size.
11827 				 * Something fishy is going on. Drop the
11828 				 * fragment and free up the reassembly list.
11829 				 */
11830 				return (IP_REASS_FAILED);
11831 			}
11832 
11833 			/*
11834 			 * We shouldn't come to this code block again for this
11835 			 * particular fragment.
11836 			 */
11837 			pkt_boundary_checked = B_TRUE;
11838 		}
11839 
11840 		/* New stuff at or beyond tail? */
11841 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11842 		if (start >= offset) {
11843 			if (ipf->ipf_last_frag_seen) {
11844 				/* current fragment is beyond last fragment */
11845 				return (IP_REASS_FAILED);
11846 			}
11847 			/* Link it on end. */
11848 			ipf->ipf_tail_mp->b_cont = mp;
11849 			ipf->ipf_tail_mp = mp;
11850 			if (more) {
11851 				if (start != offset)
11852 					ipf->ipf_hole_cnt++;
11853 			} else if (start == offset && next_mp == NULL)
11854 					ipf->ipf_hole_cnt--;
11855 			continue;
11856 		}
11857 		mp1 = ipf->ipf_mp->b_cont;
11858 		offset = IP_REASS_START(mp1);
11859 		/* New stuff at the front? */
11860 		if (start < offset) {
11861 			if (start == 0) {
11862 				if (end >= offset) {
11863 					/* Nailed the hole at the begining. */
11864 					ipf->ipf_hole_cnt--;
11865 				}
11866 			} else if (end < offset) {
11867 				/*
11868 				 * A hole, stuff, and a hole where there used
11869 				 * to be just a hole.
11870 				 */
11871 				ipf->ipf_hole_cnt++;
11872 			}
11873 			mp->b_cont = mp1;
11874 			/* Check for overlap. */
11875 			while (end > offset) {
11876 				if (end < IP_REASS_END(mp1)) {
11877 					mp->b_wptr -= end - offset;
11878 					IP_REASS_SET_END(mp, offset);
11879 					BUMP_MIB(ill->ill_ip_mib,
11880 					    ipIfStatsReasmPartDups);
11881 					break;
11882 				}
11883 				/* Did we cover another hole? */
11884 				if ((mp1->b_cont &&
11885 				    IP_REASS_END(mp1) !=
11886 				    IP_REASS_START(mp1->b_cont) &&
11887 				    end >= IP_REASS_START(mp1->b_cont)) ||
11888 				    (!ipf->ipf_last_frag_seen && !more)) {
11889 					ipf->ipf_hole_cnt--;
11890 				}
11891 				/* Clip out mp1. */
11892 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11893 					/*
11894 					 * After clipping out mp1, this guy
11895 					 * is now hanging off the end.
11896 					 */
11897 					ipf->ipf_tail_mp = mp;
11898 				}
11899 				IP_REASS_SET_START(mp1, 0);
11900 				IP_REASS_SET_END(mp1, 0);
11901 				/* Subtract byte count */
11902 				ipf->ipf_count -= mp1->b_datap->db_lim -
11903 				    mp1->b_datap->db_base;
11904 				freeb(mp1);
11905 				BUMP_MIB(ill->ill_ip_mib,
11906 				    ipIfStatsReasmPartDups);
11907 				mp1 = mp->b_cont;
11908 				if (!mp1)
11909 					break;
11910 				offset = IP_REASS_START(mp1);
11911 			}
11912 			ipf->ipf_mp->b_cont = mp;
11913 			continue;
11914 		}
11915 		/*
11916 		 * The new piece starts somewhere between the start of the head
11917 		 * and before the end of the tail.
11918 		 */
11919 		for (; mp1; mp1 = mp1->b_cont) {
11920 			offset = IP_REASS_END(mp1);
11921 			if (start < offset) {
11922 				if (end <= offset) {
11923 					/* Nothing new. */
11924 					IP_REASS_SET_START(mp, 0);
11925 					IP_REASS_SET_END(mp, 0);
11926 					/* Subtract byte count */
11927 					ipf->ipf_count -= mp->b_datap->db_lim -
11928 					    mp->b_datap->db_base;
11929 					if (incr_dups) {
11930 						ipf->ipf_num_dups++;
11931 						incr_dups = B_FALSE;
11932 					}
11933 					freeb(mp);
11934 					BUMP_MIB(ill->ill_ip_mib,
11935 					    ipIfStatsReasmDuplicates);
11936 					break;
11937 				}
11938 				/*
11939 				 * Trim redundant stuff off beginning of new
11940 				 * piece.
11941 				 */
11942 				IP_REASS_SET_START(mp, offset);
11943 				mp->b_rptr += offset - start;
11944 				BUMP_MIB(ill->ill_ip_mib,
11945 				    ipIfStatsReasmPartDups);
11946 				start = offset;
11947 				if (!mp1->b_cont) {
11948 					/*
11949 					 * After trimming, this guy is now
11950 					 * hanging off the end.
11951 					 */
11952 					mp1->b_cont = mp;
11953 					ipf->ipf_tail_mp = mp;
11954 					if (!more) {
11955 						ipf->ipf_hole_cnt--;
11956 					}
11957 					break;
11958 				}
11959 			}
11960 			if (start >= IP_REASS_START(mp1->b_cont))
11961 				continue;
11962 			/* Fill a hole */
11963 			if (start > offset)
11964 				ipf->ipf_hole_cnt++;
11965 			mp->b_cont = mp1->b_cont;
11966 			mp1->b_cont = mp;
11967 			mp1 = mp->b_cont;
11968 			offset = IP_REASS_START(mp1);
11969 			if (end >= offset) {
11970 				ipf->ipf_hole_cnt--;
11971 				/* Check for overlap. */
11972 				while (end > offset) {
11973 					if (end < IP_REASS_END(mp1)) {
11974 						mp->b_wptr -= end - offset;
11975 						IP_REASS_SET_END(mp, offset);
11976 						/*
11977 						 * TODO we might bump
11978 						 * this up twice if there is
11979 						 * overlap at both ends.
11980 						 */
11981 						BUMP_MIB(ill->ill_ip_mib,
11982 						    ipIfStatsReasmPartDups);
11983 						break;
11984 					}
11985 					/* Did we cover another hole? */
11986 					if ((mp1->b_cont &&
11987 					    IP_REASS_END(mp1)
11988 					    != IP_REASS_START(mp1->b_cont) &&
11989 					    end >=
11990 					    IP_REASS_START(mp1->b_cont)) ||
11991 					    (!ipf->ipf_last_frag_seen &&
11992 					    !more)) {
11993 						ipf->ipf_hole_cnt--;
11994 					}
11995 					/* Clip out mp1. */
11996 					if ((mp->b_cont = mp1->b_cont) ==
11997 					    NULL) {
11998 						/*
11999 						 * After clipping out mp1,
12000 						 * this guy is now hanging
12001 						 * off the end.
12002 						 */
12003 						ipf->ipf_tail_mp = mp;
12004 					}
12005 					IP_REASS_SET_START(mp1, 0);
12006 					IP_REASS_SET_END(mp1, 0);
12007 					/* Subtract byte count */
12008 					ipf->ipf_count -=
12009 					    mp1->b_datap->db_lim -
12010 					    mp1->b_datap->db_base;
12011 					freeb(mp1);
12012 					BUMP_MIB(ill->ill_ip_mib,
12013 					    ipIfStatsReasmPartDups);
12014 					mp1 = mp->b_cont;
12015 					if (!mp1)
12016 						break;
12017 					offset = IP_REASS_START(mp1);
12018 				}
12019 			}
12020 			break;
12021 		}
12022 	} while (start = end, mp = next_mp);
12023 
12024 	/* Fragment just processed could be the last one. Remember this fact */
12025 	if (!more)
12026 		ipf->ipf_last_frag_seen = B_TRUE;
12027 
12028 	/* Still got holes? */
12029 	if (ipf->ipf_hole_cnt)
12030 		return (IP_REASS_PARTIAL);
12031 	/* Clean up overloaded fields to avoid upstream disasters. */
12032 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12033 		IP_REASS_SET_START(mp1, 0);
12034 		IP_REASS_SET_END(mp1, 0);
12035 	}
12036 	return (IP_REASS_COMPLETE);
12037 }
12038 
12039 /*
12040  * ipsec processing for the fast path, used for input UDP Packets
12041  * Returns true if ready for passup to UDP.
12042  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
12043  * was an ESP-in-UDP packet, etc.).
12044  */
12045 static boolean_t
12046 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12047     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
12048 {
12049 	uint32_t	ill_index;
12050 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12051 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12052 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12053 	udp_t		*udp = connp->conn_udp;
12054 
12055 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12056 	/* The ill_index of the incoming ILL */
12057 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12058 
12059 	/* pass packet up to the transport */
12060 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12061 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12062 		    NULL, mctl_present);
12063 		if (*first_mpp == NULL) {
12064 			return (B_FALSE);
12065 		}
12066 	}
12067 
12068 	/* Initiate IPPF processing for fastpath UDP */
12069 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12070 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12071 		if (*mpp == NULL) {
12072 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12073 			    "deferred/dropped during IPPF processing\n"));
12074 			return (B_FALSE);
12075 		}
12076 	}
12077 	/*
12078 	 * Remove 0-spi if it's 0, or move everything behind
12079 	 * the UDP header over it and forward to ESP via
12080 	 * ip_proto_input().
12081 	 */
12082 	if (udp->udp_nat_t_endpoint) {
12083 		if (mctl_present) {
12084 			/* mctl_present *shouldn't* happen. */
12085 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
12086 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
12087 			    &ipss->ipsec_dropper);
12088 			*first_mpp = NULL;
12089 			return (B_FALSE);
12090 		}
12091 
12092 		/* "ill" is "recv_ill" in actuality. */
12093 		if (!zero_spi_check(q, *mpp, ire, ill, ipss))
12094 			return (B_FALSE);
12095 
12096 		/* Else continue like a normal UDP packet. */
12097 	}
12098 
12099 	/*
12100 	 * We make the checks as below since we are in the fast path
12101 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12102 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12103 	 */
12104 	if (connp->conn_recvif || connp->conn_recvslla ||
12105 	    connp->conn_ip_recvpktinfo) {
12106 		if (connp->conn_recvif) {
12107 			in_flags = IPF_RECVIF;
12108 		}
12109 		/*
12110 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12111 		 * so the flag passed to ip_add_info is based on IP version
12112 		 * of connp.
12113 		 */
12114 		if (connp->conn_ip_recvpktinfo) {
12115 			if (connp->conn_af_isv6) {
12116 				/*
12117 				 * V6 only needs index
12118 				 */
12119 				in_flags |= IPF_RECVIF;
12120 			} else {
12121 				/*
12122 				 * V4 needs index + matching address.
12123 				 */
12124 				in_flags |= IPF_RECVADDR;
12125 			}
12126 		}
12127 		if (connp->conn_recvslla) {
12128 			in_flags |= IPF_RECVSLLA;
12129 		}
12130 		/*
12131 		 * since in_flags are being set ill will be
12132 		 * referenced in ip_add_info, so it better not
12133 		 * be NULL.
12134 		 */
12135 		/*
12136 		 * the actual data will be contained in b_cont
12137 		 * upon successful return of the following call.
12138 		 * If the call fails then the original mblk is
12139 		 * returned.
12140 		 */
12141 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12142 		    ipst);
12143 	}
12144 
12145 	return (B_TRUE);
12146 }
12147 
12148 /*
12149  * Fragmentation reassembly.  Each ILL has a hash table for
12150  * queuing packets undergoing reassembly for all IPIFs
12151  * associated with the ILL.  The hash is based on the packet
12152  * IP ident field.  The ILL frag hash table was allocated
12153  * as a timer block at the time the ILL was created.  Whenever
12154  * there is anything on the reassembly queue, the timer will
12155  * be running.  Returns B_TRUE if successful else B_FALSE;
12156  * frees mp on failure.
12157  */
12158 static boolean_t
12159 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12160     uint32_t *cksum_val, uint16_t *cksum_flags)
12161 {
12162 	uint32_t	frag_offset_flags;
12163 	ill_t		*ill = (ill_t *)q->q_ptr;
12164 	mblk_t		*mp = *mpp;
12165 	mblk_t		*t_mp;
12166 	ipaddr_t	dst;
12167 	uint8_t		proto = ipha->ipha_protocol;
12168 	uint32_t	sum_val;
12169 	uint16_t	sum_flags;
12170 	ipf_t		*ipf;
12171 	ipf_t		**ipfp;
12172 	ipfb_t		*ipfb;
12173 	uint16_t	ident;
12174 	uint32_t	offset;
12175 	ipaddr_t	src;
12176 	uint_t		hdr_length;
12177 	uint32_t	end;
12178 	mblk_t		*mp1;
12179 	mblk_t		*tail_mp;
12180 	size_t		count;
12181 	size_t		msg_len;
12182 	uint8_t		ecn_info = 0;
12183 	uint32_t	packet_size;
12184 	boolean_t	pruned = B_FALSE;
12185 	ip_stack_t *ipst = ill->ill_ipst;
12186 
12187 	if (cksum_val != NULL)
12188 		*cksum_val = 0;
12189 	if (cksum_flags != NULL)
12190 		*cksum_flags = 0;
12191 
12192 	/*
12193 	 * Drop the fragmented as early as possible, if
12194 	 * we don't have resource(s) to re-assemble.
12195 	 */
12196 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12197 		freemsg(mp);
12198 		return (B_FALSE);
12199 	}
12200 
12201 	/* Check for fragmentation offset; return if there's none */
12202 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12203 	    (IPH_MF | IPH_OFFSET)) == 0)
12204 		return (B_TRUE);
12205 
12206 	/*
12207 	 * We utilize hardware computed checksum info only for UDP since
12208 	 * IP fragmentation is a normal occurence for the protocol.  In
12209 	 * addition, checksum offload support for IP fragments carrying
12210 	 * UDP payload is commonly implemented across network adapters.
12211 	 */
12212 	ASSERT(ill != NULL);
12213 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12214 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12215 		mblk_t *mp1 = mp->b_cont;
12216 		int32_t len;
12217 
12218 		/* Record checksum information from the packet */
12219 		sum_val = (uint32_t)DB_CKSUM16(mp);
12220 		sum_flags = DB_CKSUMFLAGS(mp);
12221 
12222 		/* IP payload offset from beginning of mblk */
12223 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12224 
12225 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12226 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12227 		    offset >= DB_CKSUMSTART(mp) &&
12228 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12229 			uint32_t adj;
12230 			/*
12231 			 * Partial checksum has been calculated by hardware
12232 			 * and attached to the packet; in addition, any
12233 			 * prepended extraneous data is even byte aligned.
12234 			 * If any such data exists, we adjust the checksum;
12235 			 * this would also handle any postpended data.
12236 			 */
12237 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12238 			    mp, mp1, len, adj);
12239 
12240 			/* One's complement subtract extraneous checksum */
12241 			if (adj >= sum_val)
12242 				sum_val = ~(adj - sum_val) & 0xFFFF;
12243 			else
12244 				sum_val -= adj;
12245 		}
12246 	} else {
12247 		sum_val = 0;
12248 		sum_flags = 0;
12249 	}
12250 
12251 	/* Clear hardware checksumming flag */
12252 	DB_CKSUMFLAGS(mp) = 0;
12253 
12254 	ident = ipha->ipha_ident;
12255 	offset = (frag_offset_flags << 3) & 0xFFFF;
12256 	src = ipha->ipha_src;
12257 	dst = ipha->ipha_dst;
12258 	hdr_length = IPH_HDR_LENGTH(ipha);
12259 	end = ntohs(ipha->ipha_length) - hdr_length;
12260 
12261 	/* If end == 0 then we have a packet with no data, so just free it */
12262 	if (end == 0) {
12263 		freemsg(mp);
12264 		return (B_FALSE);
12265 	}
12266 
12267 	/* Record the ECN field info. */
12268 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12269 	if (offset != 0) {
12270 		/*
12271 		 * If this isn't the first piece, strip the header, and
12272 		 * add the offset to the end value.
12273 		 */
12274 		mp->b_rptr += hdr_length;
12275 		end += offset;
12276 	}
12277 
12278 	msg_len = MBLKSIZE(mp);
12279 	tail_mp = mp;
12280 	while (tail_mp->b_cont != NULL) {
12281 		tail_mp = tail_mp->b_cont;
12282 		msg_len += MBLKSIZE(tail_mp);
12283 	}
12284 
12285 	/* If the reassembly list for this ILL will get too big, prune it */
12286 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12287 	    ipst->ips_ip_reass_queue_bytes) {
12288 		ill_frag_prune(ill,
12289 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12290 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12291 		pruned = B_TRUE;
12292 	}
12293 
12294 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12295 	mutex_enter(&ipfb->ipfb_lock);
12296 
12297 	ipfp = &ipfb->ipfb_ipf;
12298 	/* Try to find an existing fragment queue for this packet. */
12299 	for (;;) {
12300 		ipf = ipfp[0];
12301 		if (ipf != NULL) {
12302 			/*
12303 			 * It has to match on ident and src/dst address.
12304 			 */
12305 			if (ipf->ipf_ident == ident &&
12306 			    ipf->ipf_src == src &&
12307 			    ipf->ipf_dst == dst &&
12308 			    ipf->ipf_protocol == proto) {
12309 				/*
12310 				 * If we have received too many
12311 				 * duplicate fragments for this packet
12312 				 * free it.
12313 				 */
12314 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12315 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12316 					freemsg(mp);
12317 					mutex_exit(&ipfb->ipfb_lock);
12318 					return (B_FALSE);
12319 				}
12320 				/* Found it. */
12321 				break;
12322 			}
12323 			ipfp = &ipf->ipf_hash_next;
12324 			continue;
12325 		}
12326 
12327 		/*
12328 		 * If we pruned the list, do we want to store this new
12329 		 * fragment?. We apply an optimization here based on the
12330 		 * fact that most fragments will be received in order.
12331 		 * So if the offset of this incoming fragment is zero,
12332 		 * it is the first fragment of a new packet. We will
12333 		 * keep it.  Otherwise drop the fragment, as we have
12334 		 * probably pruned the packet already (since the
12335 		 * packet cannot be found).
12336 		 */
12337 		if (pruned && offset != 0) {
12338 			mutex_exit(&ipfb->ipfb_lock);
12339 			freemsg(mp);
12340 			return (B_FALSE);
12341 		}
12342 
12343 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12344 			/*
12345 			 * Too many fragmented packets in this hash
12346 			 * bucket. Free the oldest.
12347 			 */
12348 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12349 		}
12350 
12351 		/* New guy.  Allocate a frag message. */
12352 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12353 		if (mp1 == NULL) {
12354 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12355 			freemsg(mp);
12356 reass_done:
12357 			mutex_exit(&ipfb->ipfb_lock);
12358 			return (B_FALSE);
12359 		}
12360 
12361 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12362 		mp1->b_cont = mp;
12363 
12364 		/* Initialize the fragment header. */
12365 		ipf = (ipf_t *)mp1->b_rptr;
12366 		ipf->ipf_mp = mp1;
12367 		ipf->ipf_ptphn = ipfp;
12368 		ipfp[0] = ipf;
12369 		ipf->ipf_hash_next = NULL;
12370 		ipf->ipf_ident = ident;
12371 		ipf->ipf_protocol = proto;
12372 		ipf->ipf_src = src;
12373 		ipf->ipf_dst = dst;
12374 		ipf->ipf_nf_hdr_len = 0;
12375 		/* Record reassembly start time. */
12376 		ipf->ipf_timestamp = gethrestime_sec();
12377 		/* Record ipf generation and account for frag header */
12378 		ipf->ipf_gen = ill->ill_ipf_gen++;
12379 		ipf->ipf_count = MBLKSIZE(mp1);
12380 		ipf->ipf_last_frag_seen = B_FALSE;
12381 		ipf->ipf_ecn = ecn_info;
12382 		ipf->ipf_num_dups = 0;
12383 		ipfb->ipfb_frag_pkts++;
12384 		ipf->ipf_checksum = 0;
12385 		ipf->ipf_checksum_flags = 0;
12386 
12387 		/* Store checksum value in fragment header */
12388 		if (sum_flags != 0) {
12389 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12390 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12391 			ipf->ipf_checksum = sum_val;
12392 			ipf->ipf_checksum_flags = sum_flags;
12393 		}
12394 
12395 		/*
12396 		 * We handle reassembly two ways.  In the easy case,
12397 		 * where all the fragments show up in order, we do
12398 		 * minimal bookkeeping, and just clip new pieces on
12399 		 * the end.  If we ever see a hole, then we go off
12400 		 * to ip_reassemble which has to mark the pieces and
12401 		 * keep track of the number of holes, etc.  Obviously,
12402 		 * the point of having both mechanisms is so we can
12403 		 * handle the easy case as efficiently as possible.
12404 		 */
12405 		if (offset == 0) {
12406 			/* Easy case, in-order reassembly so far. */
12407 			ipf->ipf_count += msg_len;
12408 			ipf->ipf_tail_mp = tail_mp;
12409 			/*
12410 			 * Keep track of next expected offset in
12411 			 * ipf_end.
12412 			 */
12413 			ipf->ipf_end = end;
12414 			ipf->ipf_nf_hdr_len = hdr_length;
12415 		} else {
12416 			/* Hard case, hole at the beginning. */
12417 			ipf->ipf_tail_mp = NULL;
12418 			/*
12419 			 * ipf_end == 0 means that we have given up
12420 			 * on easy reassembly.
12421 			 */
12422 			ipf->ipf_end = 0;
12423 
12424 			/* Forget checksum offload from now on */
12425 			ipf->ipf_checksum_flags = 0;
12426 
12427 			/*
12428 			 * ipf_hole_cnt is set by ip_reassemble.
12429 			 * ipf_count is updated by ip_reassemble.
12430 			 * No need to check for return value here
12431 			 * as we don't expect reassembly to complete
12432 			 * or fail for the first fragment itself.
12433 			 */
12434 			(void) ip_reassemble(mp, ipf,
12435 			    (frag_offset_flags & IPH_OFFSET) << 3,
12436 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12437 		}
12438 		/* Update per ipfb and ill byte counts */
12439 		ipfb->ipfb_count += ipf->ipf_count;
12440 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12441 		ill->ill_frag_count += ipf->ipf_count;
12442 		/* If the frag timer wasn't already going, start it. */
12443 		mutex_enter(&ill->ill_lock);
12444 		ill_frag_timer_start(ill);
12445 		mutex_exit(&ill->ill_lock);
12446 		goto reass_done;
12447 	}
12448 
12449 	/*
12450 	 * If the packet's flag has changed (it could be coming up
12451 	 * from an interface different than the previous, therefore
12452 	 * possibly different checksum capability), then forget about
12453 	 * any stored checksum states.  Otherwise add the value to
12454 	 * the existing one stored in the fragment header.
12455 	 */
12456 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12457 		sum_val += ipf->ipf_checksum;
12458 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12459 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12460 		ipf->ipf_checksum = sum_val;
12461 	} else if (ipf->ipf_checksum_flags != 0) {
12462 		/* Forget checksum offload from now on */
12463 		ipf->ipf_checksum_flags = 0;
12464 	}
12465 
12466 	/*
12467 	 * We have a new piece of a datagram which is already being
12468 	 * reassembled.  Update the ECN info if all IP fragments
12469 	 * are ECN capable.  If there is one which is not, clear
12470 	 * all the info.  If there is at least one which has CE
12471 	 * code point, IP needs to report that up to transport.
12472 	 */
12473 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12474 		if (ecn_info == IPH_ECN_CE)
12475 			ipf->ipf_ecn = IPH_ECN_CE;
12476 	} else {
12477 		ipf->ipf_ecn = IPH_ECN_NECT;
12478 	}
12479 	if (offset && ipf->ipf_end == offset) {
12480 		/* The new fragment fits at the end */
12481 		ipf->ipf_tail_mp->b_cont = mp;
12482 		/* Update the byte count */
12483 		ipf->ipf_count += msg_len;
12484 		/* Update per ipfb and ill byte counts */
12485 		ipfb->ipfb_count += msg_len;
12486 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12487 		ill->ill_frag_count += msg_len;
12488 		if (frag_offset_flags & IPH_MF) {
12489 			/* More to come. */
12490 			ipf->ipf_end = end;
12491 			ipf->ipf_tail_mp = tail_mp;
12492 			goto reass_done;
12493 		}
12494 	} else {
12495 		/* Go do the hard cases. */
12496 		int ret;
12497 
12498 		if (offset == 0)
12499 			ipf->ipf_nf_hdr_len = hdr_length;
12500 
12501 		/* Save current byte count */
12502 		count = ipf->ipf_count;
12503 		ret = ip_reassemble(mp, ipf,
12504 		    (frag_offset_flags & IPH_OFFSET) << 3,
12505 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12506 		/* Count of bytes added and subtracted (freeb()ed) */
12507 		count = ipf->ipf_count - count;
12508 		if (count) {
12509 			/* Update per ipfb and ill byte counts */
12510 			ipfb->ipfb_count += count;
12511 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12512 			ill->ill_frag_count += count;
12513 		}
12514 		if (ret == IP_REASS_PARTIAL) {
12515 			goto reass_done;
12516 		} else if (ret == IP_REASS_FAILED) {
12517 			/* Reassembly failed. Free up all resources */
12518 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12519 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12520 				IP_REASS_SET_START(t_mp, 0);
12521 				IP_REASS_SET_END(t_mp, 0);
12522 			}
12523 			freemsg(mp);
12524 			goto reass_done;
12525 		}
12526 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12527 	}
12528 	/*
12529 	 * We have completed reassembly.  Unhook the frag header from
12530 	 * the reassembly list.
12531 	 *
12532 	 * Before we free the frag header, record the ECN info
12533 	 * to report back to the transport.
12534 	 */
12535 	ecn_info = ipf->ipf_ecn;
12536 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12537 	ipfp = ipf->ipf_ptphn;
12538 
12539 	/* We need to supply these to caller */
12540 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12541 		sum_val = ipf->ipf_checksum;
12542 	else
12543 		sum_val = 0;
12544 
12545 	mp1 = ipf->ipf_mp;
12546 	count = ipf->ipf_count;
12547 	ipf = ipf->ipf_hash_next;
12548 	if (ipf != NULL)
12549 		ipf->ipf_ptphn = ipfp;
12550 	ipfp[0] = ipf;
12551 	ill->ill_frag_count -= count;
12552 	ASSERT(ipfb->ipfb_count >= count);
12553 	ipfb->ipfb_count -= count;
12554 	ipfb->ipfb_frag_pkts--;
12555 	mutex_exit(&ipfb->ipfb_lock);
12556 	/* Ditch the frag header. */
12557 	mp = mp1->b_cont;
12558 
12559 	freeb(mp1);
12560 
12561 	/* Restore original IP length in header. */
12562 	packet_size = (uint32_t)msgdsize(mp);
12563 	if (packet_size > IP_MAXPACKET) {
12564 		freemsg(mp);
12565 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12566 		return (B_FALSE);
12567 	}
12568 
12569 	if (DB_REF(mp) > 1) {
12570 		mblk_t *mp2 = copymsg(mp);
12571 
12572 		freemsg(mp);
12573 		if (mp2 == NULL) {
12574 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12575 			return (B_FALSE);
12576 		}
12577 		mp = mp2;
12578 	}
12579 	ipha = (ipha_t *)mp->b_rptr;
12580 
12581 	ipha->ipha_length = htons((uint16_t)packet_size);
12582 	/* We're now complete, zip the frag state */
12583 	ipha->ipha_fragment_offset_and_flags = 0;
12584 	/* Record the ECN info. */
12585 	ipha->ipha_type_of_service &= 0xFC;
12586 	ipha->ipha_type_of_service |= ecn_info;
12587 	*mpp = mp;
12588 
12589 	/* Reassembly is successful; return checksum information if needed */
12590 	if (cksum_val != NULL)
12591 		*cksum_val = sum_val;
12592 	if (cksum_flags != NULL)
12593 		*cksum_flags = sum_flags;
12594 
12595 	return (B_TRUE);
12596 }
12597 
12598 /*
12599  * Perform ip header check sum update local options.
12600  * return B_TRUE if all is well, else return B_FALSE and release
12601  * the mp. caller is responsible for decrementing ire ref cnt.
12602  */
12603 static boolean_t
12604 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12605     ip_stack_t *ipst)
12606 {
12607 	mblk_t		*first_mp;
12608 	boolean_t	mctl_present;
12609 	uint16_t	sum;
12610 
12611 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12612 	/*
12613 	 * Don't do the checksum if it has gone through AH/ESP
12614 	 * processing.
12615 	 */
12616 	if (!mctl_present) {
12617 		sum = ip_csum_hdr(ipha);
12618 		if (sum != 0) {
12619 			if (ill != NULL) {
12620 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12621 			} else {
12622 				BUMP_MIB(&ipst->ips_ip_mib,
12623 				    ipIfStatsInCksumErrs);
12624 			}
12625 			freemsg(first_mp);
12626 			return (B_FALSE);
12627 		}
12628 	}
12629 
12630 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12631 		if (mctl_present)
12632 			freeb(first_mp);
12633 		return (B_FALSE);
12634 	}
12635 
12636 	return (B_TRUE);
12637 }
12638 
12639 /*
12640  * All udp packet are delivered to the local host via this routine.
12641  */
12642 void
12643 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12644     ill_t *recv_ill)
12645 {
12646 	uint32_t	sum;
12647 	uint32_t	u1;
12648 	boolean_t	mctl_present;
12649 	conn_t		*connp;
12650 	mblk_t		*first_mp;
12651 	uint16_t	*up;
12652 	ill_t		*ill = (ill_t *)q->q_ptr;
12653 	uint16_t	reass_hck_flags = 0;
12654 	ip_stack_t	*ipst;
12655 
12656 	ASSERT(recv_ill != NULL);
12657 	ipst = recv_ill->ill_ipst;
12658 
12659 #define	rptr    ((uchar_t *)ipha)
12660 
12661 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12662 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12663 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12664 	ASSERT(ill != NULL);
12665 
12666 	/*
12667 	 * FAST PATH for udp packets
12668 	 */
12669 
12670 	/* u1 is # words of IP options */
12671 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12672 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12673 
12674 	/* IP options present */
12675 	if (u1 != 0)
12676 		goto ipoptions;
12677 
12678 	/* Check the IP header checksum.  */
12679 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12680 		/* Clear the IP header h/w cksum flag */
12681 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12682 	} else if (!mctl_present) {
12683 		/*
12684 		 * Don't verify header checksum if this packet is coming
12685 		 * back from AH/ESP as we already did it.
12686 		 */
12687 #define	uph	((uint16_t *)ipha)
12688 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12689 		    uph[6] + uph[7] + uph[8] + uph[9];
12690 #undef	uph
12691 		/* finish doing IP checksum */
12692 		sum = (sum & 0xFFFF) + (sum >> 16);
12693 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12694 		if (sum != 0 && sum != 0xFFFF) {
12695 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12696 			freemsg(first_mp);
12697 			return;
12698 		}
12699 	}
12700 
12701 	/*
12702 	 * Count for SNMP of inbound packets for ire.
12703 	 * if mctl is present this might be a secure packet and
12704 	 * has already been counted for in ip_proto_input().
12705 	 */
12706 	if (!mctl_present) {
12707 		UPDATE_IB_PKT_COUNT(ire);
12708 		ire->ire_last_used_time = lbolt;
12709 	}
12710 
12711 	/* packet part of fragmented IP packet? */
12712 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12713 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12714 		goto fragmented;
12715 	}
12716 
12717 	/* u1 = IP header length (20 bytes) */
12718 	u1 = IP_SIMPLE_HDR_LENGTH;
12719 
12720 	/* packet does not contain complete IP & UDP headers */
12721 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12722 		goto udppullup;
12723 
12724 	/* up points to UDP header */
12725 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12726 #define	iphs    ((uint16_t *)ipha)
12727 
12728 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12729 	if (up[3] != 0) {
12730 		mblk_t *mp1 = mp->b_cont;
12731 		boolean_t cksum_err;
12732 		uint16_t hck_flags = 0;
12733 
12734 		/* Pseudo-header checksum */
12735 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12736 		    iphs[9] + up[2];
12737 
12738 		/*
12739 		 * Revert to software checksum calculation if the interface
12740 		 * isn't capable of checksum offload or if IPsec is present.
12741 		 */
12742 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12743 			hck_flags = DB_CKSUMFLAGS(mp);
12744 
12745 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12746 			IP_STAT(ipst, ip_in_sw_cksum);
12747 
12748 		IP_CKSUM_RECV(hck_flags, u1,
12749 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12750 		    (int32_t)((uchar_t *)up - rptr),
12751 		    mp, mp1, cksum_err);
12752 
12753 		if (cksum_err) {
12754 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12755 			if (hck_flags & HCK_FULLCKSUM)
12756 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12757 			else if (hck_flags & HCK_PARTIALCKSUM)
12758 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12759 			else
12760 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12761 
12762 			freemsg(first_mp);
12763 			return;
12764 		}
12765 	}
12766 
12767 	/* Non-fragmented broadcast or multicast packet? */
12768 	if (ire->ire_type == IRE_BROADCAST)
12769 		goto udpslowpath;
12770 
12771 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12772 	    ire->ire_zoneid, ipst)) != NULL) {
12773 		ASSERT(connp->conn_upq != NULL);
12774 		IP_STAT(ipst, ip_udp_fast_path);
12775 
12776 		if (CONN_UDP_FLOWCTLD(connp)) {
12777 			freemsg(mp);
12778 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12779 		} else {
12780 			if (!mctl_present) {
12781 				BUMP_MIB(ill->ill_ip_mib,
12782 				    ipIfStatsHCInDelivers);
12783 			}
12784 			/*
12785 			 * mp and first_mp can change.
12786 			 */
12787 			if (ip_udp_check(q, connp, recv_ill,
12788 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12789 				/* Send it upstream */
12790 				(connp->conn_recv)(connp, mp, NULL);
12791 			}
12792 		}
12793 		/*
12794 		 * freeb() cannot deal with null mblk being passed
12795 		 * in and first_mp can be set to null in the call
12796 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12797 		 */
12798 		if (mctl_present && first_mp != NULL) {
12799 			freeb(first_mp);
12800 		}
12801 		CONN_DEC_REF(connp);
12802 		return;
12803 	}
12804 
12805 	/*
12806 	 * if we got here we know the packet is not fragmented and
12807 	 * has no options. The classifier could not find a conn_t and
12808 	 * most likely its an icmp packet so send it through slow path.
12809 	 */
12810 
12811 	goto udpslowpath;
12812 
12813 ipoptions:
12814 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12815 		goto slow_done;
12816 	}
12817 
12818 	UPDATE_IB_PKT_COUNT(ire);
12819 	ire->ire_last_used_time = lbolt;
12820 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12821 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12822 fragmented:
12823 		/*
12824 		 * "sum" and "reass_hck_flags" are non-zero if the
12825 		 * reassembled packet has a valid hardware computed
12826 		 * checksum information associated with it.
12827 		 */
12828 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12829 			goto slow_done;
12830 		/*
12831 		 * Make sure that first_mp points back to mp as
12832 		 * the mp we came in with could have changed in
12833 		 * ip_rput_fragment().
12834 		 */
12835 		ASSERT(!mctl_present);
12836 		ipha = (ipha_t *)mp->b_rptr;
12837 		first_mp = mp;
12838 	}
12839 
12840 	/* Now we have a complete datagram, destined for this machine. */
12841 	u1 = IPH_HDR_LENGTH(ipha);
12842 	/* Pull up the UDP header, if necessary. */
12843 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12844 udppullup:
12845 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12846 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12847 			freemsg(first_mp);
12848 			goto slow_done;
12849 		}
12850 		ipha = (ipha_t *)mp->b_rptr;
12851 	}
12852 
12853 	/*
12854 	 * Validate the checksum for the reassembled packet; for the
12855 	 * pullup case we calculate the payload checksum in software.
12856 	 */
12857 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12858 	if (up[3] != 0) {
12859 		boolean_t cksum_err;
12860 
12861 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12862 			IP_STAT(ipst, ip_in_sw_cksum);
12863 
12864 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12865 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12866 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12867 		    iphs[9] + up[2], sum, cksum_err);
12868 
12869 		if (cksum_err) {
12870 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12871 
12872 			if (reass_hck_flags & HCK_FULLCKSUM)
12873 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12874 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12875 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12876 			else
12877 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12878 
12879 			freemsg(first_mp);
12880 			goto slow_done;
12881 		}
12882 	}
12883 udpslowpath:
12884 
12885 	/* Clear hardware checksum flag to be safe */
12886 	DB_CKSUMFLAGS(mp) = 0;
12887 
12888 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12889 	    (ire->ire_type == IRE_BROADCAST),
12890 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12891 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12892 
12893 slow_done:
12894 	IP_STAT(ipst, ip_udp_slow_path);
12895 	return;
12896 
12897 #undef  iphs
12898 #undef  rptr
12899 }
12900 
12901 /* ARGSUSED */
12902 static mblk_t *
12903 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12904     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12905     ill_rx_ring_t *ill_ring)
12906 {
12907 	conn_t		*connp;
12908 	uint32_t	sum;
12909 	uint32_t	u1;
12910 	uint16_t	*up;
12911 	int		offset;
12912 	ssize_t		len;
12913 	mblk_t		*mp1;
12914 	boolean_t	syn_present = B_FALSE;
12915 	tcph_t		*tcph;
12916 	uint_t		ip_hdr_len;
12917 	ill_t		*ill = (ill_t *)q->q_ptr;
12918 	zoneid_t	zoneid = ire->ire_zoneid;
12919 	boolean_t	cksum_err;
12920 	uint16_t	hck_flags = 0;
12921 	ip_stack_t	*ipst = recv_ill->ill_ipst;
12922 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12923 
12924 #define	rptr	((uchar_t *)ipha)
12925 
12926 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12927 	ASSERT(ill != NULL);
12928 
12929 	/*
12930 	 * FAST PATH for tcp packets
12931 	 */
12932 
12933 	/* u1 is # words of IP options */
12934 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12935 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12936 
12937 	/* IP options present */
12938 	if (u1) {
12939 		goto ipoptions;
12940 	} else if (!mctl_present) {
12941 		/* Check the IP header checksum.  */
12942 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12943 			/* Clear the IP header h/w cksum flag */
12944 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12945 		} else if (!mctl_present) {
12946 			/*
12947 			 * Don't verify header checksum if this packet
12948 			 * is coming back from AH/ESP as we already did it.
12949 			 */
12950 #define	uph	((uint16_t *)ipha)
12951 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12952 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12953 #undef	uph
12954 			/* finish doing IP checksum */
12955 			sum = (sum & 0xFFFF) + (sum >> 16);
12956 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12957 			if (sum != 0 && sum != 0xFFFF) {
12958 				BUMP_MIB(ill->ill_ip_mib,
12959 				    ipIfStatsInCksumErrs);
12960 				goto error;
12961 			}
12962 		}
12963 	}
12964 
12965 	if (!mctl_present) {
12966 		UPDATE_IB_PKT_COUNT(ire);
12967 		ire->ire_last_used_time = lbolt;
12968 	}
12969 
12970 	/* packet part of fragmented IP packet? */
12971 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12972 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12973 		goto fragmented;
12974 	}
12975 
12976 	/* u1 = IP header length (20 bytes) */
12977 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
12978 
12979 	/* does packet contain IP+TCP headers? */
12980 	len = mp->b_wptr - rptr;
12981 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
12982 		IP_STAT(ipst, ip_tcppullup);
12983 		goto tcppullup;
12984 	}
12985 
12986 	/* TCP options present? */
12987 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
12988 
12989 	/*
12990 	 * If options need to be pulled up, then goto tcpoptions.
12991 	 * otherwise we are still in the fast path
12992 	 */
12993 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
12994 		IP_STAT(ipst, ip_tcpoptions);
12995 		goto tcpoptions;
12996 	}
12997 
12998 	/* multiple mblks of tcp data? */
12999 	if ((mp1 = mp->b_cont) != NULL) {
13000 		/* more then two? */
13001 		if (mp1->b_cont != NULL) {
13002 			IP_STAT(ipst, ip_multipkttcp);
13003 			goto multipkttcp;
13004 		}
13005 		len += mp1->b_wptr - mp1->b_rptr;
13006 	}
13007 
13008 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13009 
13010 	/* part of pseudo checksum */
13011 
13012 	/* TCP datagram length */
13013 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13014 
13015 #define	iphs    ((uint16_t *)ipha)
13016 
13017 #ifdef	_BIG_ENDIAN
13018 	u1 += IPPROTO_TCP;
13019 #else
13020 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13021 #endif
13022 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13023 
13024 	/*
13025 	 * Revert to software checksum calculation if the interface
13026 	 * isn't capable of checksum offload or if IPsec is present.
13027 	 */
13028 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
13029 		hck_flags = DB_CKSUMFLAGS(mp);
13030 
13031 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13032 		IP_STAT(ipst, ip_in_sw_cksum);
13033 
13034 	IP_CKSUM_RECV(hck_flags, u1,
13035 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13036 	    (int32_t)((uchar_t *)up - rptr),
13037 	    mp, mp1, cksum_err);
13038 
13039 	if (cksum_err) {
13040 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13041 
13042 		if (hck_flags & HCK_FULLCKSUM)
13043 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13044 		else if (hck_flags & HCK_PARTIALCKSUM)
13045 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13046 		else
13047 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13048 
13049 		goto error;
13050 	}
13051 
13052 try_again:
13053 
13054 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13055 	    zoneid, ipst)) == NULL) {
13056 		/* Send the TH_RST */
13057 		goto no_conn;
13058 	}
13059 
13060 	/*
13061 	 * TCP FAST PATH for AF_INET socket.
13062 	 *
13063 	 * TCP fast path to avoid extra work. An AF_INET socket type
13064 	 * does not have facility to receive extra information via
13065 	 * ip_process or ip_add_info. Also, when the connection was
13066 	 * established, we made a check if this connection is impacted
13067 	 * by any global IPsec policy or per connection policy (a
13068 	 * policy that comes in effect later will not apply to this
13069 	 * connection). Since all this can be determined at the
13070 	 * connection establishment time, a quick check of flags
13071 	 * can avoid extra work.
13072 	 */
13073 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13074 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13075 		ASSERT(first_mp == mp);
13076 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13077 		SET_SQUEUE(mp, tcp_rput_data, connp);
13078 		return (mp);
13079 	}
13080 
13081 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13082 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
13083 		if (IPCL_IS_TCP(connp)) {
13084 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13085 			DB_CKSUMSTART(mp) =
13086 			    (intptr_t)ip_squeue_get(ill_ring);
13087 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13088 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13089 				BUMP_MIB(ill->ill_ip_mib,
13090 				    ipIfStatsHCInDelivers);
13091 				SET_SQUEUE(mp, connp->conn_recv, connp);
13092 				return (mp);
13093 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13094 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13095 				BUMP_MIB(ill->ill_ip_mib,
13096 				    ipIfStatsHCInDelivers);
13097 				ip_squeue_enter_unbound++;
13098 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13099 				    connp);
13100 				return (mp);
13101 			}
13102 			syn_present = B_TRUE;
13103 		}
13104 
13105 	}
13106 
13107 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13108 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13109 
13110 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13111 		/* No need to send this packet to TCP */
13112 		if ((flags & TH_RST) || (flags & TH_URG)) {
13113 			CONN_DEC_REF(connp);
13114 			freemsg(first_mp);
13115 			return (NULL);
13116 		}
13117 		if (flags & TH_ACK) {
13118 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
13119 			    ipst->ips_netstack->netstack_tcp, connp);
13120 			CONN_DEC_REF(connp);
13121 			return (NULL);
13122 		}
13123 
13124 		CONN_DEC_REF(connp);
13125 		freemsg(first_mp);
13126 		return (NULL);
13127 	}
13128 
13129 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13130 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13131 		    ipha, NULL, mctl_present);
13132 		if (first_mp == NULL) {
13133 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13134 			CONN_DEC_REF(connp);
13135 			return (NULL);
13136 		}
13137 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13138 			ASSERT(syn_present);
13139 			if (mctl_present) {
13140 				ASSERT(first_mp != mp);
13141 				first_mp->b_datap->db_struioflag |=
13142 				    STRUIO_POLICY;
13143 			} else {
13144 				ASSERT(first_mp == mp);
13145 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13146 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13147 			}
13148 		} else {
13149 			/*
13150 			 * Discard first_mp early since we're dealing with a
13151 			 * fully-connected conn_t and tcp doesn't do policy in
13152 			 * this case.
13153 			 */
13154 			if (mctl_present) {
13155 				freeb(first_mp);
13156 				mctl_present = B_FALSE;
13157 			}
13158 			first_mp = mp;
13159 		}
13160 	}
13161 
13162 	/* Initiate IPPF processing for fastpath */
13163 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13164 		uint32_t	ill_index;
13165 
13166 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13167 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13168 		if (mp == NULL) {
13169 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13170 			    "deferred/dropped during IPPF processing\n"));
13171 			CONN_DEC_REF(connp);
13172 			if (mctl_present)
13173 				freeb(first_mp);
13174 			return (NULL);
13175 		} else if (mctl_present) {
13176 			/*
13177 			 * ip_process might return a new mp.
13178 			 */
13179 			ASSERT(first_mp != mp);
13180 			first_mp->b_cont = mp;
13181 		} else {
13182 			first_mp = mp;
13183 		}
13184 
13185 	}
13186 
13187 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13188 		/*
13189 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13190 		 * make sure IPF_RECVIF is passed to ip_add_info.
13191 		 */
13192 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13193 		    IPCL_ZONEID(connp), ipst);
13194 		if (mp == NULL) {
13195 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13196 			CONN_DEC_REF(connp);
13197 			if (mctl_present)
13198 				freeb(first_mp);
13199 			return (NULL);
13200 		} else if (mctl_present) {
13201 			/*
13202 			 * ip_add_info might return a new mp.
13203 			 */
13204 			ASSERT(first_mp != mp);
13205 			first_mp->b_cont = mp;
13206 		} else {
13207 			first_mp = mp;
13208 		}
13209 	}
13210 
13211 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13212 	if (IPCL_IS_TCP(connp)) {
13213 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13214 		return (first_mp);
13215 	} else {
13216 		/* SOCK_RAW, IPPROTO_TCP case */
13217 		(connp->conn_recv)(connp, first_mp, NULL);
13218 		CONN_DEC_REF(connp);
13219 		return (NULL);
13220 	}
13221 
13222 no_conn:
13223 	/* Initiate IPPf processing, if needed. */
13224 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13225 		uint32_t ill_index;
13226 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13227 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13228 		if (first_mp == NULL) {
13229 			return (NULL);
13230 		}
13231 	}
13232 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13233 
13234 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13235 	    ipst->ips_netstack->netstack_tcp, NULL);
13236 	return (NULL);
13237 ipoptions:
13238 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13239 		goto slow_done;
13240 	}
13241 
13242 	UPDATE_IB_PKT_COUNT(ire);
13243 	ire->ire_last_used_time = lbolt;
13244 
13245 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13246 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13247 fragmented:
13248 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13249 			if (mctl_present)
13250 				freeb(first_mp);
13251 			goto slow_done;
13252 		}
13253 		/*
13254 		 * Make sure that first_mp points back to mp as
13255 		 * the mp we came in with could have changed in
13256 		 * ip_rput_fragment().
13257 		 */
13258 		ASSERT(!mctl_present);
13259 		ipha = (ipha_t *)mp->b_rptr;
13260 		first_mp = mp;
13261 	}
13262 
13263 	/* Now we have a complete datagram, destined for this machine. */
13264 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13265 
13266 	len = mp->b_wptr - mp->b_rptr;
13267 	/* Pull up a minimal TCP header, if necessary. */
13268 	if (len < (u1 + 20)) {
13269 tcppullup:
13270 		if (!pullupmsg(mp, u1 + 20)) {
13271 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13272 			goto error;
13273 		}
13274 		ipha = (ipha_t *)mp->b_rptr;
13275 		len = mp->b_wptr - mp->b_rptr;
13276 	}
13277 
13278 	/*
13279 	 * Extract the offset field from the TCP header.  As usual, we
13280 	 * try to help the compiler more than the reader.
13281 	 */
13282 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13283 	if (offset != 5) {
13284 tcpoptions:
13285 		if (offset < 5) {
13286 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13287 			goto error;
13288 		}
13289 		/*
13290 		 * There must be TCP options.
13291 		 * Make sure we can grab them.
13292 		 */
13293 		offset <<= 2;
13294 		offset += u1;
13295 		if (len < offset) {
13296 			if (!pullupmsg(mp, offset)) {
13297 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13298 				goto error;
13299 			}
13300 			ipha = (ipha_t *)mp->b_rptr;
13301 			len = mp->b_wptr - rptr;
13302 		}
13303 	}
13304 
13305 	/* Get the total packet length in len, including headers. */
13306 	if (mp->b_cont) {
13307 multipkttcp:
13308 		len = msgdsize(mp);
13309 	}
13310 
13311 	/*
13312 	 * Check the TCP checksum by pulling together the pseudo-
13313 	 * header checksum, and passing it to ip_csum to be added in
13314 	 * with the TCP datagram.
13315 	 *
13316 	 * Since we are not using the hwcksum if available we must
13317 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13318 	 * If either of these fails along the way the mblk is freed.
13319 	 * If this logic ever changes and mblk is reused to say send
13320 	 * ICMP's back, then this flag may need to be cleared in
13321 	 * other places as well.
13322 	 */
13323 	DB_CKSUMFLAGS(mp) = 0;
13324 
13325 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13326 
13327 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13328 #ifdef	_BIG_ENDIAN
13329 	u1 += IPPROTO_TCP;
13330 #else
13331 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13332 #endif
13333 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13334 	/*
13335 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13336 	 */
13337 	IP_STAT(ipst, ip_in_sw_cksum);
13338 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13339 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13340 		goto error;
13341 	}
13342 
13343 	IP_STAT(ipst, ip_tcp_slow_path);
13344 	goto try_again;
13345 #undef  iphs
13346 #undef  rptr
13347 
13348 error:
13349 	freemsg(first_mp);
13350 slow_done:
13351 	return (NULL);
13352 }
13353 
13354 /* ARGSUSED */
13355 static void
13356 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13357     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13358 {
13359 	conn_t		*connp;
13360 	uint32_t	sum;
13361 	uint32_t	u1;
13362 	ssize_t		len;
13363 	sctp_hdr_t	*sctph;
13364 	zoneid_t	zoneid = ire->ire_zoneid;
13365 	uint32_t	pktsum;
13366 	uint32_t	calcsum;
13367 	uint32_t	ports;
13368 	in6_addr_t	map_src, map_dst;
13369 	ill_t		*ill = (ill_t *)q->q_ptr;
13370 	ip_stack_t	*ipst;
13371 	sctp_stack_t	*sctps;
13372 
13373 	ASSERT(recv_ill != NULL);
13374 	ipst = recv_ill->ill_ipst;
13375 	sctps = ipst->ips_netstack->netstack_sctp;
13376 
13377 #define	rptr	((uchar_t *)ipha)
13378 
13379 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13380 	ASSERT(ill != NULL);
13381 
13382 	/* u1 is # words of IP options */
13383 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13384 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13385 
13386 	/* IP options present */
13387 	if (u1 > 0) {
13388 		goto ipoptions;
13389 	} else {
13390 		/* Check the IP header checksum.  */
13391 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill) &&
13392 		    !mctl_present) {
13393 #define	uph	((uint16_t *)ipha)
13394 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13395 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13396 #undef	uph
13397 			/* finish doing IP checksum */
13398 			sum = (sum & 0xFFFF) + (sum >> 16);
13399 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13400 			/*
13401 			 * Don't verify header checksum if this packet
13402 			 * is coming back from AH/ESP as we already did it.
13403 			 */
13404 			if (sum != 0 && sum != 0xFFFF) {
13405 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13406 				goto error;
13407 			}
13408 		}
13409 		/*
13410 		 * Since there is no SCTP h/w cksum support yet, just
13411 		 * clear the flag.
13412 		 */
13413 		DB_CKSUMFLAGS(mp) = 0;
13414 	}
13415 
13416 	/*
13417 	 * Don't verify header checksum if this packet is coming
13418 	 * back from AH/ESP as we already did it.
13419 	 */
13420 	if (!mctl_present) {
13421 		UPDATE_IB_PKT_COUNT(ire);
13422 		ire->ire_last_used_time = lbolt;
13423 	}
13424 
13425 	/* packet part of fragmented IP packet? */
13426 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13427 	if (u1 & (IPH_MF | IPH_OFFSET))
13428 		goto fragmented;
13429 
13430 	/* u1 = IP header length (20 bytes) */
13431 	u1 = IP_SIMPLE_HDR_LENGTH;
13432 
13433 find_sctp_client:
13434 	/* Pullup if we don't have the sctp common header. */
13435 	len = MBLKL(mp);
13436 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13437 		if (mp->b_cont == NULL ||
13438 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13439 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13440 			goto error;
13441 		}
13442 		ipha = (ipha_t *)mp->b_rptr;
13443 		len = MBLKL(mp);
13444 	}
13445 
13446 	sctph = (sctp_hdr_t *)(rptr + u1);
13447 #ifdef	DEBUG
13448 	if (!skip_sctp_cksum) {
13449 #endif
13450 		pktsum = sctph->sh_chksum;
13451 		sctph->sh_chksum = 0;
13452 		calcsum = sctp_cksum(mp, u1);
13453 		if (calcsum != pktsum) {
13454 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
13455 			goto error;
13456 		}
13457 		sctph->sh_chksum = pktsum;
13458 #ifdef	DEBUG	/* skip_sctp_cksum */
13459 	}
13460 #endif
13461 	/* get the ports */
13462 	ports = *(uint32_t *)&sctph->sh_sport;
13463 
13464 	IRE_REFRELE(ire);
13465 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13466 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13467 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13468 	    sctps)) == NULL) {
13469 		/* Check for raw socket or OOTB handling */
13470 		goto no_conn;
13471 	}
13472 
13473 	/* Found a client; up it goes */
13474 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13475 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13476 	return;
13477 
13478 no_conn:
13479 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13480 	    ports, mctl_present, flags, B_TRUE, zoneid);
13481 	return;
13482 
13483 ipoptions:
13484 	DB_CKSUMFLAGS(mp) = 0;
13485 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13486 		goto slow_done;
13487 
13488 	UPDATE_IB_PKT_COUNT(ire);
13489 	ire->ire_last_used_time = lbolt;
13490 
13491 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13492 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13493 fragmented:
13494 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13495 			goto slow_done;
13496 		/*
13497 		 * Make sure that first_mp points back to mp as
13498 		 * the mp we came in with could have changed in
13499 		 * ip_rput_fragment().
13500 		 */
13501 		ASSERT(!mctl_present);
13502 		ipha = (ipha_t *)mp->b_rptr;
13503 		first_mp = mp;
13504 	}
13505 
13506 	/* Now we have a complete datagram, destined for this machine. */
13507 	u1 = IPH_HDR_LENGTH(ipha);
13508 	goto find_sctp_client;
13509 #undef  iphs
13510 #undef  rptr
13511 
13512 error:
13513 	freemsg(first_mp);
13514 slow_done:
13515 	IRE_REFRELE(ire);
13516 }
13517 
13518 #define	VER_BITS	0xF0
13519 #define	VERSION_6	0x60
13520 
13521 static boolean_t
13522 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13523     ipaddr_t *dstp, ip_stack_t *ipst)
13524 {
13525 	uint_t	opt_len;
13526 	ipha_t *ipha;
13527 	ssize_t len;
13528 	uint_t	pkt_len;
13529 
13530 	ASSERT(ill != NULL);
13531 	IP_STAT(ipst, ip_ipoptions);
13532 	ipha = *iphapp;
13533 
13534 #define	rptr    ((uchar_t *)ipha)
13535 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13536 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13537 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13538 		freemsg(mp);
13539 		return (B_FALSE);
13540 	}
13541 
13542 	/* multiple mblk or too short */
13543 	pkt_len = ntohs(ipha->ipha_length);
13544 
13545 	/* Get the number of words of IP options in the IP header. */
13546 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13547 	if (opt_len) {
13548 		/* IP Options present!  Validate and process. */
13549 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13550 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13551 			goto done;
13552 		}
13553 		/*
13554 		 * Recompute complete header length and make sure we
13555 		 * have access to all of it.
13556 		 */
13557 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13558 		if (len > (mp->b_wptr - rptr)) {
13559 			if (len > pkt_len) {
13560 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13561 				goto done;
13562 			}
13563 			if (!pullupmsg(mp, len)) {
13564 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13565 				goto done;
13566 			}
13567 			ipha = (ipha_t *)mp->b_rptr;
13568 		}
13569 		/*
13570 		 * Go off to ip_rput_options which returns the next hop
13571 		 * destination address, which may have been affected
13572 		 * by source routing.
13573 		 */
13574 		IP_STAT(ipst, ip_opt);
13575 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13576 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13577 			return (B_FALSE);
13578 		}
13579 	}
13580 	*iphapp = ipha;
13581 	return (B_TRUE);
13582 done:
13583 	/* clear b_prev - used by ip_mroute_decap */
13584 	mp->b_prev = NULL;
13585 	freemsg(mp);
13586 	return (B_FALSE);
13587 #undef  rptr
13588 }
13589 
13590 /*
13591  * Deal with the fact that there is no ire for the destination.
13592  */
13593 static ire_t *
13594 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13595 {
13596 	ipha_t	*ipha;
13597 	ill_t	*ill;
13598 	ire_t	*ire;
13599 	boolean_t	check_multirt = B_FALSE;
13600 	ip_stack_t *ipst;
13601 
13602 	ipha = (ipha_t *)mp->b_rptr;
13603 	ill = (ill_t *)q->q_ptr;
13604 
13605 	ASSERT(ill != NULL);
13606 	ipst = ill->ill_ipst;
13607 
13608 	/*
13609 	 * No IRE for this destination, so it can't be for us.
13610 	 * Unless we are forwarding, drop the packet.
13611 	 * We have to let source routed packets through
13612 	 * since we don't yet know if they are 'ping -l'
13613 	 * packets i.e. if they will go out over the
13614 	 * same interface as they came in on.
13615 	 */
13616 	if (ll_multicast) {
13617 		freemsg(mp);
13618 		return (NULL);
13619 	}
13620 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13621 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13622 		freemsg(mp);
13623 		return (NULL);
13624 	}
13625 
13626 	/*
13627 	 * Mark this packet as having originated externally.
13628 	 *
13629 	 * For non-forwarding code path, ire_send later double
13630 	 * checks this interface to see if it is still exists
13631 	 * post-ARP resolution.
13632 	 *
13633 	 * Also, IPQOS uses this to differentiate between
13634 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13635 	 * QOS packet processing in ip_wput_attach_llhdr().
13636 	 * The QoS module can mark the b_band for a fastpath message
13637 	 * or the dl_priority field in a unitdata_req header for
13638 	 * CoS marking. This info can only be found in
13639 	 * ip_wput_attach_llhdr().
13640 	 */
13641 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13642 	/*
13643 	 * Clear the indication that this may have a hardware checksum
13644 	 * as we are not using it
13645 	 */
13646 	DB_CKSUMFLAGS(mp) = 0;
13647 
13648 	ire = ire_forward(dst, &check_multirt, NULL, NULL,
13649 	    MBLK_GETLABEL(mp), ipst);
13650 
13651 	if (ire == NULL && check_multirt) {
13652 		/* Let ip_newroute handle CGTP  */
13653 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13654 		return (NULL);
13655 	}
13656 
13657 	if (ire != NULL)
13658 		return (ire);
13659 
13660 	mp->b_prev = mp->b_next = 0;
13661 	/* send icmp unreachable */
13662 	q = WR(q);
13663 	/* Sent by forwarding path, and router is global zone */
13664 	if (ip_source_routed(ipha, ipst)) {
13665 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13666 		    GLOBAL_ZONEID, ipst);
13667 	} else {
13668 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13669 		    ipst);
13670 	}
13671 
13672 	return (NULL);
13673 
13674 }
13675 
13676 /*
13677  * check ip header length and align it.
13678  */
13679 static boolean_t
13680 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13681 {
13682 	ssize_t len;
13683 	ill_t *ill;
13684 	ipha_t	*ipha;
13685 
13686 	len = MBLKL(mp);
13687 
13688 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13689 		ill = (ill_t *)q->q_ptr;
13690 
13691 		if (!OK_32PTR(mp->b_rptr))
13692 			IP_STAT(ipst, ip_notaligned1);
13693 		else
13694 			IP_STAT(ipst, ip_notaligned2);
13695 		/* Guard against bogus device drivers */
13696 		if (len < 0) {
13697 			/* clear b_prev - used by ip_mroute_decap */
13698 			mp->b_prev = NULL;
13699 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13700 			freemsg(mp);
13701 			return (B_FALSE);
13702 		}
13703 
13704 		if (ip_rput_pullups++ == 0) {
13705 			ipha = (ipha_t *)mp->b_rptr;
13706 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13707 			    "ip_check_and_align_header: %s forced us to "
13708 			    " pullup pkt, hdr len %ld, hdr addr %p",
13709 			    ill->ill_name, len, ipha);
13710 		}
13711 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13712 			/* clear b_prev - used by ip_mroute_decap */
13713 			mp->b_prev = NULL;
13714 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13715 			freemsg(mp);
13716 			return (B_FALSE);
13717 		}
13718 	}
13719 	return (B_TRUE);
13720 }
13721 
13722 ire_t *
13723 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13724 {
13725 	ire_t		*new_ire;
13726 	ill_t		*ire_ill;
13727 	uint_t		ifindex;
13728 	ip_stack_t	*ipst = ill->ill_ipst;
13729 	boolean_t	strict_check = B_FALSE;
13730 
13731 	/*
13732 	 * This packet came in on an interface other than the one associated
13733 	 * with the first ire we found for the destination address. We do
13734 	 * another ire lookup here, using the ingress ill, to see if the
13735 	 * interface is in an interface group.
13736 	 * As long as the ills belong to the same group, we don't consider
13737 	 * them to be arriving on the wrong interface. Thus, if the switch
13738 	 * is doing inbound load spreading, we won't drop packets when the
13739 	 * ip*_strict_dst_multihoming switch is on. Note, the same holds true
13740 	 * for 'usesrc groups' where the destination address may belong to
13741 	 * another interface to allow multipathing to happen.
13742 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13743 	 * where the local address may not be unique. In this case we were
13744 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13745 	 * actually returned. The new lookup, which is more specific, should
13746 	 * only find the IRE_LOCAL associated with the ingress ill if one
13747 	 * exists.
13748 	 */
13749 
13750 	if (ire->ire_ipversion == IPV4_VERSION) {
13751 		if (ipst->ips_ip_strict_dst_multihoming)
13752 			strict_check = B_TRUE;
13753 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13754 		    ill->ill_ipif, ALL_ZONES, NULL,
13755 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13756 	} else {
13757 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13758 		if (ipst->ips_ipv6_strict_dst_multihoming)
13759 			strict_check = B_TRUE;
13760 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13761 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13762 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13763 	}
13764 	/*
13765 	 * If the same ire that was returned in ip_input() is found then this
13766 	 * is an indication that interface groups are in use. The packet
13767 	 * arrived on a different ill in the group than the one associated with
13768 	 * the destination address.  If a different ire was found then the same
13769 	 * IP address must be hosted on multiple ills. This is possible with
13770 	 * unnumbered point2point interfaces. We switch to use this new ire in
13771 	 * order to have accurate interface statistics.
13772 	 */
13773 	if (new_ire != NULL) {
13774 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13775 			ire_refrele(ire);
13776 			ire = new_ire;
13777 		} else {
13778 			ire_refrele(new_ire);
13779 		}
13780 		return (ire);
13781 	} else if ((ire->ire_rfq == NULL) &&
13782 	    (ire->ire_ipversion == IPV4_VERSION)) {
13783 		/*
13784 		 * The best match could have been the original ire which
13785 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13786 		 * the strict multihoming checks are irrelevant as we consider
13787 		 * local addresses hosted on lo0 to be interface agnostic. We
13788 		 * only expect a null ire_rfq on IREs which are associated with
13789 		 * lo0 hence we can return now.
13790 		 */
13791 		return (ire);
13792 	}
13793 
13794 	/*
13795 	 * Chase pointers once and store locally.
13796 	 */
13797 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13798 	    (ill_t *)(ire->ire_rfq->q_ptr);
13799 	ifindex = ill->ill_usesrc_ifindex;
13800 
13801 	/*
13802 	 * Check if it's a legal address on the 'usesrc' interface.
13803 	 */
13804 	if ((ifindex != 0) && (ire_ill != NULL) &&
13805 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13806 		return (ire);
13807 	}
13808 
13809 	/*
13810 	 * If the ip*_strict_dst_multihoming switch is on then we can
13811 	 * only accept this packet if the interface is marked as routing.
13812 	 */
13813 	if (!(strict_check))
13814 		return (ire);
13815 
13816 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13817 	    ILLF_ROUTER) != 0) {
13818 		return (ire);
13819 	}
13820 
13821 	ire_refrele(ire);
13822 	return (NULL);
13823 }
13824 
13825 ire_t *
13826 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13827 {
13828 	ipha_t	*ipha;
13829 	ipaddr_t ip_dst, ip_src;
13830 	ire_t	*src_ire = NULL;
13831 	ill_t	*stq_ill;
13832 	uint_t	hlen;
13833 	uint_t	pkt_len;
13834 	uint32_t sum;
13835 	queue_t	*dev_q;
13836 	boolean_t check_multirt = B_FALSE;
13837 	ip_stack_t *ipst = ill->ill_ipst;
13838 
13839 	ipha = (ipha_t *)mp->b_rptr;
13840 
13841 	/*
13842 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13843 	 * The loopback address check for both src and dst has already
13844 	 * been checked in ip_input
13845 	 */
13846 	ip_dst = ntohl(dst);
13847 	ip_src = ntohl(ipha->ipha_src);
13848 
13849 	if (ip_dst == INADDR_ANY || IN_BADCLASS(ip_dst) ||
13850 	    IN_CLASSD(ip_src)) {
13851 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13852 		goto drop;
13853 	}
13854 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13855 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13856 
13857 	if (src_ire != NULL) {
13858 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13859 		goto drop;
13860 	}
13861 
13862 
13863 	/* No ire cache of nexthop. So first create one  */
13864 	if (ire == NULL) {
13865 		ire = ire_forward(dst, &check_multirt, NULL, NULL, NULL, ipst);
13866 		/*
13867 		 * We only come to ip_fast_forward if ip_cgtp_filter is
13868 		 * is not set. So upon return from ire_forward
13869 		 * check_multirt should remain as false.
13870 		 */
13871 		ASSERT(!check_multirt);
13872 		if (ire == NULL) {
13873 			/* An attempt was made to forward the packet */
13874 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13875 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13876 			mp->b_prev = mp->b_next = 0;
13877 			/* send icmp unreachable */
13878 			/* Sent by forwarding path, and router is global zone */
13879 			if (ip_source_routed(ipha, ipst)) {
13880 				icmp_unreachable(ill->ill_wq, mp,
13881 				    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID,
13882 				    ipst);
13883 			} else {
13884 				icmp_unreachable(ill->ill_wq, mp,
13885 				    ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13886 				    ipst);
13887 			}
13888 			return (ire);
13889 		}
13890 	}
13891 
13892 	/*
13893 	 * Forwarding fastpath exception case:
13894 	 * If either of the follwoing case is true, we take
13895 	 * the slowpath
13896 	 *	o forwarding is not enabled
13897 	 *	o incoming and outgoing interface are the same, or the same
13898 	 *	  IPMP group
13899 	 *	o corresponding ire is in incomplete state
13900 	 *	o packet needs fragmentation
13901 	 *
13902 	 * The codeflow from here on is thus:
13903 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13904 	 */
13905 	pkt_len = ntohs(ipha->ipha_length);
13906 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13907 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13908 	    !(ill->ill_flags & ILLF_ROUTER) ||
13909 	    (ill == stq_ill) ||
13910 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
13911 	    (ire->ire_nce == NULL) ||
13912 	    (ire->ire_nce->nce_state != ND_REACHABLE) ||
13913 	    (pkt_len > ire->ire_max_frag) ||
13914 	    ipha->ipha_ttl <= 1) {
13915 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13916 		    ipha, ill, B_FALSE);
13917 		return (ire);
13918 	}
13919 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13920 
13921 	DTRACE_PROBE4(ip4__forwarding__start,
13922 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13923 
13924 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
13925 	    ipst->ips_ipv4firewall_forwarding,
13926 	    ill, stq_ill, ipha, mp, mp, ipst);
13927 
13928 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13929 
13930 	if (mp == NULL)
13931 		goto drop;
13932 
13933 	mp->b_datap->db_struioun.cksum.flags = 0;
13934 	/* Adjust the checksum to reflect the ttl decrement. */
13935 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13936 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
13937 	ipha->ipha_ttl--;
13938 
13939 	dev_q = ire->ire_stq->q_next;
13940 	if ((dev_q->q_next != NULL ||
13941 	    dev_q->q_first != NULL) && !canput(dev_q)) {
13942 		goto indiscard;
13943 	}
13944 
13945 	hlen = ire->ire_nce->nce_fp_mp != NULL ?
13946 	    MBLKL(ire->ire_nce->nce_fp_mp) : 0;
13947 
13948 	if (hlen != 0 || ire->ire_nce->nce_res_mp != NULL) {
13949 		mblk_t *mpip = mp;
13950 
13951 		mp = ip_wput_attach_llhdr(mpip, ire, 0, 0);
13952 		if (mp != NULL) {
13953 			DTRACE_PROBE4(ip4__physical__out__start,
13954 			    ill_t *, NULL, ill_t *, stq_ill,
13955 			    ipha_t *, ipha, mblk_t *, mp);
13956 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
13957 			    ipst->ips_ipv4firewall_physical_out,
13958 			    NULL, stq_ill, ipha, mp, mpip, ipst);
13959 			DTRACE_PROBE1(ip4__physical__out__end, mblk_t *,
13960 			    mp);
13961 			if (mp == NULL)
13962 				goto drop;
13963 
13964 			UPDATE_IB_PKT_COUNT(ire);
13965 			ire->ire_last_used_time = lbolt;
13966 			BUMP_MIB(stq_ill->ill_ip_mib,
13967 			    ipIfStatsHCOutForwDatagrams);
13968 			BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
13969 			UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets,
13970 			    pkt_len);
13971 			putnext(ire->ire_stq, mp);
13972 			return (ire);
13973 		}
13974 	}
13975 
13976 indiscard:
13977 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13978 drop:
13979 	if (mp != NULL)
13980 		freemsg(mp);
13981 	if (src_ire != NULL)
13982 		ire_refrele(src_ire);
13983 	return (ire);
13984 
13985 }
13986 
13987 /*
13988  * This function is called in the forwarding slowpath, when
13989  * either the ire lacks the link-layer address, or the packet needs
13990  * further processing(eg. fragmentation), before transmission.
13991  */
13992 
13993 static void
13994 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
13995     ill_t *ill, boolean_t ll_multicast)
13996 {
13997 	ill_group_t	*ill_group;
13998 	ill_group_t	*ire_group;
13999 	queue_t		*dev_q;
14000 	ire_t		*src_ire;
14001 	ip_stack_t	*ipst = ill->ill_ipst;
14002 
14003 	ASSERT(ire->ire_stq != NULL);
14004 
14005 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14006 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14007 
14008 	if (ll_multicast != 0) {
14009 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14010 		goto drop_pkt;
14011 	}
14012 
14013 	/*
14014 	 * check if ipha_src is a broadcast address. Note that this
14015 	 * check is redundant when we get here from ip_fast_forward()
14016 	 * which has already done this check. However, since we can
14017 	 * also get here from ip_rput_process_broadcast() or, for
14018 	 * for the slow path through ip_fast_forward(), we perform
14019 	 * the check again for code-reusability
14020 	 */
14021 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14022 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14023 	if (src_ire != NULL || ntohl(ipha->ipha_dst) == INADDR_ANY ||
14024 	    IN_BADCLASS(ntohl(ipha->ipha_dst))) {
14025 		if (src_ire != NULL)
14026 			ire_refrele(src_ire);
14027 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14028 		ip2dbg(("ip_rput_process_forward: Received packet with"
14029 		    " bad src/dst address on %s\n", ill->ill_name));
14030 		goto drop_pkt;
14031 	}
14032 
14033 	ill_group = ill->ill_group;
14034 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
14035 	/*
14036 	 * Check if we want to forward this one at this time.
14037 	 * We allow source routed packets on a host provided that
14038 	 * they go out the same interface or same interface group
14039 	 * as they came in on.
14040 	 *
14041 	 * XXX To be quicker, we may wish to not chase pointers to
14042 	 * get the ILLF_ROUTER flag and instead store the
14043 	 * forwarding policy in the ire.  An unfortunate
14044 	 * side-effect of that would be requiring an ire flush
14045 	 * whenever the ILLF_ROUTER flag changes.
14046 	 */
14047 	if (((ill->ill_flags &
14048 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
14049 	    ILLF_ROUTER) == 0) &&
14050 	    !(ip_source_routed(ipha, ipst) && (ire->ire_rfq == q ||
14051 	    (ill_group != NULL && ill_group == ire_group)))) {
14052 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14053 		if (ip_source_routed(ipha, ipst)) {
14054 			q = WR(q);
14055 			/*
14056 			 * Clear the indication that this may have
14057 			 * hardware checksum as we are not using it.
14058 			 */
14059 			DB_CKSUMFLAGS(mp) = 0;
14060 			/* Sent by forwarding path, and router is global zone */
14061 			icmp_unreachable(q, mp,
14062 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14063 			return;
14064 		}
14065 		goto drop_pkt;
14066 	}
14067 
14068 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14069 
14070 	/* Packet is being forwarded. Turning off hwcksum flag. */
14071 	DB_CKSUMFLAGS(mp) = 0;
14072 	if (ipst->ips_ip_g_send_redirects) {
14073 		/*
14074 		 * Check whether the incoming interface and outgoing
14075 		 * interface is part of the same group. If so,
14076 		 * send redirects.
14077 		 *
14078 		 * Check the source address to see if it originated
14079 		 * on the same logical subnet it is going back out on.
14080 		 * If so, we should be able to send it a redirect.
14081 		 * Avoid sending a redirect if the destination
14082 		 * is directly connected (i.e., ipha_dst is the same
14083 		 * as ire_gateway_addr or the ire_addr of the
14084 		 * nexthop IRE_CACHE ), or if the packet was source
14085 		 * routed out this interface.
14086 		 */
14087 		ipaddr_t src, nhop;
14088 		mblk_t	*mp1;
14089 		ire_t	*nhop_ire = NULL;
14090 
14091 		/*
14092 		 * Check whether ire_rfq and q are from the same ill
14093 		 * or if they are not same, they at least belong
14094 		 * to the same group. If so, send redirects.
14095 		 */
14096 		if ((ire->ire_rfq == q ||
14097 		    (ill_group != NULL && ill_group == ire_group)) &&
14098 		    !ip_source_routed(ipha, ipst)) {
14099 
14100 			nhop = (ire->ire_gateway_addr != 0 ?
14101 			    ire->ire_gateway_addr : ire->ire_addr);
14102 
14103 			if (ipha->ipha_dst == nhop) {
14104 				/*
14105 				 * We avoid sending a redirect if the
14106 				 * destination is directly connected
14107 				 * because it is possible that multiple
14108 				 * IP subnets may have been configured on
14109 				 * the link, and the source may not
14110 				 * be on the same subnet as ip destination,
14111 				 * even though they are on the same
14112 				 * physical link.
14113 				 */
14114 				goto sendit;
14115 			}
14116 
14117 			src = ipha->ipha_src;
14118 
14119 			/*
14120 			 * We look up the interface ire for the nexthop,
14121 			 * to see if ipha_src is in the same subnet
14122 			 * as the nexthop.
14123 			 *
14124 			 * Note that, if, in the future, IRE_CACHE entries
14125 			 * are obsoleted,  this lookup will not be needed,
14126 			 * as the ire passed to this function will be the
14127 			 * same as the nhop_ire computed below.
14128 			 */
14129 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14130 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14131 			    0, NULL, MATCH_IRE_TYPE, ipst);
14132 
14133 			if (nhop_ire != NULL) {
14134 				if ((src & nhop_ire->ire_mask) ==
14135 				    (nhop & nhop_ire->ire_mask)) {
14136 					/*
14137 					 * The source is directly connected.
14138 					 * Just copy the ip header (which is
14139 					 * in the first mblk)
14140 					 */
14141 					mp1 = copyb(mp);
14142 					if (mp1 != NULL) {
14143 						icmp_send_redirect(WR(q), mp1,
14144 						    nhop, ipst);
14145 					}
14146 				}
14147 				ire_refrele(nhop_ire);
14148 			}
14149 		}
14150 	}
14151 sendit:
14152 	dev_q = ire->ire_stq->q_next;
14153 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
14154 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14155 		freemsg(mp);
14156 		return;
14157 	}
14158 
14159 	ip_rput_forward(ire, ipha, mp, ill);
14160 	return;
14161 
14162 drop_pkt:
14163 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14164 	freemsg(mp);
14165 }
14166 
14167 ire_t *
14168 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14169     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14170 {
14171 	queue_t		*q;
14172 	uint16_t	hcksumflags;
14173 	ip_stack_t	*ipst = ill->ill_ipst;
14174 
14175 	q = *qp;
14176 
14177 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14178 
14179 	/*
14180 	 * Clear the indication that this may have hardware
14181 	 * checksum as we are not using it for forwarding.
14182 	 */
14183 	hcksumflags = DB_CKSUMFLAGS(mp);
14184 	DB_CKSUMFLAGS(mp) = 0;
14185 
14186 	/*
14187 	 * Directed broadcast forwarding: if the packet came in over a
14188 	 * different interface then it is routed out over we can forward it.
14189 	 */
14190 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14191 		ire_refrele(ire);
14192 		freemsg(mp);
14193 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14194 		return (NULL);
14195 	}
14196 	/*
14197 	 * For multicast we have set dst to be INADDR_BROADCAST
14198 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
14199 	 * only for broadcast packets.
14200 	 */
14201 	if (!CLASSD(ipha->ipha_dst)) {
14202 		ire_t *new_ire;
14203 		ipif_t *ipif;
14204 		/*
14205 		 * For ill groups, as the switch duplicates broadcasts
14206 		 * across all the ports, we need to filter out and
14207 		 * send up only one copy. There is one copy for every
14208 		 * broadcast address on each ill. Thus, we look for a
14209 		 * specific IRE on this ill and look at IRE_MARK_NORECV
14210 		 * later to see whether this ill is eligible to receive
14211 		 * them or not. ill_nominate_bcast_rcv() nominates only
14212 		 * one set of IREs for receiving.
14213 		 */
14214 
14215 		ipif = ipif_get_next_ipif(NULL, ill);
14216 		if (ipif == NULL) {
14217 			ire_refrele(ire);
14218 			freemsg(mp);
14219 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14220 			return (NULL);
14221 		}
14222 		new_ire = ire_ctable_lookup(dst, 0, 0,
14223 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14224 		ipif_refrele(ipif);
14225 
14226 		if (new_ire != NULL) {
14227 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
14228 				ire_refrele(ire);
14229 				ire_refrele(new_ire);
14230 				freemsg(mp);
14231 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14232 				return (NULL);
14233 			}
14234 			/*
14235 			 * In the special case of multirouted broadcast
14236 			 * packets, we unconditionally need to "gateway"
14237 			 * them to the appropriate interface here.
14238 			 * In the normal case, this cannot happen, because
14239 			 * there is no broadcast IRE tagged with the
14240 			 * RTF_MULTIRT flag.
14241 			 */
14242 			if (new_ire->ire_flags & RTF_MULTIRT) {
14243 				ire_refrele(new_ire);
14244 				if (ire->ire_rfq != NULL) {
14245 					q = ire->ire_rfq;
14246 					*qp = q;
14247 				}
14248 			} else {
14249 				ire_refrele(ire);
14250 				ire = new_ire;
14251 			}
14252 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14253 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14254 				/*
14255 				 * Free the message if
14256 				 * ip_g_forward_directed_bcast is turned
14257 				 * off for non-local broadcast.
14258 				 */
14259 				ire_refrele(ire);
14260 				freemsg(mp);
14261 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14262 				return (NULL);
14263 			}
14264 		} else {
14265 			/*
14266 			 * This CGTP packet successfully passed the
14267 			 * CGTP filter, but the related CGTP
14268 			 * broadcast IRE has not been found,
14269 			 * meaning that the redundant ipif is
14270 			 * probably down. However, if we discarded
14271 			 * this packet, its duplicate would be
14272 			 * filtered out by the CGTP filter so none
14273 			 * of them would get through. So we keep
14274 			 * going with this one.
14275 			 */
14276 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14277 			if (ire->ire_rfq != NULL) {
14278 				q = ire->ire_rfq;
14279 				*qp = q;
14280 			}
14281 		}
14282 	}
14283 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14284 		/*
14285 		 * Verify that there are not more then one
14286 		 * IRE_BROADCAST with this broadcast address which
14287 		 * has ire_stq set.
14288 		 * TODO: simplify, loop over all IRE's
14289 		 */
14290 		ire_t	*ire1;
14291 		int	num_stq = 0;
14292 		mblk_t	*mp1;
14293 
14294 		/* Find the first one with ire_stq set */
14295 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14296 		for (ire1 = ire; ire1 &&
14297 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14298 		    ire1 = ire1->ire_next)
14299 			;
14300 		if (ire1) {
14301 			ire_refrele(ire);
14302 			ire = ire1;
14303 			IRE_REFHOLD(ire);
14304 		}
14305 
14306 		/* Check if there are additional ones with stq set */
14307 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14308 			if (ire->ire_addr != ire1->ire_addr)
14309 				break;
14310 			if (ire1->ire_stq) {
14311 				num_stq++;
14312 				break;
14313 			}
14314 		}
14315 		rw_exit(&ire->ire_bucket->irb_lock);
14316 		if (num_stq == 1 && ire->ire_stq != NULL) {
14317 			ip1dbg(("ip_rput_process_broadcast: directed "
14318 			    "broadcast to 0x%x\n",
14319 			    ntohl(ire->ire_addr)));
14320 			mp1 = copymsg(mp);
14321 			if (mp1) {
14322 				switch (ipha->ipha_protocol) {
14323 				case IPPROTO_UDP:
14324 					ip_udp_input(q, mp1, ipha, ire, ill);
14325 					break;
14326 				default:
14327 					ip_proto_input(q, mp1, ipha, ire, ill,
14328 					    B_FALSE);
14329 					break;
14330 				}
14331 			}
14332 			/*
14333 			 * Adjust ttl to 2 (1+1 - the forward engine
14334 			 * will decrement it by one.
14335 			 */
14336 			if (ip_csum_hdr(ipha)) {
14337 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14338 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14339 				freemsg(mp);
14340 				ire_refrele(ire);
14341 				return (NULL);
14342 			}
14343 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14344 			ipha->ipha_hdr_checksum = 0;
14345 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14346 			ip_rput_process_forward(q, mp, ire, ipha,
14347 			    ill, ll_multicast);
14348 			ire_refrele(ire);
14349 			return (NULL);
14350 		}
14351 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14352 		    ntohl(ire->ire_addr)));
14353 	}
14354 
14355 
14356 	/* Restore any hardware checksum flags */
14357 	DB_CKSUMFLAGS(mp) = hcksumflags;
14358 	return (ire);
14359 }
14360 
14361 /* ARGSUSED */
14362 static boolean_t
14363 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14364     int *ll_multicast, ipaddr_t *dstp)
14365 {
14366 	ip_stack_t	*ipst = ill->ill_ipst;
14367 
14368 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14369 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14370 	    ntohs(ipha->ipha_length));
14371 
14372 	/*
14373 	 * Forward packets only if we have joined the allmulti
14374 	 * group on this interface.
14375 	 */
14376 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14377 		int retval;
14378 
14379 		/*
14380 		 * Clear the indication that this may have hardware
14381 		 * checksum as we are not using it.
14382 		 */
14383 		DB_CKSUMFLAGS(mp) = 0;
14384 		retval = ip_mforward(ill, ipha, mp);
14385 		/* ip_mforward updates mib variables if needed */
14386 		/* clear b_prev - used by ip_mroute_decap */
14387 		mp->b_prev = NULL;
14388 
14389 		switch (retval) {
14390 		case 0:
14391 			/*
14392 			 * pkt is okay and arrived on phyint.
14393 			 *
14394 			 * If we are running as a multicast router
14395 			 * we need to see all IGMP and/or PIM packets.
14396 			 */
14397 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14398 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14399 				goto done;
14400 			}
14401 			break;
14402 		case -1:
14403 			/* pkt is mal-formed, toss it */
14404 			goto drop_pkt;
14405 		case 1:
14406 			/* pkt is okay and arrived on a tunnel */
14407 			/*
14408 			 * If we are running a multicast router
14409 			 *  we need to see all igmp packets.
14410 			 */
14411 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14412 				*dstp = INADDR_BROADCAST;
14413 				*ll_multicast = 1;
14414 				return (B_FALSE);
14415 			}
14416 
14417 			goto drop_pkt;
14418 		}
14419 	}
14420 
14421 	ILM_WALKER_HOLD(ill);
14422 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14423 		/*
14424 		 * This might just be caused by the fact that
14425 		 * multiple IP Multicast addresses map to the same
14426 		 * link layer multicast - no need to increment counter!
14427 		 */
14428 		ILM_WALKER_RELE(ill);
14429 		freemsg(mp);
14430 		return (B_TRUE);
14431 	}
14432 	ILM_WALKER_RELE(ill);
14433 done:
14434 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14435 	/*
14436 	 * This assumes the we deliver to all streams for multicast
14437 	 * and broadcast packets.
14438 	 */
14439 	*dstp = INADDR_BROADCAST;
14440 	*ll_multicast = 1;
14441 	return (B_FALSE);
14442 drop_pkt:
14443 	ip2dbg(("ip_rput: drop pkt\n"));
14444 	freemsg(mp);
14445 	return (B_TRUE);
14446 }
14447 
14448 static boolean_t
14449 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14450     int *ll_multicast, mblk_t **mpp)
14451 {
14452 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14453 	boolean_t must_copy = B_FALSE;
14454 	struct iocblk   *iocp;
14455 	ipha_t		*ipha;
14456 	ip_stack_t	*ipst = ill->ill_ipst;
14457 
14458 #define	rptr    ((uchar_t *)ipha)
14459 
14460 	first_mp = *first_mpp;
14461 	mp = *mpp;
14462 
14463 	ASSERT(first_mp == mp);
14464 
14465 	/*
14466 	 * if db_ref > 1 then copymsg and free original. Packet may be
14467 	 * changed and do not want other entity who has a reference to this
14468 	 * message to trip over the changes. This is a blind change because
14469 	 * trying to catch all places that might change packet is too
14470 	 * difficult (since it may be a module above this one)
14471 	 *
14472 	 * This corresponds to the non-fast path case. We walk down the full
14473 	 * chain in this case, and check the db_ref count of all the dblks,
14474 	 * and do a copymsg if required. It is possible that the db_ref counts
14475 	 * of the data blocks in the mblk chain can be different.
14476 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14477 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14478 	 * 'snoop' is running.
14479 	 */
14480 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14481 		if (mp1->b_datap->db_ref > 1) {
14482 			must_copy = B_TRUE;
14483 			break;
14484 		}
14485 	}
14486 
14487 	if (must_copy) {
14488 		mp1 = copymsg(mp);
14489 		if (mp1 == NULL) {
14490 			for (mp1 = mp; mp1 != NULL;
14491 			    mp1 = mp1->b_cont) {
14492 				mp1->b_next = NULL;
14493 				mp1->b_prev = NULL;
14494 			}
14495 			freemsg(mp);
14496 			if (ill != NULL) {
14497 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14498 			} else {
14499 				BUMP_MIB(&ipst->ips_ip_mib,
14500 				    ipIfStatsInDiscards);
14501 			}
14502 			return (B_TRUE);
14503 		}
14504 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14505 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14506 			/* Copy b_prev - used by ip_mroute_decap */
14507 			to_mp->b_prev = from_mp->b_prev;
14508 			from_mp->b_prev = NULL;
14509 		}
14510 		*first_mpp = first_mp = mp1;
14511 		freemsg(mp);
14512 		mp = mp1;
14513 		*mpp = mp1;
14514 	}
14515 
14516 	ipha = (ipha_t *)mp->b_rptr;
14517 
14518 	/*
14519 	 * previous code has a case for M_DATA.
14520 	 * We want to check how that happens.
14521 	 */
14522 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14523 	switch (first_mp->b_datap->db_type) {
14524 	case M_PROTO:
14525 	case M_PCPROTO:
14526 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14527 		    DL_UNITDATA_IND) {
14528 			/* Go handle anything other than data elsewhere. */
14529 			ip_rput_dlpi(q, mp);
14530 			return (B_TRUE);
14531 		}
14532 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
14533 		/* Ditch the DLPI header. */
14534 		mp1 = mp->b_cont;
14535 		ASSERT(first_mp == mp);
14536 		*first_mpp = mp1;
14537 		freeb(mp);
14538 		*mpp = mp1;
14539 		return (B_FALSE);
14540 	case M_IOCACK:
14541 		ip1dbg(("got iocack "));
14542 		iocp = (struct iocblk *)mp->b_rptr;
14543 		switch (iocp->ioc_cmd) {
14544 		case DL_IOC_HDR_INFO:
14545 			ill = (ill_t *)q->q_ptr;
14546 			ill_fastpath_ack(ill, mp);
14547 			return (B_TRUE);
14548 		case SIOCSTUNPARAM:
14549 		case OSIOCSTUNPARAM:
14550 			/* Go through qwriter_ip */
14551 			break;
14552 		case SIOCGTUNPARAM:
14553 		case OSIOCGTUNPARAM:
14554 			ip_rput_other(NULL, q, mp, NULL);
14555 			return (B_TRUE);
14556 		default:
14557 			putnext(q, mp);
14558 			return (B_TRUE);
14559 		}
14560 		/* FALLTHRU */
14561 	case M_ERROR:
14562 	case M_HANGUP:
14563 		/*
14564 		 * Since this is on the ill stream we unconditionally
14565 		 * bump up the refcount
14566 		 */
14567 		ill_refhold(ill);
14568 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14569 		return (B_TRUE);
14570 	case M_CTL:
14571 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14572 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14573 		    IPHADA_M_CTL)) {
14574 			/*
14575 			 * It's an IPsec accelerated packet.
14576 			 * Make sure that the ill from which we received the
14577 			 * packet has enabled IPsec hardware acceleration.
14578 			 */
14579 			if (!(ill->ill_capabilities &
14580 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14581 				/* IPsec kstats: bean counter */
14582 				freemsg(mp);
14583 				return (B_TRUE);
14584 			}
14585 
14586 			/*
14587 			 * Make mp point to the mblk following the M_CTL,
14588 			 * then process according to type of mp.
14589 			 * After this processing, first_mp will point to
14590 			 * the data-attributes and mp to the pkt following
14591 			 * the M_CTL.
14592 			 */
14593 			mp = first_mp->b_cont;
14594 			if (mp == NULL) {
14595 				freemsg(first_mp);
14596 				return (B_TRUE);
14597 			}
14598 			/*
14599 			 * A Hardware Accelerated packet can only be M_DATA
14600 			 * ESP or AH packet.
14601 			 */
14602 			if (mp->b_datap->db_type != M_DATA) {
14603 				/* non-M_DATA IPsec accelerated packet */
14604 				IPSECHW_DEBUG(IPSECHW_PKT,
14605 				    ("non-M_DATA IPsec accelerated pkt\n"));
14606 				freemsg(first_mp);
14607 				return (B_TRUE);
14608 			}
14609 			ipha = (ipha_t *)mp->b_rptr;
14610 			if (ipha->ipha_protocol != IPPROTO_AH &&
14611 			    ipha->ipha_protocol != IPPROTO_ESP) {
14612 				IPSECHW_DEBUG(IPSECHW_PKT,
14613 				    ("non-M_DATA IPsec accelerated pkt\n"));
14614 				freemsg(first_mp);
14615 				return (B_TRUE);
14616 			}
14617 			*mpp = mp;
14618 			return (B_FALSE);
14619 		}
14620 		putnext(q, mp);
14621 		return (B_TRUE);
14622 	case M_IOCNAK:
14623 		ip1dbg(("got iocnak "));
14624 		iocp = (struct iocblk *)mp->b_rptr;
14625 		switch (iocp->ioc_cmd) {
14626 		case SIOCSTUNPARAM:
14627 		case OSIOCSTUNPARAM:
14628 			/*
14629 			 * Since this is on the ill stream we unconditionally
14630 			 * bump up the refcount
14631 			 */
14632 			ill_refhold(ill);
14633 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14634 			return (B_TRUE);
14635 		case DL_IOC_HDR_INFO:
14636 		case SIOCGTUNPARAM:
14637 		case OSIOCGTUNPARAM:
14638 			ip_rput_other(NULL, q, mp, NULL);
14639 			return (B_TRUE);
14640 		default:
14641 			break;
14642 		}
14643 		/* FALLTHRU */
14644 	default:
14645 		putnext(q, mp);
14646 		return (B_TRUE);
14647 	}
14648 }
14649 
14650 /* Read side put procedure.  Packets coming from the wire arrive here. */
14651 void
14652 ip_rput(queue_t *q, mblk_t *mp)
14653 {
14654 	ill_t	*ill;
14655 	union DL_primitives *dl;
14656 
14657 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14658 
14659 	ill = (ill_t *)q->q_ptr;
14660 
14661 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14662 		/*
14663 		 * If things are opening or closing, only accept high-priority
14664 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14665 		 * created; on close, things hanging off the ill may have been
14666 		 * freed already.)
14667 		 */
14668 		dl = (union DL_primitives *)mp->b_rptr;
14669 		if (DB_TYPE(mp) != M_PCPROTO ||
14670 		    dl->dl_primitive == DL_UNITDATA_IND) {
14671 			/*
14672 			 * SIOC[GS]TUNPARAM ioctls can come here.
14673 			 */
14674 			inet_freemsg(mp);
14675 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14676 			    "ip_rput_end: q %p (%S)", q, "uninit");
14677 			return;
14678 		}
14679 	}
14680 
14681 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14682 	    "ip_rput_end: q %p (%S)", q, "end");
14683 
14684 	ip_input(ill, NULL, mp, NULL);
14685 }
14686 
14687 static mblk_t *
14688 ip_fix_dbref(ill_t *ill, mblk_t *mp)
14689 {
14690 	mblk_t *mp1;
14691 	boolean_t adjusted = B_FALSE;
14692 	ip_stack_t *ipst = ill->ill_ipst;
14693 
14694 	IP_STAT(ipst, ip_db_ref);
14695 	/*
14696 	 * The IP_RECVSLLA option depends on having the
14697 	 * link layer header. First check that:
14698 	 * a> the underlying device is of type ether,
14699 	 * since this option is currently supported only
14700 	 * over ethernet.
14701 	 * b> there is enough room to copy over the link
14702 	 * layer header.
14703 	 *
14704 	 * Once the checks are done, adjust rptr so that
14705 	 * the link layer header will be copied via
14706 	 * copymsg. Note that, IFT_ETHER may be returned
14707 	 * by some non-ethernet drivers but in this case
14708 	 * the second check will fail.
14709 	 */
14710 	if (ill->ill_type == IFT_ETHER &&
14711 	    (mp->b_rptr - mp->b_datap->db_base) >=
14712 	    sizeof (struct ether_header)) {
14713 		mp->b_rptr -= sizeof (struct ether_header);
14714 		adjusted = B_TRUE;
14715 	}
14716 	mp1 = copymsg(mp);
14717 
14718 	if (mp1 == NULL) {
14719 		mp->b_next = NULL;
14720 		/* clear b_prev - used by ip_mroute_decap */
14721 		mp->b_prev = NULL;
14722 		freemsg(mp);
14723 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14724 		return (NULL);
14725 	}
14726 
14727 	if (adjusted) {
14728 		/*
14729 		 * Copy is done. Restore the pointer in
14730 		 * the _new_ mblk
14731 		 */
14732 		mp1->b_rptr += sizeof (struct ether_header);
14733 	}
14734 
14735 	/* Copy b_prev - used by ip_mroute_decap */
14736 	mp1->b_prev = mp->b_prev;
14737 	mp->b_prev = NULL;
14738 
14739 	/* preserve the hardware checksum flags and data, if present */
14740 	if (DB_CKSUMFLAGS(mp) != 0) {
14741 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
14742 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
14743 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
14744 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
14745 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
14746 	}
14747 
14748 	freemsg(mp);
14749 	return (mp1);
14750 }
14751 
14752 /*
14753  * Direct read side procedure capable of dealing with chains. GLDv3 based
14754  * drivers call this function directly with mblk chains while STREAMS
14755  * read side procedure ip_rput() calls this for single packet with ip_ring
14756  * set to NULL to process one packet at a time.
14757  *
14758  * The ill will always be valid if this function is called directly from
14759  * the driver.
14760  *
14761  * If ip_input() is called from GLDv3:
14762  *
14763  *   - This must be a non-VLAN IP stream.
14764  *   - 'mp' is either an untagged or a special priority-tagged packet.
14765  *   - Any VLAN tag that was in the MAC header has been stripped.
14766  *
14767  * If the IP header in packet is not 32-bit aligned, every message in the
14768  * chain will be aligned before further operations. This is required on SPARC
14769  * platform.
14770  */
14771 /* ARGSUSED */
14772 void
14773 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14774     struct mac_header_info_s *mhip)
14775 {
14776 	ipaddr_t		dst = NULL;
14777 	ipaddr_t		prev_dst;
14778 	ire_t			*ire = NULL;
14779 	ipha_t			*ipha;
14780 	uint_t			pkt_len;
14781 	ssize_t			len;
14782 	uint_t			opt_len;
14783 	int			ll_multicast;
14784 	int			cgtp_flt_pkt;
14785 	queue_t			*q = ill->ill_rq;
14786 	squeue_t		*curr_sqp = NULL;
14787 	mblk_t 			*head = NULL;
14788 	mblk_t			*tail = NULL;
14789 	mblk_t			*first_mp;
14790 	mblk_t 			*mp;
14791 	mblk_t			*dmp;
14792 	int			cnt = 0;
14793 	ip_stack_t		*ipst = ill->ill_ipst;
14794 
14795 	ASSERT(mp_chain != NULL);
14796 	ASSERT(ill != NULL);
14797 
14798 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14799 
14800 #define	rptr	((uchar_t *)ipha)
14801 
14802 	while (mp_chain != NULL) {
14803 		first_mp = mp = mp_chain;
14804 		mp_chain = mp_chain->b_next;
14805 		mp->b_next = NULL;
14806 		ll_multicast = 0;
14807 
14808 		/*
14809 		 * We do ire caching from one iteration to
14810 		 * another. In the event the packet chain contains
14811 		 * all packets from the same dst, this caching saves
14812 		 * an ire_cache_lookup for each of the succeeding
14813 		 * packets in a packet chain.
14814 		 */
14815 		prev_dst = dst;
14816 
14817 		/*
14818 		 * if db_ref > 1 then copymsg and free original. Packet
14819 		 * may be changed and we do not want the other entity
14820 		 * who has a reference to this message to trip over the
14821 		 * changes. This is a blind change because trying to
14822 		 * catch all places that might change the packet is too
14823 		 * difficult.
14824 		 *
14825 		 * This corresponds to the fast path case, where we have
14826 		 * a chain of M_DATA mblks.  We check the db_ref count
14827 		 * of only the 1st data block in the mblk chain. There
14828 		 * doesn't seem to be a reason why a device driver would
14829 		 * send up data with varying db_ref counts in the mblk
14830 		 * chain. In any case the Fast path is a private
14831 		 * interface, and our drivers don't do such a thing.
14832 		 * Given the above assumption, there is no need to walk
14833 		 * down the entire mblk chain (which could have a
14834 		 * potential performance problem)
14835 		 */
14836 
14837 		if (DB_REF(mp) > 1) {
14838 			if ((mp = ip_fix_dbref(ill, mp)) == NULL)
14839 				continue;
14840 		}
14841 
14842 		/*
14843 		 * Check and align the IP header.
14844 		 */
14845 		first_mp = mp;
14846 		if (DB_TYPE(mp) == M_DATA) {
14847 			dmp = mp;
14848 		} else if (DB_TYPE(mp) == M_PROTO &&
14849 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14850 			dmp = mp->b_cont;
14851 		} else {
14852 			dmp = NULL;
14853 		}
14854 		if (dmp != NULL) {
14855 			/*
14856 			 * IP header ptr not aligned?
14857 			 * OR IP header not complete in first mblk
14858 			 */
14859 			if (!OK_32PTR(dmp->b_rptr) ||
14860 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
14861 				if (!ip_check_and_align_header(q, dmp, ipst))
14862 					continue;
14863 			}
14864 		}
14865 
14866 		/*
14867 		 * ip_input fast path
14868 		 */
14869 
14870 		/* mblk type is not M_DATA */
14871 		if (DB_TYPE(mp) != M_DATA) {
14872 			if (ip_rput_process_notdata(q, &first_mp, ill,
14873 			    &ll_multicast, &mp))
14874 				continue;
14875 		}
14876 
14877 		/* Make sure its an M_DATA and that its aligned */
14878 		ASSERT(DB_TYPE(mp) == M_DATA);
14879 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
14880 
14881 		ipha = (ipha_t *)mp->b_rptr;
14882 		len = mp->b_wptr - rptr;
14883 		pkt_len = ntohs(ipha->ipha_length);
14884 
14885 		/*
14886 		 * We must count all incoming packets, even if they end
14887 		 * up being dropped later on.
14888 		 */
14889 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
14890 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
14891 
14892 		/* multiple mblk or too short */
14893 		len -= pkt_len;
14894 		if (len != 0) {
14895 			/*
14896 			 * Make sure we have data length consistent
14897 			 * with the IP header.
14898 			 */
14899 			if (mp->b_cont == NULL) {
14900 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14901 					BUMP_MIB(ill->ill_ip_mib,
14902 					    ipIfStatsInHdrErrors);
14903 					ip2dbg(("ip_input: drop pkt\n"));
14904 					freemsg(mp);
14905 					continue;
14906 				}
14907 				mp->b_wptr = rptr + pkt_len;
14908 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
14909 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14910 					BUMP_MIB(ill->ill_ip_mib,
14911 					    ipIfStatsInHdrErrors);
14912 					ip2dbg(("ip_input: drop pkt\n"));
14913 					freemsg(mp);
14914 					continue;
14915 				}
14916 				(void) adjmsg(mp, -len);
14917 				IP_STAT(ipst, ip_multimblk3);
14918 			}
14919 		}
14920 
14921 		/* Obtain the dst of the current packet */
14922 		dst = ipha->ipha_dst;
14923 
14924 		if (IP_LOOPBACK_ADDR(dst) ||
14925 		    IP_LOOPBACK_ADDR(ipha->ipha_src)) {
14926 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
14927 			cmn_err(CE_CONT, "dst %X src %X\n",
14928 			    dst, ipha->ipha_src);
14929 			freemsg(mp);
14930 			continue;
14931 		}
14932 
14933 		/*
14934 		 * The event for packets being received from a 'physical'
14935 		 * interface is placed after validation of the source and/or
14936 		 * destination address as being local so that packets can be
14937 		 * redirected to loopback addresses using ipnat.
14938 		 */
14939 		DTRACE_PROBE4(ip4__physical__in__start,
14940 		    ill_t *, ill, ill_t *, NULL,
14941 		    ipha_t *, ipha, mblk_t *, first_mp);
14942 
14943 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
14944 		    ipst->ips_ipv4firewall_physical_in,
14945 		    ill, NULL, ipha, first_mp, mp, ipst);
14946 
14947 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
14948 
14949 		if (first_mp == NULL) {
14950 			continue;
14951 		}
14952 		dst = ipha->ipha_dst;
14953 
14954 		/*
14955 		 * Attach any necessary label information to
14956 		 * this packet
14957 		 */
14958 		if (is_system_labeled() &&
14959 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
14960 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14961 			freemsg(mp);
14962 			continue;
14963 		}
14964 
14965 		/*
14966 		 * Reuse the cached ire only if the ipha_dst of the previous
14967 		 * packet is the same as the current packet AND it is not
14968 		 * INADDR_ANY.
14969 		 */
14970 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
14971 		    (ire != NULL)) {
14972 			ire_refrele(ire);
14973 			ire = NULL;
14974 		}
14975 		opt_len = ipha->ipha_version_and_hdr_length -
14976 		    IP_SIMPLE_HDR_VERSION;
14977 
14978 		/*
14979 		 * Check to see if we can take the fastpath.
14980 		 * That is possible if the following conditions are met
14981 		 *	o Tsol disabled
14982 		 *	o CGTP disabled
14983 		 *	o ipp_action_count is 0
14984 		 *	o no options in the packet
14985 		 *	o not a RSVP packet
14986 		 * 	o not a multicast packet
14987 		 */
14988 		if (!is_system_labeled() &&
14989 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
14990 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
14991 		    !ll_multicast && !CLASSD(dst)) {
14992 			if (ire == NULL)
14993 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL,
14994 				    ipst);
14995 
14996 			/* incoming packet is for forwarding */
14997 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
14998 				ire = ip_fast_forward(ire, dst, ill, mp);
14999 				continue;
15000 			}
15001 			/* incoming packet is for local consumption */
15002 			if (ire->ire_type & IRE_LOCAL)
15003 				goto local;
15004 		}
15005 
15006 		/*
15007 		 * Disable ire caching for anything more complex
15008 		 * than the simple fast path case we checked for above.
15009 		 */
15010 		if (ire != NULL) {
15011 			ire_refrele(ire);
15012 			ire = NULL;
15013 		}
15014 
15015 		/* Full-blown slow path */
15016 		if (opt_len != 0) {
15017 			if (len != 0)
15018 				IP_STAT(ipst, ip_multimblk4);
15019 			else
15020 				IP_STAT(ipst, ip_ipoptions);
15021 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15022 			    &dst, ipst))
15023 				continue;
15024 		}
15025 
15026 		/*
15027 		 * Invoke the CGTP (multirouting) filtering module to process
15028 		 * the incoming packet. Packets identified as duplicates
15029 		 * must be discarded. Filtering is active only if the
15030 		 * the ip_cgtp_filter ndd variable is non-zero.
15031 		 */
15032 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15033 		if (ipst->ips_ip_cgtp_filter &&
15034 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15035 			netstackid_t stackid;
15036 
15037 			stackid = ipst->ips_netstack->netstack_stackid;
15038 			cgtp_flt_pkt =
15039 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15040 			    ill->ill_phyint->phyint_ifindex, mp);
15041 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15042 				freemsg(first_mp);
15043 				continue;
15044 			}
15045 		}
15046 
15047 		/*
15048 		 * If rsvpd is running, let RSVP daemon handle its processing
15049 		 * and forwarding of RSVP multicast/unicast packets.
15050 		 * If rsvpd is not running but mrouted is running, RSVP
15051 		 * multicast packets are forwarded as multicast traffic
15052 		 * and RSVP unicast packets are forwarded by unicast router.
15053 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15054 		 * packets are not forwarded, but the unicast packets are
15055 		 * forwarded like unicast traffic.
15056 		 */
15057 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15058 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15059 		    NULL) {
15060 			/* RSVP packet and rsvpd running. Treat as ours */
15061 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15062 			/*
15063 			 * This assumes that we deliver to all streams for
15064 			 * multicast and broadcast packets.
15065 			 * We have to force ll_multicast to 1 to handle the
15066 			 * M_DATA messages passed in from ip_mroute_decap.
15067 			 */
15068 			dst = INADDR_BROADCAST;
15069 			ll_multicast = 1;
15070 		} else if (CLASSD(dst)) {
15071 			/* packet is multicast */
15072 			mp->b_next = NULL;
15073 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15074 			    &ll_multicast, &dst))
15075 				continue;
15076 		}
15077 
15078 		if (ire == NULL) {
15079 			ire = ire_cache_lookup(dst, ALL_ZONES,
15080 			    MBLK_GETLABEL(mp), ipst);
15081 		}
15082 
15083 		if (ire == NULL) {
15084 			/*
15085 			 * No IRE for this destination, so it can't be for us.
15086 			 * Unless we are forwarding, drop the packet.
15087 			 * We have to let source routed packets through
15088 			 * since we don't yet know if they are 'ping -l'
15089 			 * packets i.e. if they will go out over the
15090 			 * same interface as they came in on.
15091 			 */
15092 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15093 			if (ire == NULL)
15094 				continue;
15095 		}
15096 
15097 		/*
15098 		 * Broadcast IRE may indicate either broadcast or
15099 		 * multicast packet
15100 		 */
15101 		if (ire->ire_type == IRE_BROADCAST) {
15102 			/*
15103 			 * Skip broadcast checks if packet is UDP multicast;
15104 			 * we'd rather not enter ip_rput_process_broadcast()
15105 			 * unless the packet is broadcast for real, since
15106 			 * that routine is a no-op for multicast.
15107 			 */
15108 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15109 			    !CLASSD(ipha->ipha_dst)) {
15110 				ire = ip_rput_process_broadcast(&q, mp,
15111 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15112 				    ll_multicast);
15113 				if (ire == NULL)
15114 					continue;
15115 			}
15116 		} else if (ire->ire_stq != NULL) {
15117 			/* fowarding? */
15118 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15119 			    ll_multicast);
15120 			/* ip_rput_process_forward consumed the packet */
15121 			continue;
15122 		}
15123 
15124 local:
15125 		/*
15126 		 * If the queue in the ire is different to the ingress queue
15127 		 * then we need to check to see if we can accept the packet.
15128 		 * Note that for multicast packets and broadcast packets sent
15129 		 * to a broadcast address which is shared between multiple
15130 		 * interfaces we should not do this since we just got a random
15131 		 * broadcast ire.
15132 		 */
15133 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15134 			if ((ire = ip_check_multihome(&ipha->ipha_dst, ire,
15135 			    ill)) == NULL) {
15136 				/* Drop packet */
15137 				BUMP_MIB(ill->ill_ip_mib,
15138 				    ipIfStatsForwProhibits);
15139 				freemsg(mp);
15140 				continue;
15141 			}
15142 			if (ire->ire_rfq != NULL)
15143 				q = ire->ire_rfq;
15144 		}
15145 
15146 		switch (ipha->ipha_protocol) {
15147 		case IPPROTO_TCP:
15148 			ASSERT(first_mp == mp);
15149 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15150 			    mp, 0, q, ip_ring)) != NULL) {
15151 				if (curr_sqp == NULL) {
15152 					curr_sqp = GET_SQUEUE(mp);
15153 					ASSERT(cnt == 0);
15154 					cnt++;
15155 					head = tail = mp;
15156 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15157 					ASSERT(tail != NULL);
15158 					cnt++;
15159 					tail->b_next = mp;
15160 					tail = mp;
15161 				} else {
15162 					/*
15163 					 * A different squeue. Send the
15164 					 * chain for the previous squeue on
15165 					 * its way. This shouldn't happen
15166 					 * often unless interrupt binding
15167 					 * changes.
15168 					 */
15169 					IP_STAT(ipst, ip_input_multi_squeue);
15170 					squeue_enter_chain(curr_sqp, head,
15171 					    tail, cnt, SQTAG_IP_INPUT);
15172 					curr_sqp = GET_SQUEUE(mp);
15173 					head = mp;
15174 					tail = mp;
15175 					cnt = 1;
15176 				}
15177 			}
15178 			continue;
15179 		case IPPROTO_UDP:
15180 			ASSERT(first_mp == mp);
15181 			ip_udp_input(q, mp, ipha, ire, ill);
15182 			continue;
15183 		case IPPROTO_SCTP:
15184 			ASSERT(first_mp == mp);
15185 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15186 			    q, dst);
15187 			/* ire has been released by ip_sctp_input */
15188 			ire = NULL;
15189 			continue;
15190 		default:
15191 			ip_proto_input(q, first_mp, ipha, ire, ill, B_FALSE);
15192 			continue;
15193 		}
15194 	}
15195 
15196 	if (ire != NULL)
15197 		ire_refrele(ire);
15198 
15199 	if (head != NULL)
15200 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
15201 
15202 	/*
15203 	 * This code is there just to make netperf/ttcp look good.
15204 	 *
15205 	 * Its possible that after being in polling mode (and having cleared
15206 	 * the backlog), squeues have turned the interrupt frequency higher
15207 	 * to improve latency at the expense of more CPU utilization (less
15208 	 * packets per interrupts or more number of interrupts). Workloads
15209 	 * like ttcp/netperf do manage to tickle polling once in a while
15210 	 * but for the remaining time, stay in higher interrupt mode since
15211 	 * their packet arrival rate is pretty uniform and this shows up
15212 	 * as higher CPU utilization. Since people care about CPU utilization
15213 	 * while running netperf/ttcp, turn the interrupt frequency back to
15214 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
15215 	 */
15216 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
15217 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
15218 			ip_ring->rr_poll_state &= ~ILL_POLLING;
15219 			ip_ring->rr_blank(ip_ring->rr_handle,
15220 			    ip_ring->rr_normal_blank_time,
15221 			    ip_ring->rr_normal_pkt_cnt);
15222 		}
15223 		}
15224 
15225 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15226 	    "ip_input_end: q %p (%S)", q, "end");
15227 #undef  rptr
15228 }
15229 
15230 static void
15231 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15232     t_uscalar_t err)
15233 {
15234 	if (dl_err == DL_SYSERR) {
15235 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15236 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15237 		    ill->ill_name, dlpi_prim_str(prim), err);
15238 		return;
15239 	}
15240 
15241 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15242 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
15243 	    dlpi_err_str(dl_err));
15244 }
15245 
15246 /*
15247  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15248  * than DL_UNITDATA_IND messages. If we need to process this message
15249  * exclusively, we call qwriter_ip, in which case we also need to call
15250  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15251  */
15252 void
15253 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15254 {
15255 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15256 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15257 	ill_t		*ill = (ill_t *)q->q_ptr;
15258 	boolean_t	pending;
15259 
15260 	ip1dbg(("ip_rput_dlpi"));
15261 	if (dloa->dl_primitive == DL_ERROR_ACK) {
15262 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
15263 		    "%s (0x%x), unix %u\n", ill->ill_name,
15264 		    dlpi_prim_str(dlea->dl_error_primitive),
15265 		    dlea->dl_error_primitive,
15266 		    dlpi_err_str(dlea->dl_errno),
15267 		    dlea->dl_errno,
15268 		    dlea->dl_unix_errno));
15269 	}
15270 
15271 	/*
15272 	 * If we received an ACK but didn't send a request for it, then it
15273 	 * can't be part of any pending operation; discard up-front.
15274 	 */
15275 	switch (dloa->dl_primitive) {
15276 	case DL_NOTIFY_IND:
15277 		pending = B_TRUE;
15278 		break;
15279 	case DL_ERROR_ACK:
15280 		pending = ill_dlpi_pending(ill, dlea->dl_error_primitive);
15281 		break;
15282 	case DL_OK_ACK:
15283 		pending = ill_dlpi_pending(ill, dloa->dl_correct_primitive);
15284 		break;
15285 	case DL_INFO_ACK:
15286 		pending = ill_dlpi_pending(ill, DL_INFO_REQ);
15287 		break;
15288 	case DL_BIND_ACK:
15289 		pending = ill_dlpi_pending(ill, DL_BIND_REQ);
15290 		break;
15291 	case DL_PHYS_ADDR_ACK:
15292 		pending = ill_dlpi_pending(ill, DL_PHYS_ADDR_REQ);
15293 		break;
15294 	case DL_NOTIFY_ACK:
15295 		pending = ill_dlpi_pending(ill, DL_NOTIFY_REQ);
15296 		break;
15297 	case DL_CONTROL_ACK:
15298 		pending = ill_dlpi_pending(ill, DL_CONTROL_REQ);
15299 		break;
15300 	case DL_CAPABILITY_ACK:
15301 		pending = ill_dlpi_pending(ill, DL_CAPABILITY_REQ);
15302 		break;
15303 	default:
15304 		/* Not a DLPI message we support or were expecting */
15305 		freemsg(mp);
15306 		return;
15307 	}
15308 
15309 	if (!pending) {
15310 		freemsg(mp);
15311 		return;
15312 	}
15313 
15314 	switch (dloa->dl_primitive) {
15315 	case DL_ERROR_ACK:
15316 		if (dlea->dl_error_primitive == DL_UNBIND_REQ) {
15317 			mutex_enter(&ill->ill_lock);
15318 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15319 			cv_signal(&ill->ill_cv);
15320 			mutex_exit(&ill->ill_lock);
15321 		}
15322 		break;
15323 
15324 	case DL_OK_ACK:
15325 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
15326 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
15327 		switch (dloa->dl_correct_primitive) {
15328 		case DL_UNBIND_REQ:
15329 			mutex_enter(&ill->ill_lock);
15330 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15331 			cv_signal(&ill->ill_cv);
15332 			mutex_exit(&ill->ill_lock);
15333 			break;
15334 
15335 		case DL_ENABMULTI_REQ:
15336 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15337 				ill->ill_dlpi_multicast_state = IDS_OK;
15338 			break;
15339 		}
15340 		break;
15341 	default:
15342 		break;
15343 	}
15344 
15345 	/*
15346 	 * We know the message is one we're waiting for (or DL_NOTIFY_IND),
15347 	 * and we need to become writer to continue to process it. If it's not
15348 	 * a DL_NOTIFY_IND, we assume we're in the middle of an exclusive
15349 	 * operation and pass CUR_OP.  If this isn't true, we'll end up doing
15350 	 * some work as part of the current exclusive operation that actually
15351 	 * is not part of it -- which is wrong, but better than the
15352 	 * alternative of deadlock (if NEW_OP is always used).  Someday, we
15353 	 * should track which DLPI requests have ACKs that we wait on
15354 	 * synchronously so we can know whether to use CUR_OP or NEW_OP.
15355 	 *
15356 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15357 	 * Since this is on the ill stream we unconditionally bump up the
15358 	 * refcount without doing ILL_CAN_LOOKUP().
15359 	 */
15360 	ill_refhold(ill);
15361 	if (dloa->dl_primitive == DL_NOTIFY_IND)
15362 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15363 	else
15364 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15365 }
15366 
15367 /*
15368  * Handling of DLPI messages that require exclusive access to the ipsq.
15369  *
15370  * Need to do ill_pending_mp_release on ioctl completion, which could
15371  * happen here. (along with mi_copy_done)
15372  */
15373 /* ARGSUSED */
15374 static void
15375 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15376 {
15377 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15378 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15379 	int		err = 0;
15380 	ill_t		*ill;
15381 	ipif_t		*ipif = NULL;
15382 	mblk_t		*mp1 = NULL;
15383 	conn_t		*connp = NULL;
15384 	t_uscalar_t	paddrreq;
15385 	mblk_t		*mp_hw;
15386 	boolean_t	success;
15387 	boolean_t	ioctl_aborted = B_FALSE;
15388 	boolean_t	log = B_TRUE;
15389 	hook_nic_event_t	*info;
15390 	ip_stack_t		*ipst;
15391 
15392 	ip1dbg(("ip_rput_dlpi_writer .."));
15393 	ill = (ill_t *)q->q_ptr;
15394 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15395 
15396 	ASSERT(IAM_WRITER_ILL(ill));
15397 
15398 	ipst = ill->ill_ipst;
15399 
15400 	/*
15401 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15402 	 * both are null or non-null. However we can assert that only
15403 	 * after grabbing the ipsq_lock. So we don't make any assertion
15404 	 * here and in other places in the code.
15405 	 */
15406 	ipif = ipsq->ipsq_pending_ipif;
15407 	/*
15408 	 * The current ioctl could have been aborted by the user and a new
15409 	 * ioctl to bring up another ill could have started. We could still
15410 	 * get a response from the driver later.
15411 	 */
15412 	if (ipif != NULL && ipif->ipif_ill != ill)
15413 		ioctl_aborted = B_TRUE;
15414 
15415 	switch (dloa->dl_primitive) {
15416 	case DL_ERROR_ACK:
15417 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15418 		    dlpi_prim_str(dlea->dl_error_primitive)));
15419 
15420 		switch (dlea->dl_error_primitive) {
15421 		case DL_PROMISCON_REQ:
15422 		case DL_PROMISCOFF_REQ:
15423 		case DL_DISABMULTI_REQ:
15424 		case DL_UNBIND_REQ:
15425 		case DL_ATTACH_REQ:
15426 		case DL_INFO_REQ:
15427 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15428 			break;
15429 		case DL_NOTIFY_REQ:
15430 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15431 			log = B_FALSE;
15432 			break;
15433 		case DL_PHYS_ADDR_REQ:
15434 			/*
15435 			 * For IPv6 only, there are two additional
15436 			 * phys_addr_req's sent to the driver to get the
15437 			 * IPv6 token and lla. This allows IP to acquire
15438 			 * the hardware address format for a given interface
15439 			 * without having built in knowledge of the hardware
15440 			 * address. ill_phys_addr_pend keeps track of the last
15441 			 * DL_PAR sent so we know which response we are
15442 			 * dealing with. ill_dlpi_done will update
15443 			 * ill_phys_addr_pend when it sends the next req.
15444 			 * We don't complete the IOCTL until all three DL_PARs
15445 			 * have been attempted, so set *_len to 0 and break.
15446 			 */
15447 			paddrreq = ill->ill_phys_addr_pend;
15448 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15449 			if (paddrreq == DL_IPV6_TOKEN) {
15450 				ill->ill_token_length = 0;
15451 				log = B_FALSE;
15452 				break;
15453 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15454 				ill->ill_nd_lla_len = 0;
15455 				log = B_FALSE;
15456 				break;
15457 			}
15458 			/*
15459 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15460 			 * We presumably have an IOCTL hanging out waiting
15461 			 * for completion. Find it and complete the IOCTL
15462 			 * with the error noted.
15463 			 * However, ill_dl_phys was called on an ill queue
15464 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15465 			 * set. But the ioctl is known to be pending on ill_wq.
15466 			 */
15467 			if (!ill->ill_ifname_pending)
15468 				break;
15469 			ill->ill_ifname_pending = 0;
15470 			if (!ioctl_aborted)
15471 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15472 			if (mp1 != NULL) {
15473 				/*
15474 				 * This operation (SIOCSLIFNAME) must have
15475 				 * happened on the ill. Assert there is no conn
15476 				 */
15477 				ASSERT(connp == NULL);
15478 				q = ill->ill_wq;
15479 			}
15480 			break;
15481 		case DL_BIND_REQ:
15482 			ill_dlpi_done(ill, DL_BIND_REQ);
15483 			if (ill->ill_ifname_pending)
15484 				break;
15485 			/*
15486 			 * Something went wrong with the bind.  We presumably
15487 			 * have an IOCTL hanging out waiting for completion.
15488 			 * Find it, take down the interface that was coming
15489 			 * up, and complete the IOCTL with the error noted.
15490 			 */
15491 			if (!ioctl_aborted)
15492 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15493 			if (mp1 != NULL) {
15494 				/*
15495 				 * This operation (SIOCSLIFFLAGS) must have
15496 				 * happened from a conn.
15497 				 */
15498 				ASSERT(connp != NULL);
15499 				q = CONNP_TO_WQ(connp);
15500 				if (ill->ill_move_in_progress) {
15501 					ILL_CLEAR_MOVE(ill);
15502 				}
15503 				(void) ipif_down(ipif, NULL, NULL);
15504 				/* error is set below the switch */
15505 			}
15506 			break;
15507 		case DL_ENABMULTI_REQ:
15508 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15509 
15510 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15511 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15512 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15513 				ipif_t *ipif;
15514 
15515 				printf("ip: joining multicasts failed (%d)"
15516 				    " on %s - will use link layer "
15517 				    "broadcasts for multicast\n",
15518 				    dlea->dl_errno, ill->ill_name);
15519 
15520 				/*
15521 				 * Set up the multicast mapping alone.
15522 				 * writer, so ok to access ill->ill_ipif
15523 				 * without any lock.
15524 				 */
15525 				ipif = ill->ill_ipif;
15526 				mutex_enter(&ill->ill_phyint->phyint_lock);
15527 				ill->ill_phyint->phyint_flags |=
15528 				    PHYI_MULTI_BCAST;
15529 				mutex_exit(&ill->ill_phyint->phyint_lock);
15530 
15531 				if (!ill->ill_isv6) {
15532 					(void) ipif_arp_setup_multicast(ipif,
15533 					    NULL);
15534 				} else {
15535 					(void) ipif_ndp_setup_multicast(ipif,
15536 					    NULL);
15537 				}
15538 			}
15539 			freemsg(mp);	/* Don't want to pass this up */
15540 			return;
15541 
15542 		case DL_CAPABILITY_REQ:
15543 		case DL_CONTROL_REQ:
15544 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15545 			ill->ill_dlpi_capab_state = IDS_FAILED;
15546 			freemsg(mp);
15547 			return;
15548 		}
15549 		/*
15550 		 * Note the error for IOCTL completion (mp1 is set when
15551 		 * ready to complete ioctl). If ill_ifname_pending_err is
15552 		 * set, an error occured during plumbing (ill_ifname_pending),
15553 		 * so we want to report that error.
15554 		 *
15555 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15556 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15557 		 * expected to get errack'd if the driver doesn't support
15558 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15559 		 * if these error conditions are encountered.
15560 		 */
15561 		if (mp1 != NULL) {
15562 			if (ill->ill_ifname_pending_err != 0)  {
15563 				err = ill->ill_ifname_pending_err;
15564 				ill->ill_ifname_pending_err = 0;
15565 			} else {
15566 				err = dlea->dl_unix_errno ?
15567 				    dlea->dl_unix_errno : ENXIO;
15568 			}
15569 		/*
15570 		 * If we're plumbing an interface and an error hasn't already
15571 		 * been saved, set ill_ifname_pending_err to the error passed
15572 		 * up. Ignore the error if log is B_FALSE (see comment above).
15573 		 */
15574 		} else if (log && ill->ill_ifname_pending &&
15575 		    ill->ill_ifname_pending_err == 0) {
15576 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15577 			    dlea->dl_unix_errno : ENXIO;
15578 		}
15579 
15580 		if (log)
15581 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15582 			    dlea->dl_errno, dlea->dl_unix_errno);
15583 		break;
15584 	case DL_CAPABILITY_ACK:
15585 		/* Call a routine to handle this one. */
15586 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15587 		ill_capability_ack(ill, mp);
15588 
15589 		/*
15590 		 * If the ack is due to renegotiation, we will need to send
15591 		 * a new CAPABILITY_REQ to start the renegotiation.
15592 		 */
15593 		if (ill->ill_capab_reneg) {
15594 			ill->ill_capab_reneg = B_FALSE;
15595 			ill_capability_probe(ill);
15596 		}
15597 		break;
15598 	case DL_CONTROL_ACK:
15599 		/* We treat all of these as "fire and forget" */
15600 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15601 		break;
15602 	case DL_INFO_ACK:
15603 		/* Call a routine to handle this one. */
15604 		ill_dlpi_done(ill, DL_INFO_REQ);
15605 		ip_ll_subnet_defaults(ill, mp);
15606 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15607 		return;
15608 	case DL_BIND_ACK:
15609 		/*
15610 		 * We should have an IOCTL waiting on this unless
15611 		 * sent by ill_dl_phys, in which case just return
15612 		 */
15613 		ill_dlpi_done(ill, DL_BIND_REQ);
15614 		if (ill->ill_ifname_pending)
15615 			break;
15616 
15617 		if (!ioctl_aborted)
15618 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15619 		if (mp1 == NULL)
15620 			break;
15621 		/*
15622 		 * Because mp1 was added by ill_dl_up(), and it always
15623 		 * passes a valid connp, connp must be valid here.
15624 		 */
15625 		ASSERT(connp != NULL);
15626 		q = CONNP_TO_WQ(connp);
15627 
15628 		/*
15629 		 * We are exclusive. So nothing can change even after
15630 		 * we get the pending mp. If need be we can put it back
15631 		 * and restart, as in calling ipif_arp_up()  below.
15632 		 */
15633 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15634 
15635 		mutex_enter(&ill->ill_lock);
15636 
15637 		ill->ill_dl_up = 1;
15638 
15639 		if ((info = ill->ill_nic_event_info) != NULL) {
15640 			ip2dbg(("ip_rput_dlpi_writer: unexpected nic event %d "
15641 			    "attached for %s\n", info->hne_event,
15642 			    ill->ill_name));
15643 			if (info->hne_data != NULL)
15644 				kmem_free(info->hne_data, info->hne_datalen);
15645 			kmem_free(info, sizeof (hook_nic_event_t));
15646 		}
15647 
15648 		info = kmem_alloc(sizeof (hook_nic_event_t), KM_NOSLEEP);
15649 		if (info != NULL) {
15650 			info->hne_nic = ill->ill_phyint->phyint_hook_ifindex;
15651 			info->hne_lif = 0;
15652 			info->hne_event = NE_UP;
15653 			info->hne_data = NULL;
15654 			info->hne_datalen = 0;
15655 			info->hne_family = ill->ill_isv6 ?
15656 			    ipst->ips_ipv6_net_data : ipst->ips_ipv4_net_data;
15657 		} else
15658 			ip2dbg(("ip_rput_dlpi_writer: could not attach UP nic "
15659 			    "event information for %s (ENOMEM)\n",
15660 			    ill->ill_name));
15661 
15662 		ill->ill_nic_event_info = info;
15663 
15664 		mutex_exit(&ill->ill_lock);
15665 
15666 		/*
15667 		 * Now bring up the resolver; when that is complete, we'll
15668 		 * create IREs.  Note that we intentionally mirror what
15669 		 * ipif_up() would have done, because we got here by way of
15670 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15671 		 */
15672 		if (ill->ill_isv6) {
15673 			/*
15674 			 * v6 interfaces.
15675 			 * Unlike ARP which has to do another bind
15676 			 * and attach, once we get here we are
15677 			 * done with NDP. Except in the case of
15678 			 * ILLF_XRESOLV, in which case we send an
15679 			 * AR_INTERFACE_UP to the external resolver.
15680 			 * If all goes well, the ioctl will complete
15681 			 * in ip_rput(). If there's an error, we
15682 			 * complete it here.
15683 			 */
15684 			if ((err = ipif_ndp_up(ipif)) == 0) {
15685 				if (ill->ill_flags & ILLF_XRESOLV) {
15686 					mutex_enter(&connp->conn_lock);
15687 					mutex_enter(&ill->ill_lock);
15688 					success = ipsq_pending_mp_add(
15689 					    connp, ipif, q, mp1, 0);
15690 					mutex_exit(&ill->ill_lock);
15691 					mutex_exit(&connp->conn_lock);
15692 					if (success) {
15693 						err = ipif_resolver_up(ipif,
15694 						    Res_act_initial);
15695 						if (err == EINPROGRESS) {
15696 							freemsg(mp);
15697 							return;
15698 						}
15699 						ASSERT(err != 0);
15700 						mp1 = ipsq_pending_mp_get(ipsq,
15701 						    &connp);
15702 						ASSERT(mp1 != NULL);
15703 					} else {
15704 						/* conn has started closing */
15705 						err = EINTR;
15706 					}
15707 				} else { /* Non XRESOLV interface */
15708 					(void) ipif_resolver_up(ipif,
15709 					    Res_act_initial);
15710 					err = ipif_up_done_v6(ipif);
15711 				}
15712 			}
15713 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
15714 			/*
15715 			 * ARP and other v4 external resolvers.
15716 			 * Leave the pending mblk intact so that
15717 			 * the ioctl completes in ip_rput().
15718 			 */
15719 			mutex_enter(&connp->conn_lock);
15720 			mutex_enter(&ill->ill_lock);
15721 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
15722 			mutex_exit(&ill->ill_lock);
15723 			mutex_exit(&connp->conn_lock);
15724 			if (success) {
15725 				err = ipif_resolver_up(ipif, Res_act_initial);
15726 				if (err == EINPROGRESS) {
15727 					freemsg(mp);
15728 					return;
15729 				}
15730 				ASSERT(err != 0);
15731 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15732 			} else {
15733 				/* The conn has started closing */
15734 				err = EINTR;
15735 			}
15736 		} else {
15737 			/*
15738 			 * This one is complete. Reply to pending ioctl.
15739 			 */
15740 			(void) ipif_resolver_up(ipif, Res_act_initial);
15741 			err = ipif_up_done(ipif);
15742 		}
15743 
15744 		if ((err == 0) && (ill->ill_up_ipifs)) {
15745 			err = ill_up_ipifs(ill, q, mp1);
15746 			if (err == EINPROGRESS) {
15747 				freemsg(mp);
15748 				return;
15749 			}
15750 		}
15751 
15752 		if (ill->ill_up_ipifs) {
15753 			ill_group_cleanup(ill);
15754 		}
15755 
15756 		break;
15757 	case DL_NOTIFY_IND: {
15758 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
15759 		ire_t *ire;
15760 		boolean_t need_ire_walk_v4 = B_FALSE;
15761 		boolean_t need_ire_walk_v6 = B_FALSE;
15762 
15763 		switch (notify->dl_notification) {
15764 		case DL_NOTE_PHYS_ADDR:
15765 			err = ill_set_phys_addr(ill, mp);
15766 			break;
15767 
15768 		case DL_NOTE_FASTPATH_FLUSH:
15769 			ill_fastpath_flush(ill);
15770 			break;
15771 
15772 		case DL_NOTE_SDU_SIZE:
15773 			/*
15774 			 * Change the MTU size of the interface, of all
15775 			 * attached ipif's, and of all relevant ire's.  The
15776 			 * new value's a uint32_t at notify->dl_data.
15777 			 * Mtu change Vs. new ire creation - protocol below.
15778 			 *
15779 			 * a Mark the ipif as IPIF_CHANGING.
15780 			 * b Set the new mtu in the ipif.
15781 			 * c Change the ire_max_frag on all affected ires
15782 			 * d Unmark the IPIF_CHANGING
15783 			 *
15784 			 * To see how the protocol works, assume an interface
15785 			 * route is also being added simultaneously by
15786 			 * ip_rt_add and let 'ipif' be the ipif referenced by
15787 			 * the ire. If the ire is created before step a,
15788 			 * it will be cleaned up by step c. If the ire is
15789 			 * created after step d, it will see the new value of
15790 			 * ipif_mtu. Any attempt to create the ire between
15791 			 * steps a to d will fail because of the IPIF_CHANGING
15792 			 * flag. Note that ire_create() is passed a pointer to
15793 			 * the ipif_mtu, and not the value. During ire_add
15794 			 * under the bucket lock, the ire_max_frag of the
15795 			 * new ire being created is set from the ipif/ire from
15796 			 * which it is being derived.
15797 			 */
15798 			mutex_enter(&ill->ill_lock);
15799 			ill->ill_max_frag = (uint_t)notify->dl_data;
15800 
15801 			/*
15802 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
15803 			 * leave it alone
15804 			 */
15805 			if (ill->ill_mtu_userspecified) {
15806 				mutex_exit(&ill->ill_lock);
15807 				break;
15808 			}
15809 			ill->ill_max_mtu = ill->ill_max_frag;
15810 			if (ill->ill_isv6) {
15811 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
15812 					ill->ill_max_mtu = IPV6_MIN_MTU;
15813 			} else {
15814 				if (ill->ill_max_mtu < IP_MIN_MTU)
15815 					ill->ill_max_mtu = IP_MIN_MTU;
15816 			}
15817 			for (ipif = ill->ill_ipif; ipif != NULL;
15818 			    ipif = ipif->ipif_next) {
15819 				/*
15820 				 * Don't override the mtu if the user
15821 				 * has explicitly set it.
15822 				 */
15823 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
15824 					continue;
15825 				ipif->ipif_mtu = (uint_t)notify->dl_data;
15826 				if (ipif->ipif_isv6)
15827 					ire = ipif_to_ire_v6(ipif);
15828 				else
15829 					ire = ipif_to_ire(ipif);
15830 				if (ire != NULL) {
15831 					ire->ire_max_frag = ipif->ipif_mtu;
15832 					ire_refrele(ire);
15833 				}
15834 				if (ipif->ipif_flags & IPIF_UP) {
15835 					if (ill->ill_isv6)
15836 						need_ire_walk_v6 = B_TRUE;
15837 					else
15838 						need_ire_walk_v4 = B_TRUE;
15839 				}
15840 			}
15841 			mutex_exit(&ill->ill_lock);
15842 			if (need_ire_walk_v4)
15843 				ire_walk_v4(ill_mtu_change, (char *)ill,
15844 				    ALL_ZONES, ipst);
15845 			if (need_ire_walk_v6)
15846 				ire_walk_v6(ill_mtu_change, (char *)ill,
15847 				    ALL_ZONES, ipst);
15848 			break;
15849 		case DL_NOTE_LINK_UP:
15850 		case DL_NOTE_LINK_DOWN: {
15851 			/*
15852 			 * We are writer. ill / phyint / ipsq assocs stable.
15853 			 * The RUNNING flag reflects the state of the link.
15854 			 */
15855 			phyint_t *phyint = ill->ill_phyint;
15856 			uint64_t new_phyint_flags;
15857 			boolean_t changed = B_FALSE;
15858 			boolean_t went_up;
15859 
15860 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
15861 			mutex_enter(&phyint->phyint_lock);
15862 			new_phyint_flags = went_up ?
15863 			    phyint->phyint_flags | PHYI_RUNNING :
15864 			    phyint->phyint_flags & ~PHYI_RUNNING;
15865 			if (new_phyint_flags != phyint->phyint_flags) {
15866 				phyint->phyint_flags = new_phyint_flags;
15867 				changed = B_TRUE;
15868 			}
15869 			mutex_exit(&phyint->phyint_lock);
15870 			/*
15871 			 * ill_restart_dad handles the DAD restart and routing
15872 			 * socket notification logic.
15873 			 */
15874 			if (changed) {
15875 				ill_restart_dad(phyint->phyint_illv4, went_up);
15876 				ill_restart_dad(phyint->phyint_illv6, went_up);
15877 			}
15878 			break;
15879 		}
15880 		case DL_NOTE_PROMISC_ON_PHYS:
15881 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15882 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
15883 			mutex_enter(&ill->ill_lock);
15884 			ill->ill_promisc_on_phys = B_TRUE;
15885 			mutex_exit(&ill->ill_lock);
15886 			break;
15887 		case DL_NOTE_PROMISC_OFF_PHYS:
15888 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15889 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
15890 			mutex_enter(&ill->ill_lock);
15891 			ill->ill_promisc_on_phys = B_FALSE;
15892 			mutex_exit(&ill->ill_lock);
15893 			break;
15894 		case DL_NOTE_CAPAB_RENEG:
15895 			/*
15896 			 * Something changed on the driver side.
15897 			 * It wants us to renegotiate the capabilities
15898 			 * on this ill. One possible cause is the aggregation
15899 			 * interface under us where a port got added or
15900 			 * went away.
15901 			 *
15902 			 * If the capability negotiation is already done
15903 			 * or is in progress, reset the capabilities and
15904 			 * mark the ill's ill_capab_reneg to be B_TRUE,
15905 			 * so that when the ack comes back, we can start
15906 			 * the renegotiation process.
15907 			 *
15908 			 * Note that if ill_capab_reneg is already B_TRUE
15909 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
15910 			 * the capability resetting request has been sent
15911 			 * and the renegotiation has not been started yet;
15912 			 * nothing needs to be done in this case.
15913 			 */
15914 			if (ill->ill_dlpi_capab_state != IDS_UNKNOWN) {
15915 				ill_capability_reset(ill);
15916 				ill->ill_capab_reneg = B_TRUE;
15917 			}
15918 			break;
15919 		default:
15920 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
15921 			    "type 0x%x for DL_NOTIFY_IND\n",
15922 			    notify->dl_notification));
15923 			break;
15924 		}
15925 
15926 		/*
15927 		 * As this is an asynchronous operation, we
15928 		 * should not call ill_dlpi_done
15929 		 */
15930 		break;
15931 	}
15932 	case DL_NOTIFY_ACK: {
15933 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
15934 
15935 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
15936 			ill->ill_note_link = 1;
15937 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
15938 		break;
15939 	}
15940 	case DL_PHYS_ADDR_ACK: {
15941 		/*
15942 		 * As part of plumbing the interface via SIOCSLIFNAME,
15943 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
15944 		 * whose answers we receive here.  As each answer is received,
15945 		 * we call ill_dlpi_done() to dispatch the next request as
15946 		 * we're processing the current one.  Once all answers have
15947 		 * been received, we use ipsq_pending_mp_get() to dequeue the
15948 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
15949 		 * is invoked from an ill queue, conn_oper_pending_ill is not
15950 		 * available, but we know the ioctl is pending on ill_wq.)
15951 		 */
15952 		uint_t paddrlen, paddroff;
15953 
15954 		paddrreq = ill->ill_phys_addr_pend;
15955 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
15956 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
15957 
15958 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15959 		if (paddrreq == DL_IPV6_TOKEN) {
15960 			/*
15961 			 * bcopy to low-order bits of ill_token
15962 			 *
15963 			 * XXX Temporary hack - currently, all known tokens
15964 			 * are 64 bits, so I'll cheat for the moment.
15965 			 */
15966 			bcopy(mp->b_rptr + paddroff,
15967 			    &ill->ill_token.s6_addr32[2], paddrlen);
15968 			ill->ill_token_length = paddrlen;
15969 			break;
15970 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15971 			ASSERT(ill->ill_nd_lla_mp == NULL);
15972 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
15973 			mp = NULL;
15974 			break;
15975 		}
15976 
15977 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
15978 		ASSERT(ill->ill_phys_addr_mp == NULL);
15979 		if (!ill->ill_ifname_pending)
15980 			break;
15981 		ill->ill_ifname_pending = 0;
15982 		if (!ioctl_aborted)
15983 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15984 		if (mp1 != NULL) {
15985 			ASSERT(connp == NULL);
15986 			q = ill->ill_wq;
15987 		}
15988 		/*
15989 		 * If any error acks received during the plumbing sequence,
15990 		 * ill_ifname_pending_err will be set. Break out and send up
15991 		 * the error to the pending ioctl.
15992 		 */
15993 		if (ill->ill_ifname_pending_err != 0) {
15994 			err = ill->ill_ifname_pending_err;
15995 			ill->ill_ifname_pending_err = 0;
15996 			break;
15997 		}
15998 
15999 		ill->ill_phys_addr_mp = mp;
16000 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16001 		mp = NULL;
16002 
16003 		/*
16004 		 * If paddrlen is zero, the DLPI provider doesn't support
16005 		 * physical addresses.  The other two tests were historical
16006 		 * workarounds for bugs in our former PPP implementation, but
16007 		 * now other things have grown dependencies on them -- e.g.,
16008 		 * the tun module specifies a dl_addr_length of zero in its
16009 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16010 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16011 		 * but only after careful testing ensures that all dependent
16012 		 * broken DLPI providers have been fixed.
16013 		 */
16014 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16015 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16016 			ill->ill_phys_addr = NULL;
16017 		} else if (paddrlen != ill->ill_phys_addr_length) {
16018 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16019 			    paddrlen, ill->ill_phys_addr_length));
16020 			err = EINVAL;
16021 			break;
16022 		}
16023 
16024 		if (ill->ill_nd_lla_mp == NULL) {
16025 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16026 				err = ENOMEM;
16027 				break;
16028 			}
16029 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16030 		}
16031 
16032 		/*
16033 		 * Set the interface token.  If the zeroth interface address
16034 		 * is unspecified, then set it to the link local address.
16035 		 */
16036 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16037 			(void) ill_setdefaulttoken(ill);
16038 
16039 		ASSERT(ill->ill_ipif->ipif_id == 0);
16040 		if (ipif != NULL &&
16041 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16042 			(void) ipif_setlinklocal(ipif);
16043 		}
16044 		break;
16045 	}
16046 	case DL_OK_ACK:
16047 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16048 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
16049 		    dloa->dl_correct_primitive));
16050 		switch (dloa->dl_correct_primitive) {
16051 		case DL_PROMISCON_REQ:
16052 		case DL_PROMISCOFF_REQ:
16053 		case DL_ENABMULTI_REQ:
16054 		case DL_DISABMULTI_REQ:
16055 		case DL_UNBIND_REQ:
16056 		case DL_ATTACH_REQ:
16057 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16058 			break;
16059 		}
16060 		break;
16061 	default:
16062 		break;
16063 	}
16064 
16065 	freemsg(mp);
16066 	if (mp1 != NULL) {
16067 		/*
16068 		 * The operation must complete without EINPROGRESS
16069 		 * since ipsq_pending_mp_get() has removed the mblk
16070 		 * from ipsq_pending_mp.  Otherwise, the operation
16071 		 * will be stuck forever in the ipsq.
16072 		 */
16073 		ASSERT(err != EINPROGRESS);
16074 
16075 		switch (ipsq->ipsq_current_ioctl) {
16076 		case 0:
16077 			ipsq_current_finish(ipsq);
16078 			break;
16079 
16080 		case SIOCLIFADDIF:
16081 		case SIOCSLIFNAME:
16082 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16083 			break;
16084 
16085 		default:
16086 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16087 			break;
16088 		}
16089 	}
16090 }
16091 
16092 /*
16093  * ip_rput_other is called by ip_rput to handle messages modifying the global
16094  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16095  */
16096 /* ARGSUSED */
16097 void
16098 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16099 {
16100 	ill_t		*ill;
16101 	struct iocblk	*iocp;
16102 	mblk_t		*mp1;
16103 	conn_t		*connp = NULL;
16104 
16105 	ip1dbg(("ip_rput_other "));
16106 	ill = (ill_t *)q->q_ptr;
16107 	/*
16108 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16109 	 * in which case ipsq is NULL.
16110 	 */
16111 	if (ipsq != NULL) {
16112 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16113 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16114 	}
16115 
16116 	switch (mp->b_datap->db_type) {
16117 	case M_ERROR:
16118 	case M_HANGUP:
16119 		/*
16120 		 * The device has a problem.  We force the ILL down.  It can
16121 		 * be brought up again manually using SIOCSIFFLAGS (via
16122 		 * ifconfig or equivalent).
16123 		 */
16124 		ASSERT(ipsq != NULL);
16125 		if (mp->b_rptr < mp->b_wptr)
16126 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16127 		if (ill->ill_error == 0)
16128 			ill->ill_error = ENXIO;
16129 		if (!ill_down_start(q, mp))
16130 			return;
16131 		ipif_all_down_tail(ipsq, q, mp, NULL);
16132 		break;
16133 	case M_IOCACK:
16134 		iocp = (struct iocblk *)mp->b_rptr;
16135 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16136 		switch (iocp->ioc_cmd) {
16137 		case SIOCSTUNPARAM:
16138 		case OSIOCSTUNPARAM:
16139 			ASSERT(ipsq != NULL);
16140 			/*
16141 			 * Finish socket ioctl passed through to tun.
16142 			 * We should have an IOCTL waiting on this.
16143 			 */
16144 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16145 			if (ill->ill_isv6) {
16146 				struct iftun_req *ta;
16147 
16148 				/*
16149 				 * if a source or destination is
16150 				 * being set, try and set the link
16151 				 * local address for the tunnel
16152 				 */
16153 				ta = (struct iftun_req *)mp->b_cont->
16154 				    b_cont->b_rptr;
16155 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16156 					ipif_set_tun_llink(ill, ta);
16157 				}
16158 
16159 			}
16160 			if (mp1 != NULL) {
16161 				/*
16162 				 * Now copy back the b_next/b_prev used by
16163 				 * mi code for the mi_copy* functions.
16164 				 * See ip_sioctl_tunparam() for the reason.
16165 				 * Also protect against missing b_cont.
16166 				 */
16167 				if (mp->b_cont != NULL) {
16168 					mp->b_cont->b_next =
16169 					    mp1->b_cont->b_next;
16170 					mp->b_cont->b_prev =
16171 					    mp1->b_cont->b_prev;
16172 				}
16173 				inet_freemsg(mp1);
16174 				ASSERT(connp != NULL);
16175 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16176 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16177 			} else {
16178 				ASSERT(connp == NULL);
16179 				putnext(q, mp);
16180 			}
16181 			break;
16182 		case SIOCGTUNPARAM:
16183 		case OSIOCGTUNPARAM:
16184 			/*
16185 			 * This is really M_IOCDATA from the tunnel driver.
16186 			 * convert back and complete the ioctl.
16187 			 * We should have an IOCTL waiting on this.
16188 			 */
16189 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16190 			if (mp1) {
16191 				/*
16192 				 * Now copy back the b_next/b_prev used by
16193 				 * mi code for the mi_copy* functions.
16194 				 * See ip_sioctl_tunparam() for the reason.
16195 				 * Also protect against missing b_cont.
16196 				 */
16197 				if (mp->b_cont != NULL) {
16198 					mp->b_cont->b_next =
16199 					    mp1->b_cont->b_next;
16200 					mp->b_cont->b_prev =
16201 					    mp1->b_cont->b_prev;
16202 				}
16203 				inet_freemsg(mp1);
16204 				if (iocp->ioc_error == 0)
16205 					mp->b_datap->db_type = M_IOCDATA;
16206 				ASSERT(connp != NULL);
16207 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16208 				    iocp->ioc_error, COPYOUT, NULL);
16209 			} else {
16210 				ASSERT(connp == NULL);
16211 				putnext(q, mp);
16212 			}
16213 			break;
16214 		default:
16215 			break;
16216 		}
16217 		break;
16218 	case M_IOCNAK:
16219 		iocp = (struct iocblk *)mp->b_rptr;
16220 
16221 		switch (iocp->ioc_cmd) {
16222 		int mode;
16223 
16224 		case DL_IOC_HDR_INFO:
16225 			/*
16226 			 * If this was the first attempt turn of the
16227 			 * fastpath probing.
16228 			 */
16229 			mutex_enter(&ill->ill_lock);
16230 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16231 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16232 				mutex_exit(&ill->ill_lock);
16233 				ill_fastpath_nack(ill);
16234 				ip1dbg(("ip_rput: DLPI fastpath off on "
16235 				    "interface %s\n",
16236 				    ill->ill_name));
16237 			} else {
16238 				mutex_exit(&ill->ill_lock);
16239 			}
16240 			freemsg(mp);
16241 			break;
16242 		case SIOCSTUNPARAM:
16243 		case OSIOCSTUNPARAM:
16244 			ASSERT(ipsq != NULL);
16245 			/*
16246 			 * Finish socket ioctl passed through to tun
16247 			 * We should have an IOCTL waiting on this.
16248 			 */
16249 			/* FALLTHRU */
16250 		case SIOCGTUNPARAM:
16251 		case OSIOCGTUNPARAM:
16252 			/*
16253 			 * This is really M_IOCDATA from the tunnel driver.
16254 			 * convert back and complete the ioctl.
16255 			 * We should have an IOCTL waiting on this.
16256 			 */
16257 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16258 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16259 				mp1 = ill_pending_mp_get(ill, &connp,
16260 				    iocp->ioc_id);
16261 				mode = COPYOUT;
16262 				ipsq = NULL;
16263 			} else {
16264 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16265 				mode = NO_COPYOUT;
16266 			}
16267 			if (mp1 != NULL) {
16268 				/*
16269 				 * Now copy back the b_next/b_prev used by
16270 				 * mi code for the mi_copy* functions.
16271 				 * See ip_sioctl_tunparam() for the reason.
16272 				 * Also protect against missing b_cont.
16273 				 */
16274 				if (mp->b_cont != NULL) {
16275 					mp->b_cont->b_next =
16276 					    mp1->b_cont->b_next;
16277 					mp->b_cont->b_prev =
16278 					    mp1->b_cont->b_prev;
16279 				}
16280 				inet_freemsg(mp1);
16281 				if (iocp->ioc_error == 0)
16282 					iocp->ioc_error = EINVAL;
16283 				ASSERT(connp != NULL);
16284 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16285 				    iocp->ioc_error, mode, ipsq);
16286 			} else {
16287 				ASSERT(connp == NULL);
16288 				putnext(q, mp);
16289 			}
16290 			break;
16291 		default:
16292 			break;
16293 		}
16294 	default:
16295 		break;
16296 	}
16297 }
16298 
16299 /*
16300  * NOTE : This function does not ire_refrele the ire argument passed in.
16301  *
16302  * IPQoS notes
16303  * IP policy is invoked twice for a forwarded packet, once on the read side
16304  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16305  * enabled. An additional parameter, in_ill, has been added for this purpose.
16306  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16307  * because ip_mroute drops this information.
16308  *
16309  */
16310 void
16311 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16312 {
16313 	uint32_t	old_pkt_len;
16314 	uint32_t	pkt_len;
16315 	queue_t	*q;
16316 	uint32_t	sum;
16317 #define	rptr	((uchar_t *)ipha)
16318 	uint32_t	max_frag;
16319 	uint32_t	ill_index;
16320 	ill_t		*out_ill;
16321 	mib2_ipIfStatsEntry_t *mibptr;
16322 	ip_stack_t	*ipst = ((ill_t *)(ire->ire_stq->q_ptr))->ill_ipst;
16323 
16324 	/* Get the ill_index of the incoming ILL */
16325 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16326 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16327 
16328 	/* Initiate Read side IPPF processing */
16329 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16330 		ip_process(IPP_FWD_IN, &mp, ill_index);
16331 		if (mp == NULL) {
16332 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16333 			    "during IPPF processing\n"));
16334 			return;
16335 		}
16336 	}
16337 
16338 	/* Adjust the checksum to reflect the ttl decrement. */
16339 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16340 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16341 
16342 	if (ipha->ipha_ttl-- <= 1) {
16343 		if (ip_csum_hdr(ipha)) {
16344 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16345 			goto drop_pkt;
16346 		}
16347 		/*
16348 		 * Note: ire_stq this will be NULL for multicast
16349 		 * datagrams using the long path through arp (the IRE
16350 		 * is not an IRE_CACHE). This should not cause
16351 		 * problems since we don't generate ICMP errors for
16352 		 * multicast packets.
16353 		 */
16354 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16355 		q = ire->ire_stq;
16356 		if (q != NULL) {
16357 			/* Sent by forwarding path, and router is global zone */
16358 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16359 			    GLOBAL_ZONEID, ipst);
16360 		} else
16361 			freemsg(mp);
16362 		return;
16363 	}
16364 
16365 	/*
16366 	 * Don't forward if the interface is down
16367 	 */
16368 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16369 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16370 		ip2dbg(("ip_rput_forward:interface is down\n"));
16371 		goto drop_pkt;
16372 	}
16373 
16374 	/* Get the ill_index of the outgoing ILL */
16375 	out_ill = ire_to_ill(ire);
16376 	ill_index = out_ill->ill_phyint->phyint_ifindex;
16377 
16378 	DTRACE_PROBE4(ip4__forwarding__start,
16379 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16380 
16381 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16382 	    ipst->ips_ipv4firewall_forwarding,
16383 	    in_ill, out_ill, ipha, mp, mp, ipst);
16384 
16385 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16386 
16387 	if (mp == NULL)
16388 		return;
16389 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16390 
16391 	if (is_system_labeled()) {
16392 		mblk_t *mp1;
16393 
16394 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16395 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16396 			goto drop_pkt;
16397 		}
16398 		/* Size may have changed */
16399 		mp = mp1;
16400 		ipha = (ipha_t *)mp->b_rptr;
16401 		pkt_len = ntohs(ipha->ipha_length);
16402 	}
16403 
16404 	/* Check if there are options to update */
16405 	if (!IS_SIMPLE_IPH(ipha)) {
16406 		if (ip_csum_hdr(ipha)) {
16407 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16408 			goto drop_pkt;
16409 		}
16410 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16411 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16412 			return;
16413 		}
16414 
16415 		ipha->ipha_hdr_checksum = 0;
16416 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16417 	}
16418 	max_frag = ire->ire_max_frag;
16419 	if (pkt_len > max_frag) {
16420 		/*
16421 		 * It needs fragging on its way out.  We haven't
16422 		 * verified the header checksum yet.  Since we
16423 		 * are going to put a surely good checksum in the
16424 		 * outgoing header, we have to make sure that it
16425 		 * was good coming in.
16426 		 */
16427 		if (ip_csum_hdr(ipha)) {
16428 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16429 			goto drop_pkt;
16430 		}
16431 		/* Initiate Write side IPPF processing */
16432 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16433 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16434 			if (mp == NULL) {
16435 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16436 				    " during IPPF processing\n"));
16437 				return;
16438 			}
16439 		}
16440 		/*
16441 		 * Handle labeled packet resizing.
16442 		 *
16443 		 * If we have added a label, inform ip_wput_frag() of its
16444 		 * effect on the MTU for ICMP messages.
16445 		 */
16446 		if (pkt_len > old_pkt_len) {
16447 			uint32_t secopt_size;
16448 
16449 			secopt_size = pkt_len - old_pkt_len;
16450 			if (secopt_size < max_frag)
16451 				max_frag -= secopt_size;
16452 		}
16453 
16454 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
16455 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16456 		return;
16457 	}
16458 
16459 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16460 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16461 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16462 	    ipst->ips_ipv4firewall_physical_out,
16463 	    NULL, out_ill, ipha, mp, mp, ipst);
16464 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16465 	if (mp == NULL)
16466 		return;
16467 
16468 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16469 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16470 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16471 	/* ip_xmit_v4 always consumes the packet */
16472 	return;
16473 
16474 drop_pkt:;
16475 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16476 	freemsg(mp);
16477 #undef	rptr
16478 }
16479 
16480 void
16481 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16482 {
16483 	ire_t	*ire;
16484 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16485 
16486 	ASSERT(!ipif->ipif_isv6);
16487 	/*
16488 	 * Find an IRE which matches the destination and the outgoing
16489 	 * queue in the cache table. All we need is an IRE_CACHE which
16490 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16491 	 * then it is enough to have some IRE_CACHE in the group.
16492 	 */
16493 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16494 		dst = ipif->ipif_pp_dst_addr;
16495 
16496 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16497 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR, ipst);
16498 	if (ire == NULL) {
16499 		/*
16500 		 * Mark this packet to make it be delivered to
16501 		 * ip_rput_forward after the new ire has been
16502 		 * created.
16503 		 */
16504 		mp->b_prev = NULL;
16505 		mp->b_next = mp;
16506 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16507 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16508 	} else {
16509 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16510 		IRE_REFRELE(ire);
16511 	}
16512 }
16513 
16514 /* Update any source route, record route or timestamp options */
16515 static int
16516 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16517 {
16518 	ipoptp_t	opts;
16519 	uchar_t		*opt;
16520 	uint8_t		optval;
16521 	uint8_t		optlen;
16522 	ipaddr_t	dst;
16523 	uint32_t	ts;
16524 	ire_t		*dst_ire = NULL;
16525 	ire_t		*tmp_ire = NULL;
16526 	timestruc_t	now;
16527 
16528 	ip2dbg(("ip_rput_forward_options\n"));
16529 	dst = ipha->ipha_dst;
16530 	for (optval = ipoptp_first(&opts, ipha);
16531 	    optval != IPOPT_EOL;
16532 	    optval = ipoptp_next(&opts)) {
16533 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16534 		opt = opts.ipoptp_cur;
16535 		optlen = opts.ipoptp_len;
16536 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16537 		    optval, opts.ipoptp_len));
16538 		switch (optval) {
16539 			uint32_t off;
16540 		case IPOPT_SSRR:
16541 		case IPOPT_LSRR:
16542 			/* Check if adminstratively disabled */
16543 			if (!ipst->ips_ip_forward_src_routed) {
16544 				if (ire->ire_stq != NULL) {
16545 					/*
16546 					 * Sent by forwarding path, and router
16547 					 * is global zone
16548 					 */
16549 					icmp_unreachable(ire->ire_stq, mp,
16550 					    ICMP_SOURCE_ROUTE_FAILED,
16551 					    GLOBAL_ZONEID, ipst);
16552 				} else {
16553 					ip0dbg(("ip_rput_forward_options: "
16554 					    "unable to send unreach\n"));
16555 					freemsg(mp);
16556 				}
16557 				return (-1);
16558 			}
16559 
16560 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16561 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16562 			if (dst_ire == NULL) {
16563 				/*
16564 				 * Must be partial since ip_rput_options
16565 				 * checked for strict.
16566 				 */
16567 				break;
16568 			}
16569 			off = opt[IPOPT_OFFSET];
16570 			off--;
16571 		redo_srr:
16572 			if (optlen < IP_ADDR_LEN ||
16573 			    off > optlen - IP_ADDR_LEN) {
16574 				/* End of source route */
16575 				ip1dbg((
16576 				    "ip_rput_forward_options: end of SR\n"));
16577 				ire_refrele(dst_ire);
16578 				break;
16579 			}
16580 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16581 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16582 			    IP_ADDR_LEN);
16583 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16584 			    ntohl(dst)));
16585 
16586 			/*
16587 			 * Check if our address is present more than
16588 			 * once as consecutive hops in source route.
16589 			 */
16590 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16591 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16592 			if (tmp_ire != NULL) {
16593 				ire_refrele(tmp_ire);
16594 				off += IP_ADDR_LEN;
16595 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16596 				goto redo_srr;
16597 			}
16598 			ipha->ipha_dst = dst;
16599 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16600 			ire_refrele(dst_ire);
16601 			break;
16602 		case IPOPT_RR:
16603 			off = opt[IPOPT_OFFSET];
16604 			off--;
16605 			if (optlen < IP_ADDR_LEN ||
16606 			    off > optlen - IP_ADDR_LEN) {
16607 				/* No more room - ignore */
16608 				ip1dbg((
16609 				    "ip_rput_forward_options: end of RR\n"));
16610 				break;
16611 			}
16612 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16613 			    IP_ADDR_LEN);
16614 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16615 			break;
16616 		case IPOPT_TS:
16617 			/* Insert timestamp if there is room */
16618 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16619 			case IPOPT_TS_TSONLY:
16620 				off = IPOPT_TS_TIMELEN;
16621 				break;
16622 			case IPOPT_TS_PRESPEC:
16623 			case IPOPT_TS_PRESPEC_RFC791:
16624 				/* Verify that the address matched */
16625 				off = opt[IPOPT_OFFSET] - 1;
16626 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16627 				dst_ire = ire_ctable_lookup(dst, 0,
16628 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16629 				    MATCH_IRE_TYPE, ipst);
16630 				if (dst_ire == NULL) {
16631 					/* Not for us */
16632 					break;
16633 				}
16634 				ire_refrele(dst_ire);
16635 				/* FALLTHRU */
16636 			case IPOPT_TS_TSANDADDR:
16637 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16638 				break;
16639 			default:
16640 				/*
16641 				 * ip_*put_options should have already
16642 				 * dropped this packet.
16643 				 */
16644 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16645 				    "unknown IT - bug in ip_rput_options?\n");
16646 				return (0);	/* Keep "lint" happy */
16647 			}
16648 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16649 				/* Increase overflow counter */
16650 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16651 				opt[IPOPT_POS_OV_FLG] =
16652 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16653 				    (off << 4));
16654 				break;
16655 			}
16656 			off = opt[IPOPT_OFFSET] - 1;
16657 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16658 			case IPOPT_TS_PRESPEC:
16659 			case IPOPT_TS_PRESPEC_RFC791:
16660 			case IPOPT_TS_TSANDADDR:
16661 				bcopy(&ire->ire_src_addr,
16662 				    (char *)opt + off, IP_ADDR_LEN);
16663 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16664 				/* FALLTHRU */
16665 			case IPOPT_TS_TSONLY:
16666 				off = opt[IPOPT_OFFSET] - 1;
16667 				/* Compute # of milliseconds since midnight */
16668 				gethrestime(&now);
16669 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16670 				    now.tv_nsec / (NANOSEC / MILLISEC);
16671 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16672 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16673 				break;
16674 			}
16675 			break;
16676 		}
16677 	}
16678 	return (0);
16679 }
16680 
16681 /*
16682  * This is called after processing at least one of AH/ESP headers.
16683  *
16684  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16685  * the actual, physical interface on which the packet was received,
16686  * but, when ip_strict_dst_multihoming is set to 1, could be the
16687  * interface which had the ipha_dst configured when the packet went
16688  * through ip_rput. The ill_index corresponding to the recv_ill
16689  * is saved in ipsec_in_rill_index
16690  *
16691  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
16692  * cannot assume "ire" points to valid data for any IPv6 cases.
16693  */
16694 void
16695 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16696 {
16697 	mblk_t *mp;
16698 	ipaddr_t dst;
16699 	in6_addr_t *v6dstp;
16700 	ipha_t *ipha;
16701 	ip6_t *ip6h;
16702 	ipsec_in_t *ii;
16703 	boolean_t ill_need_rele = B_FALSE;
16704 	boolean_t rill_need_rele = B_FALSE;
16705 	boolean_t ire_need_rele = B_FALSE;
16706 	netstack_t	*ns;
16707 	ip_stack_t	*ipst;
16708 
16709 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16710 	ASSERT(ii->ipsec_in_ill_index != 0);
16711 	ns = ii->ipsec_in_ns;
16712 	ASSERT(ii->ipsec_in_ns != NULL);
16713 	ipst = ns->netstack_ip;
16714 
16715 	mp = ipsec_mp->b_cont;
16716 	ASSERT(mp != NULL);
16717 
16718 
16719 	if (ill == NULL) {
16720 		ASSERT(recv_ill == NULL);
16721 		/*
16722 		 * We need to get the original queue on which ip_rput_local
16723 		 * or ip_rput_data_v6 was called.
16724 		 */
16725 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16726 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
16727 		ill_need_rele = B_TRUE;
16728 
16729 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16730 			recv_ill = ill_lookup_on_ifindex(
16731 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16732 			    NULL, NULL, NULL, NULL, ipst);
16733 			rill_need_rele = B_TRUE;
16734 		} else {
16735 			recv_ill = ill;
16736 		}
16737 
16738 		if ((ill == NULL) || (recv_ill == NULL)) {
16739 			ip0dbg(("ip_fanout_proto_again: interface "
16740 			    "disappeared\n"));
16741 			if (ill != NULL)
16742 				ill_refrele(ill);
16743 			if (recv_ill != NULL)
16744 				ill_refrele(recv_ill);
16745 			freemsg(ipsec_mp);
16746 			return;
16747 		}
16748 	}
16749 
16750 	ASSERT(ill != NULL && recv_ill != NULL);
16751 
16752 	if (mp->b_datap->db_type == M_CTL) {
16753 		/*
16754 		 * AH/ESP is returning the ICMP message after
16755 		 * removing their headers. Fanout again till
16756 		 * it gets to the right protocol.
16757 		 */
16758 		if (ii->ipsec_in_v4) {
16759 			icmph_t *icmph;
16760 			int iph_hdr_length;
16761 			int hdr_length;
16762 
16763 			ipha = (ipha_t *)mp->b_rptr;
16764 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
16765 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
16766 			ipha = (ipha_t *)&icmph[1];
16767 			hdr_length = IPH_HDR_LENGTH(ipha);
16768 			/*
16769 			 * icmp_inbound_error_fanout may need to do pullupmsg.
16770 			 * Reset the type to M_DATA.
16771 			 */
16772 			mp->b_datap->db_type = M_DATA;
16773 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
16774 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
16775 			    B_FALSE, ill, ii->ipsec_in_zoneid);
16776 		} else {
16777 			icmp6_t *icmp6;
16778 			int hdr_length;
16779 
16780 			ip6h = (ip6_t *)mp->b_rptr;
16781 			/* Don't call hdr_length_v6() unless you have to. */
16782 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
16783 				hdr_length = ip_hdr_length_v6(mp, ip6h);
16784 			else
16785 				hdr_length = IPV6_HDR_LEN;
16786 
16787 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
16788 			/*
16789 			 * icmp_inbound_error_fanout_v6 may need to do
16790 			 * pullupmsg.  Reset the type to M_DATA.
16791 			 */
16792 			mp->b_datap->db_type = M_DATA;
16793 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
16794 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
16795 		}
16796 		if (ill_need_rele)
16797 			ill_refrele(ill);
16798 		if (rill_need_rele)
16799 			ill_refrele(recv_ill);
16800 		return;
16801 	}
16802 
16803 	if (ii->ipsec_in_v4) {
16804 		ipha = (ipha_t *)mp->b_rptr;
16805 		dst = ipha->ipha_dst;
16806 		if (CLASSD(dst)) {
16807 			/*
16808 			 * Multicast has to be delivered to all streams.
16809 			 */
16810 			dst = INADDR_BROADCAST;
16811 		}
16812 
16813 		if (ire == NULL) {
16814 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
16815 			    MBLK_GETLABEL(mp), ipst);
16816 			if (ire == NULL) {
16817 				if (ill_need_rele)
16818 					ill_refrele(ill);
16819 				if (rill_need_rele)
16820 					ill_refrele(recv_ill);
16821 				ip1dbg(("ip_fanout_proto_again: "
16822 				    "IRE not found"));
16823 				freemsg(ipsec_mp);
16824 				return;
16825 			}
16826 			ire_need_rele = B_TRUE;
16827 		}
16828 
16829 		switch (ipha->ipha_protocol) {
16830 			case IPPROTO_UDP:
16831 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
16832 				    recv_ill);
16833 				if (ire_need_rele)
16834 					ire_refrele(ire);
16835 				break;
16836 			case IPPROTO_TCP:
16837 				if (!ire_need_rele)
16838 					IRE_REFHOLD(ire);
16839 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
16840 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
16841 				IRE_REFRELE(ire);
16842 				if (mp != NULL)
16843 					squeue_enter_chain(GET_SQUEUE(mp), mp,
16844 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
16845 				break;
16846 			case IPPROTO_SCTP:
16847 				if (!ire_need_rele)
16848 					IRE_REFHOLD(ire);
16849 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
16850 				    ipsec_mp, 0, ill->ill_rq, dst);
16851 				break;
16852 			default:
16853 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
16854 				    recv_ill, B_FALSE);
16855 				if (ire_need_rele)
16856 					ire_refrele(ire);
16857 				break;
16858 		}
16859 	} else {
16860 		uint32_t rput_flags = 0;
16861 
16862 		ip6h = (ip6_t *)mp->b_rptr;
16863 		v6dstp = &ip6h->ip6_dst;
16864 		/*
16865 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
16866 		 * address.
16867 		 *
16868 		 * Currently, we don't store that state in the IPSEC_IN
16869 		 * message, and we may need to.
16870 		 */
16871 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
16872 		    IP6_IN_LLMCAST : 0);
16873 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
16874 		    NULL, NULL);
16875 	}
16876 	if (ill_need_rele)
16877 		ill_refrele(ill);
16878 	if (rill_need_rele)
16879 		ill_refrele(recv_ill);
16880 }
16881 
16882 /*
16883  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
16884  * returns 'true' if there are still fragments left on the queue, in
16885  * which case we restart the timer.
16886  */
16887 void
16888 ill_frag_timer(void *arg)
16889 {
16890 	ill_t	*ill = (ill_t *)arg;
16891 	boolean_t frag_pending;
16892 	ip_stack_t	*ipst = ill->ill_ipst;
16893 
16894 	mutex_enter(&ill->ill_lock);
16895 	ASSERT(!ill->ill_fragtimer_executing);
16896 	if (ill->ill_state_flags & ILL_CONDEMNED) {
16897 		ill->ill_frag_timer_id = 0;
16898 		mutex_exit(&ill->ill_lock);
16899 		return;
16900 	}
16901 	ill->ill_fragtimer_executing = 1;
16902 	mutex_exit(&ill->ill_lock);
16903 
16904 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
16905 
16906 	/*
16907 	 * Restart the timer, if we have fragments pending or if someone
16908 	 * wanted us to be scheduled again.
16909 	 */
16910 	mutex_enter(&ill->ill_lock);
16911 	ill->ill_fragtimer_executing = 0;
16912 	ill->ill_frag_timer_id = 0;
16913 	if (frag_pending || ill->ill_fragtimer_needrestart)
16914 		ill_frag_timer_start(ill);
16915 	mutex_exit(&ill->ill_lock);
16916 }
16917 
16918 void
16919 ill_frag_timer_start(ill_t *ill)
16920 {
16921 	ip_stack_t	*ipst = ill->ill_ipst;
16922 
16923 	ASSERT(MUTEX_HELD(&ill->ill_lock));
16924 
16925 	/* If the ill is closing or opening don't proceed */
16926 	if (ill->ill_state_flags & ILL_CONDEMNED)
16927 		return;
16928 
16929 	if (ill->ill_fragtimer_executing) {
16930 		/*
16931 		 * ill_frag_timer is currently executing. Just record the
16932 		 * the fact that we want the timer to be restarted.
16933 		 * ill_frag_timer will post a timeout before it returns,
16934 		 * ensuring it will be called again.
16935 		 */
16936 		ill->ill_fragtimer_needrestart = 1;
16937 		return;
16938 	}
16939 
16940 	if (ill->ill_frag_timer_id == 0) {
16941 		/*
16942 		 * The timer is neither running nor is the timeout handler
16943 		 * executing. Post a timeout so that ill_frag_timer will be
16944 		 * called
16945 		 */
16946 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
16947 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
16948 		ill->ill_fragtimer_needrestart = 0;
16949 	}
16950 }
16951 
16952 /*
16953  * This routine is needed for loopback when forwarding multicasts.
16954  *
16955  * IPQoS Notes:
16956  * IPPF processing is done in fanout routines.
16957  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
16958  * processing for IPsec packets is done when it comes back in clear.
16959  * NOTE : The callers of this function need to do the ire_refrele for the
16960  *	  ire that is being passed in.
16961  */
16962 void
16963 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
16964     ill_t *recv_ill, boolean_t esp_in_udp_packet)
16965 {
16966 	ill_t	*ill = (ill_t *)q->q_ptr;
16967 	uint32_t	sum;
16968 	uint32_t	u1;
16969 	uint32_t	u2;
16970 	int		hdr_length;
16971 	boolean_t	mctl_present;
16972 	mblk_t		*first_mp = mp;
16973 	mblk_t		*hada_mp = NULL;
16974 	ipha_t		*inner_ipha;
16975 	ip_stack_t	*ipst;
16976 
16977 	ASSERT(recv_ill != NULL);
16978 	ipst = recv_ill->ill_ipst;
16979 
16980 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
16981 	    "ip_rput_locl_start: q %p", q);
16982 
16983 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
16984 	ASSERT(ill != NULL);
16985 
16986 
16987 #define	rptr	((uchar_t *)ipha)
16988 #define	iphs	((uint16_t *)ipha)
16989 
16990 	/*
16991 	 * no UDP or TCP packet should come here anymore.
16992 	 */
16993 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
16994 	    ipha->ipha_protocol != IPPROTO_UDP);
16995 
16996 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
16997 	if (mctl_present &&
16998 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
16999 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17000 
17001 		/*
17002 		 * It's an IPsec accelerated packet.
17003 		 * Keep a pointer to the data attributes around until
17004 		 * we allocate the ipsec_info_t.
17005 		 */
17006 		IPSECHW_DEBUG(IPSECHW_PKT,
17007 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17008 		hada_mp = first_mp;
17009 		hada_mp->b_cont = NULL;
17010 		/*
17011 		 * Since it is accelerated, it comes directly from
17012 		 * the ill and the data attributes is followed by
17013 		 * the packet data.
17014 		 */
17015 		ASSERT(mp->b_datap->db_type != M_CTL);
17016 		first_mp = mp;
17017 		mctl_present = B_FALSE;
17018 	}
17019 
17020 	/*
17021 	 * IF M_CTL is not present, then ipsec_in_is_secure
17022 	 * should return B_TRUE. There is a case where loopback
17023 	 * packets has an M_CTL in the front with all the
17024 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17025 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17026 	 * packets never comes here, it is safe to ASSERT the
17027 	 * following.
17028 	 */
17029 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17030 
17031 	/*
17032 	 * Also, we should never have an mctl_present if this is an
17033 	 * ESP-in-UDP packet.
17034 	 */
17035 	ASSERT(!mctl_present || !esp_in_udp_packet);
17036 
17037 
17038 	/* u1 is # words of IP options */
17039 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17040 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17041 
17042 	if (u1 || (!esp_in_udp_packet && !mctl_present)) {
17043 		if (u1) {
17044 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17045 				if (hada_mp != NULL)
17046 					freemsg(hada_mp);
17047 				return;
17048 			}
17049 		} else {
17050 			/* Check the IP header checksum.  */
17051 #define	uph	((uint16_t *)ipha)
17052 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17053 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17054 #undef  uph
17055 			/* finish doing IP checksum */
17056 			sum = (sum & 0xFFFF) + (sum >> 16);
17057 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17058 			if (sum && sum != 0xFFFF) {
17059 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17060 				goto drop_pkt;
17061 			}
17062 		}
17063 	}
17064 
17065 	/*
17066 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17067 	 * might be called more than once for secure packets, count only
17068 	 * the first time.
17069 	 */
17070 	if (!mctl_present) {
17071 		UPDATE_IB_PKT_COUNT(ire);
17072 		ire->ire_last_used_time = lbolt;
17073 	}
17074 
17075 	/* Check for fragmentation offset. */
17076 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17077 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17078 	if (u1) {
17079 		/*
17080 		 * We re-assemble fragments before we do the AH/ESP
17081 		 * processing. Thus, M_CTL should not be present
17082 		 * while we are re-assembling.
17083 		 */
17084 		ASSERT(!mctl_present);
17085 		ASSERT(first_mp == mp);
17086 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
17087 			return;
17088 		}
17089 		/*
17090 		 * Make sure that first_mp points back to mp as
17091 		 * the mp we came in with could have changed in
17092 		 * ip_rput_fragment().
17093 		 */
17094 		ipha = (ipha_t *)mp->b_rptr;
17095 		first_mp = mp;
17096 	}
17097 
17098 	/*
17099 	 * Clear hardware checksumming flag as it is currently only
17100 	 * used by TCP and UDP.
17101 	 */
17102 	DB_CKSUMFLAGS(mp) = 0;
17103 
17104 	/* Now we have a complete datagram, destined for this machine. */
17105 	u1 = IPH_HDR_LENGTH(ipha);
17106 	switch (ipha->ipha_protocol) {
17107 	case IPPROTO_ICMP: {
17108 		ire_t		*ire_zone;
17109 		ilm_t		*ilm;
17110 		mblk_t		*mp1;
17111 		zoneid_t	last_zoneid;
17112 
17113 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17114 			ASSERT(ire->ire_type == IRE_BROADCAST);
17115 			/*
17116 			 * In the multicast case, applications may have joined
17117 			 * the group from different zones, so we need to deliver
17118 			 * the packet to each of them. Loop through the
17119 			 * multicast memberships structures (ilm) on the receive
17120 			 * ill and send a copy of the packet up each matching
17121 			 * one. However, we don't do this for multicasts sent on
17122 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17123 			 * they must stay in the sender's zone.
17124 			 *
17125 			 * ilm_add_v6() ensures that ilms in the same zone are
17126 			 * contiguous in the ill_ilm list. We use this property
17127 			 * to avoid sending duplicates needed when two
17128 			 * applications in the same zone join the same group on
17129 			 * different logical interfaces: we ignore the ilm if
17130 			 * its zoneid is the same as the last matching one.
17131 			 * In addition, the sending of the packet for
17132 			 * ire_zoneid is delayed until all of the other ilms
17133 			 * have been exhausted.
17134 			 */
17135 			last_zoneid = -1;
17136 			ILM_WALKER_HOLD(recv_ill);
17137 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17138 			    ilm = ilm->ilm_next) {
17139 				if ((ilm->ilm_flags & ILM_DELETED) ||
17140 				    ipha->ipha_dst != ilm->ilm_addr ||
17141 				    ilm->ilm_zoneid == last_zoneid ||
17142 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17143 				    ilm->ilm_zoneid == ALL_ZONES ||
17144 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17145 					continue;
17146 				mp1 = ip_copymsg(first_mp);
17147 				if (mp1 == NULL)
17148 					continue;
17149 				icmp_inbound(q, mp1, B_TRUE, ill,
17150 				    0, sum, mctl_present, B_TRUE,
17151 				    recv_ill, ilm->ilm_zoneid);
17152 				last_zoneid = ilm->ilm_zoneid;
17153 			}
17154 			ILM_WALKER_RELE(recv_ill);
17155 		} else if (ire->ire_type == IRE_BROADCAST) {
17156 			/*
17157 			 * In the broadcast case, there may be many zones
17158 			 * which need a copy of the packet delivered to them.
17159 			 * There is one IRE_BROADCAST per broadcast address
17160 			 * and per zone; we walk those using a helper function.
17161 			 * In addition, the sending of the packet for ire is
17162 			 * delayed until all of the other ires have been
17163 			 * processed.
17164 			 */
17165 			IRB_REFHOLD(ire->ire_bucket);
17166 			ire_zone = NULL;
17167 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17168 			    ire)) != NULL) {
17169 				mp1 = ip_copymsg(first_mp);
17170 				if (mp1 == NULL)
17171 					continue;
17172 
17173 				UPDATE_IB_PKT_COUNT(ire_zone);
17174 				ire_zone->ire_last_used_time = lbolt;
17175 				icmp_inbound(q, mp1, B_TRUE, ill,
17176 				    0, sum, mctl_present, B_TRUE,
17177 				    recv_ill, ire_zone->ire_zoneid);
17178 			}
17179 			IRB_REFRELE(ire->ire_bucket);
17180 		}
17181 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17182 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17183 		    ire->ire_zoneid);
17184 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17185 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17186 		return;
17187 	}
17188 	case IPPROTO_IGMP:
17189 		/*
17190 		 * If we are not willing to accept IGMP packets in clear,
17191 		 * then check with global policy.
17192 		 */
17193 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17194 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17195 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17196 			if (first_mp == NULL)
17197 				return;
17198 		}
17199 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17200 			freemsg(first_mp);
17201 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17202 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17203 			return;
17204 		}
17205 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17206 			/* Bad packet - discarded by igmp_input */
17207 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17208 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17209 			if (mctl_present)
17210 				freeb(first_mp);
17211 			return;
17212 		}
17213 		/*
17214 		 * igmp_input() may have returned the pulled up message.
17215 		 * So first_mp and ipha need to be reinitialized.
17216 		 */
17217 		ipha = (ipha_t *)mp->b_rptr;
17218 		if (mctl_present)
17219 			first_mp->b_cont = mp;
17220 		else
17221 			first_mp = mp;
17222 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17223 		    connf_head != NULL) {
17224 			/* No user-level listener for IGMP packets */
17225 			goto drop_pkt;
17226 		}
17227 		/* deliver to local raw users */
17228 		break;
17229 	case IPPROTO_PIM:
17230 		/*
17231 		 * If we are not willing to accept PIM packets in clear,
17232 		 * then check with global policy.
17233 		 */
17234 		if (ipst->ips_pim_accept_clear_messages == 0) {
17235 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17236 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17237 			if (first_mp == NULL)
17238 				return;
17239 		}
17240 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17241 			freemsg(first_mp);
17242 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17243 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17244 			return;
17245 		}
17246 		if (pim_input(q, mp, ill) != 0) {
17247 			/* Bad packet - discarded by pim_input */
17248 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17249 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17250 			if (mctl_present)
17251 				freeb(first_mp);
17252 			return;
17253 		}
17254 
17255 		/*
17256 		 * pim_input() may have pulled up the message so ipha needs to
17257 		 * be reinitialized.
17258 		 */
17259 		ipha = (ipha_t *)mp->b_rptr;
17260 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17261 		    connf_head != NULL) {
17262 			/* No user-level listener for PIM packets */
17263 			goto drop_pkt;
17264 		}
17265 		/* deliver to local raw users */
17266 		break;
17267 	case IPPROTO_ENCAP:
17268 		/*
17269 		 * Handle self-encapsulated packets (IP-in-IP where
17270 		 * the inner addresses == the outer addresses).
17271 		 */
17272 		hdr_length = IPH_HDR_LENGTH(ipha);
17273 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17274 		    mp->b_wptr) {
17275 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17276 			    sizeof (ipha_t) - mp->b_rptr)) {
17277 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17278 				freemsg(first_mp);
17279 				return;
17280 			}
17281 			ipha = (ipha_t *)mp->b_rptr;
17282 		}
17283 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17284 		/*
17285 		 * Check the sanity of the inner IP header.
17286 		 */
17287 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17288 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17289 			freemsg(first_mp);
17290 			return;
17291 		}
17292 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17293 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17294 			freemsg(first_mp);
17295 			return;
17296 		}
17297 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17298 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17299 			ipsec_in_t *ii;
17300 
17301 			/*
17302 			 * Self-encapsulated tunnel packet. Remove
17303 			 * the outer IP header and fanout again.
17304 			 * We also need to make sure that the inner
17305 			 * header is pulled up until options.
17306 			 */
17307 			mp->b_rptr = (uchar_t *)inner_ipha;
17308 			ipha = inner_ipha;
17309 			hdr_length = IPH_HDR_LENGTH(ipha);
17310 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17311 				if (!pullupmsg(mp, (uchar_t *)ipha +
17312 				    + hdr_length - mp->b_rptr)) {
17313 					freemsg(first_mp);
17314 					return;
17315 				}
17316 				ipha = (ipha_t *)mp->b_rptr;
17317 			}
17318 			if (!mctl_present) {
17319 				ASSERT(first_mp == mp);
17320 				/*
17321 				 * This means that somebody is sending
17322 				 * Self-encapsualted packets without AH/ESP.
17323 				 * If AH/ESP was present, we would have already
17324 				 * allocated the first_mp.
17325 				 */
17326 				first_mp = ipsec_in_alloc(B_TRUE,
17327 				    ipst->ips_netstack);
17328 				if (first_mp == NULL) {
17329 					ip1dbg(("ip_proto_input: IPSEC_IN "
17330 					    "allocation failure.\n"));
17331 					BUMP_MIB(ill->ill_ip_mib,
17332 					    ipIfStatsInDiscards);
17333 					freemsg(mp);
17334 					return;
17335 				}
17336 				first_mp->b_cont = mp;
17337 			}
17338 			/*
17339 			 * We generally store the ill_index if we need to
17340 			 * do IPsec processing as we lose the ill queue when
17341 			 * we come back. But in this case, we never should
17342 			 * have to store the ill_index here as it should have
17343 			 * been stored previously when we processed the
17344 			 * AH/ESP header in this routine or for non-ipsec
17345 			 * cases, we still have the queue. But for some bad
17346 			 * packets from the wire, we can get to IPsec after
17347 			 * this and we better store the index for that case.
17348 			 */
17349 			ill = (ill_t *)q->q_ptr;
17350 			ii = (ipsec_in_t *)first_mp->b_rptr;
17351 			ii->ipsec_in_ill_index =
17352 			    ill->ill_phyint->phyint_ifindex;
17353 			ii->ipsec_in_rill_index =
17354 			    recv_ill->ill_phyint->phyint_ifindex;
17355 			if (ii->ipsec_in_decaps) {
17356 				/*
17357 				 * This packet is self-encapsulated multiple
17358 				 * times. We don't want to recurse infinitely.
17359 				 * To keep it simple, drop the packet.
17360 				 */
17361 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17362 				freemsg(first_mp);
17363 				return;
17364 			}
17365 			ii->ipsec_in_decaps = B_TRUE;
17366 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17367 			    ire);
17368 			return;
17369 		}
17370 		break;
17371 	case IPPROTO_AH:
17372 	case IPPROTO_ESP: {
17373 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17374 
17375 		/*
17376 		 * Fast path for AH/ESP. If this is the first time
17377 		 * we are sending a datagram to AH/ESP, allocate
17378 		 * a IPSEC_IN message and prepend it. Otherwise,
17379 		 * just fanout.
17380 		 */
17381 
17382 		int ipsec_rc;
17383 		ipsec_in_t *ii;
17384 		netstack_t *ns = ipst->ips_netstack;
17385 
17386 		IP_STAT(ipst, ipsec_proto_ahesp);
17387 		if (!mctl_present) {
17388 			ASSERT(first_mp == mp);
17389 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17390 			if (first_mp == NULL) {
17391 				ip1dbg(("ip_proto_input: IPSEC_IN "
17392 				    "allocation failure.\n"));
17393 				freemsg(hada_mp); /* okay ifnull */
17394 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17395 				freemsg(mp);
17396 				return;
17397 			}
17398 			/*
17399 			 * Store the ill_index so that when we come back
17400 			 * from IPsec we ride on the same queue.
17401 			 */
17402 			ill = (ill_t *)q->q_ptr;
17403 			ii = (ipsec_in_t *)first_mp->b_rptr;
17404 			ii->ipsec_in_ill_index =
17405 			    ill->ill_phyint->phyint_ifindex;
17406 			ii->ipsec_in_rill_index =
17407 			    recv_ill->ill_phyint->phyint_ifindex;
17408 			first_mp->b_cont = mp;
17409 			/*
17410 			 * Cache hardware acceleration info.
17411 			 */
17412 			if (hada_mp != NULL) {
17413 				IPSECHW_DEBUG(IPSECHW_PKT,
17414 				    ("ip_rput_local: caching data attr.\n"));
17415 				ii->ipsec_in_accelerated = B_TRUE;
17416 				ii->ipsec_in_da = hada_mp;
17417 				hada_mp = NULL;
17418 			}
17419 		} else {
17420 			ii = (ipsec_in_t *)first_mp->b_rptr;
17421 		}
17422 
17423 		if (!ipsec_loaded(ipss)) {
17424 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17425 			    ire->ire_zoneid, ipst);
17426 			return;
17427 		}
17428 
17429 		ns = ipst->ips_netstack;
17430 		/* select inbound SA and have IPsec process the pkt */
17431 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17432 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17433 			boolean_t esp_in_udp_sa;
17434 			if (esph == NULL)
17435 				return;
17436 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17437 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17438 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
17439 			    IPSA_F_NATT) != 0);
17440 			/*
17441 			 * The following is a fancy, but quick, way of saying:
17442 			 * ESP-in-UDP SA and Raw ESP packet --> drop
17443 			 *    OR
17444 			 * ESP SA and ESP-in-UDP packet --> drop
17445 			 */
17446 			if (esp_in_udp_sa != esp_in_udp_packet) {
17447 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17448 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
17449 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
17450 				    &ns->netstack_ipsec->ipsec_dropper);
17451 				return;
17452 			}
17453 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17454 			    first_mp, esph);
17455 		} else {
17456 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17457 			if (ah == NULL)
17458 				return;
17459 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17460 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17461 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17462 			    first_mp, ah);
17463 		}
17464 
17465 		switch (ipsec_rc) {
17466 		case IPSEC_STATUS_SUCCESS:
17467 			break;
17468 		case IPSEC_STATUS_FAILED:
17469 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17470 			/* FALLTHRU */
17471 		case IPSEC_STATUS_PENDING:
17472 			return;
17473 		}
17474 		/* we're done with IPsec processing, send it up */
17475 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17476 		return;
17477 	}
17478 	default:
17479 		break;
17480 	}
17481 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17482 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17483 		    ire->ire_zoneid));
17484 		goto drop_pkt;
17485 	}
17486 	/*
17487 	 * Handle protocols with which IP is less intimate.  There
17488 	 * can be more than one stream bound to a particular
17489 	 * protocol.  When this is the case, each one gets a copy
17490 	 * of any incoming packets.
17491 	 */
17492 	ip_fanout_proto(q, first_mp, ill, ipha,
17493 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17494 	    B_TRUE, recv_ill, ire->ire_zoneid);
17495 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17496 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17497 	return;
17498 
17499 drop_pkt:
17500 	freemsg(first_mp);
17501 	if (hada_mp != NULL)
17502 		freeb(hada_mp);
17503 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17504 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17505 #undef	rptr
17506 #undef  iphs
17507 
17508 }
17509 
17510 /*
17511  * Update any source route, record route or timestamp options.
17512  * Check that we are at end of strict source route.
17513  * The options have already been checked for sanity in ip_rput_options().
17514  */
17515 static boolean_t
17516 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17517     ip_stack_t *ipst)
17518 {
17519 	ipoptp_t	opts;
17520 	uchar_t		*opt;
17521 	uint8_t		optval;
17522 	uint8_t		optlen;
17523 	ipaddr_t	dst;
17524 	uint32_t	ts;
17525 	ire_t		*dst_ire;
17526 	timestruc_t	now;
17527 	zoneid_t	zoneid;
17528 	ill_t		*ill;
17529 
17530 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17531 
17532 	ip2dbg(("ip_rput_local_options\n"));
17533 
17534 	for (optval = ipoptp_first(&opts, ipha);
17535 	    optval != IPOPT_EOL;
17536 	    optval = ipoptp_next(&opts)) {
17537 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17538 		opt = opts.ipoptp_cur;
17539 		optlen = opts.ipoptp_len;
17540 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17541 		    optval, optlen));
17542 		switch (optval) {
17543 			uint32_t off;
17544 		case IPOPT_SSRR:
17545 		case IPOPT_LSRR:
17546 			off = opt[IPOPT_OFFSET];
17547 			off--;
17548 			if (optlen < IP_ADDR_LEN ||
17549 			    off > optlen - IP_ADDR_LEN) {
17550 				/* End of source route */
17551 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17552 				break;
17553 			}
17554 			/*
17555 			 * This will only happen if two consecutive entries
17556 			 * in the source route contains our address or if
17557 			 * it is a packet with a loose source route which
17558 			 * reaches us before consuming the whole source route
17559 			 */
17560 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17561 			if (optval == IPOPT_SSRR) {
17562 				goto bad_src_route;
17563 			}
17564 			/*
17565 			 * Hack: instead of dropping the packet truncate the
17566 			 * source route to what has been used by filling the
17567 			 * rest with IPOPT_NOP.
17568 			 */
17569 			opt[IPOPT_OLEN] = (uint8_t)off;
17570 			while (off < optlen) {
17571 				opt[off++] = IPOPT_NOP;
17572 			}
17573 			break;
17574 		case IPOPT_RR:
17575 			off = opt[IPOPT_OFFSET];
17576 			off--;
17577 			if (optlen < IP_ADDR_LEN ||
17578 			    off > optlen - IP_ADDR_LEN) {
17579 				/* No more room - ignore */
17580 				ip1dbg((
17581 				    "ip_rput_local_options: end of RR\n"));
17582 				break;
17583 			}
17584 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17585 			    IP_ADDR_LEN);
17586 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17587 			break;
17588 		case IPOPT_TS:
17589 			/* Insert timestamp if there is romm */
17590 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17591 			case IPOPT_TS_TSONLY:
17592 				off = IPOPT_TS_TIMELEN;
17593 				break;
17594 			case IPOPT_TS_PRESPEC:
17595 			case IPOPT_TS_PRESPEC_RFC791:
17596 				/* Verify that the address matched */
17597 				off = opt[IPOPT_OFFSET] - 1;
17598 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17599 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17600 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
17601 				    ipst);
17602 				if (dst_ire == NULL) {
17603 					/* Not for us */
17604 					break;
17605 				}
17606 				ire_refrele(dst_ire);
17607 				/* FALLTHRU */
17608 			case IPOPT_TS_TSANDADDR:
17609 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17610 				break;
17611 			default:
17612 				/*
17613 				 * ip_*put_options should have already
17614 				 * dropped this packet.
17615 				 */
17616 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17617 				    "unknown IT - bug in ip_rput_options?\n");
17618 				return (B_TRUE);	/* Keep "lint" happy */
17619 			}
17620 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17621 				/* Increase overflow counter */
17622 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17623 				opt[IPOPT_POS_OV_FLG] =
17624 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17625 				    (off << 4));
17626 				break;
17627 			}
17628 			off = opt[IPOPT_OFFSET] - 1;
17629 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17630 			case IPOPT_TS_PRESPEC:
17631 			case IPOPT_TS_PRESPEC_RFC791:
17632 			case IPOPT_TS_TSANDADDR:
17633 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17634 				    IP_ADDR_LEN);
17635 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17636 				/* FALLTHRU */
17637 			case IPOPT_TS_TSONLY:
17638 				off = opt[IPOPT_OFFSET] - 1;
17639 				/* Compute # of milliseconds since midnight */
17640 				gethrestime(&now);
17641 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17642 				    now.tv_nsec / (NANOSEC / MILLISEC);
17643 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17644 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17645 				break;
17646 			}
17647 			break;
17648 		}
17649 	}
17650 	return (B_TRUE);
17651 
17652 bad_src_route:
17653 	q = WR(q);
17654 	if (q->q_next != NULL)
17655 		ill = q->q_ptr;
17656 	else
17657 		ill = NULL;
17658 
17659 	/* make sure we clear any indication of a hardware checksum */
17660 	DB_CKSUMFLAGS(mp) = 0;
17661 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
17662 	if (zoneid == ALL_ZONES)
17663 		freemsg(mp);
17664 	else
17665 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17666 	return (B_FALSE);
17667 
17668 }
17669 
17670 /*
17671  * Process IP options in an inbound packet.  If an option affects the
17672  * effective destination address, return the next hop address via dstp.
17673  * Returns -1 if something fails in which case an ICMP error has been sent
17674  * and mp freed.
17675  */
17676 static int
17677 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
17678     ip_stack_t *ipst)
17679 {
17680 	ipoptp_t	opts;
17681 	uchar_t		*opt;
17682 	uint8_t		optval;
17683 	uint8_t		optlen;
17684 	ipaddr_t	dst;
17685 	intptr_t	code = 0;
17686 	ire_t		*ire = NULL;
17687 	zoneid_t	zoneid;
17688 	ill_t		*ill;
17689 
17690 	ip2dbg(("ip_rput_options\n"));
17691 	dst = ipha->ipha_dst;
17692 	for (optval = ipoptp_first(&opts, ipha);
17693 	    optval != IPOPT_EOL;
17694 	    optval = ipoptp_next(&opts)) {
17695 		opt = opts.ipoptp_cur;
17696 		optlen = opts.ipoptp_len;
17697 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17698 		    optval, optlen));
17699 		/*
17700 		 * Note: we need to verify the checksum before we
17701 		 * modify anything thus this routine only extracts the next
17702 		 * hop dst from any source route.
17703 		 */
17704 		switch (optval) {
17705 			uint32_t off;
17706 		case IPOPT_SSRR:
17707 		case IPOPT_LSRR:
17708 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17709 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17710 			if (ire == NULL) {
17711 				if (optval == IPOPT_SSRR) {
17712 					ip1dbg(("ip_rput_options: not next"
17713 					    " strict source route 0x%x\n",
17714 					    ntohl(dst)));
17715 					code = (char *)&ipha->ipha_dst -
17716 					    (char *)ipha;
17717 					goto param_prob; /* RouterReq's */
17718 				}
17719 				ip2dbg(("ip_rput_options: "
17720 				    "not next source route 0x%x\n",
17721 				    ntohl(dst)));
17722 				break;
17723 			}
17724 			ire_refrele(ire);
17725 
17726 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17727 				ip1dbg((
17728 				    "ip_rput_options: bad option offset\n"));
17729 				code = (char *)&opt[IPOPT_OLEN] -
17730 				    (char *)ipha;
17731 				goto param_prob;
17732 			}
17733 			off = opt[IPOPT_OFFSET];
17734 			off--;
17735 		redo_srr:
17736 			if (optlen < IP_ADDR_LEN ||
17737 			    off > optlen - IP_ADDR_LEN) {
17738 				/* End of source route */
17739 				ip1dbg(("ip_rput_options: end of SR\n"));
17740 				break;
17741 			}
17742 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17743 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
17744 			    ntohl(dst)));
17745 
17746 			/*
17747 			 * Check if our address is present more than
17748 			 * once as consecutive hops in source route.
17749 			 * XXX verify per-interface ip_forwarding
17750 			 * for source route?
17751 			 */
17752 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17753 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17754 
17755 			if (ire != NULL) {
17756 				ire_refrele(ire);
17757 				off += IP_ADDR_LEN;
17758 				goto redo_srr;
17759 			}
17760 
17761 			if (dst == htonl(INADDR_LOOPBACK)) {
17762 				ip1dbg(("ip_rput_options: loopback addr in "
17763 				    "source route!\n"));
17764 				goto bad_src_route;
17765 			}
17766 			/*
17767 			 * For strict: verify that dst is directly
17768 			 * reachable.
17769 			 */
17770 			if (optval == IPOPT_SSRR) {
17771 				ire = ire_ftable_lookup(dst, 0, 0,
17772 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
17773 				    MBLK_GETLABEL(mp),
17774 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
17775 				if (ire == NULL) {
17776 					ip1dbg(("ip_rput_options: SSRR not "
17777 					    "directly reachable: 0x%x\n",
17778 					    ntohl(dst)));
17779 					goto bad_src_route;
17780 				}
17781 				ire_refrele(ire);
17782 			}
17783 			/*
17784 			 * Defer update of the offset and the record route
17785 			 * until the packet is forwarded.
17786 			 */
17787 			break;
17788 		case IPOPT_RR:
17789 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17790 				ip1dbg((
17791 				    "ip_rput_options: bad option offset\n"));
17792 				code = (char *)&opt[IPOPT_OLEN] -
17793 				    (char *)ipha;
17794 				goto param_prob;
17795 			}
17796 			break;
17797 		case IPOPT_TS:
17798 			/*
17799 			 * Verify that length >= 5 and that there is either
17800 			 * room for another timestamp or that the overflow
17801 			 * counter is not maxed out.
17802 			 */
17803 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
17804 			if (optlen < IPOPT_MINLEN_IT) {
17805 				goto param_prob;
17806 			}
17807 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17808 				ip1dbg((
17809 				    "ip_rput_options: bad option offset\n"));
17810 				code = (char *)&opt[IPOPT_OFFSET] -
17811 				    (char *)ipha;
17812 				goto param_prob;
17813 			}
17814 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17815 			case IPOPT_TS_TSONLY:
17816 				off = IPOPT_TS_TIMELEN;
17817 				break;
17818 			case IPOPT_TS_TSANDADDR:
17819 			case IPOPT_TS_PRESPEC:
17820 			case IPOPT_TS_PRESPEC_RFC791:
17821 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17822 				break;
17823 			default:
17824 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
17825 				    (char *)ipha;
17826 				goto param_prob;
17827 			}
17828 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
17829 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
17830 				/*
17831 				 * No room and the overflow counter is 15
17832 				 * already.
17833 				 */
17834 				goto param_prob;
17835 			}
17836 			break;
17837 		}
17838 	}
17839 
17840 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
17841 		*dstp = dst;
17842 		return (0);
17843 	}
17844 
17845 	ip1dbg(("ip_rput_options: error processing IP options."));
17846 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
17847 
17848 param_prob:
17849 	q = WR(q);
17850 	if (q->q_next != NULL)
17851 		ill = q->q_ptr;
17852 	else
17853 		ill = NULL;
17854 
17855 	/* make sure we clear any indication of a hardware checksum */
17856 	DB_CKSUMFLAGS(mp) = 0;
17857 	/* Don't know whether this is for non-global or global/forwarding */
17858 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
17859 	if (zoneid == ALL_ZONES)
17860 		freemsg(mp);
17861 	else
17862 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
17863 	return (-1);
17864 
17865 bad_src_route:
17866 	q = WR(q);
17867 	if (q->q_next != NULL)
17868 		ill = q->q_ptr;
17869 	else
17870 		ill = NULL;
17871 
17872 	/* make sure we clear any indication of a hardware checksum */
17873 	DB_CKSUMFLAGS(mp) = 0;
17874 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
17875 	if (zoneid == ALL_ZONES)
17876 		freemsg(mp);
17877 	else
17878 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17879 	return (-1);
17880 }
17881 
17882 /*
17883  * IP & ICMP info in >=14 msg's ...
17884  *  - ip fixed part (mib2_ip_t)
17885  *  - icmp fixed part (mib2_icmp_t)
17886  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
17887  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
17888  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
17889  *  - ipRouteAttributeTable (ip 102)	labeled routes
17890  *  - ip multicast membership (ip_member_t)
17891  *  - ip multicast source filtering (ip_grpsrc_t)
17892  *  - igmp fixed part (struct igmpstat)
17893  *  - multicast routing stats (struct mrtstat)
17894  *  - multicast routing vifs (array of struct vifctl)
17895  *  - multicast routing routes (array of struct mfcctl)
17896  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
17897  *					One per ill plus one generic
17898  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
17899  *					One per ill plus one generic
17900  *  - ipv6RouteEntry			all IPv6 IREs
17901  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
17902  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
17903  *  - ipv6AddrEntry			all IPv6 ipifs
17904  *  - ipv6 multicast membership (ipv6_member_t)
17905  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
17906  *
17907  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
17908  *
17909  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
17910  * already filled in by the caller.
17911  * Return value of 0 indicates that no messages were sent and caller
17912  * should free mpctl.
17913  */
17914 int
17915 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
17916 {
17917 	ip_stack_t *ipst;
17918 	sctp_stack_t *sctps;
17919 
17920 	if (q->q_next != NULL) {
17921 		ipst = ILLQ_TO_IPST(q);
17922 	} else {
17923 		ipst = CONNQ_TO_IPST(q);
17924 	}
17925 	ASSERT(ipst != NULL);
17926 	sctps = ipst->ips_netstack->netstack_sctp;
17927 
17928 	if (mpctl == NULL || mpctl->b_cont == NULL) {
17929 		return (0);
17930 	}
17931 
17932 	/*
17933 	 * For the purposes of the (broken) packet shell use
17934 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
17935 	 * to make TCP and UDP appear first in the list of mib items.
17936 	 * TBD: We could expand this and use it in netstat so that
17937 	 * the kernel doesn't have to produce large tables (connections,
17938 	 * routes, etc) when netstat only wants the statistics or a particular
17939 	 * table.
17940 	 */
17941 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
17942 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
17943 			return (1);
17944 		}
17945 	}
17946 
17947 	if (level != MIB2_TCP) {
17948 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
17949 			return (1);
17950 		}
17951 	}
17952 
17953 	if (level != MIB2_UDP) {
17954 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
17955 			return (1);
17956 		}
17957 	}
17958 
17959 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
17960 	    ipst)) == NULL) {
17961 		return (1);
17962 	}
17963 
17964 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
17965 		return (1);
17966 	}
17967 
17968 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
17969 		return (1);
17970 	}
17971 
17972 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
17973 		return (1);
17974 	}
17975 
17976 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
17977 		return (1);
17978 	}
17979 
17980 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
17981 		return (1);
17982 	}
17983 
17984 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
17985 		return (1);
17986 	}
17987 
17988 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
17989 		return (1);
17990 	}
17991 
17992 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
17993 		return (1);
17994 	}
17995 
17996 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
17997 		return (1);
17998 	}
17999 
18000 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18001 		return (1);
18002 	}
18003 
18004 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18005 		return (1);
18006 	}
18007 
18008 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18009 		return (1);
18010 	}
18011 
18012 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18013 		return (1);
18014 	}
18015 
18016 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, ipst)) == NULL) {
18017 		return (1);
18018 	}
18019 
18020 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, ipst);
18021 	if (mpctl == NULL) {
18022 		return (1);
18023 	}
18024 
18025 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18026 		return (1);
18027 	}
18028 	freemsg(mpctl);
18029 	return (1);
18030 }
18031 
18032 
18033 /* Get global (legacy) IPv4 statistics */
18034 static mblk_t *
18035 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18036     ip_stack_t *ipst)
18037 {
18038 	mib2_ip_t		old_ip_mib;
18039 	struct opthdr		*optp;
18040 	mblk_t			*mp2ctl;
18041 
18042 	/*
18043 	 * make a copy of the original message
18044 	 */
18045 	mp2ctl = copymsg(mpctl);
18046 
18047 	/* fixed length IP structure... */
18048 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18049 	optp->level = MIB2_IP;
18050 	optp->name = 0;
18051 	SET_MIB(old_ip_mib.ipForwarding,
18052 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18053 	SET_MIB(old_ip_mib.ipDefaultTTL,
18054 	    (uint32_t)ipst->ips_ip_def_ttl);
18055 	SET_MIB(old_ip_mib.ipReasmTimeout,
18056 	    ipst->ips_ip_g_frag_timeout);
18057 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18058 	    sizeof (mib2_ipAddrEntry_t));
18059 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18060 	    sizeof (mib2_ipRouteEntry_t));
18061 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18062 	    sizeof (mib2_ipNetToMediaEntry_t));
18063 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18064 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18065 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18066 	    sizeof (mib2_ipAttributeEntry_t));
18067 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18068 
18069 	/*
18070 	 * Grab the statistics from the new IP MIB
18071 	 */
18072 	SET_MIB(old_ip_mib.ipInReceives,
18073 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18074 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18075 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18076 	SET_MIB(old_ip_mib.ipForwDatagrams,
18077 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18078 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18079 	    ipmib->ipIfStatsInUnknownProtos);
18080 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18081 	SET_MIB(old_ip_mib.ipInDelivers,
18082 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18083 	SET_MIB(old_ip_mib.ipOutRequests,
18084 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18085 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18086 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18087 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18088 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18089 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18090 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18091 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18092 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18093 
18094 	/* ipRoutingDiscards is not being used */
18095 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18096 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18097 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18098 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18099 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18100 	    ipmib->ipIfStatsReasmDuplicates);
18101 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18102 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18103 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18104 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18105 	SET_MIB(old_ip_mib.rawipInOverflows,
18106 	    ipmib->rawipIfStatsInOverflows);
18107 
18108 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18109 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18110 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18111 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18112 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18113 	    ipmib->ipIfStatsOutSwitchIPVersion);
18114 
18115 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18116 	    (int)sizeof (old_ip_mib))) {
18117 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18118 		    (uint_t)sizeof (old_ip_mib)));
18119 	}
18120 
18121 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18122 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18123 	    (int)optp->level, (int)optp->name, (int)optp->len));
18124 	qreply(q, mpctl);
18125 	return (mp2ctl);
18126 }
18127 
18128 /* Per interface IPv4 statistics */
18129 static mblk_t *
18130 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18131 {
18132 	struct opthdr		*optp;
18133 	mblk_t			*mp2ctl;
18134 	ill_t			*ill;
18135 	ill_walk_context_t	ctx;
18136 	mblk_t			*mp_tail = NULL;
18137 	mib2_ipIfStatsEntry_t	global_ip_mib;
18138 
18139 	/*
18140 	 * Make a copy of the original message
18141 	 */
18142 	mp2ctl = copymsg(mpctl);
18143 
18144 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18145 	optp->level = MIB2_IP;
18146 	optp->name = MIB2_IP_TRAFFIC_STATS;
18147 	/* Include "unknown interface" ip_mib */
18148 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18149 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18150 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18151 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18152 	    (ipst->ips_ip_g_forward ? 1 : 2));
18153 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18154 	    (uint32_t)ipst->ips_ip_def_ttl);
18155 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18156 	    sizeof (mib2_ipIfStatsEntry_t));
18157 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18158 	    sizeof (mib2_ipAddrEntry_t));
18159 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18160 	    sizeof (mib2_ipRouteEntry_t));
18161 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18162 	    sizeof (mib2_ipNetToMediaEntry_t));
18163 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18164 	    sizeof (ip_member_t));
18165 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18166 	    sizeof (ip_grpsrc_t));
18167 
18168 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18169 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18170 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18171 		    "failed to allocate %u bytes\n",
18172 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18173 	}
18174 
18175 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18176 
18177 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18178 	ill = ILL_START_WALK_V4(&ctx, ipst);
18179 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18180 		ill->ill_ip_mib->ipIfStatsIfIndex =
18181 		    ill->ill_phyint->phyint_ifindex;
18182 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18183 		    (ipst->ips_ip_g_forward ? 1 : 2));
18184 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18185 		    (uint32_t)ipst->ips_ip_def_ttl);
18186 
18187 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18188 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18189 		    (char *)ill->ill_ip_mib,
18190 		    (int)sizeof (*ill->ill_ip_mib))) {
18191 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18192 			    "failed to allocate %u bytes\n",
18193 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18194 		}
18195 	}
18196 	rw_exit(&ipst->ips_ill_g_lock);
18197 
18198 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18199 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18200 	    "level %d, name %d, len %d\n",
18201 	    (int)optp->level, (int)optp->name, (int)optp->len));
18202 	qreply(q, mpctl);
18203 
18204 	if (mp2ctl == NULL)
18205 		return (NULL);
18206 
18207 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18208 }
18209 
18210 /* Global IPv4 ICMP statistics */
18211 static mblk_t *
18212 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18213 {
18214 	struct opthdr		*optp;
18215 	mblk_t			*mp2ctl;
18216 
18217 	/*
18218 	 * Make a copy of the original message
18219 	 */
18220 	mp2ctl = copymsg(mpctl);
18221 
18222 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18223 	optp->level = MIB2_ICMP;
18224 	optp->name = 0;
18225 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18226 	    (int)sizeof (ipst->ips_icmp_mib))) {
18227 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18228 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18229 	}
18230 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18231 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18232 	    (int)optp->level, (int)optp->name, (int)optp->len));
18233 	qreply(q, mpctl);
18234 	return (mp2ctl);
18235 }
18236 
18237 /* Global IPv4 IGMP statistics */
18238 static mblk_t *
18239 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18240 {
18241 	struct opthdr		*optp;
18242 	mblk_t			*mp2ctl;
18243 
18244 	/*
18245 	 * make a copy of the original message
18246 	 */
18247 	mp2ctl = copymsg(mpctl);
18248 
18249 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18250 	optp->level = EXPER_IGMP;
18251 	optp->name = 0;
18252 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18253 	    (int)sizeof (ipst->ips_igmpstat))) {
18254 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18255 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18256 	}
18257 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18258 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18259 	    (int)optp->level, (int)optp->name, (int)optp->len));
18260 	qreply(q, mpctl);
18261 	return (mp2ctl);
18262 }
18263 
18264 /* Global IPv4 Multicast Routing statistics */
18265 static mblk_t *
18266 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18267 {
18268 	struct opthdr		*optp;
18269 	mblk_t			*mp2ctl;
18270 
18271 	/*
18272 	 * make a copy of the original message
18273 	 */
18274 	mp2ctl = copymsg(mpctl);
18275 
18276 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18277 	optp->level = EXPER_DVMRP;
18278 	optp->name = 0;
18279 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18280 		ip0dbg(("ip_mroute_stats: failed\n"));
18281 	}
18282 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18283 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18284 	    (int)optp->level, (int)optp->name, (int)optp->len));
18285 	qreply(q, mpctl);
18286 	return (mp2ctl);
18287 }
18288 
18289 /* IPv4 address information */
18290 static mblk_t *
18291 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18292 {
18293 	struct opthdr		*optp;
18294 	mblk_t			*mp2ctl;
18295 	mblk_t			*mp_tail = NULL;
18296 	ill_t			*ill;
18297 	ipif_t			*ipif;
18298 	uint_t			bitval;
18299 	mib2_ipAddrEntry_t	mae;
18300 	zoneid_t		zoneid;
18301 	ill_walk_context_t ctx;
18302 
18303 	/*
18304 	 * make a copy of the original message
18305 	 */
18306 	mp2ctl = copymsg(mpctl);
18307 
18308 	/* ipAddrEntryTable */
18309 
18310 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18311 	optp->level = MIB2_IP;
18312 	optp->name = MIB2_IP_ADDR;
18313 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18314 
18315 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18316 	ill = ILL_START_WALK_V4(&ctx, ipst);
18317 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18318 		for (ipif = ill->ill_ipif; ipif != NULL;
18319 		    ipif = ipif->ipif_next) {
18320 			if (ipif->ipif_zoneid != zoneid &&
18321 			    ipif->ipif_zoneid != ALL_ZONES)
18322 				continue;
18323 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18324 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18325 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18326 
18327 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18328 			    OCTET_LENGTH);
18329 			mae.ipAdEntIfIndex.o_length =
18330 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18331 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18332 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18333 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18334 			mae.ipAdEntInfo.ae_subnet_len =
18335 			    ip_mask_to_plen(ipif->ipif_net_mask);
18336 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18337 			for (bitval = 1;
18338 			    bitval &&
18339 			    !(bitval & ipif->ipif_brd_addr);
18340 			    bitval <<= 1)
18341 				noop;
18342 			mae.ipAdEntBcastAddr = bitval;
18343 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18344 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18345 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18346 			mae.ipAdEntInfo.ae_broadcast_addr =
18347 			    ipif->ipif_brd_addr;
18348 			mae.ipAdEntInfo.ae_pp_dst_addr =
18349 			    ipif->ipif_pp_dst_addr;
18350 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18351 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18352 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18353 
18354 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18355 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18356 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18357 				    "allocate %u bytes\n",
18358 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18359 			}
18360 		}
18361 	}
18362 	rw_exit(&ipst->ips_ill_g_lock);
18363 
18364 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18365 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18366 	    (int)optp->level, (int)optp->name, (int)optp->len));
18367 	qreply(q, mpctl);
18368 	return (mp2ctl);
18369 }
18370 
18371 /* IPv6 address information */
18372 static mblk_t *
18373 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18374 {
18375 	struct opthdr		*optp;
18376 	mblk_t			*mp2ctl;
18377 	mblk_t			*mp_tail = NULL;
18378 	ill_t			*ill;
18379 	ipif_t			*ipif;
18380 	mib2_ipv6AddrEntry_t	mae6;
18381 	zoneid_t		zoneid;
18382 	ill_walk_context_t	ctx;
18383 
18384 	/*
18385 	 * make a copy of the original message
18386 	 */
18387 	mp2ctl = copymsg(mpctl);
18388 
18389 	/* ipv6AddrEntryTable */
18390 
18391 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18392 	optp->level = MIB2_IP6;
18393 	optp->name = MIB2_IP6_ADDR;
18394 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18395 
18396 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18397 	ill = ILL_START_WALK_V6(&ctx, ipst);
18398 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18399 		for (ipif = ill->ill_ipif; ipif != NULL;
18400 		    ipif = ipif->ipif_next) {
18401 			if (ipif->ipif_zoneid != zoneid &&
18402 			    ipif->ipif_zoneid != ALL_ZONES)
18403 				continue;
18404 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18405 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18406 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18407 
18408 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18409 			    OCTET_LENGTH);
18410 			mae6.ipv6AddrIfIndex.o_length =
18411 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18412 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18413 			mae6.ipv6AddrPfxLength =
18414 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18415 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18416 			mae6.ipv6AddrInfo.ae_subnet_len =
18417 			    mae6.ipv6AddrPfxLength;
18418 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18419 
18420 			/* Type: stateless(1), stateful(2), unknown(3) */
18421 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18422 				mae6.ipv6AddrType = 1;
18423 			else
18424 				mae6.ipv6AddrType = 2;
18425 			/* Anycast: true(1), false(2) */
18426 			if (ipif->ipif_flags & IPIF_ANYCAST)
18427 				mae6.ipv6AddrAnycastFlag = 1;
18428 			else
18429 				mae6.ipv6AddrAnycastFlag = 2;
18430 
18431 			/*
18432 			 * Address status: preferred(1), deprecated(2),
18433 			 * invalid(3), inaccessible(4), unknown(5)
18434 			 */
18435 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18436 				mae6.ipv6AddrStatus = 3;
18437 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18438 				mae6.ipv6AddrStatus = 2;
18439 			else
18440 				mae6.ipv6AddrStatus = 1;
18441 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18442 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18443 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18444 			    ipif->ipif_v6pp_dst_addr;
18445 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18446 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18447 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18448 			mae6.ipv6AddrIdentifier = ill->ill_token;
18449 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18450 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18451 			mae6.ipv6AddrRetransmitTime =
18452 			    ill->ill_reachable_retrans_time;
18453 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18454 			    (char *)&mae6,
18455 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18456 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18457 				    "allocate %u bytes\n",
18458 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18459 			}
18460 		}
18461 	}
18462 	rw_exit(&ipst->ips_ill_g_lock);
18463 
18464 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18465 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: 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 multicast group membership. */
18472 static mblk_t *
18473 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18474 {
18475 	struct opthdr		*optp;
18476 	mblk_t			*mp2ctl;
18477 	ill_t			*ill;
18478 	ipif_t			*ipif;
18479 	ilm_t			*ilm;
18480 	ip_member_t		ipm;
18481 	mblk_t			*mp_tail = NULL;
18482 	ill_walk_context_t	ctx;
18483 	zoneid_t		zoneid;
18484 
18485 	/*
18486 	 * make a copy of the original message
18487 	 */
18488 	mp2ctl = copymsg(mpctl);
18489 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18490 
18491 	/* ipGroupMember table */
18492 	optp = (struct opthdr *)&mpctl->b_rptr[
18493 	    sizeof (struct T_optmgmt_ack)];
18494 	optp->level = MIB2_IP;
18495 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
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 		ILM_WALKER_HOLD(ill);
18501 		for (ipif = ill->ill_ipif; ipif != NULL;
18502 		    ipif = ipif->ipif_next) {
18503 			if (ipif->ipif_zoneid != zoneid &&
18504 			    ipif->ipif_zoneid != ALL_ZONES)
18505 				continue;	/* not this zone */
18506 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
18507 			    OCTET_LENGTH);
18508 			ipm.ipGroupMemberIfIndex.o_length =
18509 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18510 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18511 				ASSERT(ilm->ilm_ipif != NULL);
18512 				ASSERT(ilm->ilm_ill == NULL);
18513 				if (ilm->ilm_ipif != ipif)
18514 					continue;
18515 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18516 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18517 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18518 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18519 				    (char *)&ipm, (int)sizeof (ipm))) {
18520 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18521 					    "failed to allocate %u bytes\n",
18522 					    (uint_t)sizeof (ipm)));
18523 				}
18524 			}
18525 		}
18526 		ILM_WALKER_RELE(ill);
18527 	}
18528 	rw_exit(&ipst->ips_ill_g_lock);
18529 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18530 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18531 	    (int)optp->level, (int)optp->name, (int)optp->len));
18532 	qreply(q, mpctl);
18533 	return (mp2ctl);
18534 }
18535 
18536 /* IPv6 multicast group membership. */
18537 static mblk_t *
18538 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18539 {
18540 	struct opthdr		*optp;
18541 	mblk_t			*mp2ctl;
18542 	ill_t			*ill;
18543 	ilm_t			*ilm;
18544 	ipv6_member_t		ipm6;
18545 	mblk_t			*mp_tail = NULL;
18546 	ill_walk_context_t	ctx;
18547 	zoneid_t		zoneid;
18548 
18549 	/*
18550 	 * make a copy of the original message
18551 	 */
18552 	mp2ctl = copymsg(mpctl);
18553 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18554 
18555 	/* ip6GroupMember table */
18556 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18557 	optp->level = MIB2_IP6;
18558 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18559 
18560 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18561 	ill = ILL_START_WALK_V6(&ctx, ipst);
18562 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18563 		ILM_WALKER_HOLD(ill);
18564 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18565 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18566 			ASSERT(ilm->ilm_ipif == NULL);
18567 			ASSERT(ilm->ilm_ill != NULL);
18568 			if (ilm->ilm_zoneid != zoneid)
18569 				continue;	/* not this zone */
18570 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18571 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18572 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18573 			if (!snmp_append_data2(mpctl->b_cont,
18574 			    &mp_tail,
18575 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18576 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18577 				    "failed to allocate %u bytes\n",
18578 				    (uint_t)sizeof (ipm6)));
18579 			}
18580 		}
18581 		ILM_WALKER_RELE(ill);
18582 	}
18583 	rw_exit(&ipst->ips_ill_g_lock);
18584 
18585 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18586 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18587 	    (int)optp->level, (int)optp->name, (int)optp->len));
18588 	qreply(q, mpctl);
18589 	return (mp2ctl);
18590 }
18591 
18592 /* IP multicast filtered sources */
18593 static mblk_t *
18594 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18595 {
18596 	struct opthdr		*optp;
18597 	mblk_t			*mp2ctl;
18598 	ill_t			*ill;
18599 	ipif_t			*ipif;
18600 	ilm_t			*ilm;
18601 	ip_grpsrc_t		ips;
18602 	mblk_t			*mp_tail = NULL;
18603 	ill_walk_context_t	ctx;
18604 	zoneid_t		zoneid;
18605 	int			i;
18606 	slist_t			*sl;
18607 
18608 	/*
18609 	 * make a copy of the original message
18610 	 */
18611 	mp2ctl = copymsg(mpctl);
18612 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18613 
18614 	/* ipGroupSource table */
18615 	optp = (struct opthdr *)&mpctl->b_rptr[
18616 	    sizeof (struct T_optmgmt_ack)];
18617 	optp->level = MIB2_IP;
18618 	optp->name = EXPER_IP_GROUP_SOURCES;
18619 
18620 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18621 	ill = ILL_START_WALK_V4(&ctx, ipst);
18622 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18623 		ILM_WALKER_HOLD(ill);
18624 		for (ipif = ill->ill_ipif; ipif != NULL;
18625 		    ipif = ipif->ipif_next) {
18626 			if (ipif->ipif_zoneid != zoneid)
18627 				continue;	/* not this zone */
18628 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
18629 			    OCTET_LENGTH);
18630 			ips.ipGroupSourceIfIndex.o_length =
18631 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18632 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18633 				ASSERT(ilm->ilm_ipif != NULL);
18634 				ASSERT(ilm->ilm_ill == NULL);
18635 				sl = ilm->ilm_filter;
18636 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18637 					continue;
18638 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18639 				for (i = 0; i < sl->sl_numsrc; i++) {
18640 					if (!IN6_IS_ADDR_V4MAPPED(
18641 					    &sl->sl_addr[i]))
18642 						continue;
18643 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18644 					    ips.ipGroupSourceAddress);
18645 					if (snmp_append_data2(mpctl->b_cont,
18646 					    &mp_tail, (char *)&ips,
18647 					    (int)sizeof (ips)) == 0) {
18648 						ip1dbg(("ip_snmp_get_mib2_"
18649 						    "ip_group_src: failed to "
18650 						    "allocate %u bytes\n",
18651 						    (uint_t)sizeof (ips)));
18652 					}
18653 				}
18654 			}
18655 		}
18656 		ILM_WALKER_RELE(ill);
18657 	}
18658 	rw_exit(&ipst->ips_ill_g_lock);
18659 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18660 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18661 	    (int)optp->level, (int)optp->name, (int)optp->len));
18662 	qreply(q, mpctl);
18663 	return (mp2ctl);
18664 }
18665 
18666 /* IPv6 multicast filtered sources. */
18667 static mblk_t *
18668 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18669 {
18670 	struct opthdr		*optp;
18671 	mblk_t			*mp2ctl;
18672 	ill_t			*ill;
18673 	ilm_t			*ilm;
18674 	ipv6_grpsrc_t		ips6;
18675 	mblk_t			*mp_tail = NULL;
18676 	ill_walk_context_t	ctx;
18677 	zoneid_t		zoneid;
18678 	int			i;
18679 	slist_t			*sl;
18680 
18681 	/*
18682 	 * make a copy of the original message
18683 	 */
18684 	mp2ctl = copymsg(mpctl);
18685 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18686 
18687 	/* ip6GroupMember table */
18688 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18689 	optp->level = MIB2_IP6;
18690 	optp->name = EXPER_IP6_GROUP_SOURCES;
18691 
18692 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18693 	ill = ILL_START_WALK_V6(&ctx, ipst);
18694 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18695 		ILM_WALKER_HOLD(ill);
18696 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18697 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18698 			ASSERT(ilm->ilm_ipif == NULL);
18699 			ASSERT(ilm->ilm_ill != NULL);
18700 			sl = ilm->ilm_filter;
18701 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18702 				continue;
18703 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18704 			for (i = 0; i < sl->sl_numsrc; i++) {
18705 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18706 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18707 				    (char *)&ips6, (int)sizeof (ips6))) {
18708 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18709 					    "group_src: failed to allocate "
18710 					    "%u bytes\n",
18711 					    (uint_t)sizeof (ips6)));
18712 				}
18713 			}
18714 		}
18715 		ILM_WALKER_RELE(ill);
18716 	}
18717 	rw_exit(&ipst->ips_ill_g_lock);
18718 
18719 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18720 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18721 	    (int)optp->level, (int)optp->name, (int)optp->len));
18722 	qreply(q, mpctl);
18723 	return (mp2ctl);
18724 }
18725 
18726 /* Multicast routing virtual interface table. */
18727 static mblk_t *
18728 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18729 {
18730 	struct opthdr		*optp;
18731 	mblk_t			*mp2ctl;
18732 
18733 	/*
18734 	 * make a copy of the original message
18735 	 */
18736 	mp2ctl = copymsg(mpctl);
18737 
18738 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18739 	optp->level = EXPER_DVMRP;
18740 	optp->name = EXPER_DVMRP_VIF;
18741 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
18742 		ip0dbg(("ip_mroute_vif: failed\n"));
18743 	}
18744 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18745 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
18746 	    (int)optp->level, (int)optp->name, (int)optp->len));
18747 	qreply(q, mpctl);
18748 	return (mp2ctl);
18749 }
18750 
18751 /* Multicast routing table. */
18752 static mblk_t *
18753 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18754 {
18755 	struct opthdr		*optp;
18756 	mblk_t			*mp2ctl;
18757 
18758 	/*
18759 	 * make a copy of the original message
18760 	 */
18761 	mp2ctl = copymsg(mpctl);
18762 
18763 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18764 	optp->level = EXPER_DVMRP;
18765 	optp->name = EXPER_DVMRP_MRT;
18766 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
18767 		ip0dbg(("ip_mroute_mrt: failed\n"));
18768 	}
18769 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18770 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
18771 	    (int)optp->level, (int)optp->name, (int)optp->len));
18772 	qreply(q, mpctl);
18773 	return (mp2ctl);
18774 }
18775 
18776 /*
18777  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
18778  * in one IRE walk.
18779  */
18780 static mblk_t *
18781 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18782 {
18783 	struct opthdr	*optp;
18784 	mblk_t		*mp2ctl;	/* Returned */
18785 	mblk_t		*mp3ctl;	/* nettomedia */
18786 	mblk_t		*mp4ctl;	/* routeattrs */
18787 	iproutedata_t	ird;
18788 	zoneid_t	zoneid;
18789 
18790 	/*
18791 	 * make copies of the original message
18792 	 *	- mp2ctl is returned unchanged to the caller for his use
18793 	 *	- mpctl is sent upstream as ipRouteEntryTable
18794 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
18795 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
18796 	 */
18797 	mp2ctl = copymsg(mpctl);
18798 	mp3ctl = copymsg(mpctl);
18799 	mp4ctl = copymsg(mpctl);
18800 	if (mp3ctl == NULL || mp4ctl == NULL) {
18801 		freemsg(mp4ctl);
18802 		freemsg(mp3ctl);
18803 		freemsg(mp2ctl);
18804 		freemsg(mpctl);
18805 		return (NULL);
18806 	}
18807 
18808 	bzero(&ird, sizeof (ird));
18809 
18810 	ird.ird_route.lp_head = mpctl->b_cont;
18811 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18812 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18813 
18814 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18815 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
18816 
18817 	/* ipRouteEntryTable in mpctl */
18818 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18819 	optp->level = MIB2_IP;
18820 	optp->name = MIB2_IP_ROUTE;
18821 	optp->len = msgdsize(ird.ird_route.lp_head);
18822 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18823 	    (int)optp->level, (int)optp->name, (int)optp->len));
18824 	qreply(q, mpctl);
18825 
18826 	/* ipNetToMediaEntryTable in mp3ctl */
18827 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18828 	optp->level = MIB2_IP;
18829 	optp->name = MIB2_IP_MEDIA;
18830 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18831 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18832 	    (int)optp->level, (int)optp->name, (int)optp->len));
18833 	qreply(q, mp3ctl);
18834 
18835 	/* ipRouteAttributeTable in mp4ctl */
18836 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18837 	optp->level = MIB2_IP;
18838 	optp->name = EXPER_IP_RTATTR;
18839 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18840 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18841 	    (int)optp->level, (int)optp->name, (int)optp->len));
18842 	if (optp->len == 0)
18843 		freemsg(mp4ctl);
18844 	else
18845 		qreply(q, mp4ctl);
18846 
18847 	return (mp2ctl);
18848 }
18849 
18850 /*
18851  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
18852  * ipv6NetToMediaEntryTable in an NDP walk.
18853  */
18854 static mblk_t *
18855 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18856 {
18857 	struct opthdr	*optp;
18858 	mblk_t		*mp2ctl;	/* Returned */
18859 	mblk_t		*mp3ctl;	/* nettomedia */
18860 	mblk_t		*mp4ctl;	/* routeattrs */
18861 	iproutedata_t	ird;
18862 	zoneid_t	zoneid;
18863 
18864 	/*
18865 	 * make copies of the original message
18866 	 *	- mp2ctl is returned unchanged to the caller for his use
18867 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
18868 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
18869 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
18870 	 */
18871 	mp2ctl = copymsg(mpctl);
18872 	mp3ctl = copymsg(mpctl);
18873 	mp4ctl = copymsg(mpctl);
18874 	if (mp3ctl == NULL || mp4ctl == NULL) {
18875 		freemsg(mp4ctl);
18876 		freemsg(mp3ctl);
18877 		freemsg(mp2ctl);
18878 		freemsg(mpctl);
18879 		return (NULL);
18880 	}
18881 
18882 	bzero(&ird, sizeof (ird));
18883 
18884 	ird.ird_route.lp_head = mpctl->b_cont;
18885 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18886 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18887 
18888 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18889 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
18890 
18891 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18892 	optp->level = MIB2_IP6;
18893 	optp->name = MIB2_IP6_ROUTE;
18894 	optp->len = msgdsize(ird.ird_route.lp_head);
18895 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18896 	    (int)optp->level, (int)optp->name, (int)optp->len));
18897 	qreply(q, mpctl);
18898 
18899 	/* ipv6NetToMediaEntryTable in mp3ctl */
18900 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
18901 
18902 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18903 	optp->level = MIB2_IP6;
18904 	optp->name = MIB2_IP6_MEDIA;
18905 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18906 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18907 	    (int)optp->level, (int)optp->name, (int)optp->len));
18908 	qreply(q, mp3ctl);
18909 
18910 	/* ipv6RouteAttributeTable in mp4ctl */
18911 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18912 	optp->level = MIB2_IP6;
18913 	optp->name = EXPER_IP_RTATTR;
18914 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18915 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18916 	    (int)optp->level, (int)optp->name, (int)optp->len));
18917 	if (optp->len == 0)
18918 		freemsg(mp4ctl);
18919 	else
18920 		qreply(q, mp4ctl);
18921 
18922 	return (mp2ctl);
18923 }
18924 
18925 /*
18926  * IPv6 mib: One per ill
18927  */
18928 static mblk_t *
18929 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18930 {
18931 	struct opthdr		*optp;
18932 	mblk_t			*mp2ctl;
18933 	ill_t			*ill;
18934 	ill_walk_context_t	ctx;
18935 	mblk_t			*mp_tail = NULL;
18936 
18937 	/*
18938 	 * Make a copy of the original message
18939 	 */
18940 	mp2ctl = copymsg(mpctl);
18941 
18942 	/* fixed length IPv6 structure ... */
18943 
18944 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18945 	optp->level = MIB2_IP6;
18946 	optp->name = 0;
18947 	/* Include "unknown interface" ip6_mib */
18948 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
18949 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
18950 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18951 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
18952 	    ipst->ips_ipv6_forward ? 1 : 2);
18953 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
18954 	    ipst->ips_ipv6_def_hops);
18955 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
18956 	    sizeof (mib2_ipIfStatsEntry_t));
18957 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
18958 	    sizeof (mib2_ipv6AddrEntry_t));
18959 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
18960 	    sizeof (mib2_ipv6RouteEntry_t));
18961 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
18962 	    sizeof (mib2_ipv6NetToMediaEntry_t));
18963 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
18964 	    sizeof (ipv6_member_t));
18965 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
18966 	    sizeof (ipv6_grpsrc_t));
18967 
18968 	/*
18969 	 * Synchronize 64- and 32-bit counters
18970 	 */
18971 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
18972 	    ipIfStatsHCInReceives);
18973 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
18974 	    ipIfStatsHCInDelivers);
18975 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
18976 	    ipIfStatsHCOutRequests);
18977 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
18978 	    ipIfStatsHCOutForwDatagrams);
18979 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
18980 	    ipIfStatsHCOutMcastPkts);
18981 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
18982 	    ipIfStatsHCInMcastPkts);
18983 
18984 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18985 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
18986 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
18987 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
18988 	}
18989 
18990 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18991 	ill = ILL_START_WALK_V6(&ctx, ipst);
18992 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18993 		ill->ill_ip_mib->ipIfStatsIfIndex =
18994 		    ill->ill_phyint->phyint_ifindex;
18995 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18996 		    ipst->ips_ipv6_forward ? 1 : 2);
18997 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
18998 		    ill->ill_max_hops);
18999 
19000 		/*
19001 		 * Synchronize 64- and 32-bit counters
19002 		 */
19003 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19004 		    ipIfStatsHCInReceives);
19005 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19006 		    ipIfStatsHCInDelivers);
19007 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19008 		    ipIfStatsHCOutRequests);
19009 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19010 		    ipIfStatsHCOutForwDatagrams);
19011 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19012 		    ipIfStatsHCOutMcastPkts);
19013 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19014 		    ipIfStatsHCInMcastPkts);
19015 
19016 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19017 		    (char *)ill->ill_ip_mib,
19018 		    (int)sizeof (*ill->ill_ip_mib))) {
19019 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19020 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19021 		}
19022 	}
19023 	rw_exit(&ipst->ips_ill_g_lock);
19024 
19025 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19026 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19027 	    (int)optp->level, (int)optp->name, (int)optp->len));
19028 	qreply(q, mpctl);
19029 	return (mp2ctl);
19030 }
19031 
19032 /*
19033  * ICMPv6 mib: One per ill
19034  */
19035 static mblk_t *
19036 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19037 {
19038 	struct opthdr		*optp;
19039 	mblk_t			*mp2ctl;
19040 	ill_t			*ill;
19041 	ill_walk_context_t	ctx;
19042 	mblk_t			*mp_tail = NULL;
19043 	/*
19044 	 * Make a copy of the original message
19045 	 */
19046 	mp2ctl = copymsg(mpctl);
19047 
19048 	/* fixed length ICMPv6 structure ... */
19049 
19050 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19051 	optp->level = MIB2_ICMP6;
19052 	optp->name = 0;
19053 	/* Include "unknown interface" icmp6_mib */
19054 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19055 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19056 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19057 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19058 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19059 	    (char *)&ipst->ips_icmp6_mib,
19060 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19061 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19062 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19063 	}
19064 
19065 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19066 	ill = ILL_START_WALK_V6(&ctx, ipst);
19067 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19068 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19069 		    ill->ill_phyint->phyint_ifindex;
19070 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19071 		    (char *)ill->ill_icmp6_mib,
19072 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19073 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19074 			    "%u bytes\n",
19075 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19076 		}
19077 	}
19078 	rw_exit(&ipst->ips_ill_g_lock);
19079 
19080 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19081 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19082 	    (int)optp->level, (int)optp->name, (int)optp->len));
19083 	qreply(q, mpctl);
19084 	return (mp2ctl);
19085 }
19086 
19087 /*
19088  * ire_walk routine to create both ipRouteEntryTable and
19089  * ipRouteAttributeTable in one IRE walk
19090  */
19091 static void
19092 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19093 {
19094 	ill_t				*ill;
19095 	ipif_t				*ipif;
19096 	mib2_ipRouteEntry_t		*re;
19097 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19098 	ipaddr_t			gw_addr;
19099 	tsol_ire_gw_secattr_t		*attrp;
19100 	tsol_gc_t			*gc = NULL;
19101 	tsol_gcgrp_t			*gcgrp = NULL;
19102 	uint_t				sacnt = 0;
19103 	int				i;
19104 
19105 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19106 
19107 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19108 		return;
19109 
19110 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19111 		mutex_enter(&attrp->igsa_lock);
19112 		if ((gc = attrp->igsa_gc) != NULL) {
19113 			gcgrp = gc->gc_grp;
19114 			ASSERT(gcgrp != NULL);
19115 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19116 			sacnt = 1;
19117 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19118 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19119 			gc = gcgrp->gcgrp_head;
19120 			sacnt = gcgrp->gcgrp_count;
19121 		}
19122 		mutex_exit(&attrp->igsa_lock);
19123 
19124 		/* do nothing if there's no gc to report */
19125 		if (gc == NULL) {
19126 			ASSERT(sacnt == 0);
19127 			if (gcgrp != NULL) {
19128 				/* we might as well drop the lock now */
19129 				rw_exit(&gcgrp->gcgrp_rwlock);
19130 				gcgrp = NULL;
19131 			}
19132 			attrp = NULL;
19133 		}
19134 
19135 		ASSERT(gc == NULL || (gcgrp != NULL &&
19136 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19137 	}
19138 	ASSERT(sacnt == 0 || gc != NULL);
19139 
19140 	if (sacnt != 0 &&
19141 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19142 		kmem_free(re, sizeof (*re));
19143 		rw_exit(&gcgrp->gcgrp_rwlock);
19144 		return;
19145 	}
19146 
19147 	/*
19148 	 * Return all IRE types for route table... let caller pick and choose
19149 	 */
19150 	re->ipRouteDest = ire->ire_addr;
19151 	ipif = ire->ire_ipif;
19152 	re->ipRouteIfIndex.o_length = 0;
19153 	if (ire->ire_type == IRE_CACHE) {
19154 		ill = (ill_t *)ire->ire_stq->q_ptr;
19155 		re->ipRouteIfIndex.o_length =
19156 		    ill->ill_name_length == 0 ? 0 :
19157 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19158 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19159 		    re->ipRouteIfIndex.o_length);
19160 	} else if (ipif != NULL) {
19161 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19162 		re->ipRouteIfIndex.o_length =
19163 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19164 	}
19165 	re->ipRouteMetric1 = -1;
19166 	re->ipRouteMetric2 = -1;
19167 	re->ipRouteMetric3 = -1;
19168 	re->ipRouteMetric4 = -1;
19169 
19170 	gw_addr = ire->ire_gateway_addr;
19171 
19172 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19173 		re->ipRouteNextHop = ire->ire_src_addr;
19174 	else
19175 		re->ipRouteNextHop = gw_addr;
19176 	/* indirect(4), direct(3), or invalid(2) */
19177 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19178 		re->ipRouteType = 2;
19179 	else
19180 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19181 	re->ipRouteProto = -1;
19182 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19183 	re->ipRouteMask = ire->ire_mask;
19184 	re->ipRouteMetric5 = -1;
19185 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19186 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19187 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19188 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19189 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19190 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19191 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19192 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19193 
19194 	if (ire->ire_flags & RTF_DYNAMIC) {
19195 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19196 	} else {
19197 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19198 	}
19199 
19200 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19201 	    (char *)re, (int)sizeof (*re))) {
19202 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19203 		    (uint_t)sizeof (*re)));
19204 	}
19205 
19206 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19207 		iaeptr->iae_routeidx = ird->ird_idx;
19208 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19209 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19210 	}
19211 
19212 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19213 	    (char *)iae, sacnt * sizeof (*iae))) {
19214 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19215 		    (unsigned)(sacnt * sizeof (*iae))));
19216 	}
19217 
19218 	/* bump route index for next pass */
19219 	ird->ird_idx++;
19220 
19221 	kmem_free(re, sizeof (*re));
19222 	if (sacnt != 0)
19223 		kmem_free(iae, sacnt * sizeof (*iae));
19224 
19225 	if (gcgrp != NULL)
19226 		rw_exit(&gcgrp->gcgrp_rwlock);
19227 }
19228 
19229 /*
19230  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19231  */
19232 static void
19233 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19234 {
19235 	ill_t				*ill;
19236 	ipif_t				*ipif;
19237 	mib2_ipv6RouteEntry_t		*re;
19238 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19239 	in6_addr_t			gw_addr_v6;
19240 	tsol_ire_gw_secattr_t		*attrp;
19241 	tsol_gc_t			*gc = NULL;
19242 	tsol_gcgrp_t			*gcgrp = NULL;
19243 	uint_t				sacnt = 0;
19244 	int				i;
19245 
19246 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19247 
19248 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19249 		return;
19250 
19251 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19252 		mutex_enter(&attrp->igsa_lock);
19253 		if ((gc = attrp->igsa_gc) != NULL) {
19254 			gcgrp = gc->gc_grp;
19255 			ASSERT(gcgrp != NULL);
19256 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19257 			sacnt = 1;
19258 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19259 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19260 			gc = gcgrp->gcgrp_head;
19261 			sacnt = gcgrp->gcgrp_count;
19262 		}
19263 		mutex_exit(&attrp->igsa_lock);
19264 
19265 		/* do nothing if there's no gc to report */
19266 		if (gc == NULL) {
19267 			ASSERT(sacnt == 0);
19268 			if (gcgrp != NULL) {
19269 				/* we might as well drop the lock now */
19270 				rw_exit(&gcgrp->gcgrp_rwlock);
19271 				gcgrp = NULL;
19272 			}
19273 			attrp = NULL;
19274 		}
19275 
19276 		ASSERT(gc == NULL || (gcgrp != NULL &&
19277 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19278 	}
19279 	ASSERT(sacnt == 0 || gc != NULL);
19280 
19281 	if (sacnt != 0 &&
19282 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19283 		kmem_free(re, sizeof (*re));
19284 		rw_exit(&gcgrp->gcgrp_rwlock);
19285 		return;
19286 	}
19287 
19288 	/*
19289 	 * Return all IRE types for route table... let caller pick and choose
19290 	 */
19291 	re->ipv6RouteDest = ire->ire_addr_v6;
19292 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19293 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19294 	re->ipv6RouteIfIndex.o_length = 0;
19295 	ipif = ire->ire_ipif;
19296 	if (ire->ire_type == IRE_CACHE) {
19297 		ill = (ill_t *)ire->ire_stq->q_ptr;
19298 		re->ipv6RouteIfIndex.o_length =
19299 		    ill->ill_name_length == 0 ? 0 :
19300 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19301 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19302 		    re->ipv6RouteIfIndex.o_length);
19303 	} else if (ipif != NULL) {
19304 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19305 		re->ipv6RouteIfIndex.o_length =
19306 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19307 	}
19308 
19309 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19310 
19311 	mutex_enter(&ire->ire_lock);
19312 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19313 	mutex_exit(&ire->ire_lock);
19314 
19315 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19316 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19317 	else
19318 		re->ipv6RouteNextHop = gw_addr_v6;
19319 
19320 	/* remote(4), local(3), or discard(2) */
19321 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19322 		re->ipv6RouteType = 2;
19323 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19324 		re->ipv6RouteType = 3;
19325 	else
19326 		re->ipv6RouteType = 4;
19327 
19328 	re->ipv6RouteProtocol	= -1;
19329 	re->ipv6RoutePolicy	= 0;
19330 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19331 	re->ipv6RouteNextHopRDI	= 0;
19332 	re->ipv6RouteWeight	= 0;
19333 	re->ipv6RouteMetric	= 0;
19334 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19335 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19336 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19337 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19338 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19339 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19340 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19341 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19342 
19343 	if (ire->ire_flags & RTF_DYNAMIC) {
19344 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19345 	} else {
19346 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19347 	}
19348 
19349 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19350 	    (char *)re, (int)sizeof (*re))) {
19351 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19352 		    (uint_t)sizeof (*re)));
19353 	}
19354 
19355 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19356 		iaeptr->iae_routeidx = ird->ird_idx;
19357 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19358 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19359 	}
19360 
19361 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19362 	    (char *)iae, sacnt * sizeof (*iae))) {
19363 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19364 		    (unsigned)(sacnt * sizeof (*iae))));
19365 	}
19366 
19367 	/* bump route index for next pass */
19368 	ird->ird_idx++;
19369 
19370 	kmem_free(re, sizeof (*re));
19371 	if (sacnt != 0)
19372 		kmem_free(iae, sacnt * sizeof (*iae));
19373 
19374 	if (gcgrp != NULL)
19375 		rw_exit(&gcgrp->gcgrp_rwlock);
19376 }
19377 
19378 /*
19379  * ndp_walk routine to create ipv6NetToMediaEntryTable
19380  */
19381 static int
19382 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19383 {
19384 	ill_t				*ill;
19385 	mib2_ipv6NetToMediaEntry_t	ntme;
19386 	dl_unitdata_req_t		*dl;
19387 
19388 	ill = nce->nce_ill;
19389 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19390 		return (0);
19391 
19392 	/*
19393 	 * Neighbor cache entry attached to IRE with on-link
19394 	 * destination.
19395 	 */
19396 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19397 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19398 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19399 	    (nce->nce_res_mp != NULL)) {
19400 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19401 		ntme.ipv6NetToMediaPhysAddress.o_length =
19402 		    dl->dl_dest_addr_length;
19403 	} else {
19404 		ntme.ipv6NetToMediaPhysAddress.o_length =
19405 		    ill->ill_phys_addr_length;
19406 	}
19407 	if (nce->nce_res_mp != NULL) {
19408 		bcopy((char *)nce->nce_res_mp->b_rptr +
19409 		    NCE_LL_ADDR_OFFSET(ill),
19410 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19411 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19412 	} else {
19413 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19414 		    ill->ill_phys_addr_length);
19415 	}
19416 	/*
19417 	 * Note: Returns ND_* states. Should be:
19418 	 * reachable(1), stale(2), delay(3), probe(4),
19419 	 * invalid(5), unknown(6)
19420 	 */
19421 	ntme.ipv6NetToMediaState = nce->nce_state;
19422 	ntme.ipv6NetToMediaLastUpdated = 0;
19423 
19424 	/* other(1), dynamic(2), static(3), local(4) */
19425 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19426 		ntme.ipv6NetToMediaType = 4;
19427 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19428 		ntme.ipv6NetToMediaType = 1;
19429 	} else {
19430 		ntme.ipv6NetToMediaType = 2;
19431 	}
19432 
19433 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19434 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19435 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19436 		    (uint_t)sizeof (ntme)));
19437 	}
19438 	return (0);
19439 }
19440 
19441 /*
19442  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19443  */
19444 /* ARGSUSED */
19445 int
19446 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19447 {
19448 	switch (level) {
19449 	case MIB2_IP:
19450 	case MIB2_ICMP:
19451 		switch (name) {
19452 		default:
19453 			break;
19454 		}
19455 		return (1);
19456 	default:
19457 		return (1);
19458 	}
19459 }
19460 
19461 /*
19462  * When there exists both a 64- and 32-bit counter of a particular type
19463  * (i.e., InReceives), only the 64-bit counters are added.
19464  */
19465 void
19466 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19467 {
19468 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19469 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19470 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19471 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19472 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19473 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19474 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19475 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19476 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19477 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19478 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19479 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19480 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19481 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19482 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19483 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19484 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19485 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19486 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19487 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19488 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19489 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19490 	    o2->ipIfStatsInWrongIPVersion);
19491 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19492 	    o2->ipIfStatsInWrongIPVersion);
19493 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19494 	    o2->ipIfStatsOutSwitchIPVersion);
19495 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19496 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19497 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19498 	    o2->ipIfStatsHCInForwDatagrams);
19499 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19500 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19501 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19502 	    o2->ipIfStatsHCOutForwDatagrams);
19503 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19504 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19505 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19506 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19507 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19508 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19509 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19510 	    o2->ipIfStatsHCOutMcastOctets);
19511 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19512 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19513 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19514 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19515 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19516 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19517 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19518 }
19519 
19520 void
19521 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19522 {
19523 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19524 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19525 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19526 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19527 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19528 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19529 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19530 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19531 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19532 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19533 	    o2->ipv6IfIcmpInRouterSolicits);
19534 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19535 	    o2->ipv6IfIcmpInRouterAdvertisements);
19536 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19537 	    o2->ipv6IfIcmpInNeighborSolicits);
19538 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19539 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19540 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19541 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19542 	    o2->ipv6IfIcmpInGroupMembQueries);
19543 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19544 	    o2->ipv6IfIcmpInGroupMembResponses);
19545 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19546 	    o2->ipv6IfIcmpInGroupMembReductions);
19547 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19548 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19549 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19550 	    o2->ipv6IfIcmpOutDestUnreachs);
19551 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19552 	    o2->ipv6IfIcmpOutAdminProhibs);
19553 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19554 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19555 	    o2->ipv6IfIcmpOutParmProblems);
19556 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19557 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19558 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19559 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19560 	    o2->ipv6IfIcmpOutRouterSolicits);
19561 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19562 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19563 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19564 	    o2->ipv6IfIcmpOutNeighborSolicits);
19565 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19566 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19567 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19568 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19569 	    o2->ipv6IfIcmpOutGroupMembQueries);
19570 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19571 	    o2->ipv6IfIcmpOutGroupMembResponses);
19572 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19573 	    o2->ipv6IfIcmpOutGroupMembReductions);
19574 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19575 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19576 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19577 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19578 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19579 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19580 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19581 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19582 	    o2->ipv6IfIcmpInGroupMembTotal);
19583 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19584 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19585 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19586 	    o2->ipv6IfIcmpInGroupMembBadReports);
19587 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19588 	    o2->ipv6IfIcmpInGroupMembOurReports);
19589 }
19590 
19591 /*
19592  * Called before the options are updated to check if this packet will
19593  * be source routed from here.
19594  * This routine assumes that the options are well formed i.e. that they
19595  * have already been checked.
19596  */
19597 static boolean_t
19598 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
19599 {
19600 	ipoptp_t	opts;
19601 	uchar_t		*opt;
19602 	uint8_t		optval;
19603 	uint8_t		optlen;
19604 	ipaddr_t	dst;
19605 	ire_t		*ire;
19606 
19607 	if (IS_SIMPLE_IPH(ipha)) {
19608 		ip2dbg(("not source routed\n"));
19609 		return (B_FALSE);
19610 	}
19611 	dst = ipha->ipha_dst;
19612 	for (optval = ipoptp_first(&opts, ipha);
19613 	    optval != IPOPT_EOL;
19614 	    optval = ipoptp_next(&opts)) {
19615 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19616 		opt = opts.ipoptp_cur;
19617 		optlen = opts.ipoptp_len;
19618 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19619 		    optval, optlen));
19620 		switch (optval) {
19621 			uint32_t off;
19622 		case IPOPT_SSRR:
19623 		case IPOPT_LSRR:
19624 			/*
19625 			 * If dst is one of our addresses and there are some
19626 			 * entries left in the source route return (true).
19627 			 */
19628 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19629 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
19630 			if (ire == NULL) {
19631 				ip2dbg(("ip_source_routed: not next"
19632 				    " source route 0x%x\n",
19633 				    ntohl(dst)));
19634 				return (B_FALSE);
19635 			}
19636 			ire_refrele(ire);
19637 			off = opt[IPOPT_OFFSET];
19638 			off--;
19639 			if (optlen < IP_ADDR_LEN ||
19640 			    off > optlen - IP_ADDR_LEN) {
19641 				/* End of source route */
19642 				ip1dbg(("ip_source_routed: end of SR\n"));
19643 				return (B_FALSE);
19644 			}
19645 			return (B_TRUE);
19646 		}
19647 	}
19648 	ip2dbg(("not source routed\n"));
19649 	return (B_FALSE);
19650 }
19651 
19652 /*
19653  * Check if the packet contains any source route.
19654  */
19655 static boolean_t
19656 ip_source_route_included(ipha_t *ipha)
19657 {
19658 	ipoptp_t	opts;
19659 	uint8_t		optval;
19660 
19661 	if (IS_SIMPLE_IPH(ipha))
19662 		return (B_FALSE);
19663 	for (optval = ipoptp_first(&opts, ipha);
19664 	    optval != IPOPT_EOL;
19665 	    optval = ipoptp_next(&opts)) {
19666 		switch (optval) {
19667 		case IPOPT_SSRR:
19668 		case IPOPT_LSRR:
19669 			return (B_TRUE);
19670 		}
19671 	}
19672 	return (B_FALSE);
19673 }
19674 
19675 /*
19676  * Called when the IRE expiration timer fires.
19677  */
19678 void
19679 ip_trash_timer_expire(void *args)
19680 {
19681 	int			flush_flag = 0;
19682 	ire_expire_arg_t	iea;
19683 	ip_stack_t		*ipst = (ip_stack_t *)args;
19684 
19685 	iea.iea_ipst = ipst;	/* No netstack_hold */
19686 
19687 	/*
19688 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19689 	 * This lock makes sure that a new invocation of this function
19690 	 * that occurs due to an almost immediate timer firing will not
19691 	 * progress beyond this point until the current invocation is done
19692 	 */
19693 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19694 	ipst->ips_ip_ire_expire_id = 0;
19695 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19696 
19697 	/* Periodic timer */
19698 	if (ipst->ips_ip_ire_arp_time_elapsed >=
19699 	    ipst->ips_ip_ire_arp_interval) {
19700 		/*
19701 		 * Remove all IRE_CACHE entries since they might
19702 		 * contain arp information.
19703 		 */
19704 		flush_flag |= FLUSH_ARP_TIME;
19705 		ipst->ips_ip_ire_arp_time_elapsed = 0;
19706 		IP_STAT(ipst, ip_ire_arp_timer_expired);
19707 	}
19708 	if (ipst->ips_ip_ire_rd_time_elapsed >=
19709 	    ipst->ips_ip_ire_redir_interval) {
19710 		/* Remove all redirects */
19711 		flush_flag |= FLUSH_REDIRECT_TIME;
19712 		ipst->ips_ip_ire_rd_time_elapsed = 0;
19713 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
19714 	}
19715 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
19716 	    ipst->ips_ip_ire_pathmtu_interval) {
19717 		/* Increase path mtu */
19718 		flush_flag |= FLUSH_MTU_TIME;
19719 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
19720 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
19721 	}
19722 
19723 	/*
19724 	 * Optimize for the case when there are no redirects in the
19725 	 * ftable, that is, no need to walk the ftable in that case.
19726 	 */
19727 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
19728 		iea.iea_flush_flag = flush_flag;
19729 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
19730 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
19731 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
19732 		    NULL, ALL_ZONES, ipst);
19733 	}
19734 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
19735 	    ipst->ips_ip_redirect_cnt > 0) {
19736 		iea.iea_flush_flag = flush_flag;
19737 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
19738 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
19739 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
19740 	}
19741 	if (flush_flag & FLUSH_MTU_TIME) {
19742 		/*
19743 		 * Walk all IPv6 IRE's and update them
19744 		 * Note that ARP and redirect timers are not
19745 		 * needed since NUD handles stale entries.
19746 		 */
19747 		flush_flag = FLUSH_MTU_TIME;
19748 		iea.iea_flush_flag = flush_flag;
19749 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
19750 		    ALL_ZONES, ipst);
19751 	}
19752 
19753 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
19754 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
19755 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
19756 
19757 	/*
19758 	 * Hold the lock to serialize timeout calls and prevent
19759 	 * stale values in ip_ire_expire_id. Otherwise it is possible
19760 	 * for the timer to fire and a new invocation of this function
19761 	 * to start before the return value of timeout has been stored
19762 	 * in ip_ire_expire_id by the current invocation.
19763 	 */
19764 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19765 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
19766 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
19767 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19768 }
19769 
19770 /*
19771  * Called by the memory allocator subsystem directly, when the system
19772  * is running low on memory.
19773  */
19774 /* ARGSUSED */
19775 void
19776 ip_trash_ire_reclaim(void *args)
19777 {
19778 	netstack_handle_t nh;
19779 	netstack_t *ns;
19780 
19781 	netstack_next_init(&nh);
19782 	while ((ns = netstack_next(&nh)) != NULL) {
19783 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
19784 		netstack_rele(ns);
19785 	}
19786 	netstack_next_fini(&nh);
19787 }
19788 
19789 static void
19790 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
19791 {
19792 	ire_cache_count_t icc;
19793 	ire_cache_reclaim_t icr;
19794 	ncc_cache_count_t ncc;
19795 	nce_cache_reclaim_t ncr;
19796 	uint_t delete_cnt;
19797 	/*
19798 	 * Memory reclaim call back.
19799 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
19800 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
19801 	 * entries, determine what fraction to free for
19802 	 * each category of IRE_CACHE entries giving absolute priority
19803 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
19804 	 * entry will be freed unless all offlink entries are freed).
19805 	 */
19806 	icc.icc_total = 0;
19807 	icc.icc_unused = 0;
19808 	icc.icc_offlink = 0;
19809 	icc.icc_pmtu = 0;
19810 	icc.icc_onlink = 0;
19811 	ire_walk(ire_cache_count, (char *)&icc, ipst);
19812 
19813 	/*
19814 	 * Free NCEs for IPv6 like the onlink ires.
19815 	 */
19816 	ncc.ncc_total = 0;
19817 	ncc.ncc_host = 0;
19818 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
19819 
19820 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
19821 	    icc.icc_pmtu + icc.icc_onlink);
19822 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
19823 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
19824 	if (delete_cnt == 0)
19825 		return;
19826 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
19827 	/* Always delete all unused offlink entries */
19828 	icr.icr_ipst = ipst;
19829 	icr.icr_unused = 1;
19830 	if (delete_cnt <= icc.icc_unused) {
19831 		/*
19832 		 * Only need to free unused entries.  In other words,
19833 		 * there are enough unused entries to free to meet our
19834 		 * target number of freed ire cache entries.
19835 		 */
19836 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
19837 		ncr.ncr_host = 0;
19838 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
19839 		/*
19840 		 * Only need to free unused entries, plus a fraction of offlink
19841 		 * entries.  It follows from the first if statement that
19842 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
19843 		 */
19844 		delete_cnt -= icc.icc_unused;
19845 		/* Round up # deleted by truncating fraction */
19846 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
19847 		icr.icr_pmtu = icr.icr_onlink = 0;
19848 		ncr.ncr_host = 0;
19849 	} else if (delete_cnt <=
19850 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
19851 		/*
19852 		 * Free all unused and offlink entries, plus a fraction of
19853 		 * pmtu entries.  It follows from the previous if statement
19854 		 * that icc_pmtu is non-zero, and that
19855 		 * delete_cnt != icc_unused + icc_offlink.
19856 		 */
19857 		icr.icr_offlink = 1;
19858 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
19859 		/* Round up # deleted by truncating fraction */
19860 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
19861 		icr.icr_onlink = 0;
19862 		ncr.ncr_host = 0;
19863 	} else {
19864 		/*
19865 		 * Free all unused, offlink, and pmtu entries, plus a fraction
19866 		 * of onlink entries.  If we're here, then we know that
19867 		 * icc_onlink is non-zero, and that
19868 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
19869 		 */
19870 		icr.icr_offlink = icr.icr_pmtu = 1;
19871 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
19872 		    icc.icc_pmtu;
19873 		/* Round up # deleted by truncating fraction */
19874 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
19875 		/* Using the same delete fraction as for onlink IREs */
19876 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
19877 	}
19878 #ifdef DEBUG
19879 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
19880 	    "fractions %d/%d/%d/%d\n",
19881 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
19882 	    icc.icc_unused, icc.icc_offlink,
19883 	    icc.icc_pmtu, icc.icc_onlink,
19884 	    icr.icr_unused, icr.icr_offlink,
19885 	    icr.icr_pmtu, icr.icr_onlink));
19886 #endif
19887 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
19888 	if (ncr.ncr_host != 0)
19889 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
19890 		    (uchar_t *)&ncr, ipst);
19891 #ifdef DEBUG
19892 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
19893 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
19894 	ire_walk(ire_cache_count, (char *)&icc, ipst);
19895 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
19896 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
19897 	    icc.icc_pmtu, icc.icc_onlink));
19898 #endif
19899 }
19900 
19901 /*
19902  * ip_unbind is called when a copy of an unbind request is received from the
19903  * upper level protocol.  We remove this conn from any fanout hash list it is
19904  * on, and zero out the bind information.  No reply is expected up above.
19905  */
19906 mblk_t *
19907 ip_unbind(queue_t *q, mblk_t *mp)
19908 {
19909 	conn_t	*connp = Q_TO_CONN(q);
19910 
19911 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
19912 
19913 	if (is_system_labeled() && connp->conn_anon_port) {
19914 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
19915 		    connp->conn_mlp_type, connp->conn_ulp,
19916 		    ntohs(connp->conn_lport), B_FALSE);
19917 		connp->conn_anon_port = 0;
19918 	}
19919 	connp->conn_mlp_type = mlptSingle;
19920 
19921 	ipcl_hash_remove(connp);
19922 
19923 	ASSERT(mp->b_cont == NULL);
19924 	/*
19925 	 * Convert mp into a T_OK_ACK
19926 	 */
19927 	mp = mi_tpi_ok_ack_alloc(mp);
19928 
19929 	/*
19930 	 * should not happen in practice... T_OK_ACK is smaller than the
19931 	 * original message.
19932 	 */
19933 	if (mp == NULL)
19934 		return (NULL);
19935 
19936 	return (mp);
19937 }
19938 
19939 /*
19940  * Write side put procedure.  Outbound data, IOCTLs, responses from
19941  * resolvers, etc, come down through here.
19942  *
19943  * arg2 is always a queue_t *.
19944  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
19945  * the zoneid.
19946  * When that queue is not an ill_t, then arg must be a conn_t pointer.
19947  */
19948 void
19949 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
19950 {
19951 	ip_output_options(arg, mp, arg2, caller, &zero_info);
19952 }
19953 
19954 void
19955 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
19956     ip_opt_info_t *infop)
19957 {
19958 	conn_t		*connp = NULL;
19959 	queue_t		*q = (queue_t *)arg2;
19960 	ipha_t		*ipha;
19961 #define	rptr	((uchar_t *)ipha)
19962 	ire_t		*ire = NULL;
19963 	ire_t		*sctp_ire = NULL;
19964 	uint32_t	v_hlen_tos_len;
19965 	ipaddr_t	dst;
19966 	mblk_t		*first_mp = NULL;
19967 	boolean_t	mctl_present;
19968 	ipsec_out_t	*io;
19969 	int		match_flags;
19970 	ill_t		*attach_ill = NULL;
19971 					/* Bind to IPIF_NOFAILOVER ill etc. */
19972 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
19973 	ipif_t		*dst_ipif;
19974 	boolean_t	multirt_need_resolve = B_FALSE;
19975 	mblk_t		*copy_mp = NULL;
19976 	int		err;
19977 	zoneid_t	zoneid;
19978 	int	adjust;
19979 	uint16_t iplen;
19980 	boolean_t	need_decref = B_FALSE;
19981 	boolean_t	ignore_dontroute = B_FALSE;
19982 	boolean_t	ignore_nexthop = B_FALSE;
19983 	boolean_t	ip_nexthop = B_FALSE;
19984 	ipaddr_t	nexthop_addr;
19985 	ip_stack_t	*ipst;
19986 
19987 #ifdef	_BIG_ENDIAN
19988 #define	V_HLEN	(v_hlen_tos_len >> 24)
19989 #else
19990 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
19991 #endif
19992 
19993 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
19994 	    "ip_wput_start: q %p", q);
19995 
19996 	/*
19997 	 * ip_wput fast path
19998 	 */
19999 
20000 	/* is packet from ARP ? */
20001 	if (q->q_next != NULL) {
20002 		zoneid = (zoneid_t)(uintptr_t)arg;
20003 		goto qnext;
20004 	}
20005 
20006 	connp = (conn_t *)arg;
20007 	ASSERT(connp != NULL);
20008 	zoneid = connp->conn_zoneid;
20009 	ipst = connp->conn_netstack->netstack_ip;
20010 
20011 	/* is queue flow controlled? */
20012 	if ((q->q_first != NULL || connp->conn_draining) &&
20013 	    (caller == IP_WPUT)) {
20014 		ASSERT(!need_decref);
20015 		(void) putq(q, mp);
20016 		return;
20017 	}
20018 
20019 	/* Multidata transmit? */
20020 	if (DB_TYPE(mp) == M_MULTIDATA) {
20021 		/*
20022 		 * We should never get here, since all Multidata messages
20023 		 * originating from tcp should have been directed over to
20024 		 * tcp_multisend() in the first place.
20025 		 */
20026 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20027 		freemsg(mp);
20028 		return;
20029 	} else if (DB_TYPE(mp) != M_DATA)
20030 		goto notdata;
20031 
20032 	if (mp->b_flag & MSGHASREF) {
20033 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20034 		mp->b_flag &= ~MSGHASREF;
20035 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20036 		need_decref = B_TRUE;
20037 	}
20038 	ipha = (ipha_t *)mp->b_rptr;
20039 
20040 	/* is IP header non-aligned or mblk smaller than basic IP header */
20041 #ifndef SAFETY_BEFORE_SPEED
20042 	if (!OK_32PTR(rptr) ||
20043 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20044 		goto hdrtoosmall;
20045 #endif
20046 
20047 	ASSERT(OK_32PTR(ipha));
20048 
20049 	/*
20050 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20051 	 * wrong version, we'll catch it again in ip_output_v6.
20052 	 *
20053 	 * Note that this is *only* locally-generated output here, and never
20054 	 * forwarded data, and that we need to deal only with transports that
20055 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20056 	 * label.)
20057 	 */
20058 	if (is_system_labeled() &&
20059 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20060 	    !connp->conn_ulp_labeled) {
20061 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
20062 		    connp->conn_mac_exempt, ipst);
20063 		ipha = (ipha_t *)mp->b_rptr;
20064 		if (err != 0) {
20065 			first_mp = mp;
20066 			if (err == EINVAL)
20067 				goto icmp_parameter_problem;
20068 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20069 			goto discard_pkt;
20070 		}
20071 		iplen = ntohs(ipha->ipha_length) + adjust;
20072 		ipha->ipha_length = htons(iplen);
20073 	}
20074 
20075 	ASSERT(infop != NULL);
20076 
20077 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20078 		/*
20079 		 * IP_PKTINFO ancillary option is present.
20080 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20081 		 * allows using address of any zone as the source address.
20082 		 */
20083 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20084 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20085 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20086 		if (ire == NULL)
20087 			goto drop_pkt;
20088 		ire_refrele(ire);
20089 		ire = NULL;
20090 	}
20091 
20092 	/*
20093 	 * IP_DONTFAILOVER_IF and IP_XMIT_IF have precedence over
20094 	 * ill index passed in IP_PKTINFO.
20095 	 */
20096 	if (infop->ip_opt_ill_index != 0 &&
20097 	    connp->conn_xmit_if_ill == NULL &&
20098 	    connp->conn_nofailover_ill == NULL) {
20099 
20100 		xmit_ill = ill_lookup_on_ifindex(
20101 		    infop->ip_opt_ill_index, B_FALSE, NULL, NULL, NULL, NULL,
20102 		    ipst);
20103 
20104 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20105 			goto drop_pkt;
20106 		/*
20107 		 * check that there is an ipif belonging
20108 		 * to our zone. IPCL_ZONEID is not used because
20109 		 * IP_ALLZONES option is valid only when the ill is
20110 		 * accessible from all zones i.e has a valid ipif in
20111 		 * all zones.
20112 		 */
20113 		if (!ipif_lookup_zoneid_group(xmit_ill, zoneid, 0, NULL)) {
20114 			goto drop_pkt;
20115 		}
20116 	}
20117 
20118 	/*
20119 	 * If there is a policy, try to attach an ipsec_out in
20120 	 * the front. At the end, first_mp either points to a
20121 	 * M_DATA message or IPSEC_OUT message linked to a
20122 	 * M_DATA message. We have to do it now as we might
20123 	 * lose the "conn" if we go through ip_newroute.
20124 	 */
20125 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20126 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20127 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20128 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20129 			if (need_decref)
20130 				CONN_DEC_REF(connp);
20131 			return;
20132 		} else {
20133 			ASSERT(mp->b_datap->db_type == M_CTL);
20134 			first_mp = mp;
20135 			mp = mp->b_cont;
20136 			mctl_present = B_TRUE;
20137 		}
20138 	} else {
20139 		first_mp = mp;
20140 		mctl_present = B_FALSE;
20141 	}
20142 
20143 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20144 
20145 	/* is wrong version or IP options present */
20146 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20147 		goto version_hdrlen_check;
20148 	dst = ipha->ipha_dst;
20149 
20150 	if (connp->conn_nofailover_ill != NULL) {
20151 		attach_ill = conn_get_held_ill(connp,
20152 		    &connp->conn_nofailover_ill, &err);
20153 		if (err == ILL_LOOKUP_FAILED) {
20154 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20155 			if (need_decref)
20156 				CONN_DEC_REF(connp);
20157 			freemsg(first_mp);
20158 			return;
20159 		}
20160 	}
20161 
20162 
20163 	/* is packet multicast? */
20164 	if (CLASSD(dst))
20165 		goto multicast;
20166 
20167 	/*
20168 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20169 	 * takes precedence over conn_dontroute and conn_nexthop_set
20170 	 */
20171 	if (xmit_ill != NULL) {
20172 		goto send_from_ill;
20173 	}
20174 
20175 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
20176 	    (connp->conn_nexthop_set)) {
20177 		/*
20178 		 * If the destination is a broadcast or a loopback
20179 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
20180 		 * through the standard path. But in the case of local
20181 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
20182 		 * the standard path not IP_XMIT_IF.
20183 		 */
20184 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20185 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
20186 		    (ire->ire_type != IRE_LOOPBACK))) {
20187 			if ((connp->conn_dontroute ||
20188 			    connp->conn_nexthop_set) && (ire != NULL) &&
20189 			    (ire->ire_type == IRE_LOCAL))
20190 				goto standard_path;
20191 
20192 			if (ire != NULL) {
20193 				ire_refrele(ire);
20194 				/* No more access to ire */
20195 				ire = NULL;
20196 			}
20197 			/*
20198 			 * bypass routing checks and go directly to
20199 			 * interface.
20200 			 */
20201 			if (connp->conn_dontroute) {
20202 				goto dontroute;
20203 			} else if (connp->conn_nexthop_set) {
20204 				ip_nexthop = B_TRUE;
20205 				nexthop_addr = connp->conn_nexthop_v4;
20206 				goto send_from_ill;
20207 			}
20208 
20209 			/*
20210 			 * If IP_XMIT_IF socket option is set,
20211 			 * then we allow unicast and multicast
20212 			 * packets to go through the ill. It is
20213 			 * quite possible that the destination
20214 			 * is not in the ire cache table and we
20215 			 * do not want to go to ip_newroute()
20216 			 * instead we call ip_newroute_ipif.
20217 			 */
20218 			xmit_ill = conn_get_held_ill(connp,
20219 			    &connp->conn_xmit_if_ill, &err);
20220 			if (err == ILL_LOOKUP_FAILED) {
20221 				BUMP_MIB(&ipst->ips_ip_mib,
20222 				    ipIfStatsOutDiscards);
20223 				if (attach_ill != NULL)
20224 					ill_refrele(attach_ill);
20225 				if (need_decref)
20226 					CONN_DEC_REF(connp);
20227 				freemsg(first_mp);
20228 				return;
20229 			}
20230 			goto send_from_ill;
20231 		}
20232 standard_path:
20233 		/* Must be a broadcast, a loopback or a local ire */
20234 		if (ire != NULL) {
20235 			ire_refrele(ire);
20236 			/* No more access to ire */
20237 			ire = NULL;
20238 		}
20239 	}
20240 
20241 	if (attach_ill != NULL)
20242 		goto send_from_ill;
20243 
20244 	/*
20245 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20246 	 * this for the tcp global queue and listen end point
20247 	 * as it does not really have a real destination to
20248 	 * talk to.  This is also true for SCTP.
20249 	 */
20250 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20251 	    !connp->conn_fully_bound) {
20252 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20253 		if (ire == NULL)
20254 			goto noirefound;
20255 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20256 		    "ip_wput_end: q %p (%S)", q, "end");
20257 
20258 		/*
20259 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20260 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20261 		 */
20262 		if (ire->ire_flags & RTF_MULTIRT) {
20263 
20264 			/*
20265 			 * Force the TTL of multirouted packets if required.
20266 			 * The TTL of such packets is bounded by the
20267 			 * ip_multirt_ttl ndd variable.
20268 			 */
20269 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20270 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20271 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20272 				    "(was %d), dst 0x%08x\n",
20273 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20274 				    ntohl(ire->ire_addr)));
20275 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20276 			}
20277 			/*
20278 			 * We look at this point if there are pending
20279 			 * unresolved routes. ire_multirt_resolvable()
20280 			 * checks in O(n) that all IRE_OFFSUBNET ire
20281 			 * entries for the packet's destination and
20282 			 * flagged RTF_MULTIRT are currently resolved.
20283 			 * If some remain unresolved, we make a copy
20284 			 * of the current message. It will be used
20285 			 * to initiate additional route resolutions.
20286 			 */
20287 			multirt_need_resolve =
20288 			    ire_multirt_need_resolve(ire->ire_addr,
20289 			    MBLK_GETLABEL(first_mp), ipst);
20290 			ip2dbg(("ip_wput[TCP]: ire %p, "
20291 			    "multirt_need_resolve %d, first_mp %p\n",
20292 			    (void *)ire, multirt_need_resolve,
20293 			    (void *)first_mp));
20294 			if (multirt_need_resolve) {
20295 				copy_mp = copymsg(first_mp);
20296 				if (copy_mp != NULL) {
20297 					MULTIRT_DEBUG_TAG(copy_mp);
20298 				}
20299 			}
20300 		}
20301 
20302 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20303 
20304 		/*
20305 		 * Try to resolve another multiroute if
20306 		 * ire_multirt_need_resolve() deemed it necessary.
20307 		 */
20308 		if (copy_mp != NULL)
20309 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20310 		if (need_decref)
20311 			CONN_DEC_REF(connp);
20312 		return;
20313 	}
20314 
20315 	/*
20316 	 * Access to conn_ire_cache. (protected by conn_lock)
20317 	 *
20318 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20319 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20320 	 * send a packet or two with the IRE_CACHE that is going away.
20321 	 * Access to the ire requires an ire refhold on the ire prior to
20322 	 * its use since an interface unplumb thread may delete the cached
20323 	 * ire and release the refhold at any time.
20324 	 *
20325 	 * Caching an ire in the conn_ire_cache
20326 	 *
20327 	 * o Caching an ire pointer in the conn requires a strict check for
20328 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20329 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20330 	 * in the conn is done after making sure under the bucket lock that the
20331 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20332 	 * caching an ire after the unplumb thread has cleaned up the conn.
20333 	 * If the conn does not send a packet subsequently the unplumb thread
20334 	 * will be hanging waiting for the ire count to drop to zero.
20335 	 *
20336 	 * o We also need to atomically test for a null conn_ire_cache and
20337 	 * set the conn_ire_cache under the the protection of the conn_lock
20338 	 * to avoid races among concurrent threads trying to simultaneously
20339 	 * cache an ire in the conn_ire_cache.
20340 	 */
20341 	mutex_enter(&connp->conn_lock);
20342 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20343 
20344 	if (ire != NULL && ire->ire_addr == dst &&
20345 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20346 
20347 		IRE_REFHOLD(ire);
20348 		mutex_exit(&connp->conn_lock);
20349 
20350 	} else {
20351 		boolean_t cached = B_FALSE;
20352 		connp->conn_ire_cache = NULL;
20353 		mutex_exit(&connp->conn_lock);
20354 		/* Release the old ire */
20355 		if (ire != NULL && sctp_ire == NULL)
20356 			IRE_REFRELE_NOTR(ire);
20357 
20358 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20359 		if (ire == NULL)
20360 			goto noirefound;
20361 		IRE_REFHOLD_NOTR(ire);
20362 
20363 		mutex_enter(&connp->conn_lock);
20364 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20365 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20366 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20367 				if (connp->conn_ulp == IPPROTO_TCP)
20368 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20369 				connp->conn_ire_cache = ire;
20370 				cached = B_TRUE;
20371 			}
20372 			rw_exit(&ire->ire_bucket->irb_lock);
20373 		}
20374 		mutex_exit(&connp->conn_lock);
20375 
20376 		/*
20377 		 * We can continue to use the ire but since it was
20378 		 * not cached, we should drop the extra reference.
20379 		 */
20380 		if (!cached)
20381 			IRE_REFRELE_NOTR(ire);
20382 	}
20383 
20384 
20385 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20386 	    "ip_wput_end: q %p (%S)", q, "end");
20387 
20388 	/*
20389 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20390 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20391 	 */
20392 	if (ire->ire_flags & RTF_MULTIRT) {
20393 
20394 		/*
20395 		 * Force the TTL of multirouted packets if required.
20396 		 * The TTL of such packets is bounded by the
20397 		 * ip_multirt_ttl ndd variable.
20398 		 */
20399 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20400 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20401 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20402 			    "(was %d), dst 0x%08x\n",
20403 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20404 			    ntohl(ire->ire_addr)));
20405 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20406 		}
20407 
20408 		/*
20409 		 * At this point, we check to see if there are any pending
20410 		 * unresolved routes. ire_multirt_resolvable()
20411 		 * checks in O(n) that all IRE_OFFSUBNET ire
20412 		 * entries for the packet's destination and
20413 		 * flagged RTF_MULTIRT are currently resolved.
20414 		 * If some remain unresolved, we make a copy
20415 		 * of the current message. It will be used
20416 		 * to initiate additional route resolutions.
20417 		 */
20418 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20419 		    MBLK_GETLABEL(first_mp), ipst);
20420 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20421 		    "multirt_need_resolve %d, first_mp %p\n",
20422 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20423 		if (multirt_need_resolve) {
20424 			copy_mp = copymsg(first_mp);
20425 			if (copy_mp != NULL) {
20426 				MULTIRT_DEBUG_TAG(copy_mp);
20427 			}
20428 		}
20429 	}
20430 
20431 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20432 
20433 	/*
20434 	 * Try to resolve another multiroute if
20435 	 * ire_multirt_resolvable() deemed it necessary
20436 	 */
20437 	if (copy_mp != NULL)
20438 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20439 	if (need_decref)
20440 		CONN_DEC_REF(connp);
20441 	return;
20442 
20443 qnext:
20444 	/*
20445 	 * Upper Level Protocols pass down complete IP datagrams
20446 	 * as M_DATA messages.	Everything else is a sideshow.
20447 	 *
20448 	 * 1) We could be re-entering ip_wput because of ip_neworute
20449 	 *    in which case we could have a IPSEC_OUT message. We
20450 	 *    need to pass through ip_wput like other datagrams and
20451 	 *    hence cannot branch to ip_wput_nondata.
20452 	 *
20453 	 * 2) ARP, AH, ESP, and other clients who are on the module
20454 	 *    instance of IP stream, give us something to deal with.
20455 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20456 	 *
20457 	 * 3) ICMP replies also could come here.
20458 	 */
20459 	ipst = ILLQ_TO_IPST(q);
20460 
20461 	if (DB_TYPE(mp) != M_DATA) {
20462 notdata:
20463 		if (DB_TYPE(mp) == M_CTL) {
20464 			/*
20465 			 * M_CTL messages are used by ARP, AH and ESP to
20466 			 * communicate with IP. We deal with IPSEC_IN and
20467 			 * IPSEC_OUT here. ip_wput_nondata handles other
20468 			 * cases.
20469 			 */
20470 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20471 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20472 				first_mp = mp->b_cont;
20473 				first_mp->b_flag &= ~MSGHASREF;
20474 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20475 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20476 				CONN_DEC_REF(connp);
20477 				connp = NULL;
20478 			}
20479 			if (ii->ipsec_info_type == IPSEC_IN) {
20480 				/*
20481 				 * Either this message goes back to
20482 				 * IPsec for further processing or to
20483 				 * ULP after policy checks.
20484 				 */
20485 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20486 				return;
20487 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20488 				io = (ipsec_out_t *)ii;
20489 				if (io->ipsec_out_proc_begin) {
20490 					/*
20491 					 * IPsec processing has already started.
20492 					 * Complete it.
20493 					 * IPQoS notes: We don't care what is
20494 					 * in ipsec_out_ill_index since this
20495 					 * won't be processed for IPQoS policies
20496 					 * in ipsec_out_process.
20497 					 */
20498 					ipsec_out_process(q, mp, NULL,
20499 					    io->ipsec_out_ill_index);
20500 					return;
20501 				} else {
20502 					connp = (q->q_next != NULL) ?
20503 					    NULL : Q_TO_CONN(q);
20504 					first_mp = mp;
20505 					mp = mp->b_cont;
20506 					mctl_present = B_TRUE;
20507 				}
20508 				zoneid = io->ipsec_out_zoneid;
20509 				ASSERT(zoneid != ALL_ZONES);
20510 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20511 				/*
20512 				 * It's an IPsec control message requesting
20513 				 * an SADB update to be sent to the IPsec
20514 				 * hardware acceleration capable ills.
20515 				 */
20516 				ipsec_ctl_t *ipsec_ctl =
20517 				    (ipsec_ctl_t *)mp->b_rptr;
20518 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20519 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20520 				mblk_t *cmp = mp->b_cont;
20521 
20522 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20523 				ASSERT(cmp != NULL);
20524 
20525 				freeb(mp);
20526 				ill_ipsec_capab_send_all(satype, cmp, sa,
20527 				    ipst->ips_netstack);
20528 				return;
20529 			} else {
20530 				/*
20531 				 * This must be ARP or special TSOL signaling.
20532 				 */
20533 				ip_wput_nondata(NULL, q, mp, NULL);
20534 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20535 				    "ip_wput_end: q %p (%S)", q, "nondata");
20536 				return;
20537 			}
20538 		} else {
20539 			/*
20540 			 * This must be non-(ARP/AH/ESP) messages.
20541 			 */
20542 			ASSERT(!need_decref);
20543 			ip_wput_nondata(NULL, q, mp, NULL);
20544 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20545 			    "ip_wput_end: q %p (%S)", q, "nondata");
20546 			return;
20547 		}
20548 	} else {
20549 		first_mp = mp;
20550 		mctl_present = B_FALSE;
20551 	}
20552 
20553 	ASSERT(first_mp != NULL);
20554 	/*
20555 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20556 	 * to make sure that this packet goes out on the same interface it
20557 	 * came in. We handle that here.
20558 	 */
20559 	if (mctl_present) {
20560 		uint_t ifindex;
20561 
20562 		io = (ipsec_out_t *)first_mp->b_rptr;
20563 		if (io->ipsec_out_attach_if || io->ipsec_out_ip_nexthop) {
20564 			/*
20565 			 * We may have lost the conn context if we are
20566 			 * coming here from ip_newroute(). Copy the
20567 			 * nexthop information.
20568 			 */
20569 			if (io->ipsec_out_ip_nexthop) {
20570 				ip_nexthop = B_TRUE;
20571 				nexthop_addr = io->ipsec_out_nexthop_addr;
20572 
20573 				ipha = (ipha_t *)mp->b_rptr;
20574 				dst = ipha->ipha_dst;
20575 				goto send_from_ill;
20576 			} else {
20577 				ASSERT(io->ipsec_out_ill_index != 0);
20578 				ifindex = io->ipsec_out_ill_index;
20579 				attach_ill = ill_lookup_on_ifindex(ifindex,
20580 				    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20581 				if (attach_ill == NULL) {
20582 					ASSERT(xmit_ill == NULL);
20583 					ip1dbg(("ip_output: bad ifindex for "
20584 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20585 					    ifindex));
20586 					freemsg(first_mp);
20587 					BUMP_MIB(&ipst->ips_ip_mib,
20588 					    ipIfStatsOutDiscards);
20589 					ASSERT(!need_decref);
20590 					return;
20591 				}
20592 			}
20593 		}
20594 	}
20595 
20596 	ASSERT(xmit_ill == NULL);
20597 
20598 	/* We have a complete IP datagram heading outbound. */
20599 	ipha = (ipha_t *)mp->b_rptr;
20600 
20601 #ifndef SPEED_BEFORE_SAFETY
20602 	/*
20603 	 * Make sure we have a full-word aligned message and that at least
20604 	 * a simple IP header is accessible in the first message.  If not,
20605 	 * try a pullup.
20606 	 */
20607 	if (!OK_32PTR(rptr) ||
20608 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
20609 hdrtoosmall:
20610 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20611 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20612 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20613 			if (first_mp == NULL)
20614 				first_mp = mp;
20615 			goto discard_pkt;
20616 		}
20617 
20618 		/* This function assumes that mp points to an IPv4 packet. */
20619 		if (is_system_labeled() && q->q_next == NULL &&
20620 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20621 		    !connp->conn_ulp_labeled) {
20622 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20623 			    &adjust, connp->conn_mac_exempt, ipst);
20624 			ipha = (ipha_t *)mp->b_rptr;
20625 			if (first_mp != NULL)
20626 				first_mp->b_cont = mp;
20627 			if (err != 0) {
20628 				if (first_mp == NULL)
20629 					first_mp = mp;
20630 				if (err == EINVAL)
20631 					goto icmp_parameter_problem;
20632 				ip2dbg(("ip_wput: label check failed (%d)\n",
20633 				    err));
20634 				goto discard_pkt;
20635 			}
20636 			iplen = ntohs(ipha->ipha_length) + adjust;
20637 			ipha->ipha_length = htons(iplen);
20638 		}
20639 
20640 		ipha = (ipha_t *)mp->b_rptr;
20641 		if (first_mp == NULL) {
20642 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20643 			/*
20644 			 * If we got here because of "goto hdrtoosmall"
20645 			 * We need to attach a IPSEC_OUT.
20646 			 */
20647 			if (connp->conn_out_enforce_policy) {
20648 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
20649 				    NULL, ipha->ipha_protocol,
20650 				    ipst->ips_netstack)) == NULL)) {
20651 					BUMP_MIB(&ipst->ips_ip_mib,
20652 					    ipIfStatsOutDiscards);
20653 					if (need_decref)
20654 						CONN_DEC_REF(connp);
20655 					return;
20656 				} else {
20657 					ASSERT(mp->b_datap->db_type == M_CTL);
20658 					first_mp = mp;
20659 					mp = mp->b_cont;
20660 					mctl_present = B_TRUE;
20661 				}
20662 			} else {
20663 				first_mp = mp;
20664 				mctl_present = B_FALSE;
20665 			}
20666 		}
20667 	}
20668 #endif
20669 
20670 	/* Most of the code below is written for speed, not readability */
20671 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20672 
20673 	/*
20674 	 * If ip_newroute() fails, we're going to need a full
20675 	 * header for the icmp wraparound.
20676 	 */
20677 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20678 		uint_t	v_hlen;
20679 version_hdrlen_check:
20680 		ASSERT(first_mp != NULL);
20681 		v_hlen = V_HLEN;
20682 		/*
20683 		 * siphon off IPv6 packets coming down from transport
20684 		 * layer modules here.
20685 		 * Note: high-order bit carries NUD reachability confirmation
20686 		 */
20687 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20688 			/*
20689 			 * FIXME: assume that callers of ip_output* call
20690 			 * the right version?
20691 			 */
20692 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
20693 			ASSERT(xmit_ill == NULL);
20694 			if (attach_ill != NULL)
20695 				ill_refrele(attach_ill);
20696 			if (need_decref)
20697 				mp->b_flag |= MSGHASREF;
20698 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20699 			return;
20700 		}
20701 
20702 		if ((v_hlen >> 4) != IP_VERSION) {
20703 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20704 			    "ip_wput_end: q %p (%S)", q, "badvers");
20705 			goto discard_pkt;
20706 		}
20707 		/*
20708 		 * Is the header length at least 20 bytes?
20709 		 *
20710 		 * Are there enough bytes accessible in the header?  If
20711 		 * not, try a pullup.
20712 		 */
20713 		v_hlen &= 0xF;
20714 		v_hlen <<= 2;
20715 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20716 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20717 			    "ip_wput_end: q %p (%S)", q, "badlen");
20718 			goto discard_pkt;
20719 		}
20720 		if (v_hlen > (mp->b_wptr - rptr)) {
20721 			if (!pullupmsg(mp, v_hlen)) {
20722 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20723 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20724 				goto discard_pkt;
20725 			}
20726 			ipha = (ipha_t *)mp->b_rptr;
20727 		}
20728 		/*
20729 		 * Move first entry from any source route into ipha_dst and
20730 		 * verify the options
20731 		 */
20732 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
20733 		    zoneid, ipst)) {
20734 			ASSERT(xmit_ill == NULL);
20735 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20736 			if (attach_ill != NULL)
20737 				ill_refrele(attach_ill);
20738 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20739 			    "ip_wput_end: q %p (%S)", q, "badopts");
20740 			if (need_decref)
20741 				CONN_DEC_REF(connp);
20742 			return;
20743 		}
20744 	}
20745 	dst = ipha->ipha_dst;
20746 
20747 	/*
20748 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20749 	 * we have to run the packet through ip_newroute which will take
20750 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
20751 	 * a resolver, or assigning a default gateway, etc.
20752 	 */
20753 	if (CLASSD(dst)) {
20754 		ipif_t	*ipif;
20755 		uint32_t setsrc = 0;
20756 
20757 multicast:
20758 		ASSERT(first_mp != NULL);
20759 		ip2dbg(("ip_wput: CLASSD\n"));
20760 		if (connp == NULL) {
20761 			/*
20762 			 * Use the first good ipif on the ill.
20763 			 * XXX Should this ever happen? (Appears
20764 			 * to show up with just ppp and no ethernet due
20765 			 * to in.rdisc.)
20766 			 * However, ire_send should be able to
20767 			 * call ip_wput_ire directly.
20768 			 *
20769 			 * XXX Also, this can happen for ICMP and other packets
20770 			 * with multicast source addresses.  Perhaps we should
20771 			 * fix things so that we drop the packet in question,
20772 			 * but for now, just run with it.
20773 			 */
20774 			ill_t *ill = (ill_t *)q->q_ptr;
20775 
20776 			/*
20777 			 * Don't honor attach_if for this case. If ill
20778 			 * is part of the group, ipif could belong to
20779 			 * any ill and we cannot maintain attach_ill
20780 			 * and ipif_ill same anymore and the assert
20781 			 * below would fail.
20782 			 */
20783 			if (mctl_present && io->ipsec_out_attach_if) {
20784 				io->ipsec_out_ill_index = 0;
20785 				io->ipsec_out_attach_if = B_FALSE;
20786 				ASSERT(attach_ill != NULL);
20787 				ill_refrele(attach_ill);
20788 				attach_ill = NULL;
20789 			}
20790 
20791 			ASSERT(attach_ill == NULL);
20792 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
20793 			if (ipif == NULL) {
20794 				if (need_decref)
20795 					CONN_DEC_REF(connp);
20796 				freemsg(first_mp);
20797 				return;
20798 			}
20799 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
20800 			    ntohl(dst), ill->ill_name));
20801 		} else {
20802 			/*
20803 			 * The order of precedence is IP_XMIT_IF, IP_PKTINFO
20804 			 * and IP_MULTICAST_IF.
20805 			 * Block comment above this function explains the
20806 			 * locking mechanism used here
20807 			 */
20808 			if (xmit_ill == NULL) {
20809 				xmit_ill = conn_get_held_ill(connp,
20810 				    &connp->conn_xmit_if_ill, &err);
20811 				if (err == ILL_LOOKUP_FAILED) {
20812 					ip1dbg(("ip_wput: No ill for "
20813 					    "IP_XMIT_IF\n"));
20814 					BUMP_MIB(&ipst->ips_ip_mib,
20815 					    ipIfStatsOutNoRoutes);
20816 					goto drop_pkt;
20817 				}
20818 			}
20819 
20820 			if (xmit_ill == NULL) {
20821 				ipif = conn_get_held_ipif(connp,
20822 				    &connp->conn_multicast_ipif, &err);
20823 				if (err == IPIF_LOOKUP_FAILED) {
20824 					ip1dbg(("ip_wput: No ipif for "
20825 					    "multicast\n"));
20826 					BUMP_MIB(&ipst->ips_ip_mib,
20827 					    ipIfStatsOutNoRoutes);
20828 					goto drop_pkt;
20829 				}
20830 			}
20831 			if (xmit_ill != NULL) {
20832 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20833 				if (ipif == NULL) {
20834 					ip1dbg(("ip_wput: No ipif for "
20835 					    "IP_XMIT_IF\n"));
20836 					BUMP_MIB(&ipst->ips_ip_mib,
20837 					    ipIfStatsOutNoRoutes);
20838 					goto drop_pkt;
20839 				}
20840 			} else if (ipif == NULL || ipif->ipif_isv6) {
20841 				/*
20842 				 * We must do this ipif determination here
20843 				 * else we could pass through ip_newroute
20844 				 * and come back here without the conn context.
20845 				 *
20846 				 * Note: we do late binding i.e. we bind to
20847 				 * the interface when the first packet is sent.
20848 				 * For performance reasons we do not rebind on
20849 				 * each packet but keep the binding until the
20850 				 * next IP_MULTICAST_IF option.
20851 				 *
20852 				 * conn_multicast_{ipif,ill} are shared between
20853 				 * IPv4 and IPv6 and AF_INET6 sockets can
20854 				 * send both IPv4 and IPv6 packets. Hence
20855 				 * we have to check that "isv6" matches above.
20856 				 */
20857 				if (ipif != NULL)
20858 					ipif_refrele(ipif);
20859 				ipif = ipif_lookup_group(dst, zoneid, ipst);
20860 				if (ipif == NULL) {
20861 					ip1dbg(("ip_wput: No ipif for "
20862 					    "multicast\n"));
20863 					BUMP_MIB(&ipst->ips_ip_mib,
20864 					    ipIfStatsOutNoRoutes);
20865 					goto drop_pkt;
20866 				}
20867 				err = conn_set_held_ipif(connp,
20868 				    &connp->conn_multicast_ipif, ipif);
20869 				if (err == IPIF_LOOKUP_FAILED) {
20870 					ipif_refrele(ipif);
20871 					ip1dbg(("ip_wput: No ipif for "
20872 					    "multicast\n"));
20873 					BUMP_MIB(&ipst->ips_ip_mib,
20874 					    ipIfStatsOutNoRoutes);
20875 					goto drop_pkt;
20876 				}
20877 			}
20878 		}
20879 		ASSERT(!ipif->ipif_isv6);
20880 		/*
20881 		 * As we may lose the conn by the time we reach ip_wput_ire,
20882 		 * we copy conn_multicast_loop and conn_dontroute on to an
20883 		 * ipsec_out. In case if this datagram goes out secure,
20884 		 * we need the ill_index also. Copy that also into the
20885 		 * ipsec_out.
20886 		 */
20887 		if (mctl_present) {
20888 			io = (ipsec_out_t *)first_mp->b_rptr;
20889 			ASSERT(first_mp->b_datap->db_type == M_CTL);
20890 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
20891 		} else {
20892 			ASSERT(mp == first_mp);
20893 			if ((first_mp = allocb(sizeof (ipsec_info_t),
20894 			    BPRI_HI)) == NULL) {
20895 				ipif_refrele(ipif);
20896 				first_mp = mp;
20897 				goto discard_pkt;
20898 			}
20899 			first_mp->b_datap->db_type = M_CTL;
20900 			first_mp->b_wptr += sizeof (ipsec_info_t);
20901 			/* ipsec_out_secure is B_FALSE now */
20902 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
20903 			io = (ipsec_out_t *)first_mp->b_rptr;
20904 			io->ipsec_out_type = IPSEC_OUT;
20905 			io->ipsec_out_len = sizeof (ipsec_out_t);
20906 			io->ipsec_out_use_global_policy = B_TRUE;
20907 			io->ipsec_out_ns = ipst->ips_netstack;
20908 			first_mp->b_cont = mp;
20909 			mctl_present = B_TRUE;
20910 		}
20911 		if (attach_ill != NULL) {
20912 			ASSERT(attach_ill == ipif->ipif_ill);
20913 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
20914 
20915 			/*
20916 			 * Check if we need an ire that will not be
20917 			 * looked up by anybody else i.e. HIDDEN.
20918 			 */
20919 			if (ill_is_probeonly(attach_ill)) {
20920 				match_flags |= MATCH_IRE_MARK_HIDDEN;
20921 			}
20922 			io->ipsec_out_ill_index =
20923 			    attach_ill->ill_phyint->phyint_ifindex;
20924 			io->ipsec_out_attach_if = B_TRUE;
20925 		} else {
20926 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
20927 			io->ipsec_out_ill_index =
20928 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
20929 		}
20930 		if (connp != NULL) {
20931 			io->ipsec_out_multicast_loop =
20932 			    connp->conn_multicast_loop;
20933 			io->ipsec_out_dontroute = connp->conn_dontroute;
20934 			io->ipsec_out_zoneid = connp->conn_zoneid;
20935 		}
20936 		/*
20937 		 * If the application uses IP_MULTICAST_IF with
20938 		 * different logical addresses of the same ILL, we
20939 		 * need to make sure that the soruce address of
20940 		 * the packet matches the logical IP address used
20941 		 * in the option. We do it by initializing ipha_src
20942 		 * here. This should keep IPsec also happy as
20943 		 * when we return from IPsec processing, we don't
20944 		 * have to worry about getting the right address on
20945 		 * the packet. Thus it is sufficient to look for
20946 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
20947 		 * MATCH_IRE_IPIF.
20948 		 *
20949 		 * NOTE : We need to do it for non-secure case also as
20950 		 * this might go out secure if there is a global policy
20951 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
20952 		 * address, the source should be initialized already and
20953 		 * hence we won't be initializing here.
20954 		 *
20955 		 * As we do not have the ire yet, it is possible that
20956 		 * we set the source address here and then later discover
20957 		 * that the ire implies the source address to be assigned
20958 		 * through the RTF_SETSRC flag.
20959 		 * In that case, the setsrc variable will remind us
20960 		 * that overwritting the source address by the one
20961 		 * of the RTF_SETSRC-flagged ire is allowed.
20962 		 */
20963 		if (ipha->ipha_src == INADDR_ANY &&
20964 		    (connp == NULL || !connp->conn_unspec_src)) {
20965 			ipha->ipha_src = ipif->ipif_src_addr;
20966 			setsrc = RTF_SETSRC;
20967 		}
20968 		/*
20969 		 * Find an IRE which matches the destination and the outgoing
20970 		 * queue (i.e. the outgoing interface.)
20971 		 * For loopback use a unicast IP address for
20972 		 * the ire lookup.
20973 		 */
20974 		if (IS_LOOPBACK(ipif->ipif_ill))
20975 			dst = ipif->ipif_lcl_addr;
20976 
20977 		/*
20978 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
20979 		 * We don't need to lookup ire in ctable as the packet
20980 		 * needs to be sent to the destination through the specified
20981 		 * ill irrespective of ires in the cache table.
20982 		 */
20983 		ire = NULL;
20984 		if (xmit_ill == NULL) {
20985 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
20986 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
20987 		}
20988 
20989 		/*
20990 		 * refrele attach_ill as its not needed anymore.
20991 		 */
20992 		if (attach_ill != NULL) {
20993 			ill_refrele(attach_ill);
20994 			attach_ill = NULL;
20995 		}
20996 
20997 		if (ire == NULL) {
20998 			/*
20999 			 * Multicast loopback and multicast forwarding is
21000 			 * done in ip_wput_ire.
21001 			 *
21002 			 * Mark this packet to make it be delivered to
21003 			 * ip_wput_ire after the new ire has been
21004 			 * created.
21005 			 *
21006 			 * The call to ip_newroute_ipif takes into account
21007 			 * the setsrc reminder. In any case, we take care
21008 			 * of the RTF_MULTIRT flag.
21009 			 */
21010 			mp->b_prev = mp->b_next = NULL;
21011 			if (xmit_ill == NULL ||
21012 			    xmit_ill->ill_ipif_up_count > 0) {
21013 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21014 				    setsrc | RTF_MULTIRT, zoneid, infop);
21015 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21016 				    "ip_wput_end: q %p (%S)", q, "noire");
21017 			} else {
21018 				freemsg(first_mp);
21019 			}
21020 			ipif_refrele(ipif);
21021 			if (xmit_ill != NULL)
21022 				ill_refrele(xmit_ill);
21023 			if (need_decref)
21024 				CONN_DEC_REF(connp);
21025 			return;
21026 		}
21027 
21028 		ipif_refrele(ipif);
21029 		ipif = NULL;
21030 		ASSERT(xmit_ill == NULL);
21031 
21032 		/*
21033 		 * Honor the RTF_SETSRC flag for multicast packets,
21034 		 * if allowed by the setsrc reminder.
21035 		 */
21036 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21037 			ipha->ipha_src = ire->ire_src_addr;
21038 		}
21039 
21040 		/*
21041 		 * Unconditionally force the TTL to 1 for
21042 		 * multirouted multicast packets:
21043 		 * multirouted multicast should not cross
21044 		 * multicast routers.
21045 		 */
21046 		if (ire->ire_flags & RTF_MULTIRT) {
21047 			if (ipha->ipha_ttl > 1) {
21048 				ip2dbg(("ip_wput: forcing multicast "
21049 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21050 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21051 				ipha->ipha_ttl = 1;
21052 			}
21053 		}
21054 	} else {
21055 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
21056 		if ((ire != NULL) && (ire->ire_type &
21057 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21058 			ignore_dontroute = B_TRUE;
21059 			ignore_nexthop = B_TRUE;
21060 		}
21061 		if (ire != NULL) {
21062 			ire_refrele(ire);
21063 			ire = NULL;
21064 		}
21065 		/*
21066 		 * Guard against coming in from arp in which case conn is NULL.
21067 		 * Also guard against non M_DATA with dontroute set but
21068 		 * destined to local, loopback or broadcast addresses.
21069 		 */
21070 		if (connp != NULL && connp->conn_dontroute &&
21071 		    !ignore_dontroute) {
21072 dontroute:
21073 			/*
21074 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21075 			 * routing protocols from seeing false direct
21076 			 * connectivity.
21077 			 */
21078 			ipha->ipha_ttl = 1;
21079 			/*
21080 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
21081 			 * along with SO_DONTROUTE, higher precedence is
21082 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
21083 			 */
21084 			if (connp->conn_xmit_if_ill == NULL) {
21085 				/* If suitable ipif not found, drop packet */
21086 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid,
21087 				    ipst);
21088 				if (dst_ipif == NULL) {
21089 					ip1dbg(("ip_wput: no route for "
21090 					    "dst using SO_DONTROUTE\n"));
21091 					BUMP_MIB(&ipst->ips_ip_mib,
21092 					    ipIfStatsOutNoRoutes);
21093 					mp->b_prev = mp->b_next = NULL;
21094 					if (first_mp == NULL)
21095 						first_mp = mp;
21096 					goto drop_pkt;
21097 				} else {
21098 					/*
21099 					 * If suitable ipif has been found, set
21100 					 * xmit_ill to the corresponding
21101 					 * ipif_ill because we'll be following
21102 					 * the IP_XMIT_IF logic.
21103 					 */
21104 					ASSERT(xmit_ill == NULL);
21105 					xmit_ill = dst_ipif->ipif_ill;
21106 					mutex_enter(&xmit_ill->ill_lock);
21107 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
21108 						mutex_exit(&xmit_ill->ill_lock);
21109 						xmit_ill = NULL;
21110 						ipif_refrele(dst_ipif);
21111 						ip1dbg(("ip_wput: no route for"
21112 						    " dst using"
21113 						    " SO_DONTROUTE\n"));
21114 						BUMP_MIB(&ipst->ips_ip_mib,
21115 						    ipIfStatsOutNoRoutes);
21116 						mp->b_prev = mp->b_next = NULL;
21117 						if (first_mp == NULL)
21118 							first_mp = mp;
21119 						goto drop_pkt;
21120 					}
21121 					ill_refhold_locked(xmit_ill);
21122 					mutex_exit(&xmit_ill->ill_lock);
21123 					ipif_refrele(dst_ipif);
21124 				}
21125 			}
21126 
21127 		}
21128 		/*
21129 		 * If we are bound to IPIF_NOFAILOVER address, look for
21130 		 * an IRE_CACHE matching the ill.
21131 		 */
21132 send_from_ill:
21133 		if (attach_ill != NULL) {
21134 			ipif_t	*attach_ipif;
21135 
21136 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21137 
21138 			/*
21139 			 * Check if we need an ire that will not be
21140 			 * looked up by anybody else i.e. HIDDEN.
21141 			 */
21142 			if (ill_is_probeonly(attach_ill)) {
21143 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21144 			}
21145 
21146 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
21147 			if (attach_ipif == NULL) {
21148 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
21149 				goto discard_pkt;
21150 			}
21151 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
21152 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21153 			ipif_refrele(attach_ipif);
21154 		} else if (xmit_ill != NULL || (connp != NULL &&
21155 		    connp->conn_xmit_if_ill != NULL)) {
21156 			/*
21157 			 * Mark this packet as originated locally
21158 			 */
21159 			mp->b_prev = mp->b_next = NULL;
21160 			/*
21161 			 * xmit_ill could be NULL if SO_DONTROUTE
21162 			 * is also set.
21163 			 */
21164 			if (xmit_ill == NULL) {
21165 				xmit_ill = conn_get_held_ill(connp,
21166 				    &connp->conn_xmit_if_ill, &err);
21167 				if (err == ILL_LOOKUP_FAILED) {
21168 					BUMP_MIB(&ipst->ips_ip_mib,
21169 					    ipIfStatsOutDiscards);
21170 					if (need_decref)
21171 						CONN_DEC_REF(connp);
21172 					freemsg(first_mp);
21173 					return;
21174 				}
21175 				if (xmit_ill == NULL) {
21176 					if (connp->conn_dontroute)
21177 						goto dontroute;
21178 					goto send_from_ill;
21179 				}
21180 			}
21181 			/*
21182 			 * Could be SO_DONTROUTE case also.
21183 			 * check at least one interface is UP as
21184 			 * specified by this ILL
21185 			 */
21186 			if (xmit_ill->ill_ipif_up_count > 0) {
21187 				ipif_t *ipif;
21188 
21189 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21190 				if (ipif == NULL) {
21191 					ip1dbg(("ip_output: "
21192 					    "xmit_ill NULL ipif\n"));
21193 					goto drop_pkt;
21194 				}
21195 				/*
21196 				 * Look for a ire that is part of the group,
21197 				 * if found use it else call ip_newroute_ipif.
21198 				 * IPCL_ZONEID is not used for matching because
21199 				 * IP_ALLZONES option is valid only when the
21200 				 * ill is accessible from all zones i.e has a
21201 				 * valid ipif in all zones.
21202 				 */
21203 				match_flags = MATCH_IRE_ILL_GROUP |
21204 				    MATCH_IRE_SECATTR;
21205 				ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21206 				    MBLK_GETLABEL(mp), match_flags, ipst);
21207 				/*
21208 				 * If an ire exists use it or else create
21209 				 * an ire but don't add it to the cache.
21210 				 * Adding an ire may cause issues with
21211 				 * asymmetric routing.
21212 				 * In case of multiroute always act as if
21213 				 * ire does not exist.
21214 				 */
21215 				if (ire == NULL ||
21216 				    ire->ire_flags & RTF_MULTIRT) {
21217 					if (ire != NULL)
21218 						ire_refrele(ire);
21219 					ip_newroute_ipif(q, first_mp, ipif,
21220 					    dst, connp, 0, zoneid, infop);
21221 					ipif_refrele(ipif);
21222 					ip1dbg(("ip_wput: ip_unicast_if\n"));
21223 					ill_refrele(xmit_ill);
21224 					if (need_decref)
21225 						CONN_DEC_REF(connp);
21226 					return;
21227 				}
21228 				ipif_refrele(ipif);
21229 			} else {
21230 				goto drop_pkt;
21231 			}
21232 		} else if (ip_nexthop || (connp != NULL &&
21233 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21234 			if (!ip_nexthop) {
21235 				ip_nexthop = B_TRUE;
21236 				nexthop_addr = connp->conn_nexthop_v4;
21237 			}
21238 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21239 			    MATCH_IRE_GW;
21240 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21241 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21242 		} else {
21243 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp),
21244 			    ipst);
21245 		}
21246 		if (!ire) {
21247 			/*
21248 			 * Make sure we don't load spread if this
21249 			 * is IPIF_NOFAILOVER case.
21250 			 */
21251 			if ((attach_ill != NULL) ||
21252 			    (ip_nexthop && !ignore_nexthop)) {
21253 				if (mctl_present) {
21254 					io = (ipsec_out_t *)first_mp->b_rptr;
21255 					ASSERT(first_mp->b_datap->db_type ==
21256 					    M_CTL);
21257 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21258 				} else {
21259 					ASSERT(mp == first_mp);
21260 					first_mp = allocb(
21261 					    sizeof (ipsec_info_t), BPRI_HI);
21262 					if (first_mp == NULL) {
21263 						first_mp = mp;
21264 						goto discard_pkt;
21265 					}
21266 					first_mp->b_datap->db_type = M_CTL;
21267 					first_mp->b_wptr +=
21268 					    sizeof (ipsec_info_t);
21269 					/* ipsec_out_secure is B_FALSE now */
21270 					bzero(first_mp->b_rptr,
21271 					    sizeof (ipsec_info_t));
21272 					io = (ipsec_out_t *)first_mp->b_rptr;
21273 					io->ipsec_out_type = IPSEC_OUT;
21274 					io->ipsec_out_len =
21275 					    sizeof (ipsec_out_t);
21276 					io->ipsec_out_use_global_policy =
21277 					    B_TRUE;
21278 					io->ipsec_out_ns = ipst->ips_netstack;
21279 					first_mp->b_cont = mp;
21280 					mctl_present = B_TRUE;
21281 				}
21282 				if (attach_ill != NULL) {
21283 					io->ipsec_out_ill_index = attach_ill->
21284 					    ill_phyint->phyint_ifindex;
21285 					io->ipsec_out_attach_if = B_TRUE;
21286 				} else {
21287 					io->ipsec_out_ip_nexthop = ip_nexthop;
21288 					io->ipsec_out_nexthop_addr =
21289 					    nexthop_addr;
21290 				}
21291 			}
21292 noirefound:
21293 			/*
21294 			 * Mark this packet as having originated on
21295 			 * this machine.  This will be noted in
21296 			 * ire_add_then_send, which needs to know
21297 			 * whether to run it back through ip_wput or
21298 			 * ip_rput following successful resolution.
21299 			 */
21300 			mp->b_prev = NULL;
21301 			mp->b_next = NULL;
21302 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21303 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21304 			    "ip_wput_end: q %p (%S)", q, "newroute");
21305 			if (attach_ill != NULL)
21306 				ill_refrele(attach_ill);
21307 			if (xmit_ill != NULL)
21308 				ill_refrele(xmit_ill);
21309 			if (need_decref)
21310 				CONN_DEC_REF(connp);
21311 			return;
21312 		}
21313 	}
21314 
21315 	/* We now know where we are going with it. */
21316 
21317 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21318 	    "ip_wput_end: q %p (%S)", q, "end");
21319 
21320 	/*
21321 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21322 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21323 	 */
21324 	if (ire->ire_flags & RTF_MULTIRT) {
21325 		/*
21326 		 * Force the TTL of multirouted packets if required.
21327 		 * The TTL of such packets is bounded by the
21328 		 * ip_multirt_ttl ndd variable.
21329 		 */
21330 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21331 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21332 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21333 			    "(was %d), dst 0x%08x\n",
21334 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21335 			    ntohl(ire->ire_addr)));
21336 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21337 		}
21338 		/*
21339 		 * At this point, we check to see if there are any pending
21340 		 * unresolved routes. ire_multirt_resolvable()
21341 		 * checks in O(n) that all IRE_OFFSUBNET ire
21342 		 * entries for the packet's destination and
21343 		 * flagged RTF_MULTIRT are currently resolved.
21344 		 * If some remain unresolved, we make a copy
21345 		 * of the current message. It will be used
21346 		 * to initiate additional route resolutions.
21347 		 */
21348 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21349 		    MBLK_GETLABEL(first_mp), ipst);
21350 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21351 		    "multirt_need_resolve %d, first_mp %p\n",
21352 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21353 		if (multirt_need_resolve) {
21354 			copy_mp = copymsg(first_mp);
21355 			if (copy_mp != NULL) {
21356 				MULTIRT_DEBUG_TAG(copy_mp);
21357 			}
21358 		}
21359 	}
21360 
21361 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21362 	/*
21363 	 * Try to resolve another multiroute if
21364 	 * ire_multirt_resolvable() deemed it necessary.
21365 	 * At this point, we need to distinguish
21366 	 * multicasts from other packets. For multicasts,
21367 	 * we call ip_newroute_ipif() and request that both
21368 	 * multirouting and setsrc flags are checked.
21369 	 */
21370 	if (copy_mp != NULL) {
21371 		if (CLASSD(dst)) {
21372 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21373 			if (ipif) {
21374 				ASSERT(infop->ip_opt_ill_index == 0);
21375 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21376 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21377 				ipif_refrele(ipif);
21378 			} else {
21379 				MULTIRT_DEBUG_UNTAG(copy_mp);
21380 				freemsg(copy_mp);
21381 				copy_mp = NULL;
21382 			}
21383 		} else {
21384 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21385 		}
21386 	}
21387 	if (attach_ill != NULL)
21388 		ill_refrele(attach_ill);
21389 	if (xmit_ill != NULL)
21390 		ill_refrele(xmit_ill);
21391 	if (need_decref)
21392 		CONN_DEC_REF(connp);
21393 	return;
21394 
21395 icmp_parameter_problem:
21396 	/* could not have originated externally */
21397 	ASSERT(mp->b_prev == NULL);
21398 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21399 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21400 		/* it's the IP header length that's in trouble */
21401 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21402 		first_mp = NULL;
21403 	}
21404 
21405 discard_pkt:
21406 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21407 drop_pkt:
21408 	ip1dbg(("ip_wput: dropped packet\n"));
21409 	if (ire != NULL)
21410 		ire_refrele(ire);
21411 	if (need_decref)
21412 		CONN_DEC_REF(connp);
21413 	freemsg(first_mp);
21414 	if (attach_ill != NULL)
21415 		ill_refrele(attach_ill);
21416 	if (xmit_ill != NULL)
21417 		ill_refrele(xmit_ill);
21418 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21419 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21420 }
21421 
21422 /*
21423  * If this is a conn_t queue, then we pass in the conn. This includes the
21424  * zoneid.
21425  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21426  * in which case we use the global zoneid since those are all part of
21427  * the global zone.
21428  */
21429 void
21430 ip_wput(queue_t *q, mblk_t *mp)
21431 {
21432 	if (CONN_Q(q))
21433 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21434 	else
21435 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21436 }
21437 
21438 /*
21439  *
21440  * The following rules must be observed when accessing any ipif or ill
21441  * that has been cached in the conn. Typically conn_nofailover_ill,
21442  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
21443  *
21444  * Access: The ipif or ill pointed to from the conn can be accessed under
21445  * the protection of the conn_lock or after it has been refheld under the
21446  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21447  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21448  * The reason for this is that a concurrent unplumb could actually be
21449  * cleaning up these cached pointers by walking the conns and might have
21450  * finished cleaning up the conn in question. The macros check that an
21451  * unplumb has not yet started on the ipif or ill.
21452  *
21453  * Caching: An ipif or ill pointer may be cached in the conn only after
21454  * making sure that an unplumb has not started. So the caching is done
21455  * while holding both the conn_lock and the ill_lock and after using the
21456  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21457  * flag before starting the cleanup of conns.
21458  *
21459  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21460  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21461  * or a reference to the ipif or a reference to an ire that references the
21462  * ipif. An ipif does not change its ill except for failover/failback. Since
21463  * failover/failback happens only after bringing down the ipif and making sure
21464  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
21465  * the above holds.
21466  */
21467 ipif_t *
21468 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21469 {
21470 	ipif_t	*ipif;
21471 	ill_t	*ill;
21472 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21473 
21474 	*err = 0;
21475 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21476 	mutex_enter(&connp->conn_lock);
21477 	ipif = *ipifp;
21478 	if (ipif != NULL) {
21479 		ill = ipif->ipif_ill;
21480 		mutex_enter(&ill->ill_lock);
21481 		if (IPIF_CAN_LOOKUP(ipif)) {
21482 			ipif_refhold_locked(ipif);
21483 			mutex_exit(&ill->ill_lock);
21484 			mutex_exit(&connp->conn_lock);
21485 			rw_exit(&ipst->ips_ill_g_lock);
21486 			return (ipif);
21487 		} else {
21488 			*err = IPIF_LOOKUP_FAILED;
21489 		}
21490 		mutex_exit(&ill->ill_lock);
21491 	}
21492 	mutex_exit(&connp->conn_lock);
21493 	rw_exit(&ipst->ips_ill_g_lock);
21494 	return (NULL);
21495 }
21496 
21497 ill_t *
21498 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21499 {
21500 	ill_t	*ill;
21501 
21502 	*err = 0;
21503 	mutex_enter(&connp->conn_lock);
21504 	ill = *illp;
21505 	if (ill != NULL) {
21506 		mutex_enter(&ill->ill_lock);
21507 		if (ILL_CAN_LOOKUP(ill)) {
21508 			ill_refhold_locked(ill);
21509 			mutex_exit(&ill->ill_lock);
21510 			mutex_exit(&connp->conn_lock);
21511 			return (ill);
21512 		} else {
21513 			*err = ILL_LOOKUP_FAILED;
21514 		}
21515 		mutex_exit(&ill->ill_lock);
21516 	}
21517 	mutex_exit(&connp->conn_lock);
21518 	return (NULL);
21519 }
21520 
21521 static int
21522 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21523 {
21524 	ill_t	*ill;
21525 
21526 	ill = ipif->ipif_ill;
21527 	mutex_enter(&connp->conn_lock);
21528 	mutex_enter(&ill->ill_lock);
21529 	if (IPIF_CAN_LOOKUP(ipif)) {
21530 		*ipifp = ipif;
21531 		mutex_exit(&ill->ill_lock);
21532 		mutex_exit(&connp->conn_lock);
21533 		return (0);
21534 	}
21535 	mutex_exit(&ill->ill_lock);
21536 	mutex_exit(&connp->conn_lock);
21537 	return (IPIF_LOOKUP_FAILED);
21538 }
21539 
21540 /*
21541  * This is called if the outbound datagram needs fragmentation.
21542  *
21543  * NOTE : This function does not ire_refrele the ire argument passed in.
21544  */
21545 static void
21546 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21547     ip_stack_t *ipst)
21548 {
21549 	ipha_t		*ipha;
21550 	mblk_t		*mp;
21551 	uint32_t	v_hlen_tos_len;
21552 	uint32_t	max_frag;
21553 	uint32_t	frag_flag;
21554 	boolean_t	dont_use;
21555 
21556 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21557 		mp = ipsec_mp->b_cont;
21558 	} else {
21559 		mp = ipsec_mp;
21560 	}
21561 
21562 	ipha = (ipha_t *)mp->b_rptr;
21563 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21564 
21565 #ifdef	_BIG_ENDIAN
21566 #define	V_HLEN	(v_hlen_tos_len >> 24)
21567 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21568 #else
21569 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21570 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21571 #endif
21572 
21573 #ifndef SPEED_BEFORE_SAFETY
21574 	/*
21575 	 * Check that ipha_length is consistent with
21576 	 * the mblk length
21577 	 */
21578 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21579 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21580 		    LENGTH, msgdsize(mp)));
21581 		freemsg(ipsec_mp);
21582 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21583 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21584 		    "packet length mismatch");
21585 		return;
21586 	}
21587 #endif
21588 	/*
21589 	 * Don't use frag_flag if pre-built packet or source
21590 	 * routed or if multicast (since multicast packets do not solicit
21591 	 * ICMP "packet too big" messages). Get the values of
21592 	 * max_frag and frag_flag atomically by acquiring the
21593 	 * ire_lock.
21594 	 */
21595 	mutex_enter(&ire->ire_lock);
21596 	max_frag = ire->ire_max_frag;
21597 	frag_flag = ire->ire_frag_flag;
21598 	mutex_exit(&ire->ire_lock);
21599 
21600 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21601 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21602 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21603 
21604 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21605 	    (dont_use ? 0 : frag_flag), zoneid, ipst);
21606 }
21607 
21608 /*
21609  * Used for deciding the MSS size for the upper layer. Thus
21610  * we need to check the outbound policy values in the conn.
21611  */
21612 int
21613 conn_ipsec_length(conn_t *connp)
21614 {
21615 	ipsec_latch_t *ipl;
21616 
21617 	ipl = connp->conn_latch;
21618 	if (ipl == NULL)
21619 		return (0);
21620 
21621 	if (ipl->ipl_out_policy == NULL)
21622 		return (0);
21623 
21624 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21625 }
21626 
21627 /*
21628  * Returns an estimate of the IPsec headers size. This is used if
21629  * we don't want to call into IPsec to get the exact size.
21630  */
21631 int
21632 ipsec_out_extra_length(mblk_t *ipsec_mp)
21633 {
21634 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21635 	ipsec_action_t *a;
21636 
21637 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21638 	if (!io->ipsec_out_secure)
21639 		return (0);
21640 
21641 	a = io->ipsec_out_act;
21642 
21643 	if (a == NULL) {
21644 		ASSERT(io->ipsec_out_policy != NULL);
21645 		a = io->ipsec_out_policy->ipsp_act;
21646 	}
21647 	ASSERT(a != NULL);
21648 
21649 	return (a->ipa_ovhd);
21650 }
21651 
21652 /*
21653  * Returns an estimate of the IPsec headers size. This is used if
21654  * we don't want to call into IPsec to get the exact size.
21655  */
21656 int
21657 ipsec_in_extra_length(mblk_t *ipsec_mp)
21658 {
21659 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21660 	ipsec_action_t *a;
21661 
21662 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21663 
21664 	a = ii->ipsec_in_action;
21665 	return (a == NULL ? 0 : a->ipa_ovhd);
21666 }
21667 
21668 /*
21669  * If there are any source route options, return the true final
21670  * destination. Otherwise, return the destination.
21671  */
21672 ipaddr_t
21673 ip_get_dst(ipha_t *ipha)
21674 {
21675 	ipoptp_t	opts;
21676 	uchar_t		*opt;
21677 	uint8_t		optval;
21678 	uint8_t		optlen;
21679 	ipaddr_t	dst;
21680 	uint32_t off;
21681 
21682 	dst = ipha->ipha_dst;
21683 
21684 	if (IS_SIMPLE_IPH(ipha))
21685 		return (dst);
21686 
21687 	for (optval = ipoptp_first(&opts, ipha);
21688 	    optval != IPOPT_EOL;
21689 	    optval = ipoptp_next(&opts)) {
21690 		opt = opts.ipoptp_cur;
21691 		optlen = opts.ipoptp_len;
21692 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21693 		switch (optval) {
21694 		case IPOPT_SSRR:
21695 		case IPOPT_LSRR:
21696 			off = opt[IPOPT_OFFSET];
21697 			/*
21698 			 * If one of the conditions is true, it means
21699 			 * end of options and dst already has the right
21700 			 * value.
21701 			 */
21702 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21703 				off = optlen - IP_ADDR_LEN;
21704 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21705 			}
21706 			return (dst);
21707 		default:
21708 			break;
21709 		}
21710 	}
21711 
21712 	return (dst);
21713 }
21714 
21715 mblk_t *
21716 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21717     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21718 {
21719 	ipsec_out_t	*io;
21720 	mblk_t		*first_mp;
21721 	boolean_t policy_present;
21722 	ip_stack_t	*ipst;
21723 	ipsec_stack_t	*ipss;
21724 
21725 	ASSERT(ire != NULL);
21726 	ipst = ire->ire_ipst;
21727 	ipss = ipst->ips_netstack->netstack_ipsec;
21728 
21729 	first_mp = mp;
21730 	if (mp->b_datap->db_type == M_CTL) {
21731 		io = (ipsec_out_t *)first_mp->b_rptr;
21732 		/*
21733 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21734 		 *
21735 		 * 1) There is per-socket policy (including cached global
21736 		 *    policy) or a policy on the IP-in-IP tunnel.
21737 		 * 2) There is no per-socket policy, but it is
21738 		 *    a multicast packet that needs to go out
21739 		 *    on a specific interface. This is the case
21740 		 *    where (ip_wput and ip_wput_multicast) attaches
21741 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21742 		 *
21743 		 * In case (2) we check with global policy to
21744 		 * see if there is a match and set the ill_index
21745 		 * appropriately so that we can lookup the ire
21746 		 * properly in ip_wput_ipsec_out.
21747 		 */
21748 
21749 		/*
21750 		 * ipsec_out_use_global_policy is set to B_FALSE
21751 		 * in ipsec_in_to_out(). Refer to that function for
21752 		 * details.
21753 		 */
21754 		if ((io->ipsec_out_latch == NULL) &&
21755 		    (io->ipsec_out_use_global_policy)) {
21756 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21757 			    ire, connp, unspec_src, zoneid));
21758 		}
21759 		if (!io->ipsec_out_secure) {
21760 			/*
21761 			 * If this is not a secure packet, drop
21762 			 * the IPSEC_OUT mp and treat it as a clear
21763 			 * packet. This happens when we are sending
21764 			 * a ICMP reply back to a clear packet. See
21765 			 * ipsec_in_to_out() for details.
21766 			 */
21767 			mp = first_mp->b_cont;
21768 			freeb(first_mp);
21769 		}
21770 		return (mp);
21771 	}
21772 	/*
21773 	 * See whether we need to attach a global policy here. We
21774 	 * don't depend on the conn (as it could be null) for deciding
21775 	 * what policy this datagram should go through because it
21776 	 * should have happened in ip_wput if there was some
21777 	 * policy. This normally happens for connections which are not
21778 	 * fully bound preventing us from caching policies in
21779 	 * ip_bind. Packets coming from the TCP listener/global queue
21780 	 * - which are non-hard_bound - could also be affected by
21781 	 * applying policy here.
21782 	 *
21783 	 * If this packet is coming from tcp global queue or listener,
21784 	 * we will be applying policy here.  This may not be *right*
21785 	 * if these packets are coming from the detached connection as
21786 	 * it could have gone in clear before. This happens only if a
21787 	 * TCP connection started when there is no policy and somebody
21788 	 * added policy before it became detached. Thus packets of the
21789 	 * detached connection could go out secure and the other end
21790 	 * would drop it because it will be expecting in clear. The
21791 	 * converse is not true i.e if somebody starts a TCP
21792 	 * connection and deletes the policy, all the packets will
21793 	 * still go out with the policy that existed before deleting
21794 	 * because ip_unbind sends up policy information which is used
21795 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21796 	 * TCP to attach a dummy IPSEC_OUT and set
21797 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21798 	 * affect performance for normal cases, we are not doing it.
21799 	 * Thus, set policy before starting any TCP connections.
21800 	 *
21801 	 * NOTE - We might apply policy even for a hard bound connection
21802 	 * - for which we cached policy in ip_bind - if somebody added
21803 	 * global policy after we inherited the policy in ip_bind.
21804 	 * This means that the packets that were going out in clear
21805 	 * previously would start going secure and hence get dropped
21806 	 * on the other side. To fix this, TCP attaches a dummy
21807 	 * ipsec_out and make sure that we don't apply global policy.
21808 	 */
21809 	if (ipha != NULL)
21810 		policy_present = ipss->ipsec_outbound_v4_policy_present;
21811 	else
21812 		policy_present = ipss->ipsec_outbound_v6_policy_present;
21813 	if (!policy_present)
21814 		return (mp);
21815 
21816 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21817 	    zoneid));
21818 }
21819 
21820 ire_t *
21821 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
21822 {
21823 	ipaddr_t addr;
21824 	ire_t *save_ire;
21825 	irb_t *irb;
21826 	ill_group_t *illgrp;
21827 	int	err;
21828 
21829 	save_ire = ire;
21830 	addr = ire->ire_addr;
21831 
21832 	ASSERT(ire->ire_type == IRE_BROADCAST);
21833 
21834 	illgrp = connp->conn_outgoing_ill->ill_group;
21835 	if (illgrp == NULL) {
21836 		*conn_outgoing_ill = conn_get_held_ill(connp,
21837 		    &connp->conn_outgoing_ill, &err);
21838 		if (err == ILL_LOOKUP_FAILED) {
21839 			ire_refrele(save_ire);
21840 			return (NULL);
21841 		}
21842 		return (save_ire);
21843 	}
21844 	/*
21845 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
21846 	 * If it is part of the group, we need to send on the ire
21847 	 * that has been cleared of IRE_MARK_NORECV and that belongs
21848 	 * to this group. This is okay as IP_BOUND_IF really means
21849 	 * any ill in the group. We depend on the fact that the
21850 	 * first ire in the group is always cleared of IRE_MARK_NORECV
21851 	 * if such an ire exists. This is possible only if you have
21852 	 * at least one ill in the group that has not failed.
21853 	 *
21854 	 * First get to the ire that matches the address and group.
21855 	 *
21856 	 * We don't look for an ire with a matching zoneid because a given zone
21857 	 * won't always have broadcast ires on all ills in the group.
21858 	 */
21859 	irb = ire->ire_bucket;
21860 	rw_enter(&irb->irb_lock, RW_READER);
21861 	if (ire->ire_marks & IRE_MARK_NORECV) {
21862 		/*
21863 		 * If the current zone only has an ire broadcast for this
21864 		 * address marked NORECV, the ire we want is ahead in the
21865 		 * bucket, so we look it up deliberately ignoring the zoneid.
21866 		 */
21867 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
21868 			if (ire->ire_addr != addr)
21869 				continue;
21870 			/* skip over deleted ires */
21871 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
21872 				continue;
21873 		}
21874 	}
21875 	while (ire != NULL) {
21876 		/*
21877 		 * If a new interface is coming up, we could end up
21878 		 * seeing the loopback ire and the non-loopback ire
21879 		 * may not have been added yet. So check for ire_stq
21880 		 */
21881 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
21882 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
21883 			break;
21884 		}
21885 		ire = ire->ire_next;
21886 	}
21887 	if (ire != NULL && ire->ire_addr == addr &&
21888 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
21889 		IRE_REFHOLD(ire);
21890 		rw_exit(&irb->irb_lock);
21891 		ire_refrele(save_ire);
21892 		*conn_outgoing_ill = ire_to_ill(ire);
21893 		/*
21894 		 * Refhold the ill to make the conn_outgoing_ill
21895 		 * independent of the ire. ip_wput_ire goes in a loop
21896 		 * and may refrele the ire. Since we have an ire at this
21897 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
21898 		 */
21899 		ill_refhold(*conn_outgoing_ill);
21900 		return (ire);
21901 	}
21902 	rw_exit(&irb->irb_lock);
21903 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
21904 	/*
21905 	 * If we can't find a suitable ire, return the original ire.
21906 	 */
21907 	return (save_ire);
21908 }
21909 
21910 /*
21911  * This function does the ire_refrele of the ire passed in as the
21912  * argument. As this function looks up more ires i.e broadcast ires,
21913  * it needs to REFRELE them. Currently, for simplicity we don't
21914  * differentiate the one passed in and looked up here. We always
21915  * REFRELE.
21916  * IPQoS Notes:
21917  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
21918  * IPsec packets are done in ipsec_out_process.
21919  *
21920  */
21921 void
21922 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
21923     zoneid_t zoneid)
21924 {
21925 	ipha_t		*ipha;
21926 #define	rptr	((uchar_t *)ipha)
21927 	queue_t		*stq;
21928 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
21929 	uint32_t	v_hlen_tos_len;
21930 	uint32_t	ttl_protocol;
21931 	ipaddr_t	src;
21932 	ipaddr_t	dst;
21933 	uint32_t	cksum;
21934 	ipaddr_t	orig_src;
21935 	ire_t		*ire1;
21936 	mblk_t		*next_mp;
21937 	uint_t		hlen;
21938 	uint16_t	*up;
21939 	uint32_t	max_frag = ire->ire_max_frag;
21940 	ill_t		*ill = ire_to_ill(ire);
21941 	int		clusterwide;
21942 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
21943 	int		ipsec_len;
21944 	mblk_t		*first_mp;
21945 	ipsec_out_t	*io;
21946 	boolean_t	conn_dontroute;		/* conn value for multicast */
21947 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
21948 	boolean_t	multicast_forward;	/* Should we forward ? */
21949 	boolean_t	unspec_src;
21950 	ill_t		*conn_outgoing_ill = NULL;
21951 	ill_t		*ire_ill;
21952 	ill_t		*ire1_ill;
21953 	ill_t		*out_ill;
21954 	uint32_t 	ill_index = 0;
21955 	boolean_t	multirt_send = B_FALSE;
21956 	int		err;
21957 	ipxmit_state_t	pktxmit_state;
21958 	ip_stack_t	*ipst = ire->ire_ipst;
21959 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
21960 
21961 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
21962 	    "ip_wput_ire_start: q %p", q);
21963 
21964 	multicast_forward = B_FALSE;
21965 	unspec_src = (connp != NULL && connp->conn_unspec_src);
21966 
21967 	if (ire->ire_flags & RTF_MULTIRT) {
21968 		/*
21969 		 * Multirouting case. The bucket where ire is stored
21970 		 * probably holds other RTF_MULTIRT flagged ire
21971 		 * to the destination. In this call to ip_wput_ire,
21972 		 * we attempt to send the packet through all
21973 		 * those ires. Thus, we first ensure that ire is the
21974 		 * first RTF_MULTIRT ire in the bucket,
21975 		 * before walking the ire list.
21976 		 */
21977 		ire_t *first_ire;
21978 		irb_t *irb = ire->ire_bucket;
21979 		ASSERT(irb != NULL);
21980 
21981 		/* Make sure we do not omit any multiroute ire. */
21982 		IRB_REFHOLD(irb);
21983 		for (first_ire = irb->irb_ire;
21984 		    first_ire != NULL;
21985 		    first_ire = first_ire->ire_next) {
21986 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
21987 			    (first_ire->ire_addr == ire->ire_addr) &&
21988 			    !(first_ire->ire_marks &
21989 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
21990 				break;
21991 			}
21992 		}
21993 
21994 		if ((first_ire != NULL) && (first_ire != ire)) {
21995 			IRE_REFHOLD(first_ire);
21996 			ire_refrele(ire);
21997 			ire = first_ire;
21998 			ill = ire_to_ill(ire);
21999 		}
22000 		IRB_REFRELE(irb);
22001 	}
22002 
22003 	/*
22004 	 * conn_outgoing_ill is used only in the broadcast loop.
22005 	 * for performance we don't grab the mutexs in the fastpath
22006 	 */
22007 	if ((connp != NULL) &&
22008 	    (connp->conn_xmit_if_ill == NULL) &&
22009 	    (ire->ire_type == IRE_BROADCAST) &&
22010 	    ((connp->conn_nofailover_ill != NULL) ||
22011 	    (connp->conn_outgoing_ill != NULL))) {
22012 		/*
22013 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
22014 		 * option. So, see if this endpoint is bound to a
22015 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
22016 		 * that if the interface is failed, we will still send
22017 		 * the packet on the same ill which is what we want.
22018 		 */
22019 		conn_outgoing_ill = conn_get_held_ill(connp,
22020 		    &connp->conn_nofailover_ill, &err);
22021 		if (err == ILL_LOOKUP_FAILED) {
22022 			ire_refrele(ire);
22023 			freemsg(mp);
22024 			return;
22025 		}
22026 		if (conn_outgoing_ill == NULL) {
22027 			/*
22028 			 * Choose a good ill in the group to send the
22029 			 * packets on.
22030 			 */
22031 			ire = conn_set_outgoing_ill(connp, ire,
22032 			    &conn_outgoing_ill);
22033 			if (ire == NULL) {
22034 				freemsg(mp);
22035 				return;
22036 			}
22037 		}
22038 	}
22039 
22040 	if (mp->b_datap->db_type != M_CTL) {
22041 		ipha = (ipha_t *)mp->b_rptr;
22042 	} else {
22043 		io = (ipsec_out_t *)mp->b_rptr;
22044 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22045 		ASSERT(zoneid == io->ipsec_out_zoneid);
22046 		ASSERT(zoneid != ALL_ZONES);
22047 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22048 		dst = ipha->ipha_dst;
22049 		/*
22050 		 * For the multicast case, ipsec_out carries conn_dontroute and
22051 		 * conn_multicast_loop as conn may not be available here. We
22052 		 * need this for multicast loopback and forwarding which is done
22053 		 * later in the code.
22054 		 */
22055 		if (CLASSD(dst)) {
22056 			conn_dontroute = io->ipsec_out_dontroute;
22057 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22058 			/*
22059 			 * If conn_dontroute is not set or conn_multicast_loop
22060 			 * is set, we need to do forwarding/loopback. For
22061 			 * datagrams from ip_wput_multicast, conn_dontroute is
22062 			 * set to B_TRUE and conn_multicast_loop is set to
22063 			 * B_FALSE so that we neither do forwarding nor
22064 			 * loopback.
22065 			 */
22066 			if (!conn_dontroute || conn_multicast_loop)
22067 				multicast_forward = B_TRUE;
22068 		}
22069 	}
22070 
22071 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22072 	    ire->ire_zoneid != ALL_ZONES) {
22073 		/*
22074 		 * When a zone sends a packet to another zone, we try to deliver
22075 		 * the packet under the same conditions as if the destination
22076 		 * was a real node on the network. To do so, we look for a
22077 		 * matching route in the forwarding table.
22078 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22079 		 * ip_newroute() does.
22080 		 * Note that IRE_LOCAL are special, since they are used
22081 		 * when the zoneid doesn't match in some cases. This means that
22082 		 * we need to handle ipha_src differently since ire_src_addr
22083 		 * belongs to the receiving zone instead of the sending zone.
22084 		 * When ip_restrict_interzone_loopback is set, then
22085 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22086 		 * for loopback between zones when the logical "Ethernet" would
22087 		 * have looped them back.
22088 		 */
22089 		ire_t *src_ire;
22090 
22091 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22092 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22093 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22094 		if (src_ire != NULL &&
22095 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22096 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22097 		    ire_local_same_ill_group(ire, src_ire))) {
22098 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22099 				ipha->ipha_src = src_ire->ire_src_addr;
22100 			ire_refrele(src_ire);
22101 		} else {
22102 			ire_refrele(ire);
22103 			if (conn_outgoing_ill != NULL)
22104 				ill_refrele(conn_outgoing_ill);
22105 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22106 			if (src_ire != NULL) {
22107 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22108 					ire_refrele(src_ire);
22109 					freemsg(mp);
22110 					return;
22111 				}
22112 				ire_refrele(src_ire);
22113 			}
22114 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22115 				/* Failed */
22116 				freemsg(mp);
22117 				return;
22118 			}
22119 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22120 			    ipst);
22121 			return;
22122 		}
22123 	}
22124 
22125 	if (mp->b_datap->db_type == M_CTL ||
22126 	    ipss->ipsec_outbound_v4_policy_present) {
22127 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22128 		    unspec_src, zoneid);
22129 		if (mp == NULL) {
22130 			ire_refrele(ire);
22131 			if (conn_outgoing_ill != NULL)
22132 				ill_refrele(conn_outgoing_ill);
22133 			return;
22134 		}
22135 	}
22136 
22137 	first_mp = mp;
22138 	ipsec_len = 0;
22139 
22140 	if (first_mp->b_datap->db_type == M_CTL) {
22141 		io = (ipsec_out_t *)first_mp->b_rptr;
22142 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22143 		mp = first_mp->b_cont;
22144 		ipsec_len = ipsec_out_extra_length(first_mp);
22145 		ASSERT(ipsec_len >= 0);
22146 		/* We already picked up the zoneid from the M_CTL above */
22147 		ASSERT(zoneid == io->ipsec_out_zoneid);
22148 		ASSERT(zoneid != ALL_ZONES);
22149 
22150 		/*
22151 		 * Drop M_CTL here if IPsec processing is not needed.
22152 		 * (Non-IPsec use of M_CTL extracted any information it
22153 		 * needed above).
22154 		 */
22155 		if (ipsec_len == 0) {
22156 			freeb(first_mp);
22157 			first_mp = mp;
22158 		}
22159 	}
22160 
22161 	/*
22162 	 * Fast path for ip_wput_ire
22163 	 */
22164 
22165 	ipha = (ipha_t *)mp->b_rptr;
22166 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22167 	dst = ipha->ipha_dst;
22168 
22169 	/*
22170 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22171 	 * if the socket is a SOCK_RAW type. The transport checksum should
22172 	 * be provided in the pre-built packet, so we don't need to compute it.
22173 	 * Also, other application set flags, like DF, should not be altered.
22174 	 * Other transport MUST pass down zero.
22175 	 */
22176 	ip_hdr_included = ipha->ipha_ident;
22177 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22178 
22179 	if (CLASSD(dst)) {
22180 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22181 		    ntohl(dst),
22182 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22183 		    ntohl(ire->ire_addr)));
22184 	}
22185 
22186 /* Macros to extract header fields from data already in registers */
22187 #ifdef	_BIG_ENDIAN
22188 #define	V_HLEN	(v_hlen_tos_len >> 24)
22189 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22190 #define	PROTO	(ttl_protocol & 0xFF)
22191 #else
22192 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22193 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22194 #define	PROTO	(ttl_protocol >> 8)
22195 #endif
22196 
22197 
22198 	orig_src = src = ipha->ipha_src;
22199 	/* (The loop back to "another" is explained down below.) */
22200 another:;
22201 	/*
22202 	 * Assign an ident value for this packet.  We assign idents on
22203 	 * a per destination basis out of the IRE.  There could be
22204 	 * other threads targeting the same destination, so we have to
22205 	 * arrange for a atomic increment.  Note that we use a 32-bit
22206 	 * atomic add because it has better performance than its
22207 	 * 16-bit sibling.
22208 	 *
22209 	 * If running in cluster mode and if the source address
22210 	 * belongs to a replicated service then vector through
22211 	 * cl_inet_ipident vector to allocate ip identifier
22212 	 * NOTE: This is a contract private interface with the
22213 	 * clustering group.
22214 	 */
22215 	clusterwide = 0;
22216 	if (cl_inet_ipident) {
22217 		ASSERT(cl_inet_isclusterwide);
22218 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
22219 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
22220 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
22221 			    AF_INET, (uint8_t *)(uintptr_t)src,
22222 			    (uint8_t *)(uintptr_t)dst);
22223 			clusterwide = 1;
22224 		}
22225 	}
22226 	if (!clusterwide) {
22227 		ipha->ipha_ident =
22228 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22229 	}
22230 
22231 #ifndef _BIG_ENDIAN
22232 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22233 #endif
22234 
22235 	/*
22236 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22237 	 * This is needed to obey conn_unspec_src when packets go through
22238 	 * ip_newroute + arp.
22239 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22240 	 */
22241 	if (src == INADDR_ANY && !unspec_src) {
22242 		/*
22243 		 * Assign the appropriate source address from the IRE if none
22244 		 * was specified.
22245 		 */
22246 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22247 
22248 		/*
22249 		 * With IP multipathing, broadcast packets are sent on the ire
22250 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
22251 		 * the group. However, this ire might not be in the same zone so
22252 		 * we can't always use its source address. We look for a
22253 		 * broadcast ire in the same group and in the right zone.
22254 		 */
22255 		if (ire->ire_type == IRE_BROADCAST &&
22256 		    ire->ire_zoneid != zoneid) {
22257 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
22258 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
22259 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
22260 			if (src_ire != NULL) {
22261 				src = src_ire->ire_src_addr;
22262 				ire_refrele(src_ire);
22263 			} else {
22264 				ire_refrele(ire);
22265 				if (conn_outgoing_ill != NULL)
22266 					ill_refrele(conn_outgoing_ill);
22267 				freemsg(first_mp);
22268 				if (ill != NULL) {
22269 					BUMP_MIB(ill->ill_ip_mib,
22270 					    ipIfStatsOutDiscards);
22271 				} else {
22272 					BUMP_MIB(&ipst->ips_ip_mib,
22273 					    ipIfStatsOutDiscards);
22274 				}
22275 				return;
22276 			}
22277 		} else {
22278 			src = ire->ire_src_addr;
22279 		}
22280 
22281 		if (connp == NULL) {
22282 			ip1dbg(("ip_wput_ire: no connp and no src "
22283 			    "address for dst 0x%x, using src 0x%x\n",
22284 			    ntohl(dst),
22285 			    ntohl(src)));
22286 		}
22287 		ipha->ipha_src = src;
22288 	}
22289 	stq = ire->ire_stq;
22290 
22291 	/*
22292 	 * We only allow ire chains for broadcasts since there will
22293 	 * be multiple IRE_CACHE entries for the same multicast
22294 	 * address (one per ipif).
22295 	 */
22296 	next_mp = NULL;
22297 
22298 	/* broadcast packet */
22299 	if (ire->ire_type == IRE_BROADCAST)
22300 		goto broadcast;
22301 
22302 	/* loopback ? */
22303 	if (stq == NULL)
22304 		goto nullstq;
22305 
22306 	/* The ill_index for outbound ILL */
22307 	ill_index = Q_TO_INDEX(stq);
22308 
22309 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22310 	ttl_protocol = ((uint16_t *)ipha)[4];
22311 
22312 	/* pseudo checksum (do it in parts for IP header checksum) */
22313 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22314 
22315 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22316 		queue_t *dev_q = stq->q_next;
22317 
22318 		/* flow controlled */
22319 		if ((dev_q->q_next || dev_q->q_first) &&
22320 		    !canput(dev_q))
22321 			goto blocked;
22322 		if ((PROTO == IPPROTO_UDP) &&
22323 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22324 			hlen = (V_HLEN & 0xF) << 2;
22325 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22326 			if (*up != 0) {
22327 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22328 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22329 				/* Software checksum? */
22330 				if (DB_CKSUMFLAGS(mp) == 0) {
22331 					IP_STAT(ipst, ip_out_sw_cksum);
22332 					IP_STAT_UPDATE(ipst,
22333 					    ip_udp_out_sw_cksum_bytes,
22334 					    LENGTH - hlen);
22335 				}
22336 			}
22337 		}
22338 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22339 		hlen = (V_HLEN & 0xF) << 2;
22340 		if (PROTO == IPPROTO_TCP) {
22341 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22342 			/*
22343 			 * The packet header is processed once and for all, even
22344 			 * in the multirouting case. We disable hardware
22345 			 * checksum if the packet is multirouted, as it will be
22346 			 * replicated via several interfaces, and not all of
22347 			 * them may have this capability.
22348 			 */
22349 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22350 			    LENGTH, max_frag, ipsec_len, cksum);
22351 			/* Software checksum? */
22352 			if (DB_CKSUMFLAGS(mp) == 0) {
22353 				IP_STAT(ipst, ip_out_sw_cksum);
22354 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22355 				    LENGTH - hlen);
22356 			}
22357 		} else {
22358 			sctp_hdr_t	*sctph;
22359 
22360 			ASSERT(PROTO == IPPROTO_SCTP);
22361 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22362 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22363 			/*
22364 			 * Zero out the checksum field to ensure proper
22365 			 * checksum calculation.
22366 			 */
22367 			sctph->sh_chksum = 0;
22368 #ifdef	DEBUG
22369 			if (!skip_sctp_cksum)
22370 #endif
22371 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22372 		}
22373 	}
22374 
22375 	/*
22376 	 * If this is a multicast packet and originated from ip_wput
22377 	 * we need to do loopback and forwarding checks. If it comes
22378 	 * from ip_wput_multicast, we SHOULD not do this.
22379 	 */
22380 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22381 
22382 	/* checksum */
22383 	cksum += ttl_protocol;
22384 
22385 	/* fragment the packet */
22386 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22387 		goto fragmentit;
22388 	/*
22389 	 * Don't use frag_flag if packet is pre-built or source
22390 	 * routed or if multicast (since multicast packets do
22391 	 * not solicit ICMP "packet too big" messages).
22392 	 */
22393 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22394 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22395 	    !ip_source_route_included(ipha)) &&
22396 	    !CLASSD(ipha->ipha_dst))
22397 		ipha->ipha_fragment_offset_and_flags |=
22398 		    htons(ire->ire_frag_flag);
22399 
22400 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22401 		/* calculate IP header checksum */
22402 		cksum += ipha->ipha_ident;
22403 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22404 		cksum += ipha->ipha_fragment_offset_and_flags;
22405 
22406 		/* IP options present */
22407 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22408 		if (hlen)
22409 			goto checksumoptions;
22410 
22411 		/* calculate hdr checksum */
22412 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22413 		cksum = ~(cksum + (cksum >> 16));
22414 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22415 	}
22416 	if (ipsec_len != 0) {
22417 		/*
22418 		 * We will do the rest of the processing after
22419 		 * we come back from IPsec in ip_wput_ipsec_out().
22420 		 */
22421 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22422 
22423 		io = (ipsec_out_t *)first_mp->b_rptr;
22424 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
22425 		    ill_phyint->phyint_ifindex;
22426 
22427 		ipsec_out_process(q, first_mp, ire, ill_index);
22428 		ire_refrele(ire);
22429 		if (conn_outgoing_ill != NULL)
22430 			ill_refrele(conn_outgoing_ill);
22431 		return;
22432 	}
22433 
22434 	/*
22435 	 * In most cases, the emission loop below is entered only
22436 	 * once. Only in the case where the ire holds the
22437 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22438 	 * flagged ires in the bucket, and send the packet
22439 	 * through all crossed RTF_MULTIRT routes.
22440 	 */
22441 	if (ire->ire_flags & RTF_MULTIRT) {
22442 		multirt_send = B_TRUE;
22443 	}
22444 	do {
22445 		if (multirt_send) {
22446 			irb_t *irb;
22447 			/*
22448 			 * We are in a multiple send case, need to get
22449 			 * the next ire and make a duplicate of the packet.
22450 			 * ire1 holds here the next ire to process in the
22451 			 * bucket. If multirouting is expected,
22452 			 * any non-RTF_MULTIRT ire that has the
22453 			 * right destination address is ignored.
22454 			 */
22455 			irb = ire->ire_bucket;
22456 			ASSERT(irb != NULL);
22457 
22458 			IRB_REFHOLD(irb);
22459 			for (ire1 = ire->ire_next;
22460 			    ire1 != NULL;
22461 			    ire1 = ire1->ire_next) {
22462 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22463 					continue;
22464 				if (ire1->ire_addr != ire->ire_addr)
22465 					continue;
22466 				if (ire1->ire_marks &
22467 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22468 					continue;
22469 
22470 				/* Got one */
22471 				IRE_REFHOLD(ire1);
22472 				break;
22473 			}
22474 			IRB_REFRELE(irb);
22475 
22476 			if (ire1 != NULL) {
22477 				next_mp = copyb(mp);
22478 				if ((next_mp == NULL) ||
22479 				    ((mp->b_cont != NULL) &&
22480 				    ((next_mp->b_cont =
22481 				    dupmsg(mp->b_cont)) == NULL))) {
22482 					freemsg(next_mp);
22483 					next_mp = NULL;
22484 					ire_refrele(ire1);
22485 					ire1 = NULL;
22486 				}
22487 			}
22488 
22489 			/* Last multiroute ire; don't loop anymore. */
22490 			if (ire1 == NULL) {
22491 				multirt_send = B_FALSE;
22492 			}
22493 		}
22494 
22495 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22496 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22497 		    mblk_t *, mp);
22498 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22499 		    ipst->ips_ipv4firewall_physical_out,
22500 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, ipst);
22501 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22502 		if (mp == NULL)
22503 			goto release_ire_and_ill;
22504 
22505 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22506 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22507 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
22508 		if ((pktxmit_state == SEND_FAILED) ||
22509 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22510 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22511 			    "- packet dropped\n"));
22512 release_ire_and_ill:
22513 			ire_refrele(ire);
22514 			if (next_mp != NULL) {
22515 				freemsg(next_mp);
22516 				ire_refrele(ire1);
22517 			}
22518 			if (conn_outgoing_ill != NULL)
22519 				ill_refrele(conn_outgoing_ill);
22520 			return;
22521 		}
22522 
22523 		if (CLASSD(dst)) {
22524 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22525 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22526 			    LENGTH);
22527 		}
22528 
22529 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22530 		    "ip_wput_ire_end: q %p (%S)",
22531 		    q, "last copy out");
22532 		IRE_REFRELE(ire);
22533 
22534 		if (multirt_send) {
22535 			ASSERT(ire1);
22536 			/*
22537 			 * Proceed with the next RTF_MULTIRT ire,
22538 			 * Also set up the send-to queue accordingly.
22539 			 */
22540 			ire = ire1;
22541 			ire1 = NULL;
22542 			stq = ire->ire_stq;
22543 			mp = next_mp;
22544 			next_mp = NULL;
22545 			ipha = (ipha_t *)mp->b_rptr;
22546 			ill_index = Q_TO_INDEX(stq);
22547 			ill = (ill_t *)stq->q_ptr;
22548 		}
22549 	} while (multirt_send);
22550 	if (conn_outgoing_ill != NULL)
22551 		ill_refrele(conn_outgoing_ill);
22552 	return;
22553 
22554 	/*
22555 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22556 	 */
22557 broadcast:
22558 	{
22559 		/*
22560 		 * Avoid broadcast storms by setting the ttl to 1
22561 		 * for broadcasts. This parameter can be set
22562 		 * via ndd, so make sure that for the SO_DONTROUTE
22563 		 * case that ipha_ttl is always set to 1.
22564 		 * In the event that we are replying to incoming
22565 		 * ICMP packets, conn could be NULL.
22566 		 */
22567 		if ((connp != NULL) && connp->conn_dontroute)
22568 			ipha->ipha_ttl = 1;
22569 		else
22570 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22571 
22572 		/*
22573 		 * Note that we are not doing a IRB_REFHOLD here.
22574 		 * Actually we don't care if the list changes i.e
22575 		 * if somebody deletes an IRE from the list while
22576 		 * we drop the lock, the next time we come around
22577 		 * ire_next will be NULL and hence we won't send
22578 		 * out multiple copies which is fine.
22579 		 */
22580 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22581 		ire1 = ire->ire_next;
22582 		if (conn_outgoing_ill != NULL) {
22583 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22584 				ASSERT(ire1 == ire->ire_next);
22585 				if (ire1 != NULL && ire1->ire_addr == dst) {
22586 					ire_refrele(ire);
22587 					ire = ire1;
22588 					IRE_REFHOLD(ire);
22589 					ire1 = ire->ire_next;
22590 					continue;
22591 				}
22592 				rw_exit(&ire->ire_bucket->irb_lock);
22593 				/* Did not find a matching ill */
22594 				ip1dbg(("ip_wput_ire: broadcast with no "
22595 				    "matching IP_BOUND_IF ill %s\n",
22596 				    conn_outgoing_ill->ill_name));
22597 				freemsg(first_mp);
22598 				if (ire != NULL)
22599 					ire_refrele(ire);
22600 				ill_refrele(conn_outgoing_ill);
22601 				return;
22602 			}
22603 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22604 			/*
22605 			 * If the next IRE has the same address and is not one
22606 			 * of the two copies that we need to send, try to see
22607 			 * whether this copy should be sent at all. This
22608 			 * assumes that we insert loopbacks first and then
22609 			 * non-loopbacks. This is acheived by inserting the
22610 			 * loopback always before non-loopback.
22611 			 * This is used to send a single copy of a broadcast
22612 			 * packet out all physical interfaces that have an
22613 			 * matching IRE_BROADCAST while also looping
22614 			 * back one copy (to ip_wput_local) for each
22615 			 * matching physical interface. However, we avoid
22616 			 * sending packets out different logical that match by
22617 			 * having ipif_up/ipif_down supress duplicate
22618 			 * IRE_BROADCASTS.
22619 			 *
22620 			 * This feature is currently used to get broadcasts
22621 			 * sent to multiple interfaces, when the broadcast
22622 			 * address being used applies to multiple interfaces.
22623 			 * For example, a whole net broadcast will be
22624 			 * replicated on every connected subnet of
22625 			 * the target net.
22626 			 *
22627 			 * Each zone has its own set of IRE_BROADCASTs, so that
22628 			 * we're able to distribute inbound packets to multiple
22629 			 * zones who share a broadcast address. We avoid looping
22630 			 * back outbound packets in different zones but on the
22631 			 * same ill, as the application would see duplicates.
22632 			 *
22633 			 * If the interfaces are part of the same group,
22634 			 * we would want to send only one copy out for
22635 			 * whole group.
22636 			 *
22637 			 * This logic assumes that ire_add_v4() groups the
22638 			 * IRE_BROADCAST entries so that those with the same
22639 			 * ire_addr and ill_group are kept together.
22640 			 */
22641 			ire_ill = ire->ire_ipif->ipif_ill;
22642 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22643 				if (ire_ill->ill_group != NULL &&
22644 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22645 					/*
22646 					 * If the current zone only has an ire
22647 					 * broadcast for this address marked
22648 					 * NORECV, the ire we want is ahead in
22649 					 * the bucket, so we look it up
22650 					 * deliberately ignoring the zoneid.
22651 					 */
22652 					for (ire1 = ire->ire_bucket->irb_ire;
22653 					    ire1 != NULL;
22654 					    ire1 = ire1->ire_next) {
22655 						ire1_ill =
22656 						    ire1->ire_ipif->ipif_ill;
22657 						if (ire1->ire_addr != dst)
22658 							continue;
22659 						/* skip over the current ire */
22660 						if (ire1 == ire)
22661 							continue;
22662 						/* skip over deleted ires */
22663 						if (ire1->ire_marks &
22664 						    IRE_MARK_CONDEMNED)
22665 							continue;
22666 						/*
22667 						 * non-loopback ire in our
22668 						 * group: use it for the next
22669 						 * pass in the loop
22670 						 */
22671 						if (ire1->ire_stq != NULL &&
22672 						    ire1_ill->ill_group ==
22673 						    ire_ill->ill_group)
22674 							break;
22675 					}
22676 				}
22677 			} else {
22678 				while (ire1 != NULL && ire1->ire_addr == dst) {
22679 					ire1_ill = ire1->ire_ipif->ipif_ill;
22680 					/*
22681 					 * We can have two broadcast ires on the
22682 					 * same ill in different zones; here
22683 					 * we'll send a copy of the packet on
22684 					 * each ill and the fanout code will
22685 					 * call conn_wantpacket() to check that
22686 					 * the zone has the broadcast address
22687 					 * configured on the ill. If the two
22688 					 * ires are in the same group we only
22689 					 * send one copy up.
22690 					 */
22691 					if (ire1_ill != ire_ill &&
22692 					    (ire1_ill->ill_group == NULL ||
22693 					    ire_ill->ill_group == NULL ||
22694 					    ire1_ill->ill_group !=
22695 					    ire_ill->ill_group)) {
22696 						break;
22697 					}
22698 					ire1 = ire1->ire_next;
22699 				}
22700 			}
22701 		}
22702 		ASSERT(multirt_send == B_FALSE);
22703 		if (ire1 != NULL && ire1->ire_addr == dst) {
22704 			if ((ire->ire_flags & RTF_MULTIRT) &&
22705 			    (ire1->ire_flags & RTF_MULTIRT)) {
22706 				/*
22707 				 * We are in the multirouting case.
22708 				 * The message must be sent at least
22709 				 * on both ires. These ires have been
22710 				 * inserted AFTER the standard ones
22711 				 * in ip_rt_add(). There are thus no
22712 				 * other ire entries for the destination
22713 				 * address in the rest of the bucket
22714 				 * that do not have the RTF_MULTIRT
22715 				 * flag. We don't process a copy
22716 				 * of the message here. This will be
22717 				 * done in the final sending loop.
22718 				 */
22719 				multirt_send = B_TRUE;
22720 			} else {
22721 				next_mp = ip_copymsg(first_mp);
22722 				if (next_mp != NULL)
22723 					IRE_REFHOLD(ire1);
22724 			}
22725 		}
22726 		rw_exit(&ire->ire_bucket->irb_lock);
22727 	}
22728 
22729 	if (stq) {
22730 		/*
22731 		 * A non-NULL send-to queue means this packet is going
22732 		 * out of this machine.
22733 		 */
22734 		out_ill = (ill_t *)stq->q_ptr;
22735 
22736 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22737 		ttl_protocol = ((uint16_t *)ipha)[4];
22738 		/*
22739 		 * We accumulate the pseudo header checksum in cksum.
22740 		 * This is pretty hairy code, so watch close.  One
22741 		 * thing to keep in mind is that UDP and TCP have
22742 		 * stored their respective datagram lengths in their
22743 		 * checksum fields.  This lines things up real nice.
22744 		 */
22745 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22746 		    (src >> 16) + (src & 0xFFFF);
22747 		/*
22748 		 * We assume the udp checksum field contains the
22749 		 * length, so to compute the pseudo header checksum,
22750 		 * all we need is the protocol number and src/dst.
22751 		 */
22752 		/* Provide the checksums for UDP and TCP. */
22753 		if ((PROTO == IPPROTO_TCP) &&
22754 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22755 			/* hlen gets the number of uchar_ts in the IP header */
22756 			hlen = (V_HLEN & 0xF) << 2;
22757 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22758 			IP_STAT(ipst, ip_out_sw_cksum);
22759 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22760 			    LENGTH - hlen);
22761 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22762 		} else if (PROTO == IPPROTO_SCTP &&
22763 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22764 			sctp_hdr_t	*sctph;
22765 
22766 			hlen = (V_HLEN & 0xF) << 2;
22767 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22768 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22769 			sctph->sh_chksum = 0;
22770 #ifdef	DEBUG
22771 			if (!skip_sctp_cksum)
22772 #endif
22773 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22774 		} else {
22775 			queue_t *dev_q = stq->q_next;
22776 
22777 			if ((dev_q->q_next || dev_q->q_first) &&
22778 			    !canput(dev_q)) {
22779 blocked:
22780 				ipha->ipha_ident = ip_hdr_included;
22781 				/*
22782 				 * If we don't have a conn to apply
22783 				 * backpressure, free the message.
22784 				 * In the ire_send path, we don't know
22785 				 * the position to requeue the packet. Rather
22786 				 * than reorder packets, we just drop this
22787 				 * packet.
22788 				 */
22789 				if (ipst->ips_ip_output_queue &&
22790 				    connp != NULL &&
22791 				    caller != IRE_SEND) {
22792 					if (caller == IP_WSRV) {
22793 						connp->conn_did_putbq = 1;
22794 						(void) putbq(connp->conn_wq,
22795 						    first_mp);
22796 						conn_drain_insert(connp);
22797 						/*
22798 						 * This is the service thread,
22799 						 * and the queue is already
22800 						 * noenabled. The check for
22801 						 * canput and the putbq is not
22802 						 * atomic. So we need to check
22803 						 * again.
22804 						 */
22805 						if (canput(stq->q_next))
22806 							connp->conn_did_putbq
22807 							    = 0;
22808 						IP_STAT(ipst, ip_conn_flputbq);
22809 					} else {
22810 						/*
22811 						 * We are not the service proc.
22812 						 * ip_wsrv will be scheduled or
22813 						 * is already running.
22814 						 */
22815 						(void) putq(connp->conn_wq,
22816 						    first_mp);
22817 					}
22818 				} else {
22819 					out_ill = (ill_t *)stq->q_ptr;
22820 					BUMP_MIB(out_ill->ill_ip_mib,
22821 					    ipIfStatsOutDiscards);
22822 					freemsg(first_mp);
22823 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22824 					    "ip_wput_ire_end: q %p (%S)",
22825 					    q, "discard");
22826 				}
22827 				ire_refrele(ire);
22828 				if (next_mp) {
22829 					ire_refrele(ire1);
22830 					freemsg(next_mp);
22831 				}
22832 				if (conn_outgoing_ill != NULL)
22833 					ill_refrele(conn_outgoing_ill);
22834 				return;
22835 			}
22836 			if ((PROTO == IPPROTO_UDP) &&
22837 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22838 				/*
22839 				 * hlen gets the number of uchar_ts in the
22840 				 * IP header
22841 				 */
22842 				hlen = (V_HLEN & 0xF) << 2;
22843 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22844 				max_frag = ire->ire_max_frag;
22845 				if (*up != 0) {
22846 					IP_CKSUM_XMIT(out_ill, ire, mp, ipha,
22847 					    up, PROTO, hlen, LENGTH, max_frag,
22848 					    ipsec_len, cksum);
22849 					/* Software checksum? */
22850 					if (DB_CKSUMFLAGS(mp) == 0) {
22851 						IP_STAT(ipst, ip_out_sw_cksum);
22852 						IP_STAT_UPDATE(ipst,
22853 						    ip_udp_out_sw_cksum_bytes,
22854 						    LENGTH - hlen);
22855 					}
22856 				}
22857 			}
22858 		}
22859 		/*
22860 		 * Need to do this even when fragmenting. The local
22861 		 * loopback can be done without computing checksums
22862 		 * but forwarding out other interface must be done
22863 		 * after the IP checksum (and ULP checksums) have been
22864 		 * computed.
22865 		 *
22866 		 * NOTE : multicast_forward is set only if this packet
22867 		 * originated from ip_wput. For packets originating from
22868 		 * ip_wput_multicast, it is not set.
22869 		 */
22870 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
22871 multi_loopback:
22872 			ip2dbg(("ip_wput: multicast, loop %d\n",
22873 			    conn_multicast_loop));
22874 
22875 			/*  Forget header checksum offload */
22876 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
22877 
22878 			/*
22879 			 * Local loopback of multicasts?  Check the
22880 			 * ill.
22881 			 *
22882 			 * Note that the loopback function will not come
22883 			 * in through ip_rput - it will only do the
22884 			 * client fanout thus we need to do an mforward
22885 			 * as well.  The is different from the BSD
22886 			 * logic.
22887 			 */
22888 			if (ill != NULL) {
22889 				ilm_t	*ilm;
22890 
22891 				ILM_WALKER_HOLD(ill);
22892 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
22893 				    ALL_ZONES);
22894 				ILM_WALKER_RELE(ill);
22895 				if (ilm != NULL) {
22896 					/*
22897 					 * Pass along the virtual output q.
22898 					 * ip_wput_local() will distribute the
22899 					 * packet to all the matching zones,
22900 					 * except the sending zone when
22901 					 * IP_MULTICAST_LOOP is false.
22902 					 */
22903 					ip_multicast_loopback(q, ill, first_mp,
22904 					    conn_multicast_loop ? 0 :
22905 					    IP_FF_NO_MCAST_LOOP, zoneid);
22906 				}
22907 			}
22908 			if (ipha->ipha_ttl == 0) {
22909 				/*
22910 				 * 0 => only to this host i.e. we are
22911 				 * done. We are also done if this was the
22912 				 * loopback interface since it is sufficient
22913 				 * to loopback one copy of a multicast packet.
22914 				 */
22915 				freemsg(first_mp);
22916 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22917 				    "ip_wput_ire_end: q %p (%S)",
22918 				    q, "loopback");
22919 				ire_refrele(ire);
22920 				if (conn_outgoing_ill != NULL)
22921 					ill_refrele(conn_outgoing_ill);
22922 				return;
22923 			}
22924 			/*
22925 			 * ILLF_MULTICAST is checked in ip_newroute
22926 			 * i.e. we don't need to check it here since
22927 			 * all IRE_CACHEs come from ip_newroute.
22928 			 * For multicast traffic, SO_DONTROUTE is interpreted
22929 			 * to mean only send the packet out the interface
22930 			 * (optionally specified with IP_MULTICAST_IF)
22931 			 * and do not forward it out additional interfaces.
22932 			 * RSVP and the rsvp daemon is an example of a
22933 			 * protocol and user level process that
22934 			 * handles it's own routing. Hence, it uses the
22935 			 * SO_DONTROUTE option to accomplish this.
22936 			 */
22937 
22938 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
22939 			    ill != NULL) {
22940 				/* Unconditionally redo the checksum */
22941 				ipha->ipha_hdr_checksum = 0;
22942 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22943 
22944 				/*
22945 				 * If this needs to go out secure, we need
22946 				 * to wait till we finish the IPsec
22947 				 * processing.
22948 				 */
22949 				if (ipsec_len == 0 &&
22950 				    ip_mforward(ill, ipha, mp)) {
22951 					freemsg(first_mp);
22952 					ip1dbg(("ip_wput: mforward failed\n"));
22953 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22954 					    "ip_wput_ire_end: q %p (%S)",
22955 					    q, "mforward failed");
22956 					ire_refrele(ire);
22957 					if (conn_outgoing_ill != NULL)
22958 						ill_refrele(conn_outgoing_ill);
22959 					return;
22960 				}
22961 			}
22962 		}
22963 		max_frag = ire->ire_max_frag;
22964 		cksum += ttl_protocol;
22965 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
22966 			/* No fragmentation required for this one. */
22967 			/*
22968 			 * Don't use frag_flag if packet is pre-built or source
22969 			 * routed or if multicast (since multicast packets do
22970 			 * not solicit ICMP "packet too big" messages).
22971 			 */
22972 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22973 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22974 			    !ip_source_route_included(ipha)) &&
22975 			    !CLASSD(ipha->ipha_dst))
22976 				ipha->ipha_fragment_offset_and_flags |=
22977 				    htons(ire->ire_frag_flag);
22978 
22979 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22980 				/* Complete the IP header checksum. */
22981 				cksum += ipha->ipha_ident;
22982 				cksum += (v_hlen_tos_len >> 16)+
22983 				    (v_hlen_tos_len & 0xFFFF);
22984 				cksum += ipha->ipha_fragment_offset_and_flags;
22985 				hlen = (V_HLEN & 0xF) -
22986 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22987 				if (hlen) {
22988 checksumoptions:
22989 					/*
22990 					 * Account for the IP Options in the IP
22991 					 * header checksum.
22992 					 */
22993 					up = (uint16_t *)(rptr+
22994 					    IP_SIMPLE_HDR_LENGTH);
22995 					do {
22996 						cksum += up[0];
22997 						cksum += up[1];
22998 						up += 2;
22999 					} while (--hlen);
23000 				}
23001 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23002 				cksum = ~(cksum + (cksum >> 16));
23003 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23004 			}
23005 			if (ipsec_len != 0) {
23006 				ipsec_out_process(q, first_mp, ire, ill_index);
23007 				if (!next_mp) {
23008 					ire_refrele(ire);
23009 					if (conn_outgoing_ill != NULL)
23010 						ill_refrele(conn_outgoing_ill);
23011 					return;
23012 				}
23013 				goto next;
23014 			}
23015 
23016 			/*
23017 			 * multirt_send has already been handled
23018 			 * for broadcast, but not yet for multicast
23019 			 * or IP options.
23020 			 */
23021 			if (next_mp == NULL) {
23022 				if (ire->ire_flags & RTF_MULTIRT) {
23023 					multirt_send = B_TRUE;
23024 				}
23025 			}
23026 
23027 			/*
23028 			 * In most cases, the emission loop below is
23029 			 * entered only once. Only in the case where
23030 			 * the ire holds the RTF_MULTIRT flag, do we loop
23031 			 * to process all RTF_MULTIRT ires in the bucket,
23032 			 * and send the packet through all crossed
23033 			 * RTF_MULTIRT routes.
23034 			 */
23035 			do {
23036 				if (multirt_send) {
23037 					irb_t *irb;
23038 
23039 					irb = ire->ire_bucket;
23040 					ASSERT(irb != NULL);
23041 					/*
23042 					 * We are in a multiple send case,
23043 					 * need to get the next IRE and make
23044 					 * a duplicate of the packet.
23045 					 */
23046 					IRB_REFHOLD(irb);
23047 					for (ire1 = ire->ire_next;
23048 					    ire1 != NULL;
23049 					    ire1 = ire1->ire_next) {
23050 						if (!(ire1->ire_flags &
23051 						    RTF_MULTIRT)) {
23052 							continue;
23053 						}
23054 						if (ire1->ire_addr !=
23055 						    ire->ire_addr) {
23056 							continue;
23057 						}
23058 						if (ire1->ire_marks &
23059 						    (IRE_MARK_CONDEMNED|
23060 						    IRE_MARK_HIDDEN)) {
23061 							continue;
23062 						}
23063 
23064 						/* Got one */
23065 						IRE_REFHOLD(ire1);
23066 						break;
23067 					}
23068 					IRB_REFRELE(irb);
23069 
23070 					if (ire1 != NULL) {
23071 						next_mp = copyb(mp);
23072 						if ((next_mp == NULL) ||
23073 						    ((mp->b_cont != NULL) &&
23074 						    ((next_mp->b_cont =
23075 						    dupmsg(mp->b_cont))
23076 						    == NULL))) {
23077 							freemsg(next_mp);
23078 							next_mp = NULL;
23079 							ire_refrele(ire1);
23080 							ire1 = NULL;
23081 						}
23082 					}
23083 
23084 					/*
23085 					 * Last multiroute ire; don't loop
23086 					 * anymore. The emission is over
23087 					 * and next_mp is NULL.
23088 					 */
23089 					if (ire1 == NULL) {
23090 						multirt_send = B_FALSE;
23091 					}
23092 				}
23093 
23094 				out_ill = ire_to_ill(ire);
23095 				DTRACE_PROBE4(ip4__physical__out__start,
23096 				    ill_t *, NULL,
23097 				    ill_t *, out_ill,
23098 				    ipha_t *, ipha, mblk_t *, mp);
23099 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23100 				    ipst->ips_ipv4firewall_physical_out,
23101 				    NULL, out_ill, ipha, mp, mp, ipst);
23102 				DTRACE_PROBE1(ip4__physical__out__end,
23103 				    mblk_t *, mp);
23104 				if (mp == NULL)
23105 					goto release_ire_and_ill_2;
23106 
23107 				ASSERT(ipsec_len == 0);
23108 				mp->b_prev =
23109 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23110 				DTRACE_PROBE2(ip__xmit__2,
23111 				    mblk_t *, mp, ire_t *, ire);
23112 				pktxmit_state = ip_xmit_v4(mp, ire,
23113 				    NULL, B_TRUE);
23114 				if ((pktxmit_state == SEND_FAILED) ||
23115 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23116 release_ire_and_ill_2:
23117 					if (next_mp) {
23118 						freemsg(next_mp);
23119 						ire_refrele(ire1);
23120 					}
23121 					ire_refrele(ire);
23122 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23123 					    "ip_wput_ire_end: q %p (%S)",
23124 					    q, "discard MDATA");
23125 					if (conn_outgoing_ill != NULL)
23126 						ill_refrele(conn_outgoing_ill);
23127 					return;
23128 				}
23129 
23130 				if (CLASSD(dst)) {
23131 					BUMP_MIB(out_ill->ill_ip_mib,
23132 					    ipIfStatsHCOutMcastPkts);
23133 					UPDATE_MIB(out_ill->ill_ip_mib,
23134 					    ipIfStatsHCOutMcastOctets,
23135 					    LENGTH);
23136 				} else if (ire->ire_type == IRE_BROADCAST) {
23137 					BUMP_MIB(out_ill->ill_ip_mib,
23138 					    ipIfStatsHCOutBcastPkts);
23139 				}
23140 
23141 				if (multirt_send) {
23142 					/*
23143 					 * We are in a multiple send case,
23144 					 * need to re-enter the sending loop
23145 					 * using the next ire.
23146 					 */
23147 					ire_refrele(ire);
23148 					ire = ire1;
23149 					stq = ire->ire_stq;
23150 					mp = next_mp;
23151 					next_mp = NULL;
23152 					ipha = (ipha_t *)mp->b_rptr;
23153 					ill_index = Q_TO_INDEX(stq);
23154 				}
23155 			} while (multirt_send);
23156 
23157 			if (!next_mp) {
23158 				/*
23159 				 * Last copy going out (the ultra-common
23160 				 * case).  Note that we intentionally replicate
23161 				 * the putnext rather than calling it before
23162 				 * the next_mp check in hopes of a little
23163 				 * tail-call action out of the compiler.
23164 				 */
23165 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23166 				    "ip_wput_ire_end: q %p (%S)",
23167 				    q, "last copy out(1)");
23168 				ire_refrele(ire);
23169 				if (conn_outgoing_ill != NULL)
23170 					ill_refrele(conn_outgoing_ill);
23171 				return;
23172 			}
23173 			/* More copies going out below. */
23174 		} else {
23175 			int offset;
23176 fragmentit:
23177 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23178 			/*
23179 			 * If this would generate a icmp_frag_needed message,
23180 			 * we need to handle it before we do the IPsec
23181 			 * processing. Otherwise, we need to strip the IPsec
23182 			 * headers before we send up the message to the ULPs
23183 			 * which becomes messy and difficult.
23184 			 */
23185 			if (ipsec_len != 0) {
23186 				if ((max_frag < (unsigned int)(LENGTH +
23187 				    ipsec_len)) && (offset & IPH_DF)) {
23188 					out_ill = (ill_t *)stq->q_ptr;
23189 					BUMP_MIB(out_ill->ill_ip_mib,
23190 					    ipIfStatsOutFragFails);
23191 					BUMP_MIB(out_ill->ill_ip_mib,
23192 					    ipIfStatsOutFragReqds);
23193 					ipha->ipha_hdr_checksum = 0;
23194 					ipha->ipha_hdr_checksum =
23195 					    (uint16_t)ip_csum_hdr(ipha);
23196 					icmp_frag_needed(ire->ire_stq, first_mp,
23197 					    max_frag, zoneid, ipst);
23198 					if (!next_mp) {
23199 						ire_refrele(ire);
23200 						if (conn_outgoing_ill != NULL) {
23201 							ill_refrele(
23202 							    conn_outgoing_ill);
23203 						}
23204 						return;
23205 					}
23206 				} else {
23207 					/*
23208 					 * This won't cause a icmp_frag_needed
23209 					 * message. to be generated. Send it on
23210 					 * the wire. Note that this could still
23211 					 * cause fragmentation and all we
23212 					 * do is the generation of the message
23213 					 * to the ULP if needed before IPsec.
23214 					 */
23215 					if (!next_mp) {
23216 						ipsec_out_process(q, first_mp,
23217 						    ire, ill_index);
23218 						TRACE_2(TR_FAC_IP,
23219 						    TR_IP_WPUT_IRE_END,
23220 						    "ip_wput_ire_end: q %p "
23221 						    "(%S)", q,
23222 						    "last ipsec_out_process");
23223 						ire_refrele(ire);
23224 						if (conn_outgoing_ill != NULL) {
23225 							ill_refrele(
23226 							    conn_outgoing_ill);
23227 						}
23228 						return;
23229 					}
23230 					ipsec_out_process(q, first_mp,
23231 					    ire, ill_index);
23232 				}
23233 			} else {
23234 				/*
23235 				 * Initiate IPPF processing. For
23236 				 * fragmentable packets we finish
23237 				 * all QOS packet processing before
23238 				 * calling:
23239 				 * ip_wput_ire_fragmentit->ip_wput_frag
23240 				 */
23241 
23242 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23243 					ip_process(IPP_LOCAL_OUT, &mp,
23244 					    ill_index);
23245 					if (mp == NULL) {
23246 						out_ill = (ill_t *)stq->q_ptr;
23247 						BUMP_MIB(out_ill->ill_ip_mib,
23248 						    ipIfStatsOutDiscards);
23249 						if (next_mp != NULL) {
23250 							freemsg(next_mp);
23251 							ire_refrele(ire1);
23252 						}
23253 						ire_refrele(ire);
23254 						TRACE_2(TR_FAC_IP,
23255 						    TR_IP_WPUT_IRE_END,
23256 						    "ip_wput_ire: q %p (%S)",
23257 						    q, "discard MDATA");
23258 						if (conn_outgoing_ill != NULL) {
23259 							ill_refrele(
23260 							    conn_outgoing_ill);
23261 						}
23262 						return;
23263 					}
23264 				}
23265 				if (!next_mp) {
23266 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23267 					    "ip_wput_ire_end: q %p (%S)",
23268 					    q, "last fragmentation");
23269 					ip_wput_ire_fragmentit(mp, ire,
23270 					    zoneid, ipst);
23271 					ire_refrele(ire);
23272 					if (conn_outgoing_ill != NULL)
23273 						ill_refrele(conn_outgoing_ill);
23274 					return;
23275 				}
23276 				ip_wput_ire_fragmentit(mp, ire, zoneid, ipst);
23277 			}
23278 		}
23279 	} else {
23280 nullstq:
23281 		/* A NULL stq means the destination address is local. */
23282 		UPDATE_OB_PKT_COUNT(ire);
23283 		ire->ire_last_used_time = lbolt;
23284 		ASSERT(ire->ire_ipif != NULL);
23285 		if (!next_mp) {
23286 			/*
23287 			 * Is there an "in" and "out" for traffic local
23288 			 * to a host (loopback)?  The code in Solaris doesn't
23289 			 * explicitly draw a line in its code for in vs out,
23290 			 * so we've had to draw a line in the sand: ip_wput_ire
23291 			 * is considered to be the "output" side and
23292 			 * ip_wput_local to be the "input" side.
23293 			 */
23294 			out_ill = ire_to_ill(ire);
23295 
23296 			DTRACE_PROBE4(ip4__loopback__out__start,
23297 			    ill_t *, NULL, ill_t *, out_ill,
23298 			    ipha_t *, ipha, mblk_t *, first_mp);
23299 
23300 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23301 			    ipst->ips_ipv4firewall_loopback_out,
23302 			    NULL, out_ill, ipha, first_mp, mp, ipst);
23303 
23304 			DTRACE_PROBE1(ip4__loopback__out_end,
23305 			    mblk_t *, first_mp);
23306 
23307 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23308 			    "ip_wput_ire_end: q %p (%S)",
23309 			    q, "local address");
23310 
23311 			if (first_mp != NULL)
23312 				ip_wput_local(q, out_ill, ipha,
23313 				    first_mp, ire, 0, ire->ire_zoneid);
23314 			ire_refrele(ire);
23315 			if (conn_outgoing_ill != NULL)
23316 				ill_refrele(conn_outgoing_ill);
23317 			return;
23318 		}
23319 
23320 		out_ill = ire_to_ill(ire);
23321 
23322 		DTRACE_PROBE4(ip4__loopback__out__start,
23323 		    ill_t *, NULL, ill_t *, out_ill,
23324 		    ipha_t *, ipha, mblk_t *, first_mp);
23325 
23326 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23327 		    ipst->ips_ipv4firewall_loopback_out,
23328 		    NULL, out_ill, ipha, first_mp, mp, ipst);
23329 
23330 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23331 
23332 		if (first_mp != NULL)
23333 			ip_wput_local(q, out_ill, ipha,
23334 			    first_mp, ire, 0, ire->ire_zoneid);
23335 	}
23336 next:
23337 	/*
23338 	 * More copies going out to additional interfaces.
23339 	 * ire1 has already been held. We don't need the
23340 	 * "ire" anymore.
23341 	 */
23342 	ire_refrele(ire);
23343 	ire = ire1;
23344 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23345 	mp = next_mp;
23346 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23347 	ill = ire_to_ill(ire);
23348 	first_mp = mp;
23349 	if (ipsec_len != 0) {
23350 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23351 		mp = mp->b_cont;
23352 	}
23353 	dst = ire->ire_addr;
23354 	ipha = (ipha_t *)mp->b_rptr;
23355 	/*
23356 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23357 	 * Restore ipha_ident "no checksum" flag.
23358 	 */
23359 	src = orig_src;
23360 	ipha->ipha_ident = ip_hdr_included;
23361 	goto another;
23362 
23363 #undef	rptr
23364 #undef	Q_TO_INDEX
23365 }
23366 
23367 /*
23368  * Routine to allocate a message that is used to notify the ULP about MDT.
23369  * The caller may provide a pointer to the link-layer MDT capabilities,
23370  * or NULL if MDT is to be disabled on the stream.
23371  */
23372 mblk_t *
23373 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23374 {
23375 	mblk_t *mp;
23376 	ip_mdt_info_t *mdti;
23377 	ill_mdt_capab_t *idst;
23378 
23379 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23380 		DB_TYPE(mp) = M_CTL;
23381 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23382 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23383 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23384 		idst = &(mdti->mdt_capab);
23385 
23386 		/*
23387 		 * If the caller provides us with the capability, copy
23388 		 * it over into our notification message; otherwise
23389 		 * we zero out the capability portion.
23390 		 */
23391 		if (isrc != NULL)
23392 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23393 		else
23394 			bzero((caddr_t)idst, sizeof (*idst));
23395 	}
23396 	return (mp);
23397 }
23398 
23399 /*
23400  * Routine which determines whether MDT can be enabled on the destination
23401  * IRE and IPC combination, and if so, allocates and returns the MDT
23402  * notification mblk that may be used by ULP.  We also check if we need to
23403  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23404  * MDT usage in the past have been lifted.  This gets called during IP
23405  * and ULP binding.
23406  */
23407 mblk_t *
23408 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23409     ill_mdt_capab_t *mdt_cap)
23410 {
23411 	mblk_t *mp;
23412 	boolean_t rc = B_FALSE;
23413 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23414 
23415 	ASSERT(dst_ire != NULL);
23416 	ASSERT(connp != NULL);
23417 	ASSERT(mdt_cap != NULL);
23418 
23419 	/*
23420 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23421 	 * Multidata, which is handled in tcp_multisend().  This
23422 	 * is the reason why we do all these checks here, to ensure
23423 	 * that we don't enable Multidata for the cases which we
23424 	 * can't handle at the moment.
23425 	 */
23426 	do {
23427 		/* Only do TCP at the moment */
23428 		if (connp->conn_ulp != IPPROTO_TCP)
23429 			break;
23430 
23431 		/*
23432 		 * IPsec outbound policy present?  Note that we get here
23433 		 * after calling ipsec_conn_cache_policy() where the global
23434 		 * policy checking is performed.  conn_latch will be
23435 		 * non-NULL as long as there's a policy defined,
23436 		 * i.e. conn_out_enforce_policy may be NULL in such case
23437 		 * when the connection is non-secure, and hence we check
23438 		 * further if the latch refers to an outbound policy.
23439 		 */
23440 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23441 			break;
23442 
23443 		/* CGTP (multiroute) is enabled? */
23444 		if (dst_ire->ire_flags & RTF_MULTIRT)
23445 			break;
23446 
23447 		/* Outbound IPQoS enabled? */
23448 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23449 			/*
23450 			 * In this case, we disable MDT for this and all
23451 			 * future connections going over the interface.
23452 			 */
23453 			mdt_cap->ill_mdt_on = 0;
23454 			break;
23455 		}
23456 
23457 		/* socket option(s) present? */
23458 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23459 			break;
23460 
23461 		rc = B_TRUE;
23462 	/* CONSTCOND */
23463 	} while (0);
23464 
23465 	/* Remember the result */
23466 	connp->conn_mdt_ok = rc;
23467 
23468 	if (!rc)
23469 		return (NULL);
23470 	else if (!mdt_cap->ill_mdt_on) {
23471 		/*
23472 		 * If MDT has been previously turned off in the past, and we
23473 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23474 		 * then enable it for this interface.
23475 		 */
23476 		mdt_cap->ill_mdt_on = 1;
23477 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23478 		    "interface %s\n", ill_name));
23479 	}
23480 
23481 	/* Allocate the MDT info mblk */
23482 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23483 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23484 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23485 		return (NULL);
23486 	}
23487 	return (mp);
23488 }
23489 
23490 /*
23491  * Routine to allocate a message that is used to notify the ULP about LSO.
23492  * The caller may provide a pointer to the link-layer LSO capabilities,
23493  * or NULL if LSO is to be disabled on the stream.
23494  */
23495 mblk_t *
23496 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23497 {
23498 	mblk_t *mp;
23499 	ip_lso_info_t *lsoi;
23500 	ill_lso_capab_t *idst;
23501 
23502 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23503 		DB_TYPE(mp) = M_CTL;
23504 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23505 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23506 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23507 		idst = &(lsoi->lso_capab);
23508 
23509 		/*
23510 		 * If the caller provides us with the capability, copy
23511 		 * it over into our notification message; otherwise
23512 		 * we zero out the capability portion.
23513 		 */
23514 		if (isrc != NULL)
23515 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23516 		else
23517 			bzero((caddr_t)idst, sizeof (*idst));
23518 	}
23519 	return (mp);
23520 }
23521 
23522 /*
23523  * Routine which determines whether LSO can be enabled on the destination
23524  * IRE and IPC combination, and if so, allocates and returns the LSO
23525  * notification mblk that may be used by ULP.  We also check if we need to
23526  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23527  * LSO usage in the past have been lifted.  This gets called during IP
23528  * and ULP binding.
23529  */
23530 mblk_t *
23531 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23532     ill_lso_capab_t *lso_cap)
23533 {
23534 	mblk_t *mp;
23535 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23536 
23537 	ASSERT(dst_ire != NULL);
23538 	ASSERT(connp != NULL);
23539 	ASSERT(lso_cap != NULL);
23540 
23541 	connp->conn_lso_ok = B_TRUE;
23542 
23543 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23544 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23545 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23546 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23547 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23548 		connp->conn_lso_ok = B_FALSE;
23549 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23550 			/*
23551 			 * Disable LSO for this and all future connections going
23552 			 * over the interface.
23553 			 */
23554 			lso_cap->ill_lso_on = 0;
23555 		}
23556 	}
23557 
23558 	if (!connp->conn_lso_ok)
23559 		return (NULL);
23560 	else if (!lso_cap->ill_lso_on) {
23561 		/*
23562 		 * If LSO has been previously turned off in the past, and we
23563 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23564 		 * then enable it for this interface.
23565 		 */
23566 		lso_cap->ill_lso_on = 1;
23567 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23568 		    ill_name));
23569 	}
23570 
23571 	/* Allocate the LSO info mblk */
23572 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23573 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23574 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23575 
23576 	return (mp);
23577 }
23578 
23579 /*
23580  * Create destination address attribute, and fill it with the physical
23581  * destination address and SAP taken from the template DL_UNITDATA_REQ
23582  * message block.
23583  */
23584 boolean_t
23585 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23586 {
23587 	dl_unitdata_req_t *dlurp;
23588 	pattr_t *pa;
23589 	pattrinfo_t pa_info;
23590 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23591 	uint_t das_len, das_off;
23592 
23593 	ASSERT(dlmp != NULL);
23594 
23595 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23596 	das_len = dlurp->dl_dest_addr_length;
23597 	das_off = dlurp->dl_dest_addr_offset;
23598 
23599 	pa_info.type = PATTR_DSTADDRSAP;
23600 	pa_info.len = sizeof (**das) + das_len - 1;
23601 
23602 	/* create and associate the attribute */
23603 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23604 	if (pa != NULL) {
23605 		ASSERT(*das != NULL);
23606 		(*das)->addr_is_group = 0;
23607 		(*das)->addr_len = (uint8_t)das_len;
23608 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23609 	}
23610 
23611 	return (pa != NULL);
23612 }
23613 
23614 /*
23615  * Create hardware checksum attribute and fill it with the values passed.
23616  */
23617 boolean_t
23618 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23619     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23620 {
23621 	pattr_t *pa;
23622 	pattrinfo_t pa_info;
23623 
23624 	ASSERT(mmd != NULL);
23625 
23626 	pa_info.type = PATTR_HCKSUM;
23627 	pa_info.len = sizeof (pattr_hcksum_t);
23628 
23629 	/* create and associate the attribute */
23630 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23631 	if (pa != NULL) {
23632 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23633 
23634 		hck->hcksum_start_offset = start_offset;
23635 		hck->hcksum_stuff_offset = stuff_offset;
23636 		hck->hcksum_end_offset = end_offset;
23637 		hck->hcksum_flags = flags;
23638 	}
23639 	return (pa != NULL);
23640 }
23641 
23642 /*
23643  * Create zerocopy attribute and fill it with the specified flags
23644  */
23645 boolean_t
23646 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23647 {
23648 	pattr_t *pa;
23649 	pattrinfo_t pa_info;
23650 
23651 	ASSERT(mmd != NULL);
23652 	pa_info.type = PATTR_ZCOPY;
23653 	pa_info.len = sizeof (pattr_zcopy_t);
23654 
23655 	/* create and associate the attribute */
23656 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23657 	if (pa != NULL) {
23658 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23659 
23660 		zcopy->zcopy_flags = flags;
23661 	}
23662 	return (pa != NULL);
23663 }
23664 
23665 /*
23666  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23667  * block chain. We could rewrite to handle arbitrary message block chains but
23668  * that would make the code complicated and slow. Right now there three
23669  * restrictions:
23670  *
23671  *   1. The first message block must contain the complete IP header and
23672  *	at least 1 byte of payload data.
23673  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23674  *	so that we can use a single Multidata message.
23675  *   3. No frag must be distributed over two or more message blocks so
23676  *	that we don't need more than two packet descriptors per frag.
23677  *
23678  * The above restrictions allow us to support userland applications (which
23679  * will send down a single message block) and NFS over UDP (which will
23680  * send down a chain of at most three message blocks).
23681  *
23682  * We also don't use MDT for payloads with less than or equal to
23683  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23684  */
23685 boolean_t
23686 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23687 {
23688 	int	blocks;
23689 	ssize_t	total, missing, size;
23690 
23691 	ASSERT(mp != NULL);
23692 	ASSERT(hdr_len > 0);
23693 
23694 	size = MBLKL(mp) - hdr_len;
23695 	if (size <= 0)
23696 		return (B_FALSE);
23697 
23698 	/* The first mblk contains the header and some payload. */
23699 	blocks = 1;
23700 	total = size;
23701 	size %= len;
23702 	missing = (size == 0) ? 0 : (len - size);
23703 	mp = mp->b_cont;
23704 
23705 	while (mp != NULL) {
23706 		/*
23707 		 * Give up if we encounter a zero length message block.
23708 		 * In practice, this should rarely happen and therefore
23709 		 * not worth the trouble of freeing and re-linking the
23710 		 * mblk from the chain to handle such case.
23711 		 */
23712 		if ((size = MBLKL(mp)) == 0)
23713 			return (B_FALSE);
23714 
23715 		/* Too many payload buffers for a single Multidata message? */
23716 		if (++blocks > MULTIDATA_MAX_PBUFS)
23717 			return (B_FALSE);
23718 
23719 		total += size;
23720 		/* Is a frag distributed over two or more message blocks? */
23721 		if (missing > size)
23722 			return (B_FALSE);
23723 		size -= missing;
23724 
23725 		size %= len;
23726 		missing = (size == 0) ? 0 : (len - size);
23727 
23728 		mp = mp->b_cont;
23729 	}
23730 
23731 	return (total > ip_wput_frag_mdt_min);
23732 }
23733 
23734 /*
23735  * Outbound IPv4 fragmentation routine using MDT.
23736  */
23737 static void
23738 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23739     uint32_t frag_flag, int offset)
23740 {
23741 	ipha_t		*ipha_orig;
23742 	int		i1, ip_data_end;
23743 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23744 	mblk_t		*hdr_mp, *md_mp = NULL;
23745 	unsigned char	*hdr_ptr, *pld_ptr;
23746 	multidata_t	*mmd;
23747 	ip_pdescinfo_t	pdi;
23748 	ill_t		*ill;
23749 	ip_stack_t	*ipst = ire->ire_ipst;
23750 
23751 	ASSERT(DB_TYPE(mp) == M_DATA);
23752 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23753 
23754 	ill = ire_to_ill(ire);
23755 	ASSERT(ill != NULL);
23756 
23757 	ipha_orig = (ipha_t *)mp->b_rptr;
23758 	mp->b_rptr += sizeof (ipha_t);
23759 
23760 	/* Calculate how many packets we will send out */
23761 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23762 	pkts = (i1 + len - 1) / len;
23763 	ASSERT(pkts > 1);
23764 
23765 	/* Allocate a message block which will hold all the IP Headers. */
23766 	wroff = ipst->ips_ip_wroff_extra;
23767 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23768 
23769 	i1 = pkts * hdr_chunk_len;
23770 	/*
23771 	 * Create the header buffer, Multidata and destination address
23772 	 * and SAP attribute that should be associated with it.
23773 	 */
23774 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23775 	    ((hdr_mp->b_wptr += i1),
23776 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23777 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23778 		freemsg(mp);
23779 		if (md_mp == NULL) {
23780 			freemsg(hdr_mp);
23781 		} else {
23782 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
23783 			freemsg(md_mp);
23784 		}
23785 		IP_STAT(ipst, ip_frag_mdt_allocfail);
23786 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
23787 		return;
23788 	}
23789 	IP_STAT(ipst, ip_frag_mdt_allocd);
23790 
23791 	/*
23792 	 * Add a payload buffer to the Multidata; this operation must not
23793 	 * fail, or otherwise our logic in this routine is broken.  There
23794 	 * is no memory allocation done by the routine, so any returned
23795 	 * failure simply tells us that we've done something wrong.
23796 	 *
23797 	 * A failure tells us that either we're adding the same payload
23798 	 * buffer more than once, or we're trying to add more buffers than
23799 	 * allowed.  None of the above cases should happen, and we panic
23800 	 * because either there's horrible heap corruption, and/or
23801 	 * programming mistake.
23802 	 */
23803 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23804 		goto pbuf_panic;
23805 
23806 	hdr_ptr = hdr_mp->b_rptr;
23807 	pld_ptr = mp->b_rptr;
23808 
23809 	/* Establish the ending byte offset, based on the starting offset. */
23810 	offset <<= 3;
23811 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23812 	    IP_SIMPLE_HDR_LENGTH;
23813 
23814 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23815 
23816 	while (pld_ptr < mp->b_wptr) {
23817 		ipha_t		*ipha;
23818 		uint16_t	offset_and_flags;
23819 		uint16_t	ip_len;
23820 		int		error;
23821 
23822 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23823 		ipha = (ipha_t *)(hdr_ptr + wroff);
23824 		ASSERT(OK_32PTR(ipha));
23825 		*ipha = *ipha_orig;
23826 
23827 		if (ip_data_end - offset > len) {
23828 			offset_and_flags = IPH_MF;
23829 		} else {
23830 			/*
23831 			 * Last frag. Set len to the length of this last piece.
23832 			 */
23833 			len = ip_data_end - offset;
23834 			/* A frag of a frag might have IPH_MF non-zero */
23835 			offset_and_flags =
23836 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23837 			    IPH_MF;
23838 		}
23839 		offset_and_flags |= (uint16_t)(offset >> 3);
23840 		offset_and_flags |= (uint16_t)frag_flag;
23841 		/* Store the offset and flags in the IP header. */
23842 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23843 
23844 		/* Store the length in the IP header. */
23845 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23846 		ipha->ipha_length = htons(ip_len);
23847 
23848 		/*
23849 		 * Set the IP header checksum.  Note that mp is just
23850 		 * the header, so this is easy to pass to ip_csum.
23851 		 */
23852 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23853 
23854 		/*
23855 		 * Record offset and size of header and data of the next packet
23856 		 * in the multidata message.
23857 		 */
23858 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
23859 		PDESC_PLD_INIT(&pdi);
23860 		i1 = MIN(mp->b_wptr - pld_ptr, len);
23861 		ASSERT(i1 > 0);
23862 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
23863 		if (i1 == len) {
23864 			pld_ptr += len;
23865 		} else {
23866 			i1 = len - i1;
23867 			mp = mp->b_cont;
23868 			ASSERT(mp != NULL);
23869 			ASSERT(MBLKL(mp) >= i1);
23870 			/*
23871 			 * Attach the next payload message block to the
23872 			 * multidata message.
23873 			 */
23874 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23875 				goto pbuf_panic;
23876 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
23877 			pld_ptr = mp->b_rptr + i1;
23878 		}
23879 
23880 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
23881 		    KM_NOSLEEP)) == NULL) {
23882 			/*
23883 			 * Any failure other than ENOMEM indicates that we
23884 			 * have passed in invalid pdesc info or parameters
23885 			 * to mmd_addpdesc, which must not happen.
23886 			 *
23887 			 * EINVAL is a result of failure on boundary checks
23888 			 * against the pdesc info contents.  It should not
23889 			 * happen, and we panic because either there's
23890 			 * horrible heap corruption, and/or programming
23891 			 * mistake.
23892 			 */
23893 			if (error != ENOMEM) {
23894 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
23895 				    "pdesc logic error detected for "
23896 				    "mmd %p pinfo %p (%d)\n",
23897 				    (void *)mmd, (void *)&pdi, error);
23898 				/* NOTREACHED */
23899 			}
23900 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
23901 			/* Free unattached payload message blocks as well */
23902 			md_mp->b_cont = mp->b_cont;
23903 			goto free_mmd;
23904 		}
23905 
23906 		/* Advance fragment offset. */
23907 		offset += len;
23908 
23909 		/* Advance to location for next header in the buffer. */
23910 		hdr_ptr += hdr_chunk_len;
23911 
23912 		/* Did we reach the next payload message block? */
23913 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
23914 			mp = mp->b_cont;
23915 			/*
23916 			 * Attach the next message block with payload
23917 			 * data to the multidata message.
23918 			 */
23919 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23920 				goto pbuf_panic;
23921 			pld_ptr = mp->b_rptr;
23922 		}
23923 	}
23924 
23925 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
23926 	ASSERT(mp->b_wptr == pld_ptr);
23927 
23928 	/* Update IP statistics */
23929 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
23930 
23931 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
23932 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
23933 
23934 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
23935 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
23936 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
23937 
23938 	if (pkt_type == OB_PKT) {
23939 		ire->ire_ob_pkt_count += pkts;
23940 		if (ire->ire_ipif != NULL)
23941 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
23942 	} else {
23943 		/* The type is IB_PKT in the forwarding path. */
23944 		ire->ire_ib_pkt_count += pkts;
23945 		ASSERT(!IRE_IS_LOCAL(ire));
23946 		if (ire->ire_type & IRE_BROADCAST) {
23947 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
23948 		} else {
23949 			UPDATE_MIB(ill->ill_ip_mib,
23950 			    ipIfStatsHCOutForwDatagrams, pkts);
23951 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
23952 		}
23953 	}
23954 	ire->ire_last_used_time = lbolt;
23955 	/* Send it down */
23956 	putnext(ire->ire_stq, md_mp);
23957 	return;
23958 
23959 pbuf_panic:
23960 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
23961 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
23962 	    pbuf_idx);
23963 	/* NOTREACHED */
23964 }
23965 
23966 /*
23967  * Outbound IP fragmentation routine.
23968  *
23969  * NOTE : This routine does not ire_refrele the ire that is passed in
23970  * as the argument.
23971  */
23972 static void
23973 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
23974     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst)
23975 {
23976 	int		i1;
23977 	mblk_t		*ll_hdr_mp;
23978 	int 		ll_hdr_len;
23979 	int		hdr_len;
23980 	mblk_t		*hdr_mp;
23981 	ipha_t		*ipha;
23982 	int		ip_data_end;
23983 	int		len;
23984 	mblk_t		*mp = mp_orig, *mp1;
23985 	int		offset;
23986 	queue_t		*q;
23987 	uint32_t	v_hlen_tos_len;
23988 	mblk_t		*first_mp;
23989 	boolean_t	mctl_present;
23990 	ill_t		*ill;
23991 	ill_t		*out_ill;
23992 	mblk_t		*xmit_mp;
23993 	mblk_t		*carve_mp;
23994 	ire_t		*ire1 = NULL;
23995 	ire_t		*save_ire = NULL;
23996 	mblk_t  	*next_mp = NULL;
23997 	boolean_t	last_frag = B_FALSE;
23998 	boolean_t	multirt_send = B_FALSE;
23999 	ire_t		*first_ire = NULL;
24000 	irb_t		*irb = NULL;
24001 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24002 
24003 	ill = ire_to_ill(ire);
24004 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24005 
24006 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24007 
24008 	if (max_frag == 0) {
24009 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24010 		    " -  dropping packet\n"));
24011 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24012 		freemsg(mp);
24013 		return;
24014 	}
24015 
24016 	/*
24017 	 * IPsec does not allow hw accelerated packets to be fragmented
24018 	 * This check is made in ip_wput_ipsec_out prior to coming here
24019 	 * via ip_wput_ire_fragmentit.
24020 	 *
24021 	 * If at this point we have an ire whose ARP request has not
24022 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24023 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24024 	 * This packet and all fragmentable packets for this ire will
24025 	 * continue to get dropped while ire_nce->nce_state remains in
24026 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24027 	 * ND_REACHABLE, all subsquent large packets for this ire will
24028 	 * get fragemented and sent out by this function.
24029 	 */
24030 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24031 		/* If nce_state is ND_INITIAL, trigger ARP query */
24032 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
24033 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24034 		    " -  dropping packet\n"));
24035 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24036 		freemsg(mp);
24037 		return;
24038 	}
24039 
24040 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24041 	    "ip_wput_frag_start:");
24042 
24043 	if (mp->b_datap->db_type == M_CTL) {
24044 		first_mp = mp;
24045 		mp_orig = mp = mp->b_cont;
24046 		mctl_present = B_TRUE;
24047 	} else {
24048 		first_mp = mp;
24049 		mctl_present = B_FALSE;
24050 	}
24051 
24052 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24053 	ipha = (ipha_t *)mp->b_rptr;
24054 
24055 	/*
24056 	 * If the Don't Fragment flag is on, generate an ICMP destination
24057 	 * unreachable, fragmentation needed.
24058 	 */
24059 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24060 	if (offset & IPH_DF) {
24061 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24062 		if (is_system_labeled()) {
24063 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24064 			    ire->ire_max_frag - max_frag, AF_INET);
24065 		}
24066 		/*
24067 		 * Need to compute hdr checksum if called from ip_wput_ire.
24068 		 * Note that ip_rput_forward verifies the checksum before
24069 		 * calling this routine so in that case this is a noop.
24070 		 */
24071 		ipha->ipha_hdr_checksum = 0;
24072 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24073 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24074 		    ipst);
24075 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24076 		    "ip_wput_frag_end:(%S)",
24077 		    "don't fragment");
24078 		return;
24079 	}
24080 	/*
24081 	 * Labeled systems adjust max_frag if they add a label
24082 	 * to send the correct path mtu.  We need the real mtu since we
24083 	 * are fragmenting the packet after label adjustment.
24084 	 */
24085 	if (is_system_labeled())
24086 		max_frag = ire->ire_max_frag;
24087 	if (mctl_present)
24088 		freeb(first_mp);
24089 	/*
24090 	 * Establish the starting offset.  May not be zero if we are fragging
24091 	 * a fragment that is being forwarded.
24092 	 */
24093 	offset = offset & IPH_OFFSET;
24094 
24095 	/* TODO why is this test needed? */
24096 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24097 	if (((max_frag - LENGTH) & ~7) < 8) {
24098 		/* TODO: notify ulp somehow */
24099 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24100 		freemsg(mp);
24101 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24102 		    "ip_wput_frag_end:(%S)",
24103 		    "len < 8");
24104 		return;
24105 	}
24106 
24107 	hdr_len = (V_HLEN & 0xF) << 2;
24108 
24109 	ipha->ipha_hdr_checksum = 0;
24110 
24111 	/*
24112 	 * Establish the number of bytes maximum per frag, after putting
24113 	 * in the header.
24114 	 */
24115 	len = (max_frag - hdr_len) & ~7;
24116 
24117 	/* Check if we can use MDT to send out the frags. */
24118 	ASSERT(!IRE_IS_LOCAL(ire));
24119 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24120 	    ipst->ips_ip_multidata_outbound &&
24121 	    !(ire->ire_flags & RTF_MULTIRT) &&
24122 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24123 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24124 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24125 		ASSERT(ill->ill_mdt_capab != NULL);
24126 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24127 			/*
24128 			 * If MDT has been previously turned off in the past,
24129 			 * and we currently can do MDT (due to IPQoS policy
24130 			 * removal, etc.) then enable it for this interface.
24131 			 */
24132 			ill->ill_mdt_capab->ill_mdt_on = 1;
24133 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24134 			    ill->ill_name));
24135 		}
24136 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24137 		    offset);
24138 		return;
24139 	}
24140 
24141 	/* Get a copy of the header for the trailing frags */
24142 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst);
24143 	if (!hdr_mp) {
24144 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24145 		freemsg(mp);
24146 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24147 		    "ip_wput_frag_end:(%S)",
24148 		    "couldn't copy hdr");
24149 		return;
24150 	}
24151 	if (DB_CRED(mp) != NULL)
24152 		mblk_setcred(hdr_mp, DB_CRED(mp));
24153 
24154 	/* Store the starting offset, with the MoreFrags flag. */
24155 	i1 = offset | IPH_MF | frag_flag;
24156 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24157 
24158 	/* Establish the ending byte offset, based on the starting offset. */
24159 	offset <<= 3;
24160 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24161 
24162 	/* Store the length of the first fragment in the IP header. */
24163 	i1 = len + hdr_len;
24164 	ASSERT(i1 <= IP_MAXPACKET);
24165 	ipha->ipha_length = htons((uint16_t)i1);
24166 
24167 	/*
24168 	 * Compute the IP header checksum for the first frag.  We have to
24169 	 * watch out that we stop at the end of the header.
24170 	 */
24171 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24172 
24173 	/*
24174 	 * Now carve off the first frag.  Note that this will include the
24175 	 * original IP header.
24176 	 */
24177 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24178 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24179 		freeb(hdr_mp);
24180 		freemsg(mp_orig);
24181 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24182 		    "ip_wput_frag_end:(%S)",
24183 		    "couldn't carve first");
24184 		return;
24185 	}
24186 
24187 	/*
24188 	 * Multirouting case. Each fragment is replicated
24189 	 * via all non-condemned RTF_MULTIRT routes
24190 	 * currently resolved.
24191 	 * We ensure that first_ire is the first RTF_MULTIRT
24192 	 * ire in the bucket.
24193 	 */
24194 	if (ire->ire_flags & RTF_MULTIRT) {
24195 		irb = ire->ire_bucket;
24196 		ASSERT(irb != NULL);
24197 
24198 		multirt_send = B_TRUE;
24199 
24200 		/* Make sure we do not omit any multiroute ire. */
24201 		IRB_REFHOLD(irb);
24202 		for (first_ire = irb->irb_ire;
24203 		    first_ire != NULL;
24204 		    first_ire = first_ire->ire_next) {
24205 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24206 			    (first_ire->ire_addr == ire->ire_addr) &&
24207 			    !(first_ire->ire_marks &
24208 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
24209 				break;
24210 			}
24211 		}
24212 
24213 		if (first_ire != NULL) {
24214 			if (first_ire != ire) {
24215 				IRE_REFHOLD(first_ire);
24216 				/*
24217 				 * Do not release the ire passed in
24218 				 * as the argument.
24219 				 */
24220 				ire = first_ire;
24221 			} else {
24222 				first_ire = NULL;
24223 			}
24224 		}
24225 		IRB_REFRELE(irb);
24226 
24227 		/*
24228 		 * Save the first ire; we will need to restore it
24229 		 * for the trailing frags.
24230 		 * We REFHOLD save_ire, as each iterated ire will be
24231 		 * REFRELEd.
24232 		 */
24233 		save_ire = ire;
24234 		IRE_REFHOLD(save_ire);
24235 	}
24236 
24237 	/*
24238 	 * First fragment emission loop.
24239 	 * In most cases, the emission loop below is entered only
24240 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24241 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24242 	 * bucket, and send the fragment through all crossed
24243 	 * RTF_MULTIRT routes.
24244 	 */
24245 	do {
24246 		if (ire->ire_flags & RTF_MULTIRT) {
24247 			/*
24248 			 * We are in a multiple send case, need to get
24249 			 * the next ire and make a copy of the packet.
24250 			 * ire1 holds here the next ire to process in the
24251 			 * bucket. If multirouting is expected,
24252 			 * any non-RTF_MULTIRT ire that has the
24253 			 * right destination address is ignored.
24254 			 *
24255 			 * We have to take into account the MTU of
24256 			 * each walked ire. max_frag is set by the
24257 			 * the caller and generally refers to
24258 			 * the primary ire entry. Here we ensure that
24259 			 * no route with a lower MTU will be used, as
24260 			 * fragments are carved once for all ires,
24261 			 * then replicated.
24262 			 */
24263 			ASSERT(irb != NULL);
24264 			IRB_REFHOLD(irb);
24265 			for (ire1 = ire->ire_next;
24266 			    ire1 != NULL;
24267 			    ire1 = ire1->ire_next) {
24268 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24269 					continue;
24270 				if (ire1->ire_addr != ire->ire_addr)
24271 					continue;
24272 				if (ire1->ire_marks &
24273 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24274 					continue;
24275 				/*
24276 				 * Ensure we do not exceed the MTU
24277 				 * of the next route.
24278 				 */
24279 				if (ire1->ire_max_frag < max_frag) {
24280 					ip_multirt_bad_mtu(ire1, max_frag);
24281 					continue;
24282 				}
24283 
24284 				/* Got one. */
24285 				IRE_REFHOLD(ire1);
24286 				break;
24287 			}
24288 			IRB_REFRELE(irb);
24289 
24290 			if (ire1 != NULL) {
24291 				next_mp = copyb(mp);
24292 				if ((next_mp == NULL) ||
24293 				    ((mp->b_cont != NULL) &&
24294 				    ((next_mp->b_cont =
24295 				    dupmsg(mp->b_cont)) == NULL))) {
24296 					freemsg(next_mp);
24297 					next_mp = NULL;
24298 					ire_refrele(ire1);
24299 					ire1 = NULL;
24300 				}
24301 			}
24302 
24303 			/* Last multiroute ire; don't loop anymore. */
24304 			if (ire1 == NULL) {
24305 				multirt_send = B_FALSE;
24306 			}
24307 		}
24308 
24309 		ll_hdr_len = 0;
24310 		LOCK_IRE_FP_MP(ire);
24311 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24312 		if (ll_hdr_mp != NULL) {
24313 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24314 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24315 		} else {
24316 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24317 		}
24318 
24319 		/* If there is a transmit header, get a copy for this frag. */
24320 		/*
24321 		 * TODO: should check db_ref before calling ip_carve_mp since
24322 		 * it might give us a dup.
24323 		 */
24324 		if (!ll_hdr_mp) {
24325 			/* No xmit header. */
24326 			xmit_mp = mp;
24327 
24328 		/* We have a link-layer header that can fit in our mblk. */
24329 		} else if (mp->b_datap->db_ref == 1 &&
24330 		    ll_hdr_len != 0 &&
24331 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24332 			/* M_DATA fastpath */
24333 			mp->b_rptr -= ll_hdr_len;
24334 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24335 			xmit_mp = mp;
24336 
24337 		/* Corner case if copyb has failed */
24338 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24339 			UNLOCK_IRE_FP_MP(ire);
24340 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24341 			freeb(hdr_mp);
24342 			freemsg(mp);
24343 			freemsg(mp_orig);
24344 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24345 			    "ip_wput_frag_end:(%S)",
24346 			    "discard");
24347 
24348 			if (multirt_send) {
24349 				ASSERT(ire1);
24350 				ASSERT(next_mp);
24351 
24352 				freemsg(next_mp);
24353 				ire_refrele(ire1);
24354 			}
24355 			if (save_ire != NULL)
24356 				IRE_REFRELE(save_ire);
24357 
24358 			if (first_ire != NULL)
24359 				ire_refrele(first_ire);
24360 			return;
24361 
24362 		/*
24363 		 * Case of res_mp OR the fastpath mp can't fit
24364 		 * in the mblk
24365 		 */
24366 		} else {
24367 			xmit_mp->b_cont = mp;
24368 			if (DB_CRED(mp) != NULL)
24369 				mblk_setcred(xmit_mp, DB_CRED(mp));
24370 			/*
24371 			 * Get priority marking, if any.
24372 			 * We propagate the CoS marking from the
24373 			 * original packet that went to QoS processing
24374 			 * in ip_wput_ire to the newly carved mp.
24375 			 */
24376 			if (DB_TYPE(xmit_mp) == M_DATA)
24377 				xmit_mp->b_band = mp->b_band;
24378 		}
24379 		UNLOCK_IRE_FP_MP(ire);
24380 
24381 		q = ire->ire_stq;
24382 		out_ill = (ill_t *)q->q_ptr;
24383 
24384 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24385 
24386 		DTRACE_PROBE4(ip4__physical__out__start,
24387 		    ill_t *, NULL, ill_t *, out_ill,
24388 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24389 
24390 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24391 		    ipst->ips_ipv4firewall_physical_out,
24392 		    NULL, out_ill, ipha, xmit_mp, mp, ipst);
24393 
24394 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24395 
24396 		if (xmit_mp != NULL) {
24397 			putnext(q, xmit_mp);
24398 
24399 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24400 			UPDATE_MIB(out_ill->ill_ip_mib,
24401 			    ipIfStatsHCOutOctets, i1);
24402 
24403 			if (pkt_type != OB_PKT) {
24404 				/*
24405 				 * Update the packet count and MIB stats
24406 				 * of trailing RTF_MULTIRT ires.
24407 				 */
24408 				UPDATE_OB_PKT_COUNT(ire);
24409 				BUMP_MIB(out_ill->ill_ip_mib,
24410 				    ipIfStatsOutFragReqds);
24411 			}
24412 		}
24413 
24414 		if (multirt_send) {
24415 			/*
24416 			 * We are in a multiple send case; look for
24417 			 * the next ire and re-enter the loop.
24418 			 */
24419 			ASSERT(ire1);
24420 			ASSERT(next_mp);
24421 			/* REFRELE the current ire before looping */
24422 			ire_refrele(ire);
24423 			ire = ire1;
24424 			ire1 = NULL;
24425 			mp = next_mp;
24426 			next_mp = NULL;
24427 		}
24428 	} while (multirt_send);
24429 
24430 	ASSERT(ire1 == NULL);
24431 
24432 	/* Restore the original ire; we need it for the trailing frags */
24433 	if (save_ire != NULL) {
24434 		/* REFRELE the last iterated ire */
24435 		ire_refrele(ire);
24436 		/* save_ire has been REFHOLDed */
24437 		ire = save_ire;
24438 		save_ire = NULL;
24439 		q = ire->ire_stq;
24440 	}
24441 
24442 	if (pkt_type == OB_PKT) {
24443 		UPDATE_OB_PKT_COUNT(ire);
24444 	} else {
24445 		out_ill = (ill_t *)q->q_ptr;
24446 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24447 		UPDATE_IB_PKT_COUNT(ire);
24448 	}
24449 
24450 	/* Advance the offset to the second frag starting point. */
24451 	offset += len;
24452 	/*
24453 	 * Update hdr_len from the copied header - there might be less options
24454 	 * in the later fragments.
24455 	 */
24456 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24457 	/* Loop until done. */
24458 	for (;;) {
24459 		uint16_t	offset_and_flags;
24460 		uint16_t	ip_len;
24461 
24462 		if (ip_data_end - offset > len) {
24463 			/*
24464 			 * Carve off the appropriate amount from the original
24465 			 * datagram.
24466 			 */
24467 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24468 				mp = NULL;
24469 				break;
24470 			}
24471 			/*
24472 			 * More frags after this one.  Get another copy
24473 			 * of the header.
24474 			 */
24475 			if (carve_mp->b_datap->db_ref == 1 &&
24476 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24477 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24478 				/* Inline IP header */
24479 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24480 				    hdr_mp->b_rptr;
24481 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24482 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24483 				mp = carve_mp;
24484 			} else {
24485 				if (!(mp = copyb(hdr_mp))) {
24486 					freemsg(carve_mp);
24487 					break;
24488 				}
24489 				/* Get priority marking, if any. */
24490 				mp->b_band = carve_mp->b_band;
24491 				mp->b_cont = carve_mp;
24492 			}
24493 			ipha = (ipha_t *)mp->b_rptr;
24494 			offset_and_flags = IPH_MF;
24495 		} else {
24496 			/*
24497 			 * Last frag.  Consume the header. Set len to
24498 			 * the length of this last piece.
24499 			 */
24500 			len = ip_data_end - offset;
24501 
24502 			/*
24503 			 * Carve off the appropriate amount from the original
24504 			 * datagram.
24505 			 */
24506 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24507 				mp = NULL;
24508 				break;
24509 			}
24510 			if (carve_mp->b_datap->db_ref == 1 &&
24511 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24512 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24513 				/* Inline IP header */
24514 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24515 				    hdr_mp->b_rptr;
24516 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24517 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24518 				mp = carve_mp;
24519 				freeb(hdr_mp);
24520 				hdr_mp = mp;
24521 			} else {
24522 				mp = hdr_mp;
24523 				/* Get priority marking, if any. */
24524 				mp->b_band = carve_mp->b_band;
24525 				mp->b_cont = carve_mp;
24526 			}
24527 			ipha = (ipha_t *)mp->b_rptr;
24528 			/* A frag of a frag might have IPH_MF non-zero */
24529 			offset_and_flags =
24530 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24531 			    IPH_MF;
24532 		}
24533 		offset_and_flags |= (uint16_t)(offset >> 3);
24534 		offset_and_flags |= (uint16_t)frag_flag;
24535 		/* Store the offset and flags in the IP header. */
24536 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24537 
24538 		/* Store the length in the IP header. */
24539 		ip_len = (uint16_t)(len + hdr_len);
24540 		ipha->ipha_length = htons(ip_len);
24541 
24542 		/*
24543 		 * Set the IP header checksum.	Note that mp is just
24544 		 * the header, so this is easy to pass to ip_csum.
24545 		 */
24546 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24547 
24548 		/* Attach a transmit header, if any, and ship it. */
24549 		if (pkt_type == OB_PKT) {
24550 			UPDATE_OB_PKT_COUNT(ire);
24551 		} else {
24552 			out_ill = (ill_t *)q->q_ptr;
24553 			BUMP_MIB(out_ill->ill_ip_mib,
24554 			    ipIfStatsHCOutForwDatagrams);
24555 			UPDATE_IB_PKT_COUNT(ire);
24556 		}
24557 
24558 		if (ire->ire_flags & RTF_MULTIRT) {
24559 			irb = ire->ire_bucket;
24560 			ASSERT(irb != NULL);
24561 
24562 			multirt_send = B_TRUE;
24563 
24564 			/*
24565 			 * Save the original ire; we will need to restore it
24566 			 * for the tailing frags.
24567 			 */
24568 			save_ire = ire;
24569 			IRE_REFHOLD(save_ire);
24570 		}
24571 		/*
24572 		 * Emission loop for this fragment, similar
24573 		 * to what is done for the first fragment.
24574 		 */
24575 		do {
24576 			if (multirt_send) {
24577 				/*
24578 				 * We are in a multiple send case, need to get
24579 				 * the next ire and make a copy of the packet.
24580 				 */
24581 				ASSERT(irb != NULL);
24582 				IRB_REFHOLD(irb);
24583 				for (ire1 = ire->ire_next;
24584 				    ire1 != NULL;
24585 				    ire1 = ire1->ire_next) {
24586 					if (!(ire1->ire_flags & RTF_MULTIRT))
24587 						continue;
24588 					if (ire1->ire_addr != ire->ire_addr)
24589 						continue;
24590 					if (ire1->ire_marks &
24591 					    (IRE_MARK_CONDEMNED|
24592 					    IRE_MARK_HIDDEN)) {
24593 						continue;
24594 					}
24595 					/*
24596 					 * Ensure we do not exceed the MTU
24597 					 * of the next route.
24598 					 */
24599 					if (ire1->ire_max_frag < max_frag) {
24600 						ip_multirt_bad_mtu(ire1,
24601 						    max_frag);
24602 						continue;
24603 					}
24604 
24605 					/* Got one. */
24606 					IRE_REFHOLD(ire1);
24607 					break;
24608 				}
24609 				IRB_REFRELE(irb);
24610 
24611 				if (ire1 != NULL) {
24612 					next_mp = copyb(mp);
24613 					if ((next_mp == NULL) ||
24614 					    ((mp->b_cont != NULL) &&
24615 					    ((next_mp->b_cont =
24616 					    dupmsg(mp->b_cont)) == NULL))) {
24617 						freemsg(next_mp);
24618 						next_mp = NULL;
24619 						ire_refrele(ire1);
24620 						ire1 = NULL;
24621 					}
24622 				}
24623 
24624 				/* Last multiroute ire; don't loop anymore. */
24625 				if (ire1 == NULL) {
24626 					multirt_send = B_FALSE;
24627 				}
24628 			}
24629 
24630 			/* Update transmit header */
24631 			ll_hdr_len = 0;
24632 			LOCK_IRE_FP_MP(ire);
24633 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24634 			if (ll_hdr_mp != NULL) {
24635 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24636 				ll_hdr_len = MBLKL(ll_hdr_mp);
24637 			} else {
24638 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24639 			}
24640 
24641 			if (!ll_hdr_mp) {
24642 				xmit_mp = mp;
24643 
24644 			/*
24645 			 * We have link-layer header that can fit in
24646 			 * our mblk.
24647 			 */
24648 			} else if (mp->b_datap->db_ref == 1 &&
24649 			    ll_hdr_len != 0 &&
24650 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24651 				/* M_DATA fastpath */
24652 				mp->b_rptr -= ll_hdr_len;
24653 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24654 				    ll_hdr_len);
24655 				xmit_mp = mp;
24656 
24657 			/*
24658 			 * Case of res_mp OR the fastpath mp can't fit
24659 			 * in the mblk
24660 			 */
24661 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24662 				xmit_mp->b_cont = mp;
24663 				if (DB_CRED(mp) != NULL)
24664 					mblk_setcred(xmit_mp, DB_CRED(mp));
24665 				/* Get priority marking, if any. */
24666 				if (DB_TYPE(xmit_mp) == M_DATA)
24667 					xmit_mp->b_band = mp->b_band;
24668 
24669 			/* Corner case if copyb failed */
24670 			} else {
24671 				/*
24672 				 * Exit both the replication and
24673 				 * fragmentation loops.
24674 				 */
24675 				UNLOCK_IRE_FP_MP(ire);
24676 				goto drop_pkt;
24677 			}
24678 			UNLOCK_IRE_FP_MP(ire);
24679 
24680 			mp1 = mp;
24681 			out_ill = (ill_t *)q->q_ptr;
24682 
24683 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24684 
24685 			DTRACE_PROBE4(ip4__physical__out__start,
24686 			    ill_t *, NULL, ill_t *, out_ill,
24687 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24688 
24689 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24690 			    ipst->ips_ipv4firewall_physical_out,
24691 			    NULL, out_ill, ipha, xmit_mp, mp, ipst);
24692 
24693 			DTRACE_PROBE1(ip4__physical__out__end,
24694 			    mblk_t *, xmit_mp);
24695 
24696 			if (mp != mp1 && hdr_mp == mp1)
24697 				hdr_mp = mp;
24698 			if (mp != mp1 && mp_orig == mp1)
24699 				mp_orig = mp;
24700 
24701 			if (xmit_mp != NULL) {
24702 				putnext(q, xmit_mp);
24703 
24704 				BUMP_MIB(out_ill->ill_ip_mib,
24705 				    ipIfStatsHCOutTransmits);
24706 				UPDATE_MIB(out_ill->ill_ip_mib,
24707 				    ipIfStatsHCOutOctets, ip_len);
24708 
24709 				if (pkt_type != OB_PKT) {
24710 					/*
24711 					 * Update the packet count of trailing
24712 					 * RTF_MULTIRT ires.
24713 					 */
24714 					UPDATE_OB_PKT_COUNT(ire);
24715 				}
24716 			}
24717 
24718 			/* All done if we just consumed the hdr_mp. */
24719 			if (mp == hdr_mp) {
24720 				last_frag = B_TRUE;
24721 				BUMP_MIB(out_ill->ill_ip_mib,
24722 				    ipIfStatsOutFragOKs);
24723 			}
24724 
24725 			if (multirt_send) {
24726 				/*
24727 				 * We are in a multiple send case; look for
24728 				 * the next ire and re-enter the loop.
24729 				 */
24730 				ASSERT(ire1);
24731 				ASSERT(next_mp);
24732 				/* REFRELE the current ire before looping */
24733 				ire_refrele(ire);
24734 				ire = ire1;
24735 				ire1 = NULL;
24736 				q = ire->ire_stq;
24737 				mp = next_mp;
24738 				next_mp = NULL;
24739 			}
24740 		} while (multirt_send);
24741 		/*
24742 		 * Restore the original ire; we need it for the
24743 		 * trailing frags
24744 		 */
24745 		if (save_ire != NULL) {
24746 			ASSERT(ire1 == NULL);
24747 			/* REFRELE the last iterated ire */
24748 			ire_refrele(ire);
24749 			/* save_ire has been REFHOLDed */
24750 			ire = save_ire;
24751 			q = ire->ire_stq;
24752 			save_ire = NULL;
24753 		}
24754 
24755 		if (last_frag) {
24756 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24757 			    "ip_wput_frag_end:(%S)",
24758 			    "consumed hdr_mp");
24759 
24760 			if (first_ire != NULL)
24761 				ire_refrele(first_ire);
24762 			return;
24763 		}
24764 		/* Otherwise, advance and loop. */
24765 		offset += len;
24766 	}
24767 
24768 drop_pkt:
24769 	/* Clean up following allocation failure. */
24770 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24771 	freemsg(mp);
24772 	if (mp != hdr_mp)
24773 		freeb(hdr_mp);
24774 	if (mp != mp_orig)
24775 		freemsg(mp_orig);
24776 
24777 	if (save_ire != NULL)
24778 		IRE_REFRELE(save_ire);
24779 	if (first_ire != NULL)
24780 		ire_refrele(first_ire);
24781 
24782 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24783 	    "ip_wput_frag_end:(%S)",
24784 	    "end--alloc failure");
24785 }
24786 
24787 /*
24788  * Copy the header plus those options which have the copy bit set
24789  */
24790 static mblk_t *
24791 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst)
24792 {
24793 	mblk_t	*mp;
24794 	uchar_t	*up;
24795 
24796 	/*
24797 	 * Quick check if we need to look for options without the copy bit
24798 	 * set
24799 	 */
24800 	mp = allocb(ipst->ips_ip_wroff_extra + hdr_len, BPRI_HI);
24801 	if (!mp)
24802 		return (mp);
24803 	mp->b_rptr += ipst->ips_ip_wroff_extra;
24804 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24805 		bcopy(rptr, mp->b_rptr, hdr_len);
24806 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
24807 		return (mp);
24808 	}
24809 	up  = mp->b_rptr;
24810 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24811 	up += IP_SIMPLE_HDR_LENGTH;
24812 	rptr += IP_SIMPLE_HDR_LENGTH;
24813 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24814 	while (hdr_len > 0) {
24815 		uint32_t optval;
24816 		uint32_t optlen;
24817 
24818 		optval = *rptr;
24819 		if (optval == IPOPT_EOL)
24820 			break;
24821 		if (optval == IPOPT_NOP)
24822 			optlen = 1;
24823 		else
24824 			optlen = rptr[1];
24825 		if (optval & IPOPT_COPY) {
24826 			bcopy(rptr, up, optlen);
24827 			up += optlen;
24828 		}
24829 		rptr += optlen;
24830 		hdr_len -= optlen;
24831 	}
24832 	/*
24833 	 * Make sure that we drop an even number of words by filling
24834 	 * with EOL to the next word boundary.
24835 	 */
24836 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
24837 	    hdr_len & 0x3; hdr_len++)
24838 		*up++ = IPOPT_EOL;
24839 	mp->b_wptr = up;
24840 	/* Update header length */
24841 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
24842 	return (mp);
24843 }
24844 
24845 /*
24846  * Delivery to local recipients including fanout to multiple recipients.
24847  * Does not do checksumming of UDP/TCP.
24848  * Note: q should be the read side queue for either the ill or conn.
24849  * Note: rq should be the read side q for the lower (ill) stream.
24850  * We don't send packets to IPPF processing, thus the last argument
24851  * to all the fanout calls are B_FALSE.
24852  */
24853 void
24854 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
24855     int fanout_flags, zoneid_t zoneid)
24856 {
24857 	uint32_t	protocol;
24858 	mblk_t		*first_mp;
24859 	boolean_t	mctl_present;
24860 	int		ire_type;
24861 #define	rptr	((uchar_t *)ipha)
24862 	ip_stack_t	*ipst = ill->ill_ipst;
24863 
24864 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
24865 	    "ip_wput_local_start: q %p", q);
24866 
24867 	if (ire != NULL) {
24868 		ire_type = ire->ire_type;
24869 	} else {
24870 		/*
24871 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
24872 		 * packet is not multicast, we can't tell the ire type.
24873 		 */
24874 		ASSERT(CLASSD(ipha->ipha_dst));
24875 		ire_type = IRE_BROADCAST;
24876 	}
24877 
24878 	first_mp = mp;
24879 	if (first_mp->b_datap->db_type == M_CTL) {
24880 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
24881 		if (!io->ipsec_out_secure) {
24882 			/*
24883 			 * This ipsec_out_t was allocated in ip_wput
24884 			 * for multicast packets to store the ill_index.
24885 			 * As this is being delivered locally, we don't
24886 			 * need this anymore.
24887 			 */
24888 			mp = first_mp->b_cont;
24889 			freeb(first_mp);
24890 			first_mp = mp;
24891 			mctl_present = B_FALSE;
24892 		} else {
24893 			/*
24894 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
24895 			 * security properties for the looped-back packet.
24896 			 */
24897 			mctl_present = B_TRUE;
24898 			mp = first_mp->b_cont;
24899 			ASSERT(mp != NULL);
24900 			ipsec_out_to_in(first_mp);
24901 		}
24902 	} else {
24903 		mctl_present = B_FALSE;
24904 	}
24905 
24906 	DTRACE_PROBE4(ip4__loopback__in__start,
24907 	    ill_t *, ill, ill_t *, NULL,
24908 	    ipha_t *, ipha, mblk_t *, first_mp);
24909 
24910 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
24911 	    ipst->ips_ipv4firewall_loopback_in,
24912 	    ill, NULL, ipha, first_mp, mp, ipst);
24913 
24914 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
24915 
24916 	if (first_mp == NULL)
24917 		return;
24918 
24919 	ipst->ips_loopback_packets++;
24920 
24921 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
24922 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
24923 	if (!IS_SIMPLE_IPH(ipha)) {
24924 		ip_wput_local_options(ipha, ipst);
24925 	}
24926 
24927 	protocol = ipha->ipha_protocol;
24928 	switch (protocol) {
24929 	case IPPROTO_ICMP: {
24930 		ire_t		*ire_zone;
24931 		ilm_t		*ilm;
24932 		mblk_t		*mp1;
24933 		zoneid_t	last_zoneid;
24934 
24935 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
24936 			ASSERT(ire_type == IRE_BROADCAST);
24937 			/*
24938 			 * In the multicast case, applications may have joined
24939 			 * the group from different zones, so we need to deliver
24940 			 * the packet to each of them. Loop through the
24941 			 * multicast memberships structures (ilm) on the receive
24942 			 * ill and send a copy of the packet up each matching
24943 			 * one. However, we don't do this for multicasts sent on
24944 			 * the loopback interface (PHYI_LOOPBACK flag set) as
24945 			 * they must stay in the sender's zone.
24946 			 *
24947 			 * ilm_add_v6() ensures that ilms in the same zone are
24948 			 * contiguous in the ill_ilm list. We use this property
24949 			 * to avoid sending duplicates needed when two
24950 			 * applications in the same zone join the same group on
24951 			 * different logical interfaces: we ignore the ilm if
24952 			 * it's zoneid is the same as the last matching one.
24953 			 * In addition, the sending of the packet for
24954 			 * ire_zoneid is delayed until all of the other ilms
24955 			 * have been exhausted.
24956 			 */
24957 			last_zoneid = -1;
24958 			ILM_WALKER_HOLD(ill);
24959 			for (ilm = ill->ill_ilm; ilm != NULL;
24960 			    ilm = ilm->ilm_next) {
24961 				if ((ilm->ilm_flags & ILM_DELETED) ||
24962 				    ipha->ipha_dst != ilm->ilm_addr ||
24963 				    ilm->ilm_zoneid == last_zoneid ||
24964 				    ilm->ilm_zoneid == zoneid ||
24965 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
24966 					continue;
24967 				mp1 = ip_copymsg(first_mp);
24968 				if (mp1 == NULL)
24969 					continue;
24970 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
24971 				    mctl_present, B_FALSE, ill,
24972 				    ilm->ilm_zoneid);
24973 				last_zoneid = ilm->ilm_zoneid;
24974 			}
24975 			ILM_WALKER_RELE(ill);
24976 			/*
24977 			 * Loopback case: the sending endpoint has
24978 			 * IP_MULTICAST_LOOP disabled, therefore we don't
24979 			 * dispatch the multicast packet to the sending zone.
24980 			 */
24981 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
24982 				freemsg(first_mp);
24983 				return;
24984 			}
24985 		} else if (ire_type == IRE_BROADCAST) {
24986 			/*
24987 			 * In the broadcast case, there may be many zones
24988 			 * which need a copy of the packet delivered to them.
24989 			 * There is one IRE_BROADCAST per broadcast address
24990 			 * and per zone; we walk those using a helper function.
24991 			 * In addition, the sending of the packet for zoneid is
24992 			 * delayed until all of the other ires have been
24993 			 * processed.
24994 			 */
24995 			IRB_REFHOLD(ire->ire_bucket);
24996 			ire_zone = NULL;
24997 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
24998 			    ire)) != NULL) {
24999 				mp1 = ip_copymsg(first_mp);
25000 				if (mp1 == NULL)
25001 					continue;
25002 
25003 				UPDATE_IB_PKT_COUNT(ire_zone);
25004 				ire_zone->ire_last_used_time = lbolt;
25005 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25006 				    mctl_present, B_FALSE, ill,
25007 				    ire_zone->ire_zoneid);
25008 			}
25009 			IRB_REFRELE(ire->ire_bucket);
25010 		}
25011 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25012 		    0, mctl_present, B_FALSE, ill, zoneid);
25013 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25014 		    "ip_wput_local_end: q %p (%S)",
25015 		    q, "icmp");
25016 		return;
25017 	}
25018 	case IPPROTO_IGMP:
25019 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25020 			/* Bad packet - discarded by igmp_input */
25021 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25022 			    "ip_wput_local_end: q %p (%S)",
25023 			    q, "igmp_input--bad packet");
25024 			if (mctl_present)
25025 				freeb(first_mp);
25026 			return;
25027 		}
25028 		/*
25029 		 * igmp_input() may have returned the pulled up message.
25030 		 * So first_mp and ipha need to be reinitialized.
25031 		 */
25032 		ipha = (ipha_t *)mp->b_rptr;
25033 		if (mctl_present)
25034 			first_mp->b_cont = mp;
25035 		else
25036 			first_mp = mp;
25037 		/* deliver to local raw users */
25038 		break;
25039 	case IPPROTO_ENCAP:
25040 		/*
25041 		 * This case is covered by either ip_fanout_proto, or by
25042 		 * the above security processing for self-tunneled packets.
25043 		 */
25044 		break;
25045 	case IPPROTO_UDP: {
25046 		uint16_t	*up;
25047 		uint32_t	ports;
25048 
25049 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25050 		    UDP_PORTS_OFFSET);
25051 		/* Force a 'valid' checksum. */
25052 		up[3] = 0;
25053 
25054 		ports = *(uint32_t *)up;
25055 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25056 		    (ire_type == IRE_BROADCAST),
25057 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25058 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25059 		    ill, zoneid);
25060 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25061 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25062 		return;
25063 	}
25064 	case IPPROTO_TCP: {
25065 
25066 		/*
25067 		 * For TCP, discard broadcast packets.
25068 		 */
25069 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25070 			freemsg(first_mp);
25071 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25072 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25073 			return;
25074 		}
25075 
25076 		if (mp->b_datap->db_type == M_DATA) {
25077 			/*
25078 			 * M_DATA mblk, so init mblk (chain) for no struio().
25079 			 */
25080 			mblk_t	*mp1 = mp;
25081 
25082 			do {
25083 				mp1->b_datap->db_struioflag = 0;
25084 			} while ((mp1 = mp1->b_cont) != NULL);
25085 		}
25086 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25087 		    <= mp->b_wptr);
25088 		ip_fanout_tcp(q, first_mp, ill, ipha,
25089 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25090 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25091 		    mctl_present, B_FALSE, zoneid);
25092 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25093 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25094 		return;
25095 	}
25096 	case IPPROTO_SCTP:
25097 	{
25098 		uint32_t	ports;
25099 
25100 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25101 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25102 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25103 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25104 		return;
25105 	}
25106 
25107 	default:
25108 		break;
25109 	}
25110 	/*
25111 	 * Find a client for some other protocol.  We give
25112 	 * copies to multiple clients, if more than one is
25113 	 * bound.
25114 	 */
25115 	ip_fanout_proto(q, first_mp, ill, ipha,
25116 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25117 	    mctl_present, B_FALSE, ill, zoneid);
25118 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25119 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25120 #undef	rptr
25121 }
25122 
25123 /*
25124  * Update any source route, record route, or timestamp options.
25125  * Check that we are at end of strict source route.
25126  * The options have been sanity checked by ip_wput_options().
25127  */
25128 static void
25129 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25130 {
25131 	ipoptp_t	opts;
25132 	uchar_t		*opt;
25133 	uint8_t		optval;
25134 	uint8_t		optlen;
25135 	ipaddr_t	dst;
25136 	uint32_t	ts;
25137 	ire_t		*ire;
25138 	timestruc_t	now;
25139 
25140 	ip2dbg(("ip_wput_local_options\n"));
25141 	for (optval = ipoptp_first(&opts, ipha);
25142 	    optval != IPOPT_EOL;
25143 	    optval = ipoptp_next(&opts)) {
25144 		opt = opts.ipoptp_cur;
25145 		optlen = opts.ipoptp_len;
25146 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25147 		switch (optval) {
25148 			uint32_t off;
25149 		case IPOPT_SSRR:
25150 		case IPOPT_LSRR:
25151 			off = opt[IPOPT_OFFSET];
25152 			off--;
25153 			if (optlen < IP_ADDR_LEN ||
25154 			    off > optlen - IP_ADDR_LEN) {
25155 				/* End of source route */
25156 				break;
25157 			}
25158 			/*
25159 			 * This will only happen if two consecutive entries
25160 			 * in the source route contains our address or if
25161 			 * it is a packet with a loose source route which
25162 			 * reaches us before consuming the whole source route
25163 			 */
25164 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25165 			if (optval == IPOPT_SSRR) {
25166 				return;
25167 			}
25168 			/*
25169 			 * Hack: instead of dropping the packet truncate the
25170 			 * source route to what has been used by filling the
25171 			 * rest with IPOPT_NOP.
25172 			 */
25173 			opt[IPOPT_OLEN] = (uint8_t)off;
25174 			while (off < optlen) {
25175 				opt[off++] = IPOPT_NOP;
25176 			}
25177 			break;
25178 		case IPOPT_RR:
25179 			off = opt[IPOPT_OFFSET];
25180 			off--;
25181 			if (optlen < IP_ADDR_LEN ||
25182 			    off > optlen - IP_ADDR_LEN) {
25183 				/* No more room - ignore */
25184 				ip1dbg((
25185 				    "ip_wput_forward_options: end of RR\n"));
25186 				break;
25187 			}
25188 			dst = htonl(INADDR_LOOPBACK);
25189 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25190 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25191 			break;
25192 		case IPOPT_TS:
25193 			/* Insert timestamp if there is romm */
25194 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25195 			case IPOPT_TS_TSONLY:
25196 				off = IPOPT_TS_TIMELEN;
25197 				break;
25198 			case IPOPT_TS_PRESPEC:
25199 			case IPOPT_TS_PRESPEC_RFC791:
25200 				/* Verify that the address matched */
25201 				off = opt[IPOPT_OFFSET] - 1;
25202 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25203 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25204 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25205 				    ipst);
25206 				if (ire == NULL) {
25207 					/* Not for us */
25208 					break;
25209 				}
25210 				ire_refrele(ire);
25211 				/* FALLTHRU */
25212 			case IPOPT_TS_TSANDADDR:
25213 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25214 				break;
25215 			default:
25216 				/*
25217 				 * ip_*put_options should have already
25218 				 * dropped this packet.
25219 				 */
25220 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25221 				    "unknown IT - bug in ip_wput_options?\n");
25222 				return;	/* Keep "lint" happy */
25223 			}
25224 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25225 				/* Increase overflow counter */
25226 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25227 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25228 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25229 				    (off << 4);
25230 				break;
25231 			}
25232 			off = opt[IPOPT_OFFSET] - 1;
25233 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25234 			case IPOPT_TS_PRESPEC:
25235 			case IPOPT_TS_PRESPEC_RFC791:
25236 			case IPOPT_TS_TSANDADDR:
25237 				dst = htonl(INADDR_LOOPBACK);
25238 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25239 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25240 				/* FALLTHRU */
25241 			case IPOPT_TS_TSONLY:
25242 				off = opt[IPOPT_OFFSET] - 1;
25243 				/* Compute # of milliseconds since midnight */
25244 				gethrestime(&now);
25245 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25246 				    now.tv_nsec / (NANOSEC / MILLISEC);
25247 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25248 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25249 				break;
25250 			}
25251 			break;
25252 		}
25253 	}
25254 }
25255 
25256 /*
25257  * Send out a multicast packet on interface ipif.
25258  * The sender does not have an conn.
25259  * Caller verifies that this isn't a PHYI_LOOPBACK.
25260  */
25261 void
25262 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25263 {
25264 	ipha_t	*ipha;
25265 	ire_t	*ire;
25266 	ipaddr_t	dst;
25267 	mblk_t		*first_mp;
25268 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25269 
25270 	/* igmp_sendpkt always allocates a ipsec_out_t */
25271 	ASSERT(mp->b_datap->db_type == M_CTL);
25272 	ASSERT(!ipif->ipif_isv6);
25273 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25274 
25275 	first_mp = mp;
25276 	mp = first_mp->b_cont;
25277 	ASSERT(mp->b_datap->db_type == M_DATA);
25278 	ipha = (ipha_t *)mp->b_rptr;
25279 
25280 	/*
25281 	 * Find an IRE which matches the destination and the outgoing
25282 	 * queue (i.e. the outgoing interface.)
25283 	 */
25284 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25285 		dst = ipif->ipif_pp_dst_addr;
25286 	else
25287 		dst = ipha->ipha_dst;
25288 	/*
25289 	 * The source address has already been initialized by the
25290 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25291 	 * be sufficient rather than MATCH_IRE_IPIF.
25292 	 *
25293 	 * This function is used for sending IGMP packets. We need
25294 	 * to make sure that we send the packet out of the interface
25295 	 * (ipif->ipif_ill) where we joined the group. This is to
25296 	 * prevent from switches doing IGMP snooping to send us multicast
25297 	 * packets for a given group on the interface we have joined.
25298 	 * If we can't find an ire, igmp_sendpkt has already initialized
25299 	 * ipsec_out_attach_if so that this will not be load spread in
25300 	 * ip_newroute_ipif.
25301 	 */
25302 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25303 	    MATCH_IRE_ILL, ipst);
25304 	if (!ire) {
25305 		/*
25306 		 * Mark this packet to make it be delivered to
25307 		 * ip_wput_ire after the new ire has been
25308 		 * created.
25309 		 */
25310 		mp->b_prev = NULL;
25311 		mp->b_next = NULL;
25312 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25313 		    zoneid, &zero_info);
25314 		return;
25315 	}
25316 
25317 	/*
25318 	 * Honor the RTF_SETSRC flag; this is the only case
25319 	 * where we force this addr whatever the current src addr is,
25320 	 * because this address is set by igmp_sendpkt(), and
25321 	 * cannot be specified by any user.
25322 	 */
25323 	if (ire->ire_flags & RTF_SETSRC) {
25324 		ipha->ipha_src = ire->ire_src_addr;
25325 	}
25326 
25327 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25328 }
25329 
25330 /*
25331  * NOTE : This function does not ire_refrele the ire argument passed in.
25332  *
25333  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25334  * failure. The nce_fp_mp can vanish any time in the case of
25335  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25336  * the ire_lock to access the nce_fp_mp in this case.
25337  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25338  * prepending a fastpath message IPQoS processing must precede it, we also set
25339  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25340  * (IPQoS might have set the b_band for CoS marking).
25341  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25342  * must follow it so that IPQoS can mark the dl_priority field for CoS
25343  * marking, if needed.
25344  */
25345 static mblk_t *
25346 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
25347 {
25348 	uint_t	hlen;
25349 	ipha_t *ipha;
25350 	mblk_t *mp1;
25351 	boolean_t qos_done = B_FALSE;
25352 	uchar_t	*ll_hdr;
25353 	ip_stack_t	*ipst = ire->ire_ipst;
25354 
25355 #define	rptr	((uchar_t *)ipha)
25356 
25357 	ipha = (ipha_t *)mp->b_rptr;
25358 	hlen = 0;
25359 	LOCK_IRE_FP_MP(ire);
25360 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25361 		ASSERT(DB_TYPE(mp1) == M_DATA);
25362 		/* Initiate IPPF processing */
25363 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25364 			UNLOCK_IRE_FP_MP(ire);
25365 			ip_process(proc, &mp, ill_index);
25366 			if (mp == NULL)
25367 				return (NULL);
25368 
25369 			ipha = (ipha_t *)mp->b_rptr;
25370 			LOCK_IRE_FP_MP(ire);
25371 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25372 				qos_done = B_TRUE;
25373 				goto no_fp_mp;
25374 			}
25375 			ASSERT(DB_TYPE(mp1) == M_DATA);
25376 		}
25377 		hlen = MBLKL(mp1);
25378 		/*
25379 		 * Check if we have enough room to prepend fastpath
25380 		 * header
25381 		 */
25382 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25383 			ll_hdr = rptr - hlen;
25384 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25385 			/*
25386 			 * Set the b_rptr to the start of the link layer
25387 			 * header
25388 			 */
25389 			mp->b_rptr = ll_hdr;
25390 			mp1 = mp;
25391 		} else {
25392 			mp1 = copyb(mp1);
25393 			if (mp1 == NULL)
25394 				goto unlock_err;
25395 			mp1->b_band = mp->b_band;
25396 			mp1->b_cont = mp;
25397 			/*
25398 			 * certain system generated traffic may not
25399 			 * have cred/label in ip header block. This
25400 			 * is true even for a labeled system. But for
25401 			 * labeled traffic, inherit the label in the
25402 			 * new header.
25403 			 */
25404 			if (DB_CRED(mp) != NULL)
25405 				mblk_setcred(mp1, DB_CRED(mp));
25406 			/*
25407 			 * XXX disable ICK_VALID and compute checksum
25408 			 * here; can happen if nce_fp_mp changes and
25409 			 * it can't be copied now due to insufficient
25410 			 * space. (unlikely, fp mp can change, but it
25411 			 * does not increase in length)
25412 			 */
25413 		}
25414 		UNLOCK_IRE_FP_MP(ire);
25415 	} else {
25416 no_fp_mp:
25417 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25418 		if (mp1 == NULL) {
25419 unlock_err:
25420 			UNLOCK_IRE_FP_MP(ire);
25421 			freemsg(mp);
25422 			return (NULL);
25423 		}
25424 		UNLOCK_IRE_FP_MP(ire);
25425 		mp1->b_cont = mp;
25426 		/*
25427 		 * certain system generated traffic may not
25428 		 * have cred/label in ip header block. This
25429 		 * is true even for a labeled system. But for
25430 		 * labeled traffic, inherit the label in the
25431 		 * new header.
25432 		 */
25433 		if (DB_CRED(mp) != NULL)
25434 			mblk_setcred(mp1, DB_CRED(mp));
25435 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25436 			ip_process(proc, &mp1, ill_index);
25437 			if (mp1 == NULL)
25438 				return (NULL);
25439 		}
25440 	}
25441 	return (mp1);
25442 #undef rptr
25443 }
25444 
25445 /*
25446  * Finish the outbound IPsec processing for an IPv6 packet. This function
25447  * is called from ipsec_out_process() if the IPsec packet was processed
25448  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25449  * asynchronously.
25450  */
25451 void
25452 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25453     ire_t *ire_arg)
25454 {
25455 	in6_addr_t *v6dstp;
25456 	ire_t *ire;
25457 	mblk_t *mp;
25458 	ip6_t *ip6h1;
25459 	uint_t	ill_index;
25460 	ipsec_out_t *io;
25461 	boolean_t attach_if, hwaccel;
25462 	uint32_t flags = IP6_NO_IPPOLICY;
25463 	int match_flags;
25464 	zoneid_t zoneid;
25465 	boolean_t ill_need_rele = B_FALSE;
25466 	boolean_t ire_need_rele = B_FALSE;
25467 	ip_stack_t	*ipst;
25468 
25469 	mp = ipsec_mp->b_cont;
25470 	ip6h1 = (ip6_t *)mp->b_rptr;
25471 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25472 	ASSERT(io->ipsec_out_ns != NULL);
25473 	ipst = io->ipsec_out_ns->netstack_ip;
25474 	ill_index = io->ipsec_out_ill_index;
25475 	if (io->ipsec_out_reachable) {
25476 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25477 	}
25478 	attach_if = io->ipsec_out_attach_if;
25479 	hwaccel = io->ipsec_out_accelerated;
25480 	zoneid = io->ipsec_out_zoneid;
25481 	ASSERT(zoneid != ALL_ZONES);
25482 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25483 	/* Multicast addresses should have non-zero ill_index. */
25484 	v6dstp = &ip6h->ip6_dst;
25485 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25486 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25487 	ASSERT(!attach_if || ill_index != 0);
25488 	if (ill_index != 0) {
25489 		if (ill == NULL) {
25490 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
25491 			    B_TRUE, ipst);
25492 
25493 			/* Failure case frees things for us. */
25494 			if (ill == NULL)
25495 				return;
25496 
25497 			ill_need_rele = B_TRUE;
25498 		}
25499 		/*
25500 		 * If this packet needs to go out on a particular interface
25501 		 * honor it.
25502 		 */
25503 		if (attach_if) {
25504 			match_flags = MATCH_IRE_ILL;
25505 
25506 			/*
25507 			 * Check if we need an ire that will not be
25508 			 * looked up by anybody else i.e. HIDDEN.
25509 			 */
25510 			if (ill_is_probeonly(ill)) {
25511 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25512 			}
25513 		}
25514 	}
25515 	ASSERT(mp != NULL);
25516 
25517 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25518 		boolean_t unspec_src;
25519 		ipif_t	*ipif;
25520 
25521 		/*
25522 		 * Use the ill_index to get the right ill.
25523 		 */
25524 		unspec_src = io->ipsec_out_unspec_src;
25525 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25526 		if (ipif == NULL) {
25527 			if (ill_need_rele)
25528 				ill_refrele(ill);
25529 			freemsg(ipsec_mp);
25530 			return;
25531 		}
25532 
25533 		if (ire_arg != NULL) {
25534 			ire = ire_arg;
25535 		} else {
25536 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25537 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25538 			ire_need_rele = B_TRUE;
25539 		}
25540 		if (ire != NULL) {
25541 			ipif_refrele(ipif);
25542 			/*
25543 			 * XXX Do the multicast forwarding now, as the IPsec
25544 			 * processing has been done.
25545 			 */
25546 			goto send;
25547 		}
25548 
25549 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25550 		mp->b_prev = NULL;
25551 		mp->b_next = NULL;
25552 
25553 		/*
25554 		 * If the IPsec packet was processed asynchronously,
25555 		 * drop it now.
25556 		 */
25557 		if (q == NULL) {
25558 			if (ill_need_rele)
25559 				ill_refrele(ill);
25560 			freemsg(ipsec_mp);
25561 			return;
25562 		}
25563 
25564 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
25565 		    unspec_src, zoneid);
25566 		ipif_refrele(ipif);
25567 	} else {
25568 		if (attach_if) {
25569 			ipif_t	*ipif;
25570 
25571 			ipif = ipif_get_next_ipif(NULL, ill);
25572 			if (ipif == NULL) {
25573 				if (ill_need_rele)
25574 					ill_refrele(ill);
25575 				freemsg(ipsec_mp);
25576 				return;
25577 			}
25578 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25579 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25580 			ire_need_rele = B_TRUE;
25581 			ipif_refrele(ipif);
25582 		} else {
25583 			if (ire_arg != NULL) {
25584 				ire = ire_arg;
25585 			} else {
25586 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL,
25587 				    ipst);
25588 				ire_need_rele = B_TRUE;
25589 			}
25590 		}
25591 		if (ire != NULL)
25592 			goto send;
25593 		/*
25594 		 * ire disappeared underneath.
25595 		 *
25596 		 * What we need to do here is the ip_newroute
25597 		 * logic to get the ire without doing the IPsec
25598 		 * processing. Follow the same old path. But this
25599 		 * time, ip_wput or ire_add_then_send will call us
25600 		 * directly as all the IPsec operations are done.
25601 		 */
25602 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25603 		mp->b_prev = NULL;
25604 		mp->b_next = NULL;
25605 
25606 		/*
25607 		 * If the IPsec packet was processed asynchronously,
25608 		 * drop it now.
25609 		 */
25610 		if (q == NULL) {
25611 			if (ill_need_rele)
25612 				ill_refrele(ill);
25613 			freemsg(ipsec_mp);
25614 			return;
25615 		}
25616 
25617 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25618 		    zoneid, ipst);
25619 	}
25620 	if (ill != NULL && ill_need_rele)
25621 		ill_refrele(ill);
25622 	return;
25623 send:
25624 	if (ill != NULL && ill_need_rele)
25625 		ill_refrele(ill);
25626 
25627 	/* Local delivery */
25628 	if (ire->ire_stq == NULL) {
25629 		ill_t	*out_ill;
25630 		ASSERT(q != NULL);
25631 
25632 		/* PFHooks: LOOPBACK_OUT */
25633 		out_ill = ire_to_ill(ire);
25634 
25635 		DTRACE_PROBE4(ip6__loopback__out__start,
25636 		    ill_t *, NULL, ill_t *, out_ill,
25637 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25638 
25639 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25640 		    ipst->ips_ipv6firewall_loopback_out,
25641 		    NULL, out_ill, ip6h1, ipsec_mp, mp, ipst);
25642 
25643 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25644 
25645 		if (ipsec_mp != NULL)
25646 			ip_wput_local_v6(RD(q), out_ill,
25647 			    ip6h, ipsec_mp, ire, 0);
25648 		if (ire_need_rele)
25649 			ire_refrele(ire);
25650 		return;
25651 	}
25652 	/*
25653 	 * Everything is done. Send it out on the wire.
25654 	 * We force the insertion of a fragment header using the
25655 	 * IPH_FRAG_HDR flag in two cases:
25656 	 * - after reception of an ICMPv6 "packet too big" message
25657 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25658 	 * - for multirouted IPv6 packets, so that the receiver can
25659 	 *   discard duplicates according to their fragment identifier
25660 	 */
25661 	/* XXX fix flow control problems. */
25662 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25663 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25664 		if (hwaccel) {
25665 			/*
25666 			 * hardware acceleration does not handle these
25667 			 * "slow path" cases.
25668 			 */
25669 			/* IPsec KSTATS: should bump bean counter here. */
25670 			if (ire_need_rele)
25671 				ire_refrele(ire);
25672 			freemsg(ipsec_mp);
25673 			return;
25674 		}
25675 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25676 		    (mp->b_cont ? msgdsize(mp) :
25677 		    mp->b_wptr - (uchar_t *)ip6h)) {
25678 			/* IPsec KSTATS: should bump bean counter here. */
25679 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25680 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25681 			    msgdsize(mp)));
25682 			if (ire_need_rele)
25683 				ire_refrele(ire);
25684 			freemsg(ipsec_mp);
25685 			return;
25686 		}
25687 		ASSERT(mp->b_prev == NULL);
25688 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25689 		    ntohs(ip6h->ip6_plen) +
25690 		    IPV6_HDR_LEN, ire->ire_max_frag));
25691 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25692 		    ire->ire_max_frag);
25693 	} else {
25694 		UPDATE_OB_PKT_COUNT(ire);
25695 		ire->ire_last_used_time = lbolt;
25696 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25697 	}
25698 	if (ire_need_rele)
25699 		ire_refrele(ire);
25700 	freeb(ipsec_mp);
25701 }
25702 
25703 void
25704 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25705 {
25706 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25707 	da_ipsec_t *hada;	/* data attributes */
25708 	ill_t *ill = (ill_t *)q->q_ptr;
25709 
25710 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25711 
25712 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25713 		/* IPsec KSTATS: Bump lose counter here! */
25714 		freemsg(mp);
25715 		return;
25716 	}
25717 
25718 	/*
25719 	 * It's an IPsec packet that must be
25720 	 * accelerated by the Provider, and the
25721 	 * outbound ill is IPsec acceleration capable.
25722 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25723 	 * to the ill.
25724 	 * IPsec KSTATS: should bump packet counter here.
25725 	 */
25726 
25727 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25728 	if (hada_mp == NULL) {
25729 		/* IPsec KSTATS: should bump packet counter here. */
25730 		freemsg(mp);
25731 		return;
25732 	}
25733 
25734 	hada_mp->b_datap->db_type = M_CTL;
25735 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25736 	hada_mp->b_cont = mp;
25737 
25738 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25739 	bzero(hada, sizeof (da_ipsec_t));
25740 	hada->da_type = IPHADA_M_CTL;
25741 
25742 	putnext(q, hada_mp);
25743 }
25744 
25745 /*
25746  * Finish the outbound IPsec processing. This function is called from
25747  * ipsec_out_process() if the IPsec packet was processed
25748  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25749  * asynchronously.
25750  */
25751 void
25752 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25753     ire_t *ire_arg)
25754 {
25755 	uint32_t v_hlen_tos_len;
25756 	ipaddr_t	dst;
25757 	ipif_t	*ipif = NULL;
25758 	ire_t *ire;
25759 	ire_t *ire1 = NULL;
25760 	mblk_t *next_mp = NULL;
25761 	uint32_t max_frag;
25762 	boolean_t multirt_send = B_FALSE;
25763 	mblk_t *mp;
25764 	ipha_t *ipha1;
25765 	uint_t	ill_index;
25766 	ipsec_out_t *io;
25767 	boolean_t attach_if;
25768 	int match_flags;
25769 	irb_t *irb = NULL;
25770 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25771 	zoneid_t zoneid;
25772 	ipxmit_state_t	pktxmit_state;
25773 	ip_stack_t	*ipst;
25774 
25775 #ifdef	_BIG_ENDIAN
25776 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25777 #else
25778 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25779 #endif
25780 
25781 	mp = ipsec_mp->b_cont;
25782 	ipha1 = (ipha_t *)mp->b_rptr;
25783 	ASSERT(mp != NULL);
25784 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25785 	dst = ipha->ipha_dst;
25786 
25787 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25788 	ill_index = io->ipsec_out_ill_index;
25789 	attach_if = io->ipsec_out_attach_if;
25790 	zoneid = io->ipsec_out_zoneid;
25791 	ASSERT(zoneid != ALL_ZONES);
25792 	ipst = io->ipsec_out_ns->netstack_ip;
25793 	ASSERT(io->ipsec_out_ns != NULL);
25794 
25795 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25796 	if (ill_index != 0) {
25797 		if (ill == NULL) {
25798 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
25799 			    ill_index, B_FALSE, ipst);
25800 
25801 			/* Failure case frees things for us. */
25802 			if (ill == NULL)
25803 				return;
25804 
25805 			ill_need_rele = B_TRUE;
25806 		}
25807 		/*
25808 		 * If this packet needs to go out on a particular interface
25809 		 * honor it.
25810 		 */
25811 		if (attach_if) {
25812 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25813 
25814 			/*
25815 			 * Check if we need an ire that will not be
25816 			 * looked up by anybody else i.e. HIDDEN.
25817 			 */
25818 			if (ill_is_probeonly(ill)) {
25819 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25820 			}
25821 		}
25822 	}
25823 
25824 	if (CLASSD(dst)) {
25825 		boolean_t conn_dontroute;
25826 		/*
25827 		 * Use the ill_index to get the right ipif.
25828 		 */
25829 		conn_dontroute = io->ipsec_out_dontroute;
25830 		if (ill_index == 0)
25831 			ipif = ipif_lookup_group(dst, zoneid, ipst);
25832 		else
25833 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25834 		if (ipif == NULL) {
25835 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25836 			    " multicast\n"));
25837 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
25838 			freemsg(ipsec_mp);
25839 			goto done;
25840 		}
25841 		/*
25842 		 * ipha_src has already been intialized with the
25843 		 * value of the ipif in ip_wput. All we need now is
25844 		 * an ire to send this downstream.
25845 		 */
25846 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25847 		    MBLK_GETLABEL(mp), match_flags, ipst);
25848 		if (ire != NULL) {
25849 			ill_t *ill1;
25850 			/*
25851 			 * Do the multicast forwarding now, as the IPsec
25852 			 * processing has been done.
25853 			 */
25854 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
25855 			    (ill1 = ire_to_ill(ire))) {
25856 				if (ip_mforward(ill1, ipha, mp)) {
25857 					freemsg(ipsec_mp);
25858 					ip1dbg(("ip_wput_ipsec_out: mforward "
25859 					    "failed\n"));
25860 					ire_refrele(ire);
25861 					goto done;
25862 				}
25863 			}
25864 			goto send;
25865 		}
25866 
25867 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
25868 		mp->b_prev = NULL;
25869 		mp->b_next = NULL;
25870 
25871 		/*
25872 		 * If the IPsec packet was processed asynchronously,
25873 		 * drop it now.
25874 		 */
25875 		if (q == NULL) {
25876 			freemsg(ipsec_mp);
25877 			goto done;
25878 		}
25879 
25880 		/*
25881 		 * We may be using a wrong ipif to create the ire.
25882 		 * But it is okay as the source address is assigned
25883 		 * for the packet already. Next outbound packet would
25884 		 * create the IRE with the right IPIF in ip_wput.
25885 		 *
25886 		 * Also handle RTF_MULTIRT routes.
25887 		 */
25888 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
25889 		    zoneid, &zero_info);
25890 	} else {
25891 		if (attach_if) {
25892 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
25893 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25894 		} else {
25895 			if (ire_arg != NULL) {
25896 				ire = ire_arg;
25897 				ire_need_rele = B_FALSE;
25898 			} else {
25899 				ire = ire_cache_lookup(dst, zoneid,
25900 				    MBLK_GETLABEL(mp), ipst);
25901 			}
25902 		}
25903 		if (ire != NULL) {
25904 			goto send;
25905 		}
25906 
25907 		/*
25908 		 * ire disappeared underneath.
25909 		 *
25910 		 * What we need to do here is the ip_newroute
25911 		 * logic to get the ire without doing the IPsec
25912 		 * processing. Follow the same old path. But this
25913 		 * time, ip_wput or ire_add_then_put will call us
25914 		 * directly as all the IPsec operations are done.
25915 		 */
25916 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
25917 		mp->b_prev = NULL;
25918 		mp->b_next = NULL;
25919 
25920 		/*
25921 		 * If the IPsec packet was processed asynchronously,
25922 		 * drop it now.
25923 		 */
25924 		if (q == NULL) {
25925 			freemsg(ipsec_mp);
25926 			goto done;
25927 		}
25928 
25929 		/*
25930 		 * Since we're going through ip_newroute() again, we
25931 		 * need to make sure we don't:
25932 		 *
25933 		 *	1.) Trigger the ASSERT() with the ipha_ident
25934 		 *	    overloading.
25935 		 *	2.) Redo transport-layer checksumming, since we've
25936 		 *	    already done all that to get this far.
25937 		 *
25938 		 * The easiest way not do either of the above is to set
25939 		 * the ipha_ident field to IP_HDR_INCLUDED.
25940 		 */
25941 		ipha->ipha_ident = IP_HDR_INCLUDED;
25942 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
25943 		    zoneid, ipst);
25944 	}
25945 	goto done;
25946 send:
25947 	if (ire->ire_stq == NULL) {
25948 		ill_t	*out_ill;
25949 		/*
25950 		 * Loopbacks go through ip_wput_local except for one case.
25951 		 * We come here if we generate a icmp_frag_needed message
25952 		 * after IPsec processing is over. When this function calls
25953 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
25954 		 * icmp_frag_needed. The message generated comes back here
25955 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
25956 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
25957 		 * source address as it is usually set in ip_wput_ire. As
25958 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
25959 		 * and we end up here. We can't enter ip_wput_ire once the
25960 		 * IPsec processing is over and hence we need to do it here.
25961 		 */
25962 		ASSERT(q != NULL);
25963 		UPDATE_OB_PKT_COUNT(ire);
25964 		ire->ire_last_used_time = lbolt;
25965 		if (ipha->ipha_src == 0)
25966 			ipha->ipha_src = ire->ire_src_addr;
25967 
25968 		/* PFHooks: LOOPBACK_OUT */
25969 		out_ill = ire_to_ill(ire);
25970 
25971 		DTRACE_PROBE4(ip4__loopback__out__start,
25972 		    ill_t *, NULL, ill_t *, out_ill,
25973 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
25974 
25975 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
25976 		    ipst->ips_ipv4firewall_loopback_out,
25977 		    NULL, out_ill, ipha1, ipsec_mp, mp, ipst);
25978 
25979 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
25980 
25981 		if (ipsec_mp != NULL)
25982 			ip_wput_local(RD(q), out_ill,
25983 			    ipha, ipsec_mp, ire, 0, zoneid);
25984 		if (ire_need_rele)
25985 			ire_refrele(ire);
25986 		goto done;
25987 	}
25988 
25989 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
25990 		/*
25991 		 * We are through with IPsec processing.
25992 		 * Fragment this and send it on the wire.
25993 		 */
25994 		if (io->ipsec_out_accelerated) {
25995 			/*
25996 			 * The packet has been accelerated but must
25997 			 * be fragmented. This should not happen
25998 			 * since AH and ESP must not accelerate
25999 			 * packets that need fragmentation, however
26000 			 * the configuration could have changed
26001 			 * since the AH or ESP processing.
26002 			 * Drop packet.
26003 			 * IPsec KSTATS: bump bean counter here.
26004 			 */
26005 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26006 			    "fragmented accelerated packet!\n"));
26007 			freemsg(ipsec_mp);
26008 		} else {
26009 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid, ipst);
26010 		}
26011 		if (ire_need_rele)
26012 			ire_refrele(ire);
26013 		goto done;
26014 	}
26015 
26016 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26017 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26018 	    (void *)ire->ire_ipif, (void *)ipif));
26019 
26020 	/*
26021 	 * Multiroute the secured packet, unless IPsec really
26022 	 * requires the packet to go out only through a particular
26023 	 * interface.
26024 	 */
26025 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
26026 		ire_t *first_ire;
26027 		irb = ire->ire_bucket;
26028 		ASSERT(irb != NULL);
26029 		/*
26030 		 * This ire has been looked up as the one that
26031 		 * goes through the given ipif;
26032 		 * make sure we do not omit any other multiroute ire
26033 		 * that may be present in the bucket before this one.
26034 		 */
26035 		IRB_REFHOLD(irb);
26036 		for (first_ire = irb->irb_ire;
26037 		    first_ire != NULL;
26038 		    first_ire = first_ire->ire_next) {
26039 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26040 			    (first_ire->ire_addr == ire->ire_addr) &&
26041 			    !(first_ire->ire_marks &
26042 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
26043 				break;
26044 			}
26045 		}
26046 
26047 		if ((first_ire != NULL) && (first_ire != ire)) {
26048 			/*
26049 			 * Don't change the ire if the packet must
26050 			 * be fragmented if sent via this new one.
26051 			 */
26052 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26053 				IRE_REFHOLD(first_ire);
26054 				if (ire_need_rele)
26055 					ire_refrele(ire);
26056 				else
26057 					ire_need_rele = B_TRUE;
26058 				ire = first_ire;
26059 			}
26060 		}
26061 		IRB_REFRELE(irb);
26062 
26063 		multirt_send = B_TRUE;
26064 		max_frag = ire->ire_max_frag;
26065 	} else {
26066 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
26067 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
26068 			    "flag, attach_if %d\n", attach_if));
26069 		}
26070 	}
26071 
26072 	/*
26073 	 * In most cases, the emission loop below is entered only once.
26074 	 * Only in the case where the ire holds the RTF_MULTIRT
26075 	 * flag, we loop to process all RTF_MULTIRT ires in the
26076 	 * bucket, and send the packet through all crossed
26077 	 * RTF_MULTIRT routes.
26078 	 */
26079 	do {
26080 		if (multirt_send) {
26081 			/*
26082 			 * ire1 holds here the next ire to process in the
26083 			 * bucket. If multirouting is expected,
26084 			 * any non-RTF_MULTIRT ire that has the
26085 			 * right destination address is ignored.
26086 			 */
26087 			ASSERT(irb != NULL);
26088 			IRB_REFHOLD(irb);
26089 			for (ire1 = ire->ire_next;
26090 			    ire1 != NULL;
26091 			    ire1 = ire1->ire_next) {
26092 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26093 					continue;
26094 				if (ire1->ire_addr != ire->ire_addr)
26095 					continue;
26096 				if (ire1->ire_marks &
26097 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
26098 					continue;
26099 				/* No loopback here */
26100 				if (ire1->ire_stq == NULL)
26101 					continue;
26102 				/*
26103 				 * Ensure we do not exceed the MTU
26104 				 * of the next route.
26105 				 */
26106 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26107 					ip_multirt_bad_mtu(ire1, max_frag);
26108 					continue;
26109 				}
26110 
26111 				IRE_REFHOLD(ire1);
26112 				break;
26113 			}
26114 			IRB_REFRELE(irb);
26115 			if (ire1 != NULL) {
26116 				/*
26117 				 * We are in a multiple send case, need to
26118 				 * make a copy of the packet.
26119 				 */
26120 				next_mp = copymsg(ipsec_mp);
26121 				if (next_mp == NULL) {
26122 					ire_refrele(ire1);
26123 					ire1 = NULL;
26124 				}
26125 			}
26126 		}
26127 		/*
26128 		 * Everything is done. Send it out on the wire
26129 		 *
26130 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26131 		 * either send it on the wire or, in the case of
26132 		 * HW acceleration, call ipsec_hw_putnext.
26133 		 */
26134 		if (ire->ire_nce &&
26135 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26136 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26137 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26138 			/*
26139 			 * If ire's link-layer is unresolved (this
26140 			 * would only happen if the incomplete ire
26141 			 * was added to cachetable via forwarding path)
26142 			 * don't bother going to ip_xmit_v4. Just drop the
26143 			 * packet.
26144 			 * There is a slight risk here, in that, if we
26145 			 * have the forwarding path create an incomplete
26146 			 * IRE, then until the IRE is completed, any
26147 			 * transmitted IPsec packets will be dropped
26148 			 * instead of being queued waiting for resolution.
26149 			 *
26150 			 * But the likelihood of a forwarding packet and a wput
26151 			 * packet sending to the same dst at the same time
26152 			 * and there not yet be an ARP entry for it is small.
26153 			 * Furthermore, if this actually happens, it might
26154 			 * be likely that wput would generate multiple
26155 			 * packets (and forwarding would also have a train
26156 			 * of packets) for that destination. If this is
26157 			 * the case, some of them would have been dropped
26158 			 * anyway, since ARP only queues a few packets while
26159 			 * waiting for resolution
26160 			 *
26161 			 * NOTE: We should really call ip_xmit_v4,
26162 			 * and let it queue the packet and send the
26163 			 * ARP query and have ARP come back thus:
26164 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26165 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26166 			 * hw accel work. But it's too complex to get
26167 			 * the IPsec hw  acceleration approach to fit
26168 			 * well with ip_xmit_v4 doing ARP without
26169 			 * doing IPsec simplification. For now, we just
26170 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26171 			 * that we can continue with the send on the next
26172 			 * attempt.
26173 			 *
26174 			 * XXX THis should be revisited, when
26175 			 * the IPsec/IP interaction is cleaned up
26176 			 */
26177 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26178 			    " - dropping packet\n"));
26179 			freemsg(ipsec_mp);
26180 			/*
26181 			 * Call ip_xmit_v4() to trigger ARP query
26182 			 * in case the nce_state is ND_INITIAL
26183 			 */
26184 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26185 			goto drop_pkt;
26186 		}
26187 
26188 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26189 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26190 		    mblk_t *, ipsec_mp);
26191 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26192 		    ipst->ips_ipv4firewall_physical_out,
26193 		    NULL, ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, ipst);
26194 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26195 		if (ipsec_mp == NULL)
26196 			goto drop_pkt;
26197 
26198 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26199 		pktxmit_state = ip_xmit_v4(mp, ire,
26200 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
26201 
26202 		if ((pktxmit_state ==  SEND_FAILED) ||
26203 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26204 
26205 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26206 drop_pkt:
26207 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26208 			    ipIfStatsOutDiscards);
26209 			if (ire_need_rele)
26210 				ire_refrele(ire);
26211 			if (ire1 != NULL) {
26212 				ire_refrele(ire1);
26213 				freemsg(next_mp);
26214 			}
26215 			goto done;
26216 		}
26217 
26218 		freeb(ipsec_mp);
26219 		if (ire_need_rele)
26220 			ire_refrele(ire);
26221 
26222 		if (ire1 != NULL) {
26223 			ire = ire1;
26224 			ire_need_rele = B_TRUE;
26225 			ASSERT(next_mp);
26226 			ipsec_mp = next_mp;
26227 			mp = ipsec_mp->b_cont;
26228 			ire1 = NULL;
26229 			next_mp = NULL;
26230 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26231 		} else {
26232 			multirt_send = B_FALSE;
26233 		}
26234 	} while (multirt_send);
26235 done:
26236 	if (ill != NULL && ill_need_rele)
26237 		ill_refrele(ill);
26238 	if (ipif != NULL)
26239 		ipif_refrele(ipif);
26240 }
26241 
26242 /*
26243  * Get the ill corresponding to the specified ire, and compare its
26244  * capabilities with the protocol and algorithms specified by the
26245  * the SA obtained from ipsec_out. If they match, annotate the
26246  * ipsec_out structure to indicate that the packet needs acceleration.
26247  *
26248  *
26249  * A packet is eligible for outbound hardware acceleration if the
26250  * following conditions are satisfied:
26251  *
26252  * 1. the packet will not be fragmented
26253  * 2. the provider supports the algorithm
26254  * 3. there is no pending control message being exchanged
26255  * 4. snoop is not attached
26256  * 5. the destination address is not a broadcast or multicast address.
26257  *
26258  * Rationale:
26259  *	- Hardware drivers do not support fragmentation with
26260  *	  the current interface.
26261  *	- snoop, multicast, and broadcast may result in exposure of
26262  *	  a cleartext datagram.
26263  * We check all five of these conditions here.
26264  *
26265  * XXX would like to nuke "ire_t *" parameter here; problem is that
26266  * IRE is only way to figure out if a v4 address is a broadcast and
26267  * thus ineligible for acceleration...
26268  */
26269 static void
26270 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26271 {
26272 	ipsec_out_t *io;
26273 	mblk_t *data_mp;
26274 	uint_t plen, overhead;
26275 	ip_stack_t	*ipst;
26276 
26277 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26278 		return;
26279 
26280 	if (ill == NULL)
26281 		return;
26282 	ipst = ill->ill_ipst;
26283 	/*
26284 	 * Destination address is a broadcast or multicast.  Punt.
26285 	 */
26286 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26287 	    IRE_LOCAL)))
26288 		return;
26289 
26290 	data_mp = ipsec_mp->b_cont;
26291 
26292 	if (ill->ill_isv6) {
26293 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26294 
26295 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26296 			return;
26297 
26298 		plen = ip6h->ip6_plen;
26299 	} else {
26300 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26301 
26302 		if (CLASSD(ipha->ipha_dst))
26303 			return;
26304 
26305 		plen = ipha->ipha_length;
26306 	}
26307 	/*
26308 	 * Is there a pending DLPI control message being exchanged
26309 	 * between IP/IPsec and the DLS Provider? If there is, it
26310 	 * could be a SADB update, and the state of the DLS Provider
26311 	 * SADB might not be in sync with the SADB maintained by
26312 	 * IPsec. To avoid dropping packets or using the wrong keying
26313 	 * material, we do not accelerate this packet.
26314 	 */
26315 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26316 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26317 		    "ill_dlpi_pending! don't accelerate packet\n"));
26318 		return;
26319 	}
26320 
26321 	/*
26322 	 * Is the Provider in promiscous mode? If it does, we don't
26323 	 * accelerate the packet since it will bounce back up to the
26324 	 * listeners in the clear.
26325 	 */
26326 	if (ill->ill_promisc_on_phys) {
26327 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26328 		    "ill in promiscous mode, don't accelerate packet\n"));
26329 		return;
26330 	}
26331 
26332 	/*
26333 	 * Will the packet require fragmentation?
26334 	 */
26335 
26336 	/*
26337 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26338 	 * as is used elsewhere.
26339 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26340 	 *	+ 2-byte trailer
26341 	 */
26342 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26343 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26344 
26345 	if ((plen + overhead) > ill->ill_max_mtu)
26346 		return;
26347 
26348 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26349 
26350 	/*
26351 	 * Can the ill accelerate this IPsec protocol and algorithm
26352 	 * specified by the SA?
26353 	 */
26354 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26355 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26356 		return;
26357 	}
26358 
26359 	/*
26360 	 * Tell AH or ESP that the outbound ill is capable of
26361 	 * accelerating this packet.
26362 	 */
26363 	io->ipsec_out_is_capab_ill = B_TRUE;
26364 }
26365 
26366 /*
26367  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26368  *
26369  * If this function returns B_TRUE, the requested SA's have been filled
26370  * into the ipsec_out_*_sa pointers.
26371  *
26372  * If the function returns B_FALSE, the packet has been "consumed", most
26373  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26374  *
26375  * The SA references created by the protocol-specific "select"
26376  * function will be released when the ipsec_mp is freed, thanks to the
26377  * ipsec_out_free destructor -- see spd.c.
26378  */
26379 static boolean_t
26380 ipsec_out_select_sa(mblk_t *ipsec_mp)
26381 {
26382 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26383 	ipsec_out_t *io;
26384 	ipsec_policy_t *pp;
26385 	ipsec_action_t *ap;
26386 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26387 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26388 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26389 
26390 	if (!io->ipsec_out_secure) {
26391 		/*
26392 		 * We came here by mistake.
26393 		 * Don't bother with ipsec processing
26394 		 * We should "discourage" this path in the future.
26395 		 */
26396 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26397 		return (B_FALSE);
26398 	}
26399 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26400 	ASSERT((io->ipsec_out_policy != NULL) ||
26401 	    (io->ipsec_out_act != NULL));
26402 
26403 	ASSERT(io->ipsec_out_failed == B_FALSE);
26404 
26405 	/*
26406 	 * IPsec processing has started.
26407 	 */
26408 	io->ipsec_out_proc_begin = B_TRUE;
26409 	ap = io->ipsec_out_act;
26410 	if (ap == NULL) {
26411 		pp = io->ipsec_out_policy;
26412 		ASSERT(pp != NULL);
26413 		ap = pp->ipsp_act;
26414 		ASSERT(ap != NULL);
26415 	}
26416 
26417 	/*
26418 	 * We have an action.  now, let's select SA's.
26419 	 * (In the future, we can cache this in the conn_t..)
26420 	 */
26421 	if (ap->ipa_want_esp) {
26422 		if (io->ipsec_out_esp_sa == NULL) {
26423 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26424 			    IPPROTO_ESP);
26425 		}
26426 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26427 	}
26428 
26429 	if (ap->ipa_want_ah) {
26430 		if (io->ipsec_out_ah_sa == NULL) {
26431 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26432 			    IPPROTO_AH);
26433 		}
26434 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26435 		/*
26436 		 * The ESP and AH processing order needs to be preserved
26437 		 * when both protocols are required (ESP should be applied
26438 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26439 		 * when both ESP and AH are required, and an AH ACQUIRE
26440 		 * is needed.
26441 		 */
26442 		if (ap->ipa_want_esp && need_ah_acquire)
26443 			need_esp_acquire = B_TRUE;
26444 	}
26445 
26446 	/*
26447 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26448 	 * Release SAs that got referenced, but will not be used until we
26449 	 * acquire _all_ of the SAs we need.
26450 	 */
26451 	if (need_ah_acquire || need_esp_acquire) {
26452 		if (io->ipsec_out_ah_sa != NULL) {
26453 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26454 			io->ipsec_out_ah_sa = NULL;
26455 		}
26456 		if (io->ipsec_out_esp_sa != NULL) {
26457 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26458 			io->ipsec_out_esp_sa = NULL;
26459 		}
26460 
26461 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26462 		return (B_FALSE);
26463 	}
26464 
26465 	return (B_TRUE);
26466 }
26467 
26468 /*
26469  * Process an IPSEC_OUT message and see what you can
26470  * do with it.
26471  * IPQoS Notes:
26472  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26473  * IPsec.
26474  * XXX would like to nuke ire_t.
26475  * XXX ill_index better be "real"
26476  */
26477 void
26478 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26479 {
26480 	ipsec_out_t *io;
26481 	ipsec_policy_t *pp;
26482 	ipsec_action_t *ap;
26483 	ipha_t *ipha;
26484 	ip6_t *ip6h;
26485 	mblk_t *mp;
26486 	ill_t *ill;
26487 	zoneid_t zoneid;
26488 	ipsec_status_t ipsec_rc;
26489 	boolean_t ill_need_rele = B_FALSE;
26490 	ip_stack_t	*ipst;
26491 	ipsec_stack_t	*ipss;
26492 
26493 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26494 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26495 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26496 	ipst = io->ipsec_out_ns->netstack_ip;
26497 	mp = ipsec_mp->b_cont;
26498 
26499 	/*
26500 	 * Initiate IPPF processing. We do it here to account for packets
26501 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26502 	 * We can check for ipsec_out_proc_begin even for such packets, as
26503 	 * they will always be false (asserted below).
26504 	 */
26505 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26506 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26507 		    io->ipsec_out_ill_index : ill_index);
26508 		if (mp == NULL) {
26509 			ip2dbg(("ipsec_out_process: packet dropped "\
26510 			    "during IPPF processing\n"));
26511 			freeb(ipsec_mp);
26512 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26513 			return;
26514 		}
26515 	}
26516 
26517 	if (!io->ipsec_out_secure) {
26518 		/*
26519 		 * We came here by mistake.
26520 		 * Don't bother with ipsec processing
26521 		 * Should "discourage" this path in the future.
26522 		 */
26523 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26524 		goto done;
26525 	}
26526 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26527 	ASSERT((io->ipsec_out_policy != NULL) ||
26528 	    (io->ipsec_out_act != NULL));
26529 	ASSERT(io->ipsec_out_failed == B_FALSE);
26530 
26531 	ipss = ipst->ips_netstack->netstack_ipsec;
26532 	if (!ipsec_loaded(ipss)) {
26533 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26534 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26535 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26536 		} else {
26537 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26538 		}
26539 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26540 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26541 		    &ipss->ipsec_dropper);
26542 		return;
26543 	}
26544 
26545 	/*
26546 	 * IPsec processing has started.
26547 	 */
26548 	io->ipsec_out_proc_begin = B_TRUE;
26549 	ap = io->ipsec_out_act;
26550 	if (ap == NULL) {
26551 		pp = io->ipsec_out_policy;
26552 		ASSERT(pp != NULL);
26553 		ap = pp->ipsp_act;
26554 		ASSERT(ap != NULL);
26555 	}
26556 
26557 	/*
26558 	 * Save the outbound ill index. When the packet comes back
26559 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26560 	 * before sending it the accelerated packet.
26561 	 */
26562 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26563 		int ifindex;
26564 		ill = ire_to_ill(ire);
26565 		ifindex = ill->ill_phyint->phyint_ifindex;
26566 		io->ipsec_out_capab_ill_index = ifindex;
26567 	}
26568 
26569 	/*
26570 	 * The order of processing is first insert a IP header if needed.
26571 	 * Then insert the ESP header and then the AH header.
26572 	 */
26573 	if ((io->ipsec_out_se_done == B_FALSE) &&
26574 	    (ap->ipa_want_se)) {
26575 		/*
26576 		 * First get the outer IP header before sending
26577 		 * it to ESP.
26578 		 */
26579 		ipha_t *oipha, *iipha;
26580 		mblk_t *outer_mp, *inner_mp;
26581 
26582 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26583 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26584 			    "ipsec_out_process: "
26585 			    "Self-Encapsulation failed: Out of memory\n");
26586 			freemsg(ipsec_mp);
26587 			if (ill != NULL) {
26588 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26589 			} else {
26590 				BUMP_MIB(&ipst->ips_ip_mib,
26591 				    ipIfStatsOutDiscards);
26592 			}
26593 			return;
26594 		}
26595 		inner_mp = ipsec_mp->b_cont;
26596 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26597 		oipha = (ipha_t *)outer_mp->b_rptr;
26598 		iipha = (ipha_t *)inner_mp->b_rptr;
26599 		*oipha = *iipha;
26600 		outer_mp->b_wptr += sizeof (ipha_t);
26601 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26602 		    sizeof (ipha_t));
26603 		oipha->ipha_protocol = IPPROTO_ENCAP;
26604 		oipha->ipha_version_and_hdr_length =
26605 		    IP_SIMPLE_HDR_VERSION;
26606 		oipha->ipha_hdr_checksum = 0;
26607 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26608 		outer_mp->b_cont = inner_mp;
26609 		ipsec_mp->b_cont = outer_mp;
26610 
26611 		io->ipsec_out_se_done = B_TRUE;
26612 		io->ipsec_out_tunnel = B_TRUE;
26613 	}
26614 
26615 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26616 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26617 	    !ipsec_out_select_sa(ipsec_mp))
26618 		return;
26619 
26620 	/*
26621 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26622 	 * to do the heavy lifting.
26623 	 */
26624 	zoneid = io->ipsec_out_zoneid;
26625 	ASSERT(zoneid != ALL_ZONES);
26626 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26627 		ASSERT(io->ipsec_out_esp_sa != NULL);
26628 		io->ipsec_out_esp_done = B_TRUE;
26629 		/*
26630 		 * Note that since hw accel can only apply one transform,
26631 		 * not two, we skip hw accel for ESP if we also have AH
26632 		 * This is an design limitation of the interface
26633 		 * which should be revisited.
26634 		 */
26635 		ASSERT(ire != NULL);
26636 		if (io->ipsec_out_ah_sa == NULL) {
26637 			ill = (ill_t *)ire->ire_stq->q_ptr;
26638 			ipsec_out_is_accelerated(ipsec_mp,
26639 			    io->ipsec_out_esp_sa, ill, ire);
26640 		}
26641 
26642 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26643 		switch (ipsec_rc) {
26644 		case IPSEC_STATUS_SUCCESS:
26645 			break;
26646 		case IPSEC_STATUS_FAILED:
26647 			if (ill != NULL) {
26648 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26649 			} else {
26650 				BUMP_MIB(&ipst->ips_ip_mib,
26651 				    ipIfStatsOutDiscards);
26652 			}
26653 			/* FALLTHRU */
26654 		case IPSEC_STATUS_PENDING:
26655 			return;
26656 		}
26657 	}
26658 
26659 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26660 		ASSERT(io->ipsec_out_ah_sa != NULL);
26661 		io->ipsec_out_ah_done = B_TRUE;
26662 		if (ire == NULL) {
26663 			int idx = io->ipsec_out_capab_ill_index;
26664 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26665 			    NULL, NULL, NULL, NULL, ipst);
26666 			ill_need_rele = B_TRUE;
26667 		} else {
26668 			ill = (ill_t *)ire->ire_stq->q_ptr;
26669 		}
26670 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26671 		    ire);
26672 
26673 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26674 		switch (ipsec_rc) {
26675 		case IPSEC_STATUS_SUCCESS:
26676 			break;
26677 		case IPSEC_STATUS_FAILED:
26678 			if (ill != NULL) {
26679 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26680 			} else {
26681 				BUMP_MIB(&ipst->ips_ip_mib,
26682 				    ipIfStatsOutDiscards);
26683 			}
26684 			/* FALLTHRU */
26685 		case IPSEC_STATUS_PENDING:
26686 			if (ill != NULL && ill_need_rele)
26687 				ill_refrele(ill);
26688 			return;
26689 		}
26690 	}
26691 	/*
26692 	 * We are done with IPsec processing. Send it over
26693 	 * the wire.
26694 	 */
26695 done:
26696 	mp = ipsec_mp->b_cont;
26697 	ipha = (ipha_t *)mp->b_rptr;
26698 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26699 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
26700 	} else {
26701 		ip6h = (ip6_t *)ipha;
26702 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
26703 	}
26704 	if (ill != NULL && ill_need_rele)
26705 		ill_refrele(ill);
26706 }
26707 
26708 /* ARGSUSED */
26709 void
26710 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26711 {
26712 	opt_restart_t	*or;
26713 	int	err;
26714 	conn_t	*connp;
26715 
26716 	ASSERT(CONN_Q(q));
26717 	connp = Q_TO_CONN(q);
26718 
26719 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26720 	or = (opt_restart_t *)first_mp->b_rptr;
26721 	/*
26722 	 * We don't need to pass any credentials here since this is just
26723 	 * a restart. The credentials are passed in when svr4_optcom_req
26724 	 * is called the first time (from ip_wput_nondata).
26725 	 */
26726 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26727 		err = svr4_optcom_req(q, first_mp, NULL,
26728 		    &ip_opt_obj, B_FALSE);
26729 	} else {
26730 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26731 		err = tpi_optcom_req(q, first_mp, NULL,
26732 		    &ip_opt_obj, B_FALSE);
26733 	}
26734 	if (err != EINPROGRESS) {
26735 		/* operation is done */
26736 		CONN_OPER_PENDING_DONE(connp);
26737 	}
26738 }
26739 
26740 /*
26741  * ioctls that go through a down/up sequence may need to wait for the down
26742  * to complete. This involves waiting for the ire and ipif refcnts to go down
26743  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26744  */
26745 /* ARGSUSED */
26746 void
26747 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26748 {
26749 	struct iocblk *iocp;
26750 	mblk_t *mp1;
26751 	ip_ioctl_cmd_t *ipip;
26752 	int err;
26753 	sin_t	*sin;
26754 	struct lifreq *lifr;
26755 	struct ifreq *ifr;
26756 
26757 	iocp = (struct iocblk *)mp->b_rptr;
26758 	ASSERT(ipsq != NULL);
26759 	/* Existence of mp1 verified in ip_wput_nondata */
26760 	mp1 = mp->b_cont->b_cont;
26761 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26762 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26763 		/*
26764 		 * Special case where ipsq_current_ipif is not set:
26765 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26766 		 * ill could also have become part of a ipmp group in the
26767 		 * process, we are here as were not able to complete the
26768 		 * operation in ipif_set_values because we could not become
26769 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
26770 		 * will not be set so we need to set it.
26771 		 */
26772 		ill_t *ill = q->q_ptr;
26773 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
26774 	}
26775 	ASSERT(ipsq->ipsq_current_ipif != NULL);
26776 
26777 	if (ipip->ipi_cmd_type == IF_CMD) {
26778 		/* This a old style SIOC[GS]IF* command */
26779 		ifr = (struct ifreq *)mp1->b_rptr;
26780 		sin = (sin_t *)&ifr->ifr_addr;
26781 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26782 		/* This a new style SIOC[GS]LIF* command */
26783 		lifr = (struct lifreq *)mp1->b_rptr;
26784 		sin = (sin_t *)&lifr->lifr_addr;
26785 	} else {
26786 		sin = NULL;
26787 	}
26788 
26789 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_current_ipif, sin, q, mp,
26790 	    ipip, mp1->b_rptr);
26791 
26792 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26793 }
26794 
26795 /*
26796  * ioctl processing
26797  *
26798  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
26799  * the ioctl command in the ioctl tables, determines the copyin data size
26800  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
26801  *
26802  * ioctl processing then continues when the M_IOCDATA makes its way down to
26803  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
26804  * associated 'conn' is refheld till the end of the ioctl and the general
26805  * ioctl processing function ip_process_ioctl() is called to extract the
26806  * arguments and process the ioctl.  To simplify extraction, ioctl commands
26807  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
26808  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
26809  * is used to extract the ioctl's arguments.
26810  *
26811  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26812  * so goes thru the serialization primitive ipsq_try_enter. Then the
26813  * appropriate function to handle the ioctl is called based on the entry in
26814  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26815  * which also refreleases the 'conn' that was refheld at the start of the
26816  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26817  *
26818  * Many exclusive ioctls go thru an internal down up sequence as part of
26819  * the operation. For example an attempt to change the IP address of an
26820  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26821  * does all the cleanup such as deleting all ires that use this address.
26822  * Then we need to wait till all references to the interface go away.
26823  */
26824 void
26825 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26826 {
26827 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26828 	ip_ioctl_cmd_t *ipip = arg;
26829 	ip_extract_func_t *extract_funcp;
26830 	cmd_info_t ci;
26831 	int err;
26832 	boolean_t entered_ipsq = B_FALSE;
26833 
26834 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26835 
26836 	if (ipip == NULL)
26837 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26838 
26839 	/*
26840 	 * SIOCLIFADDIF needs to go thru a special path since the
26841 	 * ill may not exist yet. This happens in the case of lo0
26842 	 * which is created using this ioctl.
26843 	 */
26844 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26845 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26846 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26847 		return;
26848 	}
26849 
26850 	ci.ci_ipif = NULL;
26851 	if (ipip->ipi_cmd_type == MISC_CMD) {
26852 		/*
26853 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
26854 		 */
26855 		if (ipip->ipi_cmd == IF_UNITSEL) {
26856 			/* ioctl comes down the ill */
26857 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
26858 			ipif_refhold(ci.ci_ipif);
26859 		}
26860 		err = 0;
26861 		ci.ci_sin = NULL;
26862 		ci.ci_sin6 = NULL;
26863 		ci.ci_lifr = NULL;
26864 	} else {
26865 		switch (ipip->ipi_cmd_type) {
26866 		case IF_CMD:
26867 		case LIF_CMD:
26868 			extract_funcp = ip_extract_lifreq;
26869 			break;
26870 
26871 		case ARP_CMD:
26872 		case XARP_CMD:
26873 			extract_funcp = ip_extract_arpreq;
26874 			break;
26875 
26876 		case TUN_CMD:
26877 			extract_funcp = ip_extract_tunreq;
26878 			break;
26879 
26880 		case MSFILT_CMD:
26881 			extract_funcp = ip_extract_msfilter;
26882 			break;
26883 
26884 		default:
26885 			ASSERT(0);
26886 		}
26887 
26888 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
26889 		if (err != 0) {
26890 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26891 			return;
26892 		}
26893 
26894 		/*
26895 		 * All of the extraction functions return a refheld ipif.
26896 		 */
26897 		ASSERT(ci.ci_ipif != NULL);
26898 	}
26899 
26900 	/*
26901 	 * If ipsq is non-null, we are already being called exclusively
26902 	 */
26903 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
26904 	if (!(ipip->ipi_flags & IPI_WR)) {
26905 		/*
26906 		 * A return value of EINPROGRESS means the ioctl is
26907 		 * either queued and waiting for some reason or has
26908 		 * already completed.
26909 		 */
26910 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
26911 		    ci.ci_lifr);
26912 		if (ci.ci_ipif != NULL)
26913 			ipif_refrele(ci.ci_ipif);
26914 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26915 		return;
26916 	}
26917 
26918 	ASSERT(ci.ci_ipif != NULL);
26919 
26920 	if (ipsq == NULL) {
26921 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
26922 		    ip_process_ioctl, NEW_OP, B_TRUE);
26923 		entered_ipsq = B_TRUE;
26924 	}
26925 	/*
26926 	 * Release the ipif so that ipif_down and friends that wait for
26927 	 * references to go away are not misled about the current ipif_refcnt
26928 	 * values. We are writer so we can access the ipif even after releasing
26929 	 * the ipif.
26930 	 */
26931 	ipif_refrele(ci.ci_ipif);
26932 	if (ipsq == NULL)
26933 		return;
26934 
26935 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
26936 
26937 	/*
26938 	 * For most set ioctls that come here, this serves as a single point
26939 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
26940 	 * be any new references to the ipif. This helps functions that go
26941 	 * through this path and end up trying to wait for the refcnts
26942 	 * associated with the ipif to go down to zero. Some exceptions are
26943 	 * Failover, Failback, and Groupname commands that operate on more than
26944 	 * just the ci.ci_ipif. These commands internally determine the
26945 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
26946 	 * flags on that set. Another exception is the Removeif command that
26947 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
26948 	 * ipif to operate on.
26949 	 */
26950 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
26951 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
26952 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
26953 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
26954 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
26955 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
26956 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
26957 
26958 	/*
26959 	 * A return value of EINPROGRESS means the ioctl is
26960 	 * either queued and waiting for some reason or has
26961 	 * already completed.
26962 	 */
26963 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
26964 
26965 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26966 
26967 	if (entered_ipsq)
26968 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
26969 }
26970 
26971 /*
26972  * Complete the ioctl. Typically ioctls use the mi package and need to
26973  * do mi_copyout/mi_copy_done.
26974  */
26975 void
26976 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
26977 {
26978 	conn_t	*connp = NULL;
26979 
26980 	if (err == EINPROGRESS)
26981 		return;
26982 
26983 	if (CONN_Q(q)) {
26984 		connp = Q_TO_CONN(q);
26985 		ASSERT(connp->conn_ref >= 2);
26986 	}
26987 
26988 	switch (mode) {
26989 	case COPYOUT:
26990 		if (err == 0)
26991 			mi_copyout(q, mp);
26992 		else
26993 			mi_copy_done(q, mp, err);
26994 		break;
26995 
26996 	case NO_COPYOUT:
26997 		mi_copy_done(q, mp, err);
26998 		break;
26999 
27000 	default:
27001 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27002 		break;
27003 	}
27004 
27005 	/*
27006 	 * The refhold placed at the start of the ioctl is released here.
27007 	 */
27008 	if (connp != NULL)
27009 		CONN_OPER_PENDING_DONE(connp);
27010 
27011 	if (ipsq != NULL)
27012 		ipsq_current_finish(ipsq);
27013 }
27014 
27015 /*
27016  * This is called from ip_wput_nondata to resume a deferred TCP bind.
27017  */
27018 /* ARGSUSED */
27019 void
27020 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
27021 {
27022 	conn_t *connp = arg;
27023 	tcp_t	*tcp;
27024 
27025 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
27026 	tcp = connp->conn_tcp;
27027 
27028 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
27029 		freemsg(mp);
27030 	else
27031 		tcp_rput_other(tcp, mp);
27032 	CONN_OPER_PENDING_DONE(connp);
27033 }
27034 
27035 /* Called from ip_wput for all non data messages */
27036 /* ARGSUSED */
27037 void
27038 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27039 {
27040 	mblk_t		*mp1;
27041 	ire_t		*ire, *fake_ire;
27042 	ill_t		*ill;
27043 	struct iocblk	*iocp;
27044 	ip_ioctl_cmd_t	*ipip;
27045 	cred_t		*cr;
27046 	conn_t		*connp;
27047 	int		err;
27048 	nce_t		*nce;
27049 	ipif_t		*ipif;
27050 	ip_stack_t	*ipst;
27051 	char		*proto_str;
27052 
27053 	if (CONN_Q(q)) {
27054 		connp = Q_TO_CONN(q);
27055 		ipst = connp->conn_netstack->netstack_ip;
27056 	} else {
27057 		connp = NULL;
27058 		ipst = ILLQ_TO_IPST(q);
27059 	}
27060 
27061 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
27062 
27063 	switch (DB_TYPE(mp)) {
27064 	case M_IOCTL:
27065 		/*
27066 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27067 		 * will arrange to copy in associated control structures.
27068 		 */
27069 		ip_sioctl_copyin_setup(q, mp);
27070 		return;
27071 	case M_IOCDATA:
27072 		/*
27073 		 * Ensure that this is associated with one of our trans-
27074 		 * parent ioctls.  If it's not ours, discard it if we're
27075 		 * running as a driver, or pass it on if we're a module.
27076 		 */
27077 		iocp = (struct iocblk *)mp->b_rptr;
27078 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27079 		if (ipip == NULL) {
27080 			if (q->q_next == NULL) {
27081 				goto nak;
27082 			} else {
27083 				putnext(q, mp);
27084 			}
27085 			return;
27086 		}
27087 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
27088 			/*
27089 			 * the ioctl is one we recognise, but is not
27090 			 * consumed by IP as a module, pass M_IOCDATA
27091 			 * for processing downstream, but only for
27092 			 * common Streams ioctls.
27093 			 */
27094 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27095 				putnext(q, mp);
27096 				return;
27097 			} else {
27098 				goto nak;
27099 			}
27100 		}
27101 
27102 		/* IOCTL continuation following copyin or copyout. */
27103 		if (mi_copy_state(q, mp, NULL) == -1) {
27104 			/*
27105 			 * The copy operation failed.  mi_copy_state already
27106 			 * cleaned up, so we're out of here.
27107 			 */
27108 			return;
27109 		}
27110 		/*
27111 		 * If we just completed a copy in, we become writer and
27112 		 * continue processing in ip_sioctl_copyin_done.  If it
27113 		 * was a copy out, we call mi_copyout again.  If there is
27114 		 * nothing more to copy out, it will complete the IOCTL.
27115 		 */
27116 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27117 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27118 				mi_copy_done(q, mp, EPROTO);
27119 				return;
27120 			}
27121 			/*
27122 			 * Check for cases that need more copying.  A return
27123 			 * value of 0 means a second copyin has been started,
27124 			 * so we return; a return value of 1 means no more
27125 			 * copying is needed, so we continue.
27126 			 */
27127 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27128 			    MI_COPY_COUNT(mp) == 1) {
27129 				if (ip_copyin_msfilter(q, mp) == 0)
27130 					return;
27131 			}
27132 			/*
27133 			 * Refhold the conn, till the ioctl completes. This is
27134 			 * needed in case the ioctl ends up in the pending mp
27135 			 * list. Every mp in the ill_pending_mp list and
27136 			 * the ipsq_pending_mp must have a refhold on the conn
27137 			 * to resume processing. The refhold is released when
27138 			 * the ioctl completes. (normally or abnormally)
27139 			 * In all cases ip_ioctl_finish is called to finish
27140 			 * the ioctl.
27141 			 */
27142 			if (connp != NULL) {
27143 				/* This is not a reentry */
27144 				ASSERT(ipsq == NULL);
27145 				CONN_INC_REF(connp);
27146 			} else {
27147 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27148 					mi_copy_done(q, mp, EINVAL);
27149 					return;
27150 				}
27151 			}
27152 
27153 			ip_process_ioctl(ipsq, q, mp, ipip);
27154 
27155 		} else {
27156 			mi_copyout(q, mp);
27157 		}
27158 		return;
27159 nak:
27160 		iocp->ioc_error = EINVAL;
27161 		mp->b_datap->db_type = M_IOCNAK;
27162 		iocp->ioc_count = 0;
27163 		qreply(q, mp);
27164 		return;
27165 
27166 	case M_IOCNAK:
27167 		/*
27168 		 * The only way we could get here is if a resolver didn't like
27169 		 * an IOCTL we sent it.	 This shouldn't happen.
27170 		 */
27171 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27172 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27173 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27174 		freemsg(mp);
27175 		return;
27176 	case M_IOCACK:
27177 		/* /dev/ip shouldn't see this */
27178 		if (CONN_Q(q))
27179 			goto nak;
27180 
27181 		/* Finish socket ioctls passed through to ARP. */
27182 		ip_sioctl_iocack(q, mp);
27183 		return;
27184 	case M_FLUSH:
27185 		if (*mp->b_rptr & FLUSHW)
27186 			flushq(q, FLUSHALL);
27187 		if (q->q_next) {
27188 			putnext(q, mp);
27189 			return;
27190 		}
27191 		if (*mp->b_rptr & FLUSHR) {
27192 			*mp->b_rptr &= ~FLUSHW;
27193 			qreply(q, mp);
27194 			return;
27195 		}
27196 		freemsg(mp);
27197 		return;
27198 	case IRE_DB_REQ_TYPE:
27199 		if (connp == NULL) {
27200 			proto_str = "IRE_DB_REQ_TYPE";
27201 			goto protonak;
27202 		}
27203 		/* An Upper Level Protocol wants a copy of an IRE. */
27204 		ip_ire_req(q, mp);
27205 		return;
27206 	case M_CTL:
27207 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27208 			break;
27209 
27210 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27211 		    TUN_HELLO) {
27212 			ASSERT(connp != NULL);
27213 			connp->conn_flags |= IPCL_IPTUN;
27214 			freeb(mp);
27215 			return;
27216 		}
27217 
27218 		/* M_CTL messages are used by ARP to tell us things. */
27219 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27220 			break;
27221 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27222 		case AR_ENTRY_SQUERY:
27223 			ip_wput_ctl(q, mp);
27224 			return;
27225 		case AR_CLIENT_NOTIFY:
27226 			ip_arp_news(q, mp);
27227 			return;
27228 		case AR_DLPIOP_DONE:
27229 			ASSERT(q->q_next != NULL);
27230 			ill = (ill_t *)q->q_ptr;
27231 			/* qwriter_ip releases the refhold */
27232 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27233 			ill_refhold(ill);
27234 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27235 			return;
27236 		case AR_ARP_CLOSING:
27237 			/*
27238 			 * ARP (above us) is closing. If no ARP bringup is
27239 			 * currently pending, ack the message so that ARP
27240 			 * can complete its close. Also mark ill_arp_closing
27241 			 * so that new ARP bringups will fail. If any
27242 			 * ARP bringup is currently in progress, we will
27243 			 * ack this when the current ARP bringup completes.
27244 			 */
27245 			ASSERT(q->q_next != NULL);
27246 			ill = (ill_t *)q->q_ptr;
27247 			mutex_enter(&ill->ill_lock);
27248 			ill->ill_arp_closing = 1;
27249 			if (!ill->ill_arp_bringup_pending) {
27250 				mutex_exit(&ill->ill_lock);
27251 				qreply(q, mp);
27252 			} else {
27253 				mutex_exit(&ill->ill_lock);
27254 				freemsg(mp);
27255 			}
27256 			return;
27257 		case AR_ARP_EXTEND:
27258 			/*
27259 			 * The ARP module above us is capable of duplicate
27260 			 * address detection.  Old ATM drivers will not send
27261 			 * this message.
27262 			 */
27263 			ASSERT(q->q_next != NULL);
27264 			ill = (ill_t *)q->q_ptr;
27265 			ill->ill_arp_extend = B_TRUE;
27266 			freemsg(mp);
27267 			return;
27268 		default:
27269 			break;
27270 		}
27271 		break;
27272 	case M_PROTO:
27273 	case M_PCPROTO:
27274 		/*
27275 		 * The only PROTO messages we expect are ULP binds and
27276 		 * copies of option negotiation acknowledgements.
27277 		 */
27278 		switch (((union T_primitives *)mp->b_rptr)->type) {
27279 		case O_T_BIND_REQ:
27280 		case T_BIND_REQ: {
27281 			/* Request can get queued in bind */
27282 			if (connp == NULL) {
27283 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27284 				goto protonak;
27285 			}
27286 			/*
27287 			 * The transports except SCTP call ip_bind_{v4,v6}()
27288 			 * directly instead of a a putnext. SCTP doesn't
27289 			 * generate any T_BIND_REQ since it has its own
27290 			 * fanout data structures. However, ESP and AH
27291 			 * come in for regular binds; all other cases are
27292 			 * bind retries.
27293 			 */
27294 			ASSERT(!IPCL_IS_SCTP(connp));
27295 
27296 			/* Don't increment refcnt if this is a re-entry */
27297 			if (ipsq == NULL)
27298 				CONN_INC_REF(connp);
27299 
27300 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27301 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27302 			if (mp == NULL)
27303 				return;
27304 			if (IPCL_IS_TCP(connp)) {
27305 				/*
27306 				 * In the case of TCP endpoint we
27307 				 * come here only for bind retries
27308 				 */
27309 				ASSERT(ipsq != NULL);
27310 				CONN_INC_REF(connp);
27311 				squeue_fill(connp->conn_sqp, mp,
27312 				    ip_resume_tcp_bind, connp,
27313 				    SQTAG_BIND_RETRY);
27314 			} else if (IPCL_IS_UDP(connp)) {
27315 				/*
27316 				 * In the case of UDP endpoint we
27317 				 * come here only for bind retries
27318 				 */
27319 				ASSERT(ipsq != NULL);
27320 				udp_resume_bind(connp, mp);
27321 			} else if (IPCL_IS_RAWIP(connp)) {
27322 				/*
27323 				 * In the case of RAWIP endpoint we
27324 				 * come here only for bind retries
27325 				 */
27326 				ASSERT(ipsq != NULL);
27327 				rawip_resume_bind(connp, mp);
27328 			} else {
27329 				/* The case of AH and ESP */
27330 				qreply(q, mp);
27331 				CONN_OPER_PENDING_DONE(connp);
27332 			}
27333 			return;
27334 		}
27335 		case T_SVR4_OPTMGMT_REQ:
27336 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27337 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27338 
27339 			if (connp == NULL) {
27340 				proto_str = "T_SVR4_OPTMGMT_REQ";
27341 				goto protonak;
27342 			}
27343 
27344 			if (!snmpcom_req(q, mp, ip_snmp_set,
27345 			    ip_snmp_get, cr)) {
27346 				/*
27347 				 * Call svr4_optcom_req so that it can
27348 				 * generate the ack. We don't come here
27349 				 * if this operation is being restarted.
27350 				 * ip_restart_optmgmt will drop the conn ref.
27351 				 * In the case of ipsec option after the ipsec
27352 				 * load is complete conn_restart_ipsec_waiter
27353 				 * drops the conn ref.
27354 				 */
27355 				ASSERT(ipsq == NULL);
27356 				CONN_INC_REF(connp);
27357 				if (ip_check_for_ipsec_opt(q, mp))
27358 					return;
27359 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj,
27360 				    B_FALSE);
27361 				if (err != EINPROGRESS) {
27362 					/* Operation is done */
27363 					CONN_OPER_PENDING_DONE(connp);
27364 				}
27365 			}
27366 			return;
27367 		case T_OPTMGMT_REQ:
27368 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27369 			/*
27370 			 * Note: No snmpcom_req support through new
27371 			 * T_OPTMGMT_REQ.
27372 			 * Call tpi_optcom_req so that it can
27373 			 * generate the ack.
27374 			 */
27375 			if (connp == NULL) {
27376 				proto_str = "T_OPTMGMT_REQ";
27377 				goto protonak;
27378 			}
27379 
27380 			ASSERT(ipsq == NULL);
27381 			/*
27382 			 * We don't come here for restart. ip_restart_optmgmt
27383 			 * will drop the conn ref. In the case of ipsec option
27384 			 * after the ipsec load is complete
27385 			 * conn_restart_ipsec_waiter drops the conn ref.
27386 			 */
27387 			CONN_INC_REF(connp);
27388 			if (ip_check_for_ipsec_opt(q, mp))
27389 				return;
27390 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj, B_FALSE);
27391 			if (err != EINPROGRESS) {
27392 				/* Operation is done */
27393 				CONN_OPER_PENDING_DONE(connp);
27394 			}
27395 			return;
27396 		case T_UNBIND_REQ:
27397 			if (connp == NULL) {
27398 				proto_str = "T_UNBIND_REQ";
27399 				goto protonak;
27400 			}
27401 			mp = ip_unbind(q, mp);
27402 			qreply(q, mp);
27403 			return;
27404 		default:
27405 			/*
27406 			 * Have to drop any DLPI messages coming down from
27407 			 * arp (such as an info_req which would cause ip
27408 			 * to receive an extra info_ack if it was passed
27409 			 * through.
27410 			 */
27411 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27412 			    (int)*(uint_t *)mp->b_rptr));
27413 			freemsg(mp);
27414 			return;
27415 		}
27416 		/* NOTREACHED */
27417 	case IRE_DB_TYPE: {
27418 		nce_t		*nce;
27419 		ill_t		*ill;
27420 		in6_addr_t	gw_addr_v6;
27421 
27422 
27423 		/*
27424 		 * This is a response back from a resolver.  It
27425 		 * consists of a message chain containing:
27426 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27427 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27428 		 * The LL_HDR_MBLK is the DLPI header to use to get
27429 		 * the attached packet, and subsequent ones for the
27430 		 * same destination, transmitted.
27431 		 */
27432 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27433 			break;
27434 		/*
27435 		 * First, check to make sure the resolution succeeded.
27436 		 * If it failed, the second mblk will be empty.
27437 		 * If it is, free the chain, dropping the packet.
27438 		 * (We must ire_delete the ire; that frees the ire mblk)
27439 		 * We're doing this now to support PVCs for ATM; it's
27440 		 * a partial xresolv implementation. When we fully implement
27441 		 * xresolv interfaces, instead of freeing everything here
27442 		 * we'll initiate neighbor discovery.
27443 		 *
27444 		 * For v4 (ARP and other external resolvers) the resolver
27445 		 * frees the message, so no check is needed. This check
27446 		 * is required, though, for a full xresolve implementation.
27447 		 * Including this code here now both shows how external
27448 		 * resolvers can NACK a resolution request using an
27449 		 * existing design that has no specific provisions for NACKs,
27450 		 * and also takes into account that the current non-ARP
27451 		 * external resolver has been coded to use this method of
27452 		 * NACKing for all IPv6 (xresolv) cases,
27453 		 * whether our xresolv implementation is complete or not.
27454 		 *
27455 		 */
27456 		ire = (ire_t *)mp->b_rptr;
27457 		ill = ire_to_ill(ire);
27458 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27459 		if (mp1->b_rptr == mp1->b_wptr) {
27460 			if (ire->ire_ipversion == IPV6_VERSION) {
27461 				/*
27462 				 * XRESOLV interface.
27463 				 */
27464 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27465 				mutex_enter(&ire->ire_lock);
27466 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27467 				mutex_exit(&ire->ire_lock);
27468 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27469 					nce = ndp_lookup_v6(ill,
27470 					    &ire->ire_addr_v6, B_FALSE);
27471 				} else {
27472 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
27473 					    B_FALSE);
27474 				}
27475 				if (nce != NULL) {
27476 					nce_resolv_failed(nce);
27477 					ndp_delete(nce);
27478 					NCE_REFRELE(nce);
27479 				}
27480 			}
27481 			mp->b_cont = NULL;
27482 			freemsg(mp1);		/* frees the pkt as well */
27483 			ASSERT(ire->ire_nce == NULL);
27484 			ire_delete((ire_t *)mp->b_rptr);
27485 			return;
27486 		}
27487 
27488 		/*
27489 		 * Split them into IRE_MBLK and pkt and feed it into
27490 		 * ire_add_then_send. Then in ire_add_then_send
27491 		 * the IRE will be added, and then the packet will be
27492 		 * run back through ip_wput. This time it will make
27493 		 * it to the wire.
27494 		 */
27495 		mp->b_cont = NULL;
27496 		mp = mp1->b_cont;		/* now, mp points to pkt */
27497 		mp1->b_cont = NULL;
27498 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27499 		if (ire->ire_ipversion == IPV6_VERSION) {
27500 			/*
27501 			 * XRESOLV interface. Find the nce and put a copy
27502 			 * of the dl_unitdata_req in nce_res_mp
27503 			 */
27504 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27505 			mutex_enter(&ire->ire_lock);
27506 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27507 			mutex_exit(&ire->ire_lock);
27508 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27509 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
27510 				    B_FALSE);
27511 			} else {
27512 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
27513 			}
27514 			if (nce != NULL) {
27515 				/*
27516 				 * We have to protect nce_res_mp here
27517 				 * from being accessed by other threads
27518 				 * while we change the mblk pointer.
27519 				 * Other functions will also lock the nce when
27520 				 * accessing nce_res_mp.
27521 				 *
27522 				 * The reason we change the mblk pointer
27523 				 * here rather than copying the resolved address
27524 				 * into the template is that, unlike with
27525 				 * ethernet, we have no guarantee that the
27526 				 * resolved address length will be
27527 				 * smaller than or equal to the lla length
27528 				 * with which the template was allocated,
27529 				 * (for ethernet, they're equal)
27530 				 * so we have to use the actual resolved
27531 				 * address mblk - which holds the real
27532 				 * dl_unitdata_req with the resolved address.
27533 				 *
27534 				 * Doing this is the same behavior as was
27535 				 * previously used in the v4 ARP case.
27536 				 */
27537 				mutex_enter(&nce->nce_lock);
27538 				if (nce->nce_res_mp != NULL)
27539 					freemsg(nce->nce_res_mp);
27540 				nce->nce_res_mp = mp1;
27541 				mutex_exit(&nce->nce_lock);
27542 				/*
27543 				 * We do a fastpath probe here because
27544 				 * we have resolved the address without
27545 				 * using Neighbor Discovery.
27546 				 * In the non-XRESOLV v6 case, the fastpath
27547 				 * probe is done right after neighbor
27548 				 * discovery completes.
27549 				 */
27550 				if (nce->nce_res_mp != NULL) {
27551 					int res;
27552 					nce_fastpath_list_add(nce);
27553 					res = ill_fastpath_probe(ill,
27554 					    nce->nce_res_mp);
27555 					if (res != 0 && res != EAGAIN)
27556 						nce_fastpath_list_delete(nce);
27557 				}
27558 
27559 				ire_add_then_send(q, ire, mp);
27560 				/*
27561 				 * Now we have to clean out any packets
27562 				 * that may have been queued on the nce
27563 				 * while it was waiting for address resolution
27564 				 * to complete.
27565 				 */
27566 				mutex_enter(&nce->nce_lock);
27567 				mp1 = nce->nce_qd_mp;
27568 				nce->nce_qd_mp = NULL;
27569 				mutex_exit(&nce->nce_lock);
27570 				while (mp1 != NULL) {
27571 					mblk_t *nxt_mp;
27572 					queue_t *fwdq = NULL;
27573 					ill_t   *inbound_ill;
27574 					uint_t ifindex;
27575 
27576 					nxt_mp = mp1->b_next;
27577 					mp1->b_next = NULL;
27578 					/*
27579 					 * Retrieve ifindex stored in
27580 					 * ip_rput_data_v6()
27581 					 */
27582 					ifindex =
27583 					    (uint_t)(uintptr_t)mp1->b_prev;
27584 					inbound_ill =
27585 					    ill_lookup_on_ifindex(ifindex,
27586 					    B_TRUE, NULL, NULL, NULL,
27587 					    NULL, ipst);
27588 					mp1->b_prev = NULL;
27589 					if (inbound_ill != NULL)
27590 						fwdq = inbound_ill->ill_rq;
27591 
27592 					if (fwdq != NULL) {
27593 						put(fwdq, mp1);
27594 						ill_refrele(inbound_ill);
27595 					} else
27596 						put(WR(ill->ill_rq), mp1);
27597 					mp1 = nxt_mp;
27598 				}
27599 				NCE_REFRELE(nce);
27600 			} else {	/* nce is NULL; clean up */
27601 				ire_delete(ire);
27602 				freemsg(mp);
27603 				freemsg(mp1);
27604 				return;
27605 			}
27606 		} else {
27607 			nce_t *arpce;
27608 			/*
27609 			 * Link layer resolution succeeded. Recompute the
27610 			 * ire_nce.
27611 			 */
27612 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27613 			if ((arpce = ndp_lookup_v4(ill,
27614 			    (ire->ire_gateway_addr != INADDR_ANY ?
27615 			    &ire->ire_gateway_addr : &ire->ire_addr),
27616 			    B_FALSE)) == NULL) {
27617 				freeb(ire->ire_mp);
27618 				freeb(mp1);
27619 				freemsg(mp);
27620 				return;
27621 			}
27622 			mutex_enter(&arpce->nce_lock);
27623 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27624 			if (arpce->nce_state == ND_REACHABLE) {
27625 				/*
27626 				 * Someone resolved this before us;
27627 				 * cleanup the res_mp. Since ire has
27628 				 * not been added yet, the call to ire_add_v4
27629 				 * from ire_add_then_send (when a dup is
27630 				 * detected) will clean up the ire.
27631 				 */
27632 				freeb(mp1);
27633 			} else {
27634 				ASSERT(arpce->nce_res_mp == NULL);
27635 				arpce->nce_res_mp = mp1;
27636 				arpce->nce_state = ND_REACHABLE;
27637 			}
27638 			mutex_exit(&arpce->nce_lock);
27639 			if (ire->ire_marks & IRE_MARK_NOADD) {
27640 				/*
27641 				 * this ire will not be added to the ire
27642 				 * cache table, so we can set the ire_nce
27643 				 * here, as there are no atomicity constraints.
27644 				 */
27645 				ire->ire_nce = arpce;
27646 				/*
27647 				 * We are associating this nce with the ire
27648 				 * so change the nce ref taken in
27649 				 * ndp_lookup_v4() from
27650 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27651 				 */
27652 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27653 			} else {
27654 				NCE_REFRELE(arpce);
27655 			}
27656 			ire_add_then_send(q, ire, mp);
27657 		}
27658 		return;	/* All is well, the packet has been sent. */
27659 	}
27660 	case IRE_ARPRESOLVE_TYPE: {
27661 
27662 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27663 			break;
27664 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27665 		mp->b_cont = NULL;
27666 		/*
27667 		 * First, check to make sure the resolution succeeded.
27668 		 * If it failed, the second mblk will be empty.
27669 		 */
27670 		if (mp1->b_rptr == mp1->b_wptr) {
27671 			/* cleanup  the incomplete ire, free queued packets */
27672 			freemsg(mp); /* fake ire */
27673 			freeb(mp1);  /* dl_unitdata response */
27674 			return;
27675 		}
27676 
27677 		/*
27678 		 * update any incomplete nce_t found. we lookup the ctable
27679 		 * and find the nce from the ire->ire_nce because we need
27680 		 * to pass the ire to ip_xmit_v4 later, and can find both
27681 		 * ire and nce in one lookup from the ctable.
27682 		 */
27683 		fake_ire = (ire_t *)mp->b_rptr;
27684 		/*
27685 		 * By the time we come back here from ARP
27686 		 * the logical outgoing interface  of the incomplete ire
27687 		 * we added in ire_forward could have disappeared,
27688 		 * causing the incomplete ire to also have
27689 		 * dissapeared. So we need to retreive the
27690 		 * proper ipif for the ire  before looking
27691 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
27692 		 */
27693 		ill = q->q_ptr;
27694 
27695 		/* Get the outgoing ipif */
27696 		mutex_enter(&ill->ill_lock);
27697 		if (ill->ill_state_flags & ILL_CONDEMNED) {
27698 			mutex_exit(&ill->ill_lock);
27699 			freemsg(mp); /* fake ire */
27700 			freeb(mp1);  /* dl_unitdata response */
27701 			return;
27702 		}
27703 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27704 
27705 		if (ipif == NULL) {
27706 			mutex_exit(&ill->ill_lock);
27707 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27708 			freemsg(mp);
27709 			freeb(mp1);
27710 			return;
27711 		}
27712 		ipif_refhold_locked(ipif);
27713 		mutex_exit(&ill->ill_lock);
27714 		ire = ire_ctable_lookup(fake_ire->ire_addr,
27715 		    fake_ire->ire_gateway_addr, IRE_CACHE,
27716 		    ipif, fake_ire->ire_zoneid, NULL,
27717 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY), ipst);
27718 		ipif_refrele(ipif);
27719 		if (ire == NULL) {
27720 			/*
27721 			 * no ire was found; check if there is an nce
27722 			 * for this lookup; if it has no ire's pointing at it
27723 			 * cleanup.
27724 			 */
27725 			if ((nce = ndp_lookup_v4(ill,
27726 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27727 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27728 			    B_FALSE)) != NULL) {
27729 				/*
27730 				 * cleanup:
27731 				 * We check for refcnt 2 (one for the nce
27732 				 * hash list + 1 for the ref taken by
27733 				 * ndp_lookup_v4) to check that there are
27734 				 * no ire's pointing at the nce.
27735 				 */
27736 				if (nce->nce_refcnt == 2)
27737 					ndp_delete(nce);
27738 				NCE_REFRELE(nce);
27739 			}
27740 			freeb(mp1);  /* dl_unitdata response */
27741 			freemsg(mp); /* fake ire */
27742 			return;
27743 		}
27744 		nce = ire->ire_nce;
27745 		DTRACE_PROBE2(ire__arpresolve__type,
27746 		    ire_t *, ire, nce_t *, nce);
27747 		ASSERT(nce->nce_state != ND_INITIAL);
27748 		mutex_enter(&nce->nce_lock);
27749 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27750 		if (nce->nce_state == ND_REACHABLE) {
27751 			/*
27752 			 * Someone resolved this before us;
27753 			 * our response is not needed any more.
27754 			 */
27755 			mutex_exit(&nce->nce_lock);
27756 			freeb(mp1);  /* dl_unitdata response */
27757 		} else {
27758 			ASSERT(nce->nce_res_mp == NULL);
27759 			nce->nce_res_mp = mp1;
27760 			nce->nce_state = ND_REACHABLE;
27761 			mutex_exit(&nce->nce_lock);
27762 			nce_fastpath(nce);
27763 		}
27764 		/*
27765 		 * The cached nce_t has been updated to be reachable;
27766 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
27767 		 */
27768 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27769 		freemsg(mp);
27770 		/*
27771 		 * send out queued packets.
27772 		 */
27773 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
27774 
27775 		IRE_REFRELE(ire);
27776 		return;
27777 	}
27778 	default:
27779 		break;
27780 	}
27781 	if (q->q_next) {
27782 		putnext(q, mp);
27783 	} else
27784 		freemsg(mp);
27785 	return;
27786 
27787 protonak:
27788 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
27789 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
27790 		qreply(q, mp);
27791 }
27792 
27793 /*
27794  * Process IP options in an outbound packet.  Modify the destination if there
27795  * is a source route option.
27796  * Returns non-zero if something fails in which case an ICMP error has been
27797  * sent and mp freed.
27798  */
27799 static int
27800 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27801     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
27802 {
27803 	ipoptp_t	opts;
27804 	uchar_t		*opt;
27805 	uint8_t		optval;
27806 	uint8_t		optlen;
27807 	ipaddr_t	dst;
27808 	intptr_t	code = 0;
27809 	mblk_t		*mp;
27810 	ire_t		*ire = NULL;
27811 
27812 	ip2dbg(("ip_wput_options\n"));
27813 	mp = ipsec_mp;
27814 	if (mctl_present) {
27815 		mp = ipsec_mp->b_cont;
27816 	}
27817 
27818 	dst = ipha->ipha_dst;
27819 	for (optval = ipoptp_first(&opts, ipha);
27820 	    optval != IPOPT_EOL;
27821 	    optval = ipoptp_next(&opts)) {
27822 		opt = opts.ipoptp_cur;
27823 		optlen = opts.ipoptp_len;
27824 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27825 		    optval, optlen));
27826 		switch (optval) {
27827 			uint32_t off;
27828 		case IPOPT_SSRR:
27829 		case IPOPT_LSRR:
27830 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27831 				ip1dbg((
27832 				    "ip_wput_options: bad option offset\n"));
27833 				code = (char *)&opt[IPOPT_OLEN] -
27834 				    (char *)ipha;
27835 				goto param_prob;
27836 			}
27837 			off = opt[IPOPT_OFFSET];
27838 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27839 			    ntohl(dst)));
27840 			/*
27841 			 * For strict: verify that dst is directly
27842 			 * reachable.
27843 			 */
27844 			if (optval == IPOPT_SSRR) {
27845 				ire = ire_ftable_lookup(dst, 0, 0,
27846 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27847 				    MBLK_GETLABEL(mp),
27848 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
27849 				if (ire == NULL) {
27850 					ip1dbg(("ip_wput_options: SSRR not"
27851 					    " directly reachable: 0x%x\n",
27852 					    ntohl(dst)));
27853 					goto bad_src_route;
27854 				}
27855 				ire_refrele(ire);
27856 			}
27857 			break;
27858 		case IPOPT_RR:
27859 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27860 				ip1dbg((
27861 				    "ip_wput_options: bad option offset\n"));
27862 				code = (char *)&opt[IPOPT_OLEN] -
27863 				    (char *)ipha;
27864 				goto param_prob;
27865 			}
27866 			break;
27867 		case IPOPT_TS:
27868 			/*
27869 			 * Verify that length >=5 and that there is either
27870 			 * room for another timestamp or that the overflow
27871 			 * counter is not maxed out.
27872 			 */
27873 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
27874 			if (optlen < IPOPT_MINLEN_IT) {
27875 				goto param_prob;
27876 			}
27877 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27878 				ip1dbg((
27879 				    "ip_wput_options: bad option offset\n"));
27880 				code = (char *)&opt[IPOPT_OFFSET] -
27881 				    (char *)ipha;
27882 				goto param_prob;
27883 			}
27884 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
27885 			case IPOPT_TS_TSONLY:
27886 				off = IPOPT_TS_TIMELEN;
27887 				break;
27888 			case IPOPT_TS_TSANDADDR:
27889 			case IPOPT_TS_PRESPEC:
27890 			case IPOPT_TS_PRESPEC_RFC791:
27891 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
27892 				break;
27893 			default:
27894 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
27895 				    (char *)ipha;
27896 				goto param_prob;
27897 			}
27898 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
27899 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
27900 				/*
27901 				 * No room and the overflow counter is 15
27902 				 * already.
27903 				 */
27904 				goto param_prob;
27905 			}
27906 			break;
27907 		}
27908 	}
27909 
27910 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
27911 		return (0);
27912 
27913 	ip1dbg(("ip_wput_options: error processing IP options."));
27914 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
27915 
27916 param_prob:
27917 	/*
27918 	 * Since ip_wput() isn't close to finished, we fill
27919 	 * in enough of the header for credible error reporting.
27920 	 */
27921 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
27922 		/* Failed */
27923 		freemsg(ipsec_mp);
27924 		return (-1);
27925 	}
27926 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
27927 	return (-1);
27928 
27929 bad_src_route:
27930 	/*
27931 	 * Since ip_wput() isn't close to finished, we fill
27932 	 * in enough of the header for credible error reporting.
27933 	 */
27934 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
27935 		/* Failed */
27936 		freemsg(ipsec_mp);
27937 		return (-1);
27938 	}
27939 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
27940 	return (-1);
27941 }
27942 
27943 /*
27944  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
27945  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
27946  * thru /etc/system.
27947  */
27948 #define	CONN_MAXDRAINCNT	64
27949 
27950 static void
27951 conn_drain_init(ip_stack_t *ipst)
27952 {
27953 	int i;
27954 
27955 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
27956 
27957 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
27958 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
27959 		/*
27960 		 * Default value of the number of drainers is the
27961 		 * number of cpus, subject to maximum of 8 drainers.
27962 		 */
27963 		if (boot_max_ncpus != -1)
27964 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
27965 		else
27966 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
27967 	}
27968 
27969 	ipst->ips_conn_drain_list = kmem_zalloc(ipst->ips_conn_drain_list_cnt *
27970 	    sizeof (idl_t), KM_SLEEP);
27971 
27972 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
27973 		mutex_init(&ipst->ips_conn_drain_list[i].idl_lock, NULL,
27974 		    MUTEX_DEFAULT, NULL);
27975 	}
27976 }
27977 
27978 static void
27979 conn_drain_fini(ip_stack_t *ipst)
27980 {
27981 	int i;
27982 
27983 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++)
27984 		mutex_destroy(&ipst->ips_conn_drain_list[i].idl_lock);
27985 	kmem_free(ipst->ips_conn_drain_list,
27986 	    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
27987 	ipst->ips_conn_drain_list = NULL;
27988 }
27989 
27990 /*
27991  * Note: For an overview of how flowcontrol is handled in IP please see the
27992  * IP Flowcontrol notes at the top of this file.
27993  *
27994  * Flow control has blocked us from proceeding. Insert the given conn in one
27995  * of the conn drain lists. These conn wq's will be qenabled later on when
27996  * STREAMS flow control does a backenable. conn_walk_drain will enable
27997  * the first conn in each of these drain lists. Each of these qenabled conns
27998  * in turn enables the next in the list, after it runs, or when it closes,
27999  * thus sustaining the drain process.
28000  *
28001  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
28002  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
28003  * running at any time, on a given conn, since there can be only 1 service proc
28004  * running on a queue at any time.
28005  */
28006 void
28007 conn_drain_insert(conn_t *connp)
28008 {
28009 	idl_t	*idl;
28010 	uint_t	index;
28011 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28012 
28013 	mutex_enter(&connp->conn_lock);
28014 	if (connp->conn_state_flags & CONN_CLOSING) {
28015 		/*
28016 		 * The conn is closing as a result of which CONN_CLOSING
28017 		 * is set. Return.
28018 		 */
28019 		mutex_exit(&connp->conn_lock);
28020 		return;
28021 	} else if (connp->conn_idl == NULL) {
28022 		/*
28023 		 * Assign the next drain list round robin. We dont' use
28024 		 * a lock, and thus it may not be strictly round robin.
28025 		 * Atomicity of load/stores is enough to make sure that
28026 		 * conn_drain_list_index is always within bounds.
28027 		 */
28028 		index = ipst->ips_conn_drain_list_index;
28029 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28030 		connp->conn_idl = &ipst->ips_conn_drain_list[index];
28031 		index++;
28032 		if (index == ipst->ips_conn_drain_list_cnt)
28033 			index = 0;
28034 		ipst->ips_conn_drain_list_index = index;
28035 	}
28036 	mutex_exit(&connp->conn_lock);
28037 
28038 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28039 	if ((connp->conn_drain_prev != NULL) ||
28040 	    (connp->conn_state_flags & CONN_CLOSING)) {
28041 		/*
28042 		 * The conn is already in the drain list, OR
28043 		 * the conn is closing. We need to check again for
28044 		 * the closing case again since close can happen
28045 		 * after we drop the conn_lock, and before we
28046 		 * acquire the CONN_DRAIN_LIST_LOCK.
28047 		 */
28048 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28049 		return;
28050 	} else {
28051 		idl = connp->conn_idl;
28052 	}
28053 
28054 	/*
28055 	 * The conn is not in the drain list. Insert it at the
28056 	 * tail of the drain list. The drain list is circular
28057 	 * and doubly linked. idl_conn points to the 1st element
28058 	 * in the list.
28059 	 */
28060 	if (idl->idl_conn == NULL) {
28061 		idl->idl_conn = connp;
28062 		connp->conn_drain_next = connp;
28063 		connp->conn_drain_prev = connp;
28064 	} else {
28065 		conn_t *head = idl->idl_conn;
28066 
28067 		connp->conn_drain_next = head;
28068 		connp->conn_drain_prev = head->conn_drain_prev;
28069 		head->conn_drain_prev->conn_drain_next = connp;
28070 		head->conn_drain_prev = connp;
28071 	}
28072 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28073 }
28074 
28075 /*
28076  * This conn is closing, and we are called from ip_close. OR
28077  * This conn has been serviced by ip_wsrv, and we need to do the tail
28078  * processing.
28079  * If this conn is part of the drain list, we may need to sustain the drain
28080  * process by qenabling the next conn in the drain list. We may also need to
28081  * remove this conn from the list, if it is done.
28082  */
28083 static void
28084 conn_drain_tail(conn_t *connp, boolean_t closing)
28085 {
28086 	idl_t *idl;
28087 
28088 	/*
28089 	 * connp->conn_idl is stable at this point, and no lock is needed
28090 	 * to check it. If we are called from ip_close, close has already
28091 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28092 	 * called us only because conn_idl is non-null. If we are called thru
28093 	 * service, conn_idl could be null, but it cannot change because
28094 	 * service is single-threaded per queue, and there cannot be another
28095 	 * instance of service trying to call conn_drain_insert on this conn
28096 	 * now.
28097 	 */
28098 	ASSERT(!closing || (connp->conn_idl != NULL));
28099 
28100 	/*
28101 	 * If connp->conn_idl is null, the conn has not been inserted into any
28102 	 * drain list even once since creation of the conn. Just return.
28103 	 */
28104 	if (connp->conn_idl == NULL)
28105 		return;
28106 
28107 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28108 
28109 	if (connp->conn_drain_prev == NULL) {
28110 		/* This conn is currently not in the drain list.  */
28111 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28112 		return;
28113 	}
28114 	idl = connp->conn_idl;
28115 	if (idl->idl_conn_draining == connp) {
28116 		/*
28117 		 * This conn is the current drainer. If this is the last conn
28118 		 * in the drain list, we need to do more checks, in the 'if'
28119 		 * below. Otherwwise we need to just qenable the next conn,
28120 		 * to sustain the draining, and is handled in the 'else'
28121 		 * below.
28122 		 */
28123 		if (connp->conn_drain_next == idl->idl_conn) {
28124 			/*
28125 			 * This conn is the last in this list. This round
28126 			 * of draining is complete. If idl_repeat is set,
28127 			 * it means another flow enabling has happened from
28128 			 * the driver/streams and we need to another round
28129 			 * of draining.
28130 			 * If there are more than 2 conns in the drain list,
28131 			 * do a left rotate by 1, so that all conns except the
28132 			 * conn at the head move towards the head by 1, and the
28133 			 * the conn at the head goes to the tail. This attempts
28134 			 * a more even share for all queues that are being
28135 			 * drained.
28136 			 */
28137 			if ((connp->conn_drain_next != connp) &&
28138 			    (idl->idl_conn->conn_drain_next != connp)) {
28139 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28140 			}
28141 			if (idl->idl_repeat) {
28142 				qenable(idl->idl_conn->conn_wq);
28143 				idl->idl_conn_draining = idl->idl_conn;
28144 				idl->idl_repeat = 0;
28145 			} else {
28146 				idl->idl_conn_draining = NULL;
28147 			}
28148 		} else {
28149 			/*
28150 			 * If the next queue that we are now qenable'ing,
28151 			 * is closing, it will remove itself from this list
28152 			 * and qenable the subsequent queue in ip_close().
28153 			 * Serialization is acheived thru idl_lock.
28154 			 */
28155 			qenable(connp->conn_drain_next->conn_wq);
28156 			idl->idl_conn_draining = connp->conn_drain_next;
28157 		}
28158 	}
28159 	if (!connp->conn_did_putbq || closing) {
28160 		/*
28161 		 * Remove ourself from the drain list, if we did not do
28162 		 * a putbq, or if the conn is closing.
28163 		 * Note: It is possible that q->q_first is non-null. It means
28164 		 * that these messages landed after we did a enableok() in
28165 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28166 		 * service them.
28167 		 */
28168 		if (connp->conn_drain_next == connp) {
28169 			/* Singleton in the list */
28170 			ASSERT(connp->conn_drain_prev == connp);
28171 			idl->idl_conn = NULL;
28172 			idl->idl_conn_draining = NULL;
28173 		} else {
28174 			connp->conn_drain_prev->conn_drain_next =
28175 			    connp->conn_drain_next;
28176 			connp->conn_drain_next->conn_drain_prev =
28177 			    connp->conn_drain_prev;
28178 			if (idl->idl_conn == connp)
28179 				idl->idl_conn = connp->conn_drain_next;
28180 			ASSERT(idl->idl_conn_draining != connp);
28181 
28182 		}
28183 		connp->conn_drain_next = NULL;
28184 		connp->conn_drain_prev = NULL;
28185 	}
28186 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28187 }
28188 
28189 /*
28190  * Write service routine. Shared perimeter entry point.
28191  * ip_wsrv can be called in any of the following ways.
28192  * 1. The device queue's messages has fallen below the low water mark
28193  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28194  *    the drain lists and backenable the first conn in each list.
28195  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28196  *    qenabled non-tcp upper layers. We start dequeing messages and call
28197  *    ip_wput for each message.
28198  */
28199 
28200 void
28201 ip_wsrv(queue_t *q)
28202 {
28203 	conn_t	*connp;
28204 	ill_t	*ill;
28205 	mblk_t	*mp;
28206 
28207 	if (q->q_next) {
28208 		ill = (ill_t *)q->q_ptr;
28209 		if (ill->ill_state_flags == 0) {
28210 			/*
28211 			 * The device flow control has opened up.
28212 			 * Walk through conn drain lists and qenable the
28213 			 * first conn in each list. This makes sense only
28214 			 * if the stream is fully plumbed and setup.
28215 			 * Hence the if check above.
28216 			 */
28217 			ip1dbg(("ip_wsrv: walking\n"));
28218 			conn_walk_drain(ill->ill_ipst);
28219 		}
28220 		return;
28221 	}
28222 
28223 	connp = Q_TO_CONN(q);
28224 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28225 
28226 	/*
28227 	 * 1. Set conn_draining flag to signal that service is active.
28228 	 *
28229 	 * 2. ip_output determines whether it has been called from service,
28230 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28231 	 *    has been called from service.
28232 	 *
28233 	 * 3. Message ordering is preserved by the following logic.
28234 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28235 	 *    the message at the tail, if conn_draining is set (i.e. service
28236 	 *    is running) or if q->q_first is non-null.
28237 	 *
28238 	 *    ii. If ip_output is called from service, and if ip_output cannot
28239 	 *    putnext due to flow control, it does a putbq.
28240 	 *
28241 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28242 	 *    (causing an infinite loop).
28243 	 */
28244 	ASSERT(!connp->conn_did_putbq);
28245 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28246 		connp->conn_draining = 1;
28247 		noenable(q);
28248 		while ((mp = getq(q)) != NULL) {
28249 			ASSERT(CONN_Q(q));
28250 
28251 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28252 			if (connp->conn_did_putbq) {
28253 				/* ip_wput did a putbq */
28254 				break;
28255 			}
28256 		}
28257 		/*
28258 		 * At this point, a thread coming down from top, calling
28259 		 * ip_wput, may end up queueing the message. We have not yet
28260 		 * enabled the queue, so ip_wsrv won't be called again.
28261 		 * To avoid this race, check q->q_first again (in the loop)
28262 		 * If the other thread queued the message before we call
28263 		 * enableok(), we will catch it in the q->q_first check.
28264 		 * If the other thread queues the message after we call
28265 		 * enableok(), ip_wsrv will be called again by STREAMS.
28266 		 */
28267 		connp->conn_draining = 0;
28268 		enableok(q);
28269 	}
28270 
28271 	/* Enable the next conn for draining */
28272 	conn_drain_tail(connp, B_FALSE);
28273 
28274 	connp->conn_did_putbq = 0;
28275 }
28276 
28277 /*
28278  * Walk the list of all conn's calling the function provided with the
28279  * specified argument for each.	 Note that this only walks conn's that
28280  * have been bound.
28281  * Applies to both IPv4 and IPv6.
28282  */
28283 static void
28284 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28285 {
28286 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28287 	    ipst->ips_ipcl_udp_fanout_size,
28288 	    func, arg, zoneid);
28289 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28290 	    ipst->ips_ipcl_conn_fanout_size,
28291 	    func, arg, zoneid);
28292 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28293 	    ipst->ips_ipcl_bind_fanout_size,
28294 	    func, arg, zoneid);
28295 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28296 	    IPPROTO_MAX, func, arg, zoneid);
28297 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28298 	    IPPROTO_MAX, func, arg, zoneid);
28299 }
28300 
28301 /*
28302  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28303  * of conns that need to be drained, check if drain is already in progress.
28304  * If so set the idl_repeat bit, indicating that the last conn in the list
28305  * needs to reinitiate the drain once again, for the list. If drain is not
28306  * in progress for the list, initiate the draining, by qenabling the 1st
28307  * conn in the list. The drain is self-sustaining, each qenabled conn will
28308  * in turn qenable the next conn, when it is done/blocked/closing.
28309  */
28310 static void
28311 conn_walk_drain(ip_stack_t *ipst)
28312 {
28313 	int i;
28314 	idl_t *idl;
28315 
28316 	IP_STAT(ipst, ip_conn_walk_drain);
28317 
28318 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28319 		idl = &ipst->ips_conn_drain_list[i];
28320 		mutex_enter(&idl->idl_lock);
28321 		if (idl->idl_conn == NULL) {
28322 			mutex_exit(&idl->idl_lock);
28323 			continue;
28324 		}
28325 		/*
28326 		 * If this list is not being drained currently by
28327 		 * an ip_wsrv thread, start the process.
28328 		 */
28329 		if (idl->idl_conn_draining == NULL) {
28330 			ASSERT(idl->idl_repeat == 0);
28331 			qenable(idl->idl_conn->conn_wq);
28332 			idl->idl_conn_draining = idl->idl_conn;
28333 		} else {
28334 			idl->idl_repeat = 1;
28335 		}
28336 		mutex_exit(&idl->idl_lock);
28337 	}
28338 }
28339 
28340 /*
28341  * Walk an conn hash table of `count' buckets, calling func for each entry.
28342  */
28343 static void
28344 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28345     zoneid_t zoneid)
28346 {
28347 	conn_t	*connp;
28348 
28349 	while (count-- > 0) {
28350 		mutex_enter(&connfp->connf_lock);
28351 		for (connp = connfp->connf_head; connp != NULL;
28352 		    connp = connp->conn_next) {
28353 			if (zoneid == GLOBAL_ZONEID ||
28354 			    zoneid == connp->conn_zoneid) {
28355 				CONN_INC_REF(connp);
28356 				mutex_exit(&connfp->connf_lock);
28357 				(*func)(connp, arg);
28358 				mutex_enter(&connfp->connf_lock);
28359 				CONN_DEC_REF(connp);
28360 			}
28361 		}
28362 		mutex_exit(&connfp->connf_lock);
28363 		connfp++;
28364 	}
28365 }
28366 
28367 /* conn_walk_fanout routine invoked for ip_conn_report for each conn. */
28368 static void
28369 conn_report1(conn_t *connp, void *mp)
28370 {
28371 	char	buf1[INET6_ADDRSTRLEN];
28372 	char	buf2[INET6_ADDRSTRLEN];
28373 	uint_t	print_len, buf_len;
28374 
28375 	ASSERT(connp != NULL);
28376 
28377 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28378 	if (buf_len <= 0)
28379 		return;
28380 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1));
28381 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2));
28382 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28383 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28384 	    "%5d %s/%05d %s/%05d\n",
28385 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28386 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28387 	    buf1, connp->conn_lport,
28388 	    buf2, connp->conn_fport);
28389 	if (print_len < buf_len) {
28390 		((mblk_t *)mp)->b_wptr += print_len;
28391 	} else {
28392 		((mblk_t *)mp)->b_wptr += buf_len;
28393 	}
28394 }
28395 
28396 /*
28397  * Named Dispatch routine to produce a formatted report on all conns
28398  * that are listed in one of the fanout tables.
28399  * This report is accessed by using the ndd utility to "get" ND variable
28400  * "ip_conn_status".
28401  */
28402 /* ARGSUSED */
28403 static int
28404 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28405 {
28406 	conn_t *connp = Q_TO_CONN(q);
28407 
28408 	(void) mi_mpprintf(mp,
28409 	    "CONN      " MI_COL_HDRPAD_STR
28410 	    "rfq      " MI_COL_HDRPAD_STR
28411 	    "stq      " MI_COL_HDRPAD_STR
28412 	    " zone local                 remote");
28413 
28414 	/*
28415 	 * Because of the ndd constraint, at most we can have 64K buffer
28416 	 * to put in all conn info.  So to be more efficient, just
28417 	 * allocate a 64K buffer here, assuming we need that large buffer.
28418 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28419 	 */
28420 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28421 		/* The following may work even if we cannot get a large buf. */
28422 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28423 		return (0);
28424 	}
28425 
28426 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
28427 	    connp->conn_netstack->netstack_ip);
28428 	return (0);
28429 }
28430 
28431 /*
28432  * Determine if the ill and multicast aspects of that packets
28433  * "matches" the conn.
28434  */
28435 boolean_t
28436 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28437     zoneid_t zoneid)
28438 {
28439 	ill_t *in_ill;
28440 	boolean_t found;
28441 	ipif_t *ipif;
28442 	ire_t *ire;
28443 	ipaddr_t dst, src;
28444 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28445 
28446 	dst = ipha->ipha_dst;
28447 	src = ipha->ipha_src;
28448 
28449 	/*
28450 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28451 	 * unicast, broadcast and multicast reception to
28452 	 * conn_incoming_ill. conn_wantpacket itself is called
28453 	 * only for BROADCAST and multicast.
28454 	 *
28455 	 * 1) ip_rput supresses duplicate broadcasts if the ill
28456 	 *    is part of a group. Hence, we should be receiving
28457 	 *    just one copy of broadcast for the whole group.
28458 	 *    Thus, if it is part of the group the packet could
28459 	 *    come on any ill of the group and hence we need a
28460 	 *    match on the group. Otherwise, match on ill should
28461 	 *    be sufficient.
28462 	 *
28463 	 * 2) ip_rput does not suppress duplicate multicast packets.
28464 	 *    If there are two interfaces in a ill group and we have
28465 	 *    2 applications (conns) joined a multicast group G on
28466 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
28467 	 *    will give us two packets because we join G on both the
28468 	 *    interfaces rather than nominating just one interface
28469 	 *    for receiving multicast like broadcast above. So,
28470 	 *    we have to call ilg_lookup_ill to filter out duplicate
28471 	 *    copies, if ill is part of a group.
28472 	 */
28473 	in_ill = connp->conn_incoming_ill;
28474 	if (in_ill != NULL) {
28475 		if (in_ill->ill_group == NULL) {
28476 			if (in_ill != ill)
28477 				return (B_FALSE);
28478 		} else if (in_ill->ill_group != ill->ill_group) {
28479 			return (B_FALSE);
28480 		}
28481 	}
28482 
28483 	if (!CLASSD(dst)) {
28484 		if (IPCL_ZONE_MATCH(connp, zoneid))
28485 			return (B_TRUE);
28486 		/*
28487 		 * The conn is in a different zone; we need to check that this
28488 		 * broadcast address is configured in the application's zone and
28489 		 * on one ill in the group.
28490 		 */
28491 		ipif = ipif_get_next_ipif(NULL, ill);
28492 		if (ipif == NULL)
28493 			return (B_FALSE);
28494 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28495 		    connp->conn_zoneid, NULL,
28496 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
28497 		ipif_refrele(ipif);
28498 		if (ire != NULL) {
28499 			ire_refrele(ire);
28500 			return (B_TRUE);
28501 		} else {
28502 			return (B_FALSE);
28503 		}
28504 	}
28505 
28506 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28507 	    connp->conn_zoneid == zoneid) {
28508 		/*
28509 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28510 		 * disabled, therefore we don't dispatch the multicast packet to
28511 		 * the sending zone.
28512 		 */
28513 		return (B_FALSE);
28514 	}
28515 
28516 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28517 		/*
28518 		 * Multicast packet on the loopback interface: we only match
28519 		 * conns who joined the group in the specified zone.
28520 		 */
28521 		return (B_FALSE);
28522 	}
28523 
28524 	if (connp->conn_multi_router) {
28525 		/* multicast packet and multicast router socket: send up */
28526 		return (B_TRUE);
28527 	}
28528 
28529 	mutex_enter(&connp->conn_lock);
28530 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28531 	mutex_exit(&connp->conn_lock);
28532 	return (found);
28533 }
28534 
28535 /*
28536  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28537  */
28538 /* ARGSUSED */
28539 static void
28540 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28541 {
28542 	ill_t *ill = (ill_t *)q->q_ptr;
28543 	mblk_t	*mp1, *mp2;
28544 	ipif_t  *ipif;
28545 	int err = 0;
28546 	conn_t *connp = NULL;
28547 	ipsq_t	*ipsq;
28548 	arc_t	*arc;
28549 
28550 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28551 
28552 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28553 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28554 
28555 	ASSERT(IAM_WRITER_ILL(ill));
28556 	mp2 = mp->b_cont;
28557 	mp->b_cont = NULL;
28558 
28559 	/*
28560 	 * We have now received the arp bringup completion message
28561 	 * from ARP. Mark the arp bringup as done. Also if the arp
28562 	 * stream has already started closing, send up the AR_ARP_CLOSING
28563 	 * ack now since ARP is waiting in close for this ack.
28564 	 */
28565 	mutex_enter(&ill->ill_lock);
28566 	ill->ill_arp_bringup_pending = 0;
28567 	if (ill->ill_arp_closing) {
28568 		mutex_exit(&ill->ill_lock);
28569 		/* Let's reuse the mp for sending the ack */
28570 		arc = (arc_t *)mp->b_rptr;
28571 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28572 		arc->arc_cmd = AR_ARP_CLOSING;
28573 		qreply(q, mp);
28574 	} else {
28575 		mutex_exit(&ill->ill_lock);
28576 		freeb(mp);
28577 	}
28578 
28579 	ipsq = ill->ill_phyint->phyint_ipsq;
28580 	ipif = ipsq->ipsq_pending_ipif;
28581 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28582 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28583 	if (mp1 == NULL) {
28584 		/* bringup was aborted by the user */
28585 		freemsg(mp2);
28586 		return;
28587 	}
28588 
28589 	/*
28590 	 * If an IOCTL is waiting on this (ipsq_current_ioctl != 0), then we
28591 	 * must have an associated conn_t.  Otherwise, we're bringing this
28592 	 * interface back up as part of handling an asynchronous event (e.g.,
28593 	 * physical address change).
28594 	 */
28595 	if (ipsq->ipsq_current_ioctl != 0) {
28596 		ASSERT(connp != NULL);
28597 		q = CONNP_TO_WQ(connp);
28598 	} else {
28599 		ASSERT(connp == NULL);
28600 		q = ill->ill_rq;
28601 	}
28602 
28603 	/*
28604 	 * If the DL_BIND_REQ fails, it is noted
28605 	 * in arc_name_offset.
28606 	 */
28607 	err = *((int *)mp2->b_rptr);
28608 	if (err == 0) {
28609 		if (ipif->ipif_isv6) {
28610 			if ((err = ipif_up_done_v6(ipif)) != 0)
28611 				ip0dbg(("ip_arp_done: init failed\n"));
28612 		} else {
28613 			if ((err = ipif_up_done(ipif)) != 0)
28614 				ip0dbg(("ip_arp_done: init failed\n"));
28615 		}
28616 	} else {
28617 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28618 	}
28619 
28620 	freemsg(mp2);
28621 
28622 	if ((err == 0) && (ill->ill_up_ipifs)) {
28623 		err = ill_up_ipifs(ill, q, mp1);
28624 		if (err == EINPROGRESS)
28625 			return;
28626 	}
28627 
28628 	if (ill->ill_up_ipifs)
28629 		ill_group_cleanup(ill);
28630 
28631 	/*
28632 	 * The operation must complete without EINPROGRESS since
28633 	 * ipsq_pending_mp_get() has removed the mblk from ipsq_pending_mp.
28634 	 * Otherwise, the operation will be stuck forever in the ipsq.
28635 	 */
28636 	ASSERT(err != EINPROGRESS);
28637 	if (ipsq->ipsq_current_ioctl != 0)
28638 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28639 	else
28640 		ipsq_current_finish(ipsq);
28641 }
28642 
28643 /* Allocate the private structure */
28644 static int
28645 ip_priv_alloc(void **bufp)
28646 {
28647 	void	*buf;
28648 
28649 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28650 		return (ENOMEM);
28651 
28652 	*bufp = buf;
28653 	return (0);
28654 }
28655 
28656 /* Function to delete the private structure */
28657 void
28658 ip_priv_free(void *buf)
28659 {
28660 	ASSERT(buf != NULL);
28661 	kmem_free(buf, sizeof (ip_priv_t));
28662 }
28663 
28664 /*
28665  * The entry point for IPPF processing.
28666  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28667  * routine just returns.
28668  *
28669  * When called, ip_process generates an ipp_packet_t structure
28670  * which holds the state information for this packet and invokes the
28671  * the classifier (via ipp_packet_process). The classification, depending on
28672  * configured filters, results in a list of actions for this packet. Invoking
28673  * an action may cause the packet to be dropped, in which case the resulting
28674  * mblk (*mpp) is NULL. proc indicates the callout position for
28675  * this packet and ill_index is the interface this packet on or will leave
28676  * on (inbound and outbound resp.).
28677  */
28678 void
28679 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28680 {
28681 	mblk_t		*mp;
28682 	ip_priv_t	*priv;
28683 	ipp_action_id_t	aid;
28684 	int		rc = 0;
28685 	ipp_packet_t	*pp;
28686 #define	IP_CLASS	"ip"
28687 
28688 	/* If the classifier is not loaded, return  */
28689 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28690 		return;
28691 	}
28692 
28693 	mp = *mpp;
28694 	ASSERT(mp != NULL);
28695 
28696 	/* Allocate the packet structure */
28697 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28698 	if (rc != 0) {
28699 		*mpp = NULL;
28700 		freemsg(mp);
28701 		return;
28702 	}
28703 
28704 	/* Allocate the private structure */
28705 	rc = ip_priv_alloc((void **)&priv);
28706 	if (rc != 0) {
28707 		*mpp = NULL;
28708 		freemsg(mp);
28709 		ipp_packet_free(pp);
28710 		return;
28711 	}
28712 	priv->proc = proc;
28713 	priv->ill_index = ill_index;
28714 	ipp_packet_set_private(pp, priv, ip_priv_free);
28715 	ipp_packet_set_data(pp, mp);
28716 
28717 	/* Invoke the classifier */
28718 	rc = ipp_packet_process(&pp);
28719 	if (pp != NULL) {
28720 		mp = ipp_packet_get_data(pp);
28721 		ipp_packet_free(pp);
28722 		if (rc != 0) {
28723 			freemsg(mp);
28724 			*mpp = NULL;
28725 		}
28726 	} else {
28727 		*mpp = NULL;
28728 	}
28729 #undef	IP_CLASS
28730 }
28731 
28732 /*
28733  * Propagate a multicast group membership operation (add/drop) on
28734  * all the interfaces crossed by the related multirt routes.
28735  * The call is considered successful if the operation succeeds
28736  * on at least one interface.
28737  */
28738 static int
28739 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28740     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28741     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28742     mblk_t *first_mp)
28743 {
28744 	ire_t		*ire_gw;
28745 	irb_t		*irb;
28746 	int		error = 0;
28747 	opt_restart_t	*or;
28748 	ip_stack_t	*ipst = ire->ire_ipst;
28749 
28750 	irb = ire->ire_bucket;
28751 	ASSERT(irb != NULL);
28752 
28753 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28754 
28755 	or = (opt_restart_t *)first_mp->b_rptr;
28756 	IRB_REFHOLD(irb);
28757 	for (; ire != NULL; ire = ire->ire_next) {
28758 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28759 			continue;
28760 		if (ire->ire_addr != group)
28761 			continue;
28762 
28763 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28764 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28765 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
28766 		/* No resolver exists for the gateway; skip this ire. */
28767 		if (ire_gw == NULL)
28768 			continue;
28769 
28770 		/*
28771 		 * This function can return EINPROGRESS. If so the operation
28772 		 * will be restarted from ip_restart_optmgmt which will
28773 		 * call ip_opt_set and option processing will restart for
28774 		 * this option. So we may end up calling 'fn' more than once.
28775 		 * This requires that 'fn' is idempotent except for the
28776 		 * return value. The operation is considered a success if
28777 		 * it succeeds at least once on any one interface.
28778 		 */
28779 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28780 		    NULL, fmode, src, first_mp);
28781 		if (error == 0)
28782 			or->or_private = CGTP_MCAST_SUCCESS;
28783 
28784 		if (ip_debug > 0) {
28785 			ulong_t	off;
28786 			char	*ksym;
28787 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28788 			ip2dbg(("ip_multirt_apply_membership: "
28789 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28790 			    "error %d [success %u]\n",
28791 			    ksym ? ksym : "?",
28792 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28793 			    error, or->or_private));
28794 		}
28795 
28796 		ire_refrele(ire_gw);
28797 		if (error == EINPROGRESS) {
28798 			IRB_REFRELE(irb);
28799 			return (error);
28800 		}
28801 	}
28802 	IRB_REFRELE(irb);
28803 	/*
28804 	 * Consider the call as successful if we succeeded on at least
28805 	 * one interface. Otherwise, return the last encountered error.
28806 	 */
28807 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28808 }
28809 
28810 
28811 /*
28812  * Issue a warning regarding a route crossing an interface with an
28813  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28814  * amount of time is logged.
28815  */
28816 static void
28817 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28818 {
28819 	hrtime_t	current = gethrtime();
28820 	char		buf[INET_ADDRSTRLEN];
28821 	ip_stack_t	*ipst = ire->ire_ipst;
28822 
28823 	/* Convert interval in ms to hrtime in ns */
28824 	if (ipst->ips_multirt_bad_mtu_last_time +
28825 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
28826 	    current) {
28827 		cmn_err(CE_WARN, "ip: ignoring multiroute "
28828 		    "to %s, incorrect MTU %u (expected %u)\n",
28829 		    ip_dot_addr(ire->ire_addr, buf),
28830 		    ire->ire_max_frag, max_frag);
28831 
28832 		ipst->ips_multirt_bad_mtu_last_time = current;
28833 	}
28834 }
28835 
28836 
28837 /*
28838  * Get the CGTP (multirouting) filtering status.
28839  * If 0, the CGTP hooks are transparent.
28840  */
28841 /* ARGSUSED */
28842 static int
28843 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
28844 {
28845 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28846 
28847 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
28848 	return (0);
28849 }
28850 
28851 
28852 /*
28853  * Set the CGTP (multirouting) filtering status.
28854  * If the status is changed from active to transparent
28855  * or from transparent to active, forward the new status
28856  * to the filtering module (if loaded).
28857  */
28858 /* ARGSUSED */
28859 static int
28860 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
28861     cred_t *ioc_cr)
28862 {
28863 	long		new_value;
28864 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28865 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
28866 
28867 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
28868 		return (EPERM);
28869 
28870 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
28871 	    new_value < 0 || new_value > 1) {
28872 		return (EINVAL);
28873 	}
28874 
28875 	if ((!*ip_cgtp_filter_value) && new_value) {
28876 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
28877 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28878 		    " (module not loaded)" : "");
28879 	}
28880 	if (*ip_cgtp_filter_value && (!new_value)) {
28881 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
28882 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28883 		    " (module not loaded)" : "");
28884 	}
28885 
28886 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28887 		int	res;
28888 		netstackid_t stackid;
28889 
28890 		stackid = ipst->ips_netstack->netstack_stackid;
28891 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
28892 		    new_value);
28893 		if (res)
28894 			return (res);
28895 	}
28896 
28897 	*ip_cgtp_filter_value = (boolean_t)new_value;
28898 
28899 	return (0);
28900 }
28901 
28902 
28903 /*
28904  * Return the expected CGTP hooks version number.
28905  */
28906 int
28907 ip_cgtp_filter_supported(void)
28908 {
28909 	return (ip_cgtp_filter_rev);
28910 }
28911 
28912 
28913 /*
28914  * CGTP hooks can be registered by invoking this function.
28915  * Checks that the version number matches.
28916  */
28917 int
28918 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
28919 {
28920 	netstack_t *ns;
28921 	ip_stack_t *ipst;
28922 
28923 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
28924 		return (ENOTSUP);
28925 
28926 	ns = netstack_find_by_stackid(stackid);
28927 	if (ns == NULL)
28928 		return (EINVAL);
28929 	ipst = ns->netstack_ip;
28930 	ASSERT(ipst != NULL);
28931 
28932 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28933 		netstack_rele(ns);
28934 		return (EALREADY);
28935 	}
28936 
28937 	ipst->ips_ip_cgtp_filter_ops = ops;
28938 	netstack_rele(ns);
28939 	return (0);
28940 }
28941 
28942 /*
28943  * CGTP hooks can be unregistered by invoking this function.
28944  * Returns ENXIO if there was no registration.
28945  * Returns EBUSY if the ndd variable has not been turned off.
28946  */
28947 int
28948 ip_cgtp_filter_unregister(netstackid_t stackid)
28949 {
28950 	netstack_t *ns;
28951 	ip_stack_t *ipst;
28952 
28953 	ns = netstack_find_by_stackid(stackid);
28954 	if (ns == NULL)
28955 		return (EINVAL);
28956 	ipst = ns->netstack_ip;
28957 	ASSERT(ipst != NULL);
28958 
28959 	if (ipst->ips_ip_cgtp_filter) {
28960 		netstack_rele(ns);
28961 		return (EBUSY);
28962 	}
28963 
28964 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
28965 		netstack_rele(ns);
28966 		return (ENXIO);
28967 	}
28968 	ipst->ips_ip_cgtp_filter_ops = NULL;
28969 	netstack_rele(ns);
28970 	return (0);
28971 }
28972 
28973 /*
28974  * Check whether there is a CGTP filter registration.
28975  * Returns non-zero if there is a registration, otherwise returns zero.
28976  * Note: returns zero if bad stackid.
28977  */
28978 int
28979 ip_cgtp_filter_is_registered(netstackid_t stackid)
28980 {
28981 	netstack_t *ns;
28982 	ip_stack_t *ipst;
28983 	int ret;
28984 
28985 	ns = netstack_find_by_stackid(stackid);
28986 	if (ns == NULL)
28987 		return (0);
28988 	ipst = ns->netstack_ip;
28989 	ASSERT(ipst != NULL);
28990 
28991 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
28992 		ret = 1;
28993 	else
28994 		ret = 0;
28995 
28996 	netstack_rele(ns);
28997 	return (ret);
28998 }
28999 
29000 static squeue_func_t
29001 ip_squeue_switch(int val)
29002 {
29003 	squeue_func_t rval = squeue_fill;
29004 
29005 	switch (val) {
29006 	case IP_SQUEUE_ENTER_NODRAIN:
29007 		rval = squeue_enter_nodrain;
29008 		break;
29009 	case IP_SQUEUE_ENTER:
29010 		rval = squeue_enter;
29011 		break;
29012 	default:
29013 		break;
29014 	}
29015 	return (rval);
29016 }
29017 
29018 /* ARGSUSED */
29019 static int
29020 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29021     caddr_t addr, cred_t *cr)
29022 {
29023 	int *v = (int *)addr;
29024 	long new_value;
29025 
29026 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29027 		return (EPERM);
29028 
29029 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29030 		return (EINVAL);
29031 
29032 	ip_input_proc = ip_squeue_switch(new_value);
29033 	*v = new_value;
29034 	return (0);
29035 }
29036 
29037 /* ARGSUSED */
29038 static int
29039 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29040     caddr_t addr, cred_t *cr)
29041 {
29042 	int *v = (int *)addr;
29043 	long new_value;
29044 
29045 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29046 		return (EPERM);
29047 
29048 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29049 		return (EINVAL);
29050 
29051 	*v = new_value;
29052 	return (0);
29053 }
29054 
29055 /*
29056  * Handle changes to ipmp_hook_emulation ndd variable.
29057  * Need to update phyint_hook_ifindex.
29058  * Also generate a nic plumb event should a new ifidex be assigned to a group.
29059  */
29060 static void
29061 ipmp_hook_emulation_changed(ip_stack_t *ipst)
29062 {
29063 	phyint_t *phyi;
29064 	phyint_t *phyi_tmp;
29065 	char *groupname;
29066 	int namelen;
29067 	ill_t	*ill;
29068 	boolean_t new_group;
29069 
29070 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29071 	/*
29072 	 * Group indicies are stored in the phyint - a common structure
29073 	 * to both IPv4 and IPv6.
29074 	 */
29075 	phyi = avl_first(&ipst->ips_phyint_g_list->phyint_list_avl_by_index);
29076 	for (; phyi != NULL;
29077 	    phyi = avl_walk(&ipst->ips_phyint_g_list->phyint_list_avl_by_index,
29078 	    phyi, AVL_AFTER)) {
29079 		/* Ignore the ones that do not have a group */
29080 		if (phyi->phyint_groupname_len == 0)
29081 			continue;
29082 
29083 		/*
29084 		 * Look for other phyint in group.
29085 		 * Clear name/namelen so the lookup doesn't find ourselves.
29086 		 */
29087 		namelen = phyi->phyint_groupname_len;
29088 		groupname = phyi->phyint_groupname;
29089 		phyi->phyint_groupname_len = 0;
29090 		phyi->phyint_groupname = NULL;
29091 
29092 		phyi_tmp = phyint_lookup_group(groupname, B_FALSE, ipst);
29093 		/* Restore */
29094 		phyi->phyint_groupname_len = namelen;
29095 		phyi->phyint_groupname = groupname;
29096 
29097 		new_group = B_FALSE;
29098 		if (ipst->ips_ipmp_hook_emulation) {
29099 			/*
29100 			 * If the group already exists and has already
29101 			 * been assigned a group ifindex, we use the existing
29102 			 * group_ifindex, otherwise we pick a new group_ifindex
29103 			 * here.
29104 			 */
29105 			if (phyi_tmp != NULL &&
29106 			    phyi_tmp->phyint_group_ifindex != 0) {
29107 				phyi->phyint_group_ifindex =
29108 				    phyi_tmp->phyint_group_ifindex;
29109 			} else {
29110 				/* XXX We need a recovery strategy here. */
29111 				if (!ip_assign_ifindex(
29112 				    &phyi->phyint_group_ifindex, ipst))
29113 					cmn_err(CE_PANIC,
29114 					    "ip_assign_ifindex() failed");
29115 				new_group = B_TRUE;
29116 			}
29117 		} else {
29118 			phyi->phyint_group_ifindex = 0;
29119 		}
29120 		if (ipst->ips_ipmp_hook_emulation)
29121 			phyi->phyint_hook_ifindex = phyi->phyint_group_ifindex;
29122 		else
29123 			phyi->phyint_hook_ifindex = phyi->phyint_ifindex;
29124 
29125 		/*
29126 		 * For IP Filter to find out the relationship between
29127 		 * names and interface indicies, we need to generate
29128 		 * a NE_PLUMB event when a new group can appear.
29129 		 * We always generate events when a new interface appears
29130 		 * (even when ipmp_hook_emulation is set) so there
29131 		 * is no need to generate NE_PLUMB events when
29132 		 * ipmp_hook_emulation is turned off.
29133 		 * And since it isn't critical for IP Filter to get
29134 		 * the NE_UNPLUMB events we skip those here.
29135 		 */
29136 		if (new_group) {
29137 			/*
29138 			 * First phyint in group - generate group PLUMB event.
29139 			 * Since we are not running inside the ipsq we do
29140 			 * the dispatch immediately.
29141 			 */
29142 			if (phyi->phyint_illv4 != NULL)
29143 				ill = phyi->phyint_illv4;
29144 			else
29145 				ill = phyi->phyint_illv6;
29146 
29147 			if (ill != NULL) {
29148 				mutex_enter(&ill->ill_lock);
29149 				ill_nic_info_plumb(ill, B_TRUE);
29150 				ill_nic_info_dispatch(ill);
29151 				mutex_exit(&ill->ill_lock);
29152 			}
29153 		}
29154 	}
29155 	rw_exit(&ipst->ips_ill_g_lock);
29156 }
29157 
29158 /* ARGSUSED */
29159 static int
29160 ipmp_hook_emulation_set(queue_t *q, mblk_t *mp, char *value,
29161     caddr_t addr, cred_t *cr)
29162 {
29163 	int *v = (int *)addr;
29164 	long new_value;
29165 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29166 
29167 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29168 		return (EINVAL);
29169 
29170 	if (*v != new_value) {
29171 		*v = new_value;
29172 		ipmp_hook_emulation_changed(ipst);
29173 	}
29174 	return (0);
29175 }
29176 
29177 static void *
29178 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29179 {
29180 	kstat_t *ksp;
29181 
29182 	ip_stat_t template = {
29183 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29184 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29185 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29186 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29187 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29188 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29189 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29190 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29191 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29192 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29193 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29194 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29195 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29196 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29197 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29198 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29199 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29200 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29201 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29202 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29203 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29204 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29205 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29206 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29207 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29208 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29209 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29210 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29211 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29212 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29213 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29214 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29215 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29216 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29217 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29218 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29219 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29220 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29221 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29222 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29223 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29224 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29225 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29226 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29227 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29228 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29229 	};
29230 
29231 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29232 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29233 	    KSTAT_FLAG_VIRTUAL, stackid);
29234 
29235 	if (ksp == NULL)
29236 		return (NULL);
29237 
29238 	bcopy(&template, ip_statisticsp, sizeof (template));
29239 	ksp->ks_data = (void *)ip_statisticsp;
29240 	ksp->ks_private = (void *)(uintptr_t)stackid;
29241 
29242 	kstat_install(ksp);
29243 	return (ksp);
29244 }
29245 
29246 static void
29247 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29248 {
29249 	if (ksp != NULL) {
29250 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29251 		kstat_delete_netstack(ksp, stackid);
29252 	}
29253 }
29254 
29255 static void *
29256 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29257 {
29258 	kstat_t	*ksp;
29259 
29260 	ip_named_kstat_t template = {
29261 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29262 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29263 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29264 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29265 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29266 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29267 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29268 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29269 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29270 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29271 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29272 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29273 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29274 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29275 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29276 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29277 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29278 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29279 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29280 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29281 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29282 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29283 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29284 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29285 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29286 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29287 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29288 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29289 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29290 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29291 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29292 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29293 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29294 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29295 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29296 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29297 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29298 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29299 	};
29300 
29301 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29302 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29303 	if (ksp == NULL || ksp->ks_data == NULL)
29304 		return (NULL);
29305 
29306 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29307 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29308 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29309 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29310 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29311 
29312 	template.netToMediaEntrySize.value.i32 =
29313 	    sizeof (mib2_ipNetToMediaEntry_t);
29314 
29315 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29316 
29317 	bcopy(&template, ksp->ks_data, sizeof (template));
29318 	ksp->ks_update = ip_kstat_update;
29319 	ksp->ks_private = (void *)(uintptr_t)stackid;
29320 
29321 	kstat_install(ksp);
29322 	return (ksp);
29323 }
29324 
29325 static void
29326 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29327 {
29328 	if (ksp != NULL) {
29329 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29330 		kstat_delete_netstack(ksp, stackid);
29331 	}
29332 }
29333 
29334 static int
29335 ip_kstat_update(kstat_t *kp, int rw)
29336 {
29337 	ip_named_kstat_t *ipkp;
29338 	mib2_ipIfStatsEntry_t ipmib;
29339 	ill_walk_context_t ctx;
29340 	ill_t *ill;
29341 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29342 	netstack_t	*ns;
29343 	ip_stack_t	*ipst;
29344 
29345 	if (kp == NULL || kp->ks_data == NULL)
29346 		return (EIO);
29347 
29348 	if (rw == KSTAT_WRITE)
29349 		return (EACCES);
29350 
29351 	ns = netstack_find_by_stackid(stackid);
29352 	if (ns == NULL)
29353 		return (-1);
29354 	ipst = ns->netstack_ip;
29355 	if (ipst == NULL) {
29356 		netstack_rele(ns);
29357 		return (-1);
29358 	}
29359 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29360 
29361 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29362 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29363 	ill = ILL_START_WALK_V4(&ctx, ipst);
29364 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29365 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29366 	rw_exit(&ipst->ips_ill_g_lock);
29367 
29368 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29369 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29370 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29371 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29372 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29373 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29374 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29375 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29376 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29377 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29378 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29379 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29380 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29381 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29382 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29383 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29384 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29385 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29386 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29387 
29388 	ipkp->routingDiscards.value.ui32 =	0;
29389 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29390 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29391 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29392 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29393 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29394 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29395 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29396 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29397 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29398 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29399 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29400 
29401 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29402 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29403 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29404 
29405 	netstack_rele(ns);
29406 
29407 	return (0);
29408 }
29409 
29410 static void *
29411 icmp_kstat_init(netstackid_t stackid)
29412 {
29413 	kstat_t	*ksp;
29414 
29415 	icmp_named_kstat_t template = {
29416 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29417 		{ "inErrors",		KSTAT_DATA_UINT32 },
29418 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29419 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29420 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29421 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29422 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29423 		{ "inEchos",		KSTAT_DATA_UINT32 },
29424 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29425 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29426 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29427 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29428 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29429 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29430 		{ "outErrors",		KSTAT_DATA_UINT32 },
29431 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29432 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29433 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29434 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29435 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29436 		{ "outEchos",		KSTAT_DATA_UINT32 },
29437 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29438 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29439 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29440 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29441 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29442 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29443 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29444 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29445 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29446 		{ "outDrops",		KSTAT_DATA_UINT32 },
29447 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29448 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29449 	};
29450 
29451 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29452 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29453 	if (ksp == NULL || ksp->ks_data == NULL)
29454 		return (NULL);
29455 
29456 	bcopy(&template, ksp->ks_data, sizeof (template));
29457 
29458 	ksp->ks_update = icmp_kstat_update;
29459 	ksp->ks_private = (void *)(uintptr_t)stackid;
29460 
29461 	kstat_install(ksp);
29462 	return (ksp);
29463 }
29464 
29465 static void
29466 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29467 {
29468 	if (ksp != NULL) {
29469 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29470 		kstat_delete_netstack(ksp, stackid);
29471 	}
29472 }
29473 
29474 static int
29475 icmp_kstat_update(kstat_t *kp, int rw)
29476 {
29477 	icmp_named_kstat_t *icmpkp;
29478 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29479 	netstack_t	*ns;
29480 	ip_stack_t	*ipst;
29481 
29482 	if ((kp == NULL) || (kp->ks_data == NULL))
29483 		return (EIO);
29484 
29485 	if (rw == KSTAT_WRITE)
29486 		return (EACCES);
29487 
29488 	ns = netstack_find_by_stackid(stackid);
29489 	if (ns == NULL)
29490 		return (-1);
29491 	ipst = ns->netstack_ip;
29492 	if (ipst == NULL) {
29493 		netstack_rele(ns);
29494 		return (-1);
29495 	}
29496 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29497 
29498 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29499 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29500 	icmpkp->inDestUnreachs.value.ui32 =
29501 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29502 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29503 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29504 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29505 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29506 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29507 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29508 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29509 	icmpkp->inTimestampReps.value.ui32 =
29510 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29511 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29512 	icmpkp->inAddrMaskReps.value.ui32 =
29513 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29514 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29515 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29516 	icmpkp->outDestUnreachs.value.ui32 =
29517 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29518 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29519 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29520 	icmpkp->outSrcQuenchs.value.ui32 =
29521 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29522 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29523 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29524 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29525 	icmpkp->outTimestamps.value.ui32 =
29526 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29527 	icmpkp->outTimestampReps.value.ui32 =
29528 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29529 	icmpkp->outAddrMasks.value.ui32 =
29530 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29531 	icmpkp->outAddrMaskReps.value.ui32 =
29532 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29533 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29534 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29535 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29536 	icmpkp->outFragNeeded.value.ui32 =
29537 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29538 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29539 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29540 	icmpkp->inBadRedirects.value.ui32 =
29541 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29542 
29543 	netstack_rele(ns);
29544 	return (0);
29545 }
29546 
29547 /*
29548  * This is the fanout function for raw socket opened for SCTP.  Note
29549  * that it is called after SCTP checks that there is no socket which
29550  * wants a packet.  Then before SCTP handles this out of the blue packet,
29551  * this function is called to see if there is any raw socket for SCTP.
29552  * If there is and it is bound to the correct address, the packet will
29553  * be sent to that socket.  Note that only one raw socket can be bound to
29554  * a port.  This is assured in ipcl_sctp_hash_insert();
29555  */
29556 void
29557 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29558     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29559     zoneid_t zoneid)
29560 {
29561 	conn_t		*connp;
29562 	queue_t		*rq;
29563 	mblk_t		*first_mp;
29564 	boolean_t	secure;
29565 	ip6_t		*ip6h;
29566 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29567 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29568 
29569 	first_mp = mp;
29570 	if (mctl_present) {
29571 		mp = first_mp->b_cont;
29572 		secure = ipsec_in_is_secure(first_mp);
29573 		ASSERT(mp != NULL);
29574 	} else {
29575 		secure = B_FALSE;
29576 	}
29577 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29578 
29579 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29580 	if (connp == NULL) {
29581 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29582 		return;
29583 	}
29584 	rq = connp->conn_rq;
29585 	if (!canputnext(rq)) {
29586 		CONN_DEC_REF(connp);
29587 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29588 		freemsg(first_mp);
29589 		return;
29590 	}
29591 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29592 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29593 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29594 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29595 		if (first_mp == NULL) {
29596 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29597 			CONN_DEC_REF(connp);
29598 			return;
29599 		}
29600 	}
29601 	/*
29602 	 * We probably should not send M_CTL message up to
29603 	 * raw socket.
29604 	 */
29605 	if (mctl_present)
29606 		freeb(first_mp);
29607 
29608 	/* Initiate IPPF processing here if needed. */
29609 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29610 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29611 		ip_process(IPP_LOCAL_IN, &mp,
29612 		    recv_ill->ill_phyint->phyint_ifindex);
29613 		if (mp == NULL) {
29614 			CONN_DEC_REF(connp);
29615 			return;
29616 		}
29617 	}
29618 
29619 	if (connp->conn_recvif || connp->conn_recvslla ||
29620 	    ((connp->conn_ip_recvpktinfo ||
29621 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29622 	    (flags & IP_FF_IPINFO))) {
29623 		int in_flags = 0;
29624 
29625 		/*
29626 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29627 		 * IPF_RECVIF.
29628 		 */
29629 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29630 			in_flags = IPF_RECVIF;
29631 		}
29632 		if (connp->conn_recvslla) {
29633 			in_flags |= IPF_RECVSLLA;
29634 		}
29635 		if (isv4) {
29636 			mp = ip_add_info(mp, recv_ill, in_flags,
29637 			    IPCL_ZONEID(connp), ipst);
29638 		} else {
29639 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29640 			if (mp == NULL) {
29641 				BUMP_MIB(recv_ill->ill_ip_mib,
29642 				    ipIfStatsInDiscards);
29643 				CONN_DEC_REF(connp);
29644 				return;
29645 			}
29646 		}
29647 	}
29648 
29649 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29650 	/*
29651 	 * We are sending the IPSEC_IN message also up. Refer
29652 	 * to comments above this function.
29653 	 * This is the SOCK_RAW, IPPROTO_SCTP case.
29654 	 */
29655 	(connp->conn_recv)(connp, mp, NULL);
29656 	CONN_DEC_REF(connp);
29657 }
29658 
29659 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29660 {									\
29661 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29662 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29663 }
29664 /*
29665  * This function should be called only if all packet processing
29666  * including fragmentation is complete. Callers of this function
29667  * must set mp->b_prev to one of these values:
29668  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29669  * prior to handing over the mp as first argument to this function.
29670  *
29671  * If the ire passed by caller is incomplete, this function
29672  * queues the packet and if necessary, sends ARP request and bails.
29673  * If the ire passed is fully resolved, we simply prepend
29674  * the link-layer header to the packet, do ipsec hw acceleration
29675  * work if necessary, and send the packet out on the wire.
29676  *
29677  * NOTE: IPsec will only call this function with fully resolved
29678  * ires if hw acceleration is involved.
29679  * TODO list :
29680  * 	a Handle M_MULTIDATA so that
29681  *	  tcp_multisend->tcp_multisend_data can
29682  *	  call ip_xmit_v4 directly
29683  *	b Handle post-ARP work for fragments so that
29684  *	  ip_wput_frag can call this function.
29685  */
29686 ipxmit_state_t
29687 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
29688 {
29689 	nce_t		*arpce;
29690 	queue_t		*q;
29691 	int		ill_index;
29692 	mblk_t		*nxt_mp, *first_mp;
29693 	boolean_t	xmit_drop = B_FALSE;
29694 	ip_proc_t	proc;
29695 	ill_t		*out_ill;
29696 	int		pkt_len;
29697 
29698 	arpce = ire->ire_nce;
29699 	ASSERT(arpce != NULL);
29700 
29701 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29702 
29703 	mutex_enter(&arpce->nce_lock);
29704 	switch (arpce->nce_state) {
29705 	case ND_REACHABLE:
29706 		/* If there are other queued packets, queue this packet */
29707 		if (arpce->nce_qd_mp != NULL) {
29708 			if (mp != NULL)
29709 				nce_queue_mp_common(arpce, mp, B_FALSE);
29710 			mp = arpce->nce_qd_mp;
29711 		}
29712 		arpce->nce_qd_mp = NULL;
29713 		mutex_exit(&arpce->nce_lock);
29714 
29715 		/*
29716 		 * Flush the queue.  In the common case, where the
29717 		 * ARP is already resolved,  it will go through the
29718 		 * while loop only once.
29719 		 */
29720 		while (mp != NULL) {
29721 
29722 			nxt_mp = mp->b_next;
29723 			mp->b_next = NULL;
29724 			ASSERT(mp->b_datap->db_type != M_CTL);
29725 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29726 			/*
29727 			 * This info is needed for IPQOS to do COS marking
29728 			 * in ip_wput_attach_llhdr->ip_process.
29729 			 */
29730 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29731 			mp->b_prev = NULL;
29732 
29733 			/* set up ill index for outbound qos processing */
29734 			out_ill = ire_to_ill(ire);
29735 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29736 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29737 			    ill_index);
29738 			if (first_mp == NULL) {
29739 				xmit_drop = B_TRUE;
29740 				BUMP_MIB(out_ill->ill_ip_mib,
29741 				    ipIfStatsOutDiscards);
29742 				goto next_mp;
29743 			}
29744 			/* non-ipsec hw accel case */
29745 			if (io == NULL || !io->ipsec_out_accelerated) {
29746 				/* send it */
29747 				q = ire->ire_stq;
29748 				if (proc == IPP_FWD_OUT) {
29749 					UPDATE_IB_PKT_COUNT(ire);
29750 				} else {
29751 					UPDATE_OB_PKT_COUNT(ire);
29752 				}
29753 				ire->ire_last_used_time = lbolt;
29754 
29755 				if (flow_ctl_enabled || canputnext(q)) {
29756 					if (proc == IPP_FWD_OUT) {
29757 
29758 					BUMP_MIB(out_ill->ill_ip_mib,
29759 					    ipIfStatsHCOutForwDatagrams);
29760 
29761 					}
29762 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29763 					    pkt_len);
29764 
29765 					putnext(q, first_mp);
29766 				} else {
29767 					BUMP_MIB(out_ill->ill_ip_mib,
29768 					    ipIfStatsOutDiscards);
29769 					xmit_drop = B_TRUE;
29770 					freemsg(first_mp);
29771 				}
29772 			} else {
29773 				/*
29774 				 * Safety Pup says: make sure this
29775 				 *  is going to the right interface!
29776 				 */
29777 				ill_t *ill1 =
29778 				    (ill_t *)ire->ire_stq->q_ptr;
29779 				int ifindex =
29780 				    ill1->ill_phyint->phyint_ifindex;
29781 				if (ifindex !=
29782 				    io->ipsec_out_capab_ill_index) {
29783 					xmit_drop = B_TRUE;
29784 					freemsg(mp);
29785 				} else {
29786 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
29787 					    pkt_len);
29788 					ipsec_hw_putnext(ire->ire_stq, mp);
29789 				}
29790 			}
29791 next_mp:
29792 			mp = nxt_mp;
29793 		} /* while (mp != NULL) */
29794 		if (xmit_drop)
29795 			return (SEND_FAILED);
29796 		else
29797 			return (SEND_PASSED);
29798 
29799 	case ND_INITIAL:
29800 	case ND_INCOMPLETE:
29801 
29802 		/*
29803 		 * While we do send off packets to dests that
29804 		 * use fully-resolved CGTP routes, we do not
29805 		 * handle unresolved CGTP routes.
29806 		 */
29807 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
29808 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
29809 
29810 		if (mp != NULL) {
29811 			/* queue the packet */
29812 			nce_queue_mp_common(arpce, mp, B_FALSE);
29813 		}
29814 
29815 		if (arpce->nce_state == ND_INCOMPLETE) {
29816 			mutex_exit(&arpce->nce_lock);
29817 			DTRACE_PROBE3(ip__xmit__incomplete,
29818 			    (ire_t *), ire, (mblk_t *), mp,
29819 			    (ipsec_out_t *), io);
29820 			return (LOOKUP_IN_PROGRESS);
29821 		}
29822 
29823 		arpce->nce_state = ND_INCOMPLETE;
29824 		mutex_exit(&arpce->nce_lock);
29825 		/*
29826 		 * Note that ire_add() (called from ire_forward())
29827 		 * holds a ref on the ire until ARP is completed.
29828 		 */
29829 
29830 		ire_arpresolve(ire, ire_to_ill(ire));
29831 		return (LOOKUP_IN_PROGRESS);
29832 	default:
29833 		ASSERT(0);
29834 		mutex_exit(&arpce->nce_lock);
29835 		return (LLHDR_RESLV_FAILED);
29836 	}
29837 }
29838 
29839 #undef	UPDATE_IP_MIB_OB_COUNTERS
29840 
29841 /*
29842  * Return B_TRUE if the buffers differ in length or content.
29843  * This is used for comparing extension header buffers.
29844  * Note that an extension header would be declared different
29845  * even if all that changed was the next header value in that header i.e.
29846  * what really changed is the next extension header.
29847  */
29848 boolean_t
29849 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
29850     uint_t blen)
29851 {
29852 	if (!b_valid)
29853 		blen = 0;
29854 
29855 	if (alen != blen)
29856 		return (B_TRUE);
29857 	if (alen == 0)
29858 		return (B_FALSE);	/* Both zero length */
29859 	return (bcmp(abuf, bbuf, alen));
29860 }
29861 
29862 /*
29863  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
29864  * Return B_FALSE if memory allocation fails - don't change any state!
29865  */
29866 boolean_t
29867 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29868     const void *src, uint_t srclen)
29869 {
29870 	void *dst;
29871 
29872 	if (!src_valid)
29873 		srclen = 0;
29874 
29875 	ASSERT(*dstlenp == 0);
29876 	if (src != NULL && srclen != 0) {
29877 		dst = mi_alloc(srclen, BPRI_MED);
29878 		if (dst == NULL)
29879 			return (B_FALSE);
29880 	} else {
29881 		dst = NULL;
29882 	}
29883 	if (*dstp != NULL)
29884 		mi_free(*dstp);
29885 	*dstp = dst;
29886 	*dstlenp = dst == NULL ? 0 : srclen;
29887 	return (B_TRUE);
29888 }
29889 
29890 /*
29891  * Replace what is in *dst, *dstlen with the source.
29892  * Assumes ip_allocbuf has already been called.
29893  */
29894 void
29895 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29896     const void *src, uint_t srclen)
29897 {
29898 	if (!src_valid)
29899 		srclen = 0;
29900 
29901 	ASSERT(*dstlenp == srclen);
29902 	if (src != NULL && srclen != 0)
29903 		bcopy(src, *dstp, srclen);
29904 }
29905 
29906 /*
29907  * Free the storage pointed to by the members of an ip6_pkt_t.
29908  */
29909 void
29910 ip6_pkt_free(ip6_pkt_t *ipp)
29911 {
29912 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
29913 
29914 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
29915 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
29916 		ipp->ipp_hopopts = NULL;
29917 		ipp->ipp_hopoptslen = 0;
29918 	}
29919 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
29920 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
29921 		ipp->ipp_rtdstopts = NULL;
29922 		ipp->ipp_rtdstoptslen = 0;
29923 	}
29924 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
29925 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
29926 		ipp->ipp_dstopts = NULL;
29927 		ipp->ipp_dstoptslen = 0;
29928 	}
29929 	if (ipp->ipp_fields & IPPF_RTHDR) {
29930 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
29931 		ipp->ipp_rthdr = NULL;
29932 		ipp->ipp_rthdrlen = 0;
29933 	}
29934 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
29935 	    IPPF_RTHDR);
29936 }
29937