xref: /titanic_41/usr/src/uts/common/inet/ip/ip.c (revision 1ba18ff1efb9bb19540297cbee0a824685da1622)
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 	/* SIOCSENABLESDP is handled by SDP */
1299 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1300 };
1301 
1302 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1303 
1304 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1305 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1306 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1307 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1308 		TUN_CMD, ip_sioctl_tunparam, NULL },
1309 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1310 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1311 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1312 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1313 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1314 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1315 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1316 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1317 		MISC_CMD, mrt_ioctl},
1318 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1319 		MISC_CMD, mrt_ioctl},
1320 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1321 		MISC_CMD, mrt_ioctl}
1322 };
1323 
1324 int ip_misc_ioctl_count =
1325     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1326 
1327 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1328 					/* Settable in /etc/system */
1329 /* Defined in ip_ire.c */
1330 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1331 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1332 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1333 
1334 static nv_t	ire_nv_arr[] = {
1335 	{ IRE_BROADCAST, "BROADCAST" },
1336 	{ IRE_LOCAL, "LOCAL" },
1337 	{ IRE_LOOPBACK, "LOOPBACK" },
1338 	{ IRE_CACHE, "CACHE" },
1339 	{ IRE_DEFAULT, "DEFAULT" },
1340 	{ IRE_PREFIX, "PREFIX" },
1341 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1342 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1343 	{ IRE_HOST, "HOST" },
1344 	{ 0 }
1345 };
1346 
1347 nv_t	*ire_nv_tbl = ire_nv_arr;
1348 
1349 /* Defined in ip_netinfo.c */
1350 extern ddi_taskq_t	*eventq_queue_nic;
1351 
1352 /* Simple ICMP IP Header Template */
1353 static ipha_t icmp_ipha = {
1354 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1355 };
1356 
1357 struct module_info ip_mod_info = {
1358 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1359 };
1360 
1361 /*
1362  * Duplicate static symbols within a module confuses mdb; so we avoid the
1363  * problem by making the symbols here distinct from those in udp.c.
1364  */
1365 
1366 /*
1367  * Entry points for IP as a device and as a module.
1368  * FIXME: down the road we might want a separate module and driver qinit.
1369  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1370  */
1371 static struct qinit iprinitv4 = {
1372 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1373 	&ip_mod_info
1374 };
1375 
1376 struct qinit iprinitv6 = {
1377 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1378 	&ip_mod_info
1379 };
1380 
1381 static struct qinit ipwinitv4 = {
1382 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1383 	&ip_mod_info
1384 };
1385 
1386 struct qinit ipwinitv6 = {
1387 	(pfi_t)ip_wput_v6, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1388 	&ip_mod_info
1389 };
1390 
1391 static struct qinit iplrinit = {
1392 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1393 	&ip_mod_info
1394 };
1395 
1396 static struct qinit iplwinit = {
1397 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1398 	&ip_mod_info
1399 };
1400 
1401 /* For AF_INET aka /dev/ip */
1402 struct streamtab ipinfov4 = {
1403 	&iprinitv4, &ipwinitv4, &iplrinit, &iplwinit
1404 };
1405 
1406 /* For AF_INET6 aka /dev/ip6 */
1407 struct streamtab ipinfov6 = {
1408 	&iprinitv6, &ipwinitv6, &iplrinit, &iplwinit
1409 };
1410 
1411 #ifdef	DEBUG
1412 static boolean_t skip_sctp_cksum = B_FALSE;
1413 #endif
1414 
1415 /*
1416  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1417  * ip_rput_v6(), ip_output(), etc.  If the message
1418  * block already has a M_CTL at the front of it, then simply set the zoneid
1419  * appropriately.
1420  */
1421 mblk_t *
1422 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1423 {
1424 	mblk_t		*first_mp;
1425 	ipsec_out_t	*io;
1426 
1427 	ASSERT(zoneid != ALL_ZONES);
1428 	if (mp->b_datap->db_type == M_CTL) {
1429 		io = (ipsec_out_t *)mp->b_rptr;
1430 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1431 		io->ipsec_out_zoneid = zoneid;
1432 		return (mp);
1433 	}
1434 
1435 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1436 	if (first_mp == NULL)
1437 		return (NULL);
1438 	io = (ipsec_out_t *)first_mp->b_rptr;
1439 	/* This is not a secure packet */
1440 	io->ipsec_out_secure = B_FALSE;
1441 	io->ipsec_out_zoneid = zoneid;
1442 	first_mp->b_cont = mp;
1443 	return (first_mp);
1444 }
1445 
1446 /*
1447  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1448  */
1449 mblk_t *
1450 ip_copymsg(mblk_t *mp)
1451 {
1452 	mblk_t *nmp;
1453 	ipsec_info_t *in;
1454 
1455 	if (mp->b_datap->db_type != M_CTL)
1456 		return (copymsg(mp));
1457 
1458 	in = (ipsec_info_t *)mp->b_rptr;
1459 
1460 	/*
1461 	 * Note that M_CTL is also used for delivering ICMP error messages
1462 	 * upstream to transport layers.
1463 	 */
1464 	if (in->ipsec_info_type != IPSEC_OUT &&
1465 	    in->ipsec_info_type != IPSEC_IN)
1466 		return (copymsg(mp));
1467 
1468 	nmp = copymsg(mp->b_cont);
1469 
1470 	if (in->ipsec_info_type == IPSEC_OUT) {
1471 		return (ipsec_out_tag(mp, nmp,
1472 		    ((ipsec_out_t *)in)->ipsec_out_ns));
1473 	} else {
1474 		return (ipsec_in_tag(mp, nmp,
1475 		    ((ipsec_in_t *)in)->ipsec_in_ns));
1476 	}
1477 }
1478 
1479 /* Generate an ICMP fragmentation needed message. */
1480 static void
1481 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1482     ip_stack_t *ipst)
1483 {
1484 	icmph_t	icmph;
1485 	mblk_t *first_mp;
1486 	boolean_t mctl_present;
1487 
1488 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1489 
1490 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1491 		if (mctl_present)
1492 			freeb(first_mp);
1493 		return;
1494 	}
1495 
1496 	bzero(&icmph, sizeof (icmph_t));
1497 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1498 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1499 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1500 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1501 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1502 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1503 	    ipst);
1504 }
1505 
1506 /*
1507  * icmp_inbound deals with ICMP messages in the following ways.
1508  *
1509  * 1) It needs to send a reply back and possibly delivering it
1510  *    to the "interested" upper clients.
1511  * 2) It needs to send it to the upper clients only.
1512  * 3) It needs to change some values in IP only.
1513  * 4) It needs to change some values in IP and upper layers e.g TCP.
1514  *
1515  * We need to accomodate icmp messages coming in clear until we get
1516  * everything secure from the wire. If icmp_accept_clear_messages
1517  * is zero we check with the global policy and act accordingly. If
1518  * it is non-zero, we accept the message without any checks. But
1519  * *this does not mean* that this will be delivered to the upper
1520  * clients. By accepting we might send replies back, change our MTU
1521  * value etc. but delivery to the ULP/clients depends on their policy
1522  * dispositions.
1523  *
1524  * We handle the above 4 cases in the context of IPsec in the
1525  * following way :
1526  *
1527  * 1) Send the reply back in the same way as the request came in.
1528  *    If it came in encrypted, it goes out encrypted. If it came in
1529  *    clear, it goes out in clear. Thus, this will prevent chosen
1530  *    plain text attack.
1531  * 2) The client may or may not expect things to come in secure.
1532  *    If it comes in secure, the policy constraints are checked
1533  *    before delivering it to the upper layers. If it comes in
1534  *    clear, ipsec_inbound_accept_clear will decide whether to
1535  *    accept this in clear or not. In both the cases, if the returned
1536  *    message (IP header + 8 bytes) that caused the icmp message has
1537  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1538  *    sending up. If there are only 8 bytes of returned message, then
1539  *    upper client will not be notified.
1540  * 3) Check with global policy to see whether it matches the constaints.
1541  *    But this will be done only if icmp_accept_messages_in_clear is
1542  *    zero.
1543  * 4) If we need to change both in IP and ULP, then the decision taken
1544  *    while affecting the values in IP and while delivering up to TCP
1545  *    should be the same.
1546  *
1547  * 	There are two cases.
1548  *
1549  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1550  *	   failed), we will not deliver it to the ULP, even though they
1551  *	   are *willing* to accept in *clear*. This is fine as our global
1552  *	   disposition to icmp messages asks us reject the datagram.
1553  *
1554  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1555  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1556  *	   to deliver it to ULP (policy failed), it can lead to
1557  *	   consistency problems. The cases known at this time are
1558  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1559  *	   values :
1560  *
1561  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1562  *	     and Upper layer rejects. Then the communication will
1563  *	     come to a stop. This is solved by making similar decisions
1564  *	     at both levels. Currently, when we are unable to deliver
1565  *	     to the Upper Layer (due to policy failures) while IP has
1566  *	     adjusted ire_max_frag, the next outbound datagram would
1567  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1568  *	     will be with the right level of protection. Thus the right
1569  *	     value will be communicated even if we are not able to
1570  *	     communicate when we get from the wire initially. But this
1571  *	     assumes there would be at least one outbound datagram after
1572  *	     IP has adjusted its ire_max_frag value. To make things
1573  *	     simpler, we accept in clear after the validation of
1574  *	     AH/ESP headers.
1575  *
1576  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1577  *	     upper layer depending on the level of protection the upper
1578  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1579  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1580  *	     should be accepted in clear when the Upper layer expects secure.
1581  *	     Thus the communication may get aborted by some bad ICMP
1582  *	     packets.
1583  *
1584  * IPQoS Notes:
1585  * The only instance when a packet is sent for processing is when there
1586  * isn't an ICMP client and if we are interested in it.
1587  * If there is a client, IPPF processing will take place in the
1588  * ip_fanout_proto routine.
1589  *
1590  * Zones notes:
1591  * The packet is only processed in the context of the specified zone: typically
1592  * only this zone will reply to an echo request, and only interested clients in
1593  * this zone will receive a copy of the packet. This means that the caller must
1594  * call icmp_inbound() for each relevant zone.
1595  */
1596 static void
1597 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1598     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1599     ill_t *recv_ill, zoneid_t zoneid)
1600 {
1601 	icmph_t	*icmph;
1602 	ipha_t	*ipha;
1603 	int	iph_hdr_length;
1604 	int	hdr_length;
1605 	boolean_t	interested;
1606 	uint32_t	ts;
1607 	uchar_t	*wptr;
1608 	ipif_t	*ipif;
1609 	mblk_t *first_mp;
1610 	ipsec_in_t *ii;
1611 	ire_t *src_ire;
1612 	boolean_t onlink;
1613 	timestruc_t now;
1614 	uint32_t ill_index;
1615 	ip_stack_t *ipst;
1616 
1617 	ASSERT(ill != NULL);
1618 	ipst = ill->ill_ipst;
1619 
1620 	first_mp = mp;
1621 	if (mctl_present) {
1622 		mp = first_mp->b_cont;
1623 		ASSERT(mp != NULL);
1624 	}
1625 
1626 	ipha = (ipha_t *)mp->b_rptr;
1627 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1628 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1629 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1630 		if (first_mp == NULL)
1631 			return;
1632 	}
1633 
1634 	/*
1635 	 * On a labeled system, we have to check whether the zone itself is
1636 	 * permitted to receive raw traffic.
1637 	 */
1638 	if (is_system_labeled()) {
1639 		if (zoneid == ALL_ZONES)
1640 			zoneid = tsol_packet_to_zoneid(mp);
1641 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1642 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1643 			    zoneid));
1644 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1645 			freemsg(first_mp);
1646 			return;
1647 		}
1648 	}
1649 
1650 	/*
1651 	 * We have accepted the ICMP message. It means that we will
1652 	 * respond to the packet if needed. It may not be delivered
1653 	 * to the upper client depending on the policy constraints
1654 	 * and the disposition in ipsec_inbound_accept_clear.
1655 	 */
1656 
1657 	ASSERT(ill != NULL);
1658 
1659 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1660 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1661 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1662 		/* Last chance to get real. */
1663 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1664 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1665 			freemsg(first_mp);
1666 			return;
1667 		}
1668 		/* Refresh iph following the pullup. */
1669 		ipha = (ipha_t *)mp->b_rptr;
1670 	}
1671 	/* ICMP header checksum, including checksum field, should be zero. */
1672 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1673 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1674 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1675 		freemsg(first_mp);
1676 		return;
1677 	}
1678 	/* The IP header will always be a multiple of four bytes */
1679 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1680 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1681 	    icmph->icmph_code));
1682 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1683 	/* We will set "interested" to "true" if we want a copy */
1684 	interested = B_FALSE;
1685 	switch (icmph->icmph_type) {
1686 	case ICMP_ECHO_REPLY:
1687 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1688 		break;
1689 	case ICMP_DEST_UNREACHABLE:
1690 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1691 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1692 		interested = B_TRUE;	/* Pass up to transport */
1693 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1694 		break;
1695 	case ICMP_SOURCE_QUENCH:
1696 		interested = B_TRUE;	/* Pass up to transport */
1697 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1698 		break;
1699 	case ICMP_REDIRECT:
1700 		if (!ipst->ips_ip_ignore_redirect)
1701 			interested = B_TRUE;
1702 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1703 		break;
1704 	case ICMP_ECHO_REQUEST:
1705 		/*
1706 		 * Whether to respond to echo requests that come in as IP
1707 		 * broadcasts or as IP multicast is subject to debate
1708 		 * (what isn't?).  We aim to please, you pick it.
1709 		 * Default is do it.
1710 		 */
1711 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1712 			/* unicast: always respond */
1713 			interested = B_TRUE;
1714 		} else if (CLASSD(ipha->ipha_dst)) {
1715 			/* multicast: respond based on tunable */
1716 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1717 		} else if (broadcast) {
1718 			/* broadcast: respond based on tunable */
1719 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1720 		}
1721 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1722 		break;
1723 	case ICMP_ROUTER_ADVERTISEMENT:
1724 	case ICMP_ROUTER_SOLICITATION:
1725 		break;
1726 	case ICMP_TIME_EXCEEDED:
1727 		interested = B_TRUE;	/* Pass up to transport */
1728 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1729 		break;
1730 	case ICMP_PARAM_PROBLEM:
1731 		interested = B_TRUE;	/* Pass up to transport */
1732 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1733 		break;
1734 	case ICMP_TIME_STAMP_REQUEST:
1735 		/* Response to Time Stamp Requests is local policy. */
1736 		if (ipst->ips_ip_g_resp_to_timestamp &&
1737 		    /* So is whether to respond if it was an IP broadcast. */
1738 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1739 			int tstamp_len = 3 * sizeof (uint32_t);
1740 
1741 			if (wptr +  tstamp_len > mp->b_wptr) {
1742 				if (!pullupmsg(mp, wptr + tstamp_len -
1743 				    mp->b_rptr)) {
1744 					BUMP_MIB(ill->ill_ip_mib,
1745 					    ipIfStatsInDiscards);
1746 					freemsg(first_mp);
1747 					return;
1748 				}
1749 				/* Refresh ipha following the pullup. */
1750 				ipha = (ipha_t *)mp->b_rptr;
1751 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1752 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1753 			}
1754 			interested = B_TRUE;
1755 		}
1756 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1757 		break;
1758 	case ICMP_TIME_STAMP_REPLY:
1759 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1760 		break;
1761 	case ICMP_INFO_REQUEST:
1762 		/* Per RFC 1122 3.2.2.7, ignore this. */
1763 	case ICMP_INFO_REPLY:
1764 		break;
1765 	case ICMP_ADDRESS_MASK_REQUEST:
1766 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1767 		    !broadcast) &&
1768 		    /* TODO m_pullup of complete header? */
1769 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN) {
1770 			interested = B_TRUE;
1771 		}
1772 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1773 		break;
1774 	case ICMP_ADDRESS_MASK_REPLY:
1775 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1776 		break;
1777 	default:
1778 		interested = B_TRUE;	/* Pass up to transport */
1779 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1780 		break;
1781 	}
1782 	/* See if there is an ICMP client. */
1783 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1784 		/* If there is an ICMP client and we want one too, copy it. */
1785 		mblk_t *first_mp1;
1786 
1787 		if (!interested) {
1788 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1789 			    ip_policy, recv_ill, zoneid);
1790 			return;
1791 		}
1792 		first_mp1 = ip_copymsg(first_mp);
1793 		if (first_mp1 != NULL) {
1794 			ip_fanout_proto(q, first_mp1, ill, ipha,
1795 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1796 		}
1797 	} else if (!interested) {
1798 		freemsg(first_mp);
1799 		return;
1800 	} else {
1801 		/*
1802 		 * Initiate policy processing for this packet if ip_policy
1803 		 * is true.
1804 		 */
1805 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1806 			ill_index = ill->ill_phyint->phyint_ifindex;
1807 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1808 			if (mp == NULL) {
1809 				if (mctl_present) {
1810 					freeb(first_mp);
1811 				}
1812 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1813 				return;
1814 			}
1815 		}
1816 	}
1817 	/* We want to do something with it. */
1818 	/* Check db_ref to make sure we can modify the packet. */
1819 	if (mp->b_datap->db_ref > 1) {
1820 		mblk_t	*first_mp1;
1821 
1822 		first_mp1 = ip_copymsg(first_mp);
1823 		freemsg(first_mp);
1824 		if (!first_mp1) {
1825 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1826 			return;
1827 		}
1828 		first_mp = first_mp1;
1829 		if (mctl_present) {
1830 			mp = first_mp->b_cont;
1831 			ASSERT(mp != NULL);
1832 		} else {
1833 			mp = first_mp;
1834 		}
1835 		ipha = (ipha_t *)mp->b_rptr;
1836 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1837 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1838 	}
1839 	switch (icmph->icmph_type) {
1840 	case ICMP_ADDRESS_MASK_REQUEST:
1841 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1842 		if (ipif == NULL) {
1843 			freemsg(first_mp);
1844 			return;
1845 		}
1846 		/*
1847 		 * outging interface must be IPv4
1848 		 */
1849 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1850 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1851 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1852 		ipif_refrele(ipif);
1853 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1854 		break;
1855 	case ICMP_ECHO_REQUEST:
1856 		icmph->icmph_type = ICMP_ECHO_REPLY;
1857 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1858 		break;
1859 	case ICMP_TIME_STAMP_REQUEST: {
1860 		uint32_t *tsp;
1861 
1862 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1863 		tsp = (uint32_t *)wptr;
1864 		tsp++;		/* Skip past 'originate time' */
1865 		/* Compute # of milliseconds since midnight */
1866 		gethrestime(&now);
1867 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1868 		    now.tv_nsec / (NANOSEC / MILLISEC);
1869 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1870 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1871 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1872 		break;
1873 	}
1874 	default:
1875 		ipha = (ipha_t *)&icmph[1];
1876 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1877 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1878 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1879 				freemsg(first_mp);
1880 				return;
1881 			}
1882 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1883 			ipha = (ipha_t *)&icmph[1];
1884 		}
1885 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1886 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1887 			freemsg(first_mp);
1888 			return;
1889 		}
1890 		hdr_length = IPH_HDR_LENGTH(ipha);
1891 		if (hdr_length < sizeof (ipha_t)) {
1892 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1893 			freemsg(first_mp);
1894 			return;
1895 		}
1896 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1897 			if (!pullupmsg(mp,
1898 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1899 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1900 				freemsg(first_mp);
1901 				return;
1902 			}
1903 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1904 			ipha = (ipha_t *)&icmph[1];
1905 		}
1906 		switch (icmph->icmph_type) {
1907 		case ICMP_REDIRECT:
1908 			/*
1909 			 * As there is no upper client to deliver, we don't
1910 			 * need the first_mp any more.
1911 			 */
1912 			if (mctl_present) {
1913 				freeb(first_mp);
1914 			}
1915 			icmp_redirect(ill, mp);
1916 			return;
1917 		case ICMP_DEST_UNREACHABLE:
1918 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1919 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1920 				    zoneid, mp, iph_hdr_length, ipst)) {
1921 					freemsg(first_mp);
1922 					return;
1923 				}
1924 				/*
1925 				 * icmp_inbound_too_big() may alter mp.
1926 				 * Resynch ipha and icmph accordingly.
1927 				 */
1928 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1929 				ipha = (ipha_t *)&icmph[1];
1930 			}
1931 			/* FALLTHRU */
1932 		default :
1933 			/*
1934 			 * IPQoS notes: Since we have already done IPQoS
1935 			 * processing we don't want to do it again in
1936 			 * the fanout routines called by
1937 			 * icmp_inbound_error_fanout, hence the last
1938 			 * argument, ip_policy, is B_FALSE.
1939 			 */
1940 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1941 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1942 			    B_FALSE, recv_ill, zoneid);
1943 		}
1944 		return;
1945 	}
1946 	/* Send out an ICMP packet */
1947 	icmph->icmph_checksum = 0;
1948 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1949 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1950 		ipif_t	*ipif_chosen;
1951 		/*
1952 		 * Make it look like it was directed to us, so we don't look
1953 		 * like a fool with a broadcast or multicast source address.
1954 		 */
1955 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1956 		/*
1957 		 * Make sure that we haven't grabbed an interface that's DOWN.
1958 		 */
1959 		if (ipif != NULL) {
1960 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
1961 			    ipha->ipha_src, zoneid);
1962 			if (ipif_chosen != NULL) {
1963 				ipif_refrele(ipif);
1964 				ipif = ipif_chosen;
1965 			}
1966 		}
1967 		if (ipif == NULL) {
1968 			ip0dbg(("icmp_inbound: "
1969 			    "No source for broadcast/multicast:\n"
1970 			    "\tsrc 0x%x dst 0x%x ill %p "
1971 			    "ipif_lcl_addr 0x%x\n",
1972 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
1973 			    (void *)ill,
1974 			    ill->ill_ipif->ipif_lcl_addr));
1975 			freemsg(first_mp);
1976 			return;
1977 		}
1978 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1979 		ipha->ipha_dst = ipif->ipif_src_addr;
1980 		ipif_refrele(ipif);
1981 	}
1982 	/* Reset time to live. */
1983 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1984 	{
1985 		/* Swap source and destination addresses */
1986 		ipaddr_t tmp;
1987 
1988 		tmp = ipha->ipha_src;
1989 		ipha->ipha_src = ipha->ipha_dst;
1990 		ipha->ipha_dst = tmp;
1991 	}
1992 	ipha->ipha_ident = 0;
1993 	if (!IS_SIMPLE_IPH(ipha))
1994 		icmp_options_update(ipha);
1995 
1996 	/*
1997 	 * ICMP echo replies should go out on the same interface
1998 	 * the request came on as probes used by in.mpathd for detecting
1999 	 * NIC failures are ECHO packets. We turn-off load spreading
2000 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
2001 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
2002 	 * function. This is in turn handled by ip_wput and ip_newroute
2003 	 * to make sure that the packet goes out on the interface it came
2004 	 * in on. If we don't turnoff load spreading, the packets might get
2005 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
2006 	 * to go out and in.mpathd would wrongly detect a failure or
2007 	 * mis-detect a NIC failure for link failure. As load spreading
2008 	 * can happen only if ill_group is not NULL, we do only for
2009 	 * that case and this does not affect the normal case.
2010 	 *
2011 	 * We turn off load spreading only on echo packets that came from
2012 	 * on-link hosts. If the interface route has been deleted, this will
2013 	 * not be enforced as we can't do much. For off-link hosts, as the
2014 	 * default routes in IPv4 does not typically have an ire_ipif
2015 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2016 	 * Moreover, expecting a default route through this interface may
2017 	 * not be correct. We use ipha_dst because of the swap above.
2018 	 */
2019 	onlink = B_FALSE;
2020 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2021 		/*
2022 		 * First, we need to make sure that it is not one of our
2023 		 * local addresses. If we set onlink when it is one of
2024 		 * our local addresses, we will end up creating IRE_CACHES
2025 		 * for one of our local addresses. Then, we will never
2026 		 * accept packets for them afterwards.
2027 		 */
2028 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2029 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2030 		if (src_ire == NULL) {
2031 			ipif = ipif_get_next_ipif(NULL, ill);
2032 			if (ipif == NULL) {
2033 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2034 				freemsg(mp);
2035 				return;
2036 			}
2037 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2038 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2039 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE, ipst);
2040 			ipif_refrele(ipif);
2041 			if (src_ire != NULL) {
2042 				onlink = B_TRUE;
2043 				ire_refrele(src_ire);
2044 			}
2045 		} else {
2046 			ire_refrele(src_ire);
2047 		}
2048 	}
2049 	if (!mctl_present) {
2050 		/*
2051 		 * This packet should go out the same way as it
2052 		 * came in i.e in clear. To make sure that global
2053 		 * policy will not be applied to this in ip_wput_ire,
2054 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2055 		 */
2056 		ASSERT(first_mp == mp);
2057 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2058 		if (first_mp == NULL) {
2059 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2060 			freemsg(mp);
2061 			return;
2062 		}
2063 		ii = (ipsec_in_t *)first_mp->b_rptr;
2064 
2065 		/* This is not a secure packet */
2066 		ii->ipsec_in_secure = B_FALSE;
2067 		if (onlink) {
2068 			ii->ipsec_in_attach_if = B_TRUE;
2069 			ii->ipsec_in_ill_index =
2070 			    ill->ill_phyint->phyint_ifindex;
2071 			ii->ipsec_in_rill_index =
2072 			    recv_ill->ill_phyint->phyint_ifindex;
2073 		}
2074 		first_mp->b_cont = mp;
2075 	} else if (onlink) {
2076 		ii = (ipsec_in_t *)first_mp->b_rptr;
2077 		ii->ipsec_in_attach_if = B_TRUE;
2078 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2079 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2080 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2081 	} else {
2082 		ii = (ipsec_in_t *)first_mp->b_rptr;
2083 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2084 	}
2085 	ii->ipsec_in_zoneid = zoneid;
2086 	ASSERT(zoneid != ALL_ZONES);
2087 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2088 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2089 		return;
2090 	}
2091 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2092 	put(WR(q), first_mp);
2093 }
2094 
2095 static ipaddr_t
2096 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2097 {
2098 	conn_t *connp;
2099 	connf_t *connfp;
2100 	ipaddr_t nexthop_addr = INADDR_ANY;
2101 	int hdr_length = IPH_HDR_LENGTH(ipha);
2102 	uint16_t *up;
2103 	uint32_t ports;
2104 	ip_stack_t *ipst = ill->ill_ipst;
2105 
2106 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2107 	switch (ipha->ipha_protocol) {
2108 		case IPPROTO_TCP:
2109 		{
2110 			tcph_t *tcph;
2111 
2112 			/* do a reverse lookup */
2113 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2114 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2115 			    TCPS_LISTEN, ipst);
2116 			break;
2117 		}
2118 		case IPPROTO_UDP:
2119 		{
2120 			uint32_t dstport, srcport;
2121 
2122 			((uint16_t *)&ports)[0] = up[1];
2123 			((uint16_t *)&ports)[1] = up[0];
2124 
2125 			/* Extract ports in net byte order */
2126 			dstport = htons(ntohl(ports) & 0xFFFF);
2127 			srcport = htons(ntohl(ports) >> 16);
2128 
2129 			connfp = &ipst->ips_ipcl_udp_fanout[
2130 			    IPCL_UDP_HASH(dstport, ipst)];
2131 			mutex_enter(&connfp->connf_lock);
2132 			connp = connfp->connf_head;
2133 
2134 			/* do a reverse lookup */
2135 			while ((connp != NULL) &&
2136 			    (!IPCL_UDP_MATCH(connp, dstport,
2137 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2138 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2139 				connp = connp->conn_next;
2140 			}
2141 			if (connp != NULL)
2142 				CONN_INC_REF(connp);
2143 			mutex_exit(&connfp->connf_lock);
2144 			break;
2145 		}
2146 		case IPPROTO_SCTP:
2147 		{
2148 			in6_addr_t map_src, map_dst;
2149 
2150 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2151 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2152 			((uint16_t *)&ports)[0] = up[1];
2153 			((uint16_t *)&ports)[1] = up[0];
2154 
2155 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2156 			    zoneid, ipst->ips_netstack->netstack_sctp);
2157 			if (connp == NULL) {
2158 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2159 				    zoneid, ports, ipha, ipst);
2160 			} else {
2161 				CONN_INC_REF(connp);
2162 				SCTP_REFRELE(CONN2SCTP(connp));
2163 			}
2164 			break;
2165 		}
2166 		default:
2167 		{
2168 			ipha_t ripha;
2169 
2170 			ripha.ipha_src = ipha->ipha_dst;
2171 			ripha.ipha_dst = ipha->ipha_src;
2172 			ripha.ipha_protocol = ipha->ipha_protocol;
2173 
2174 			connfp = &ipst->ips_ipcl_proto_fanout[
2175 			    ipha->ipha_protocol];
2176 			mutex_enter(&connfp->connf_lock);
2177 			connp = connfp->connf_head;
2178 			for (connp = connfp->connf_head; connp != NULL;
2179 			    connp = connp->conn_next) {
2180 				if (IPCL_PROTO_MATCH(connp,
2181 				    ipha->ipha_protocol, &ripha, ill,
2182 				    0, zoneid)) {
2183 					CONN_INC_REF(connp);
2184 					break;
2185 				}
2186 			}
2187 			mutex_exit(&connfp->connf_lock);
2188 		}
2189 	}
2190 	if (connp != NULL) {
2191 		if (connp->conn_nexthop_set)
2192 			nexthop_addr = connp->conn_nexthop_v4;
2193 		CONN_DEC_REF(connp);
2194 	}
2195 	return (nexthop_addr);
2196 }
2197 
2198 /* Table from RFC 1191 */
2199 static int icmp_frag_size_table[] =
2200 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2201 
2202 /*
2203  * Process received ICMP Packet too big.
2204  * After updating any IRE it does the fanout to any matching transport streams.
2205  * Assumes the message has been pulled up till the IP header that caused
2206  * the error.
2207  *
2208  * Returns B_FALSE on failure and B_TRUE on success.
2209  */
2210 static boolean_t
2211 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2212     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2213     ip_stack_t *ipst)
2214 {
2215 	ire_t	*ire, *first_ire;
2216 	int	mtu;
2217 	int	hdr_length;
2218 	ipaddr_t nexthop_addr;
2219 
2220 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2221 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2222 	ASSERT(ill != NULL);
2223 
2224 	hdr_length = IPH_HDR_LENGTH(ipha);
2225 
2226 	/* Drop if the original packet contained a source route */
2227 	if (ip_source_route_included(ipha)) {
2228 		return (B_FALSE);
2229 	}
2230 	/*
2231 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2232 	 * header.
2233 	 */
2234 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2235 	    mp->b_wptr) {
2236 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2237 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2238 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2239 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2240 			return (B_FALSE);
2241 		}
2242 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2243 		ipha = (ipha_t *)&icmph[1];
2244 	}
2245 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2246 	if (nexthop_addr != INADDR_ANY) {
2247 		/* nexthop set */
2248 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2249 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2250 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2251 	} else {
2252 		/* nexthop not set */
2253 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2254 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2255 	}
2256 
2257 	if (!first_ire) {
2258 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2259 		    ntohl(ipha->ipha_dst)));
2260 		return (B_FALSE);
2261 	}
2262 	/* Check for MTU discovery advice as described in RFC 1191 */
2263 	mtu = ntohs(icmph->icmph_du_mtu);
2264 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2265 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2266 	    ire = ire->ire_next) {
2267 		/*
2268 		 * Look for the connection to which this ICMP message is
2269 		 * directed. If it has the IP_NEXTHOP option set, then the
2270 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2271 		 * option. Else the search is limited to regular IREs.
2272 		 */
2273 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2274 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2275 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2276 		    (nexthop_addr != INADDR_ANY)))
2277 			continue;
2278 
2279 		mutex_enter(&ire->ire_lock);
2280 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2281 			/* Reduce the IRE max frag value as advised. */
2282 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2283 			    mtu, ire->ire_max_frag));
2284 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2285 		} else {
2286 			uint32_t length;
2287 			int	i;
2288 
2289 			/*
2290 			 * Use the table from RFC 1191 to figure out
2291 			 * the next "plateau" based on the length in
2292 			 * the original IP packet.
2293 			 */
2294 			length = ntohs(ipha->ipha_length);
2295 			if (ire->ire_max_frag <= length &&
2296 			    ire->ire_max_frag >= length - hdr_length) {
2297 				/*
2298 				 * Handle broken BSD 4.2 systems that
2299 				 * return the wrong iph_length in ICMP
2300 				 * errors.
2301 				 */
2302 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2303 				    length, ire->ire_max_frag));
2304 				length -= hdr_length;
2305 			}
2306 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2307 				if (length > icmp_frag_size_table[i])
2308 					break;
2309 			}
2310 			if (i == A_CNT(icmp_frag_size_table)) {
2311 				/* Smaller than 68! */
2312 				ip1dbg(("Too big for packet size %d\n",
2313 				    length));
2314 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2315 				ire->ire_frag_flag = 0;
2316 			} else {
2317 				mtu = icmp_frag_size_table[i];
2318 				ip1dbg(("Calculated mtu %d, packet size %d, "
2319 				    "before %d", mtu, length,
2320 				    ire->ire_max_frag));
2321 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2322 				ip1dbg((", after %d\n", ire->ire_max_frag));
2323 			}
2324 			/* Record the new max frag size for the ULP. */
2325 			icmph->icmph_du_zero = 0;
2326 			icmph->icmph_du_mtu =
2327 			    htons((uint16_t)ire->ire_max_frag);
2328 		}
2329 		mutex_exit(&ire->ire_lock);
2330 	}
2331 	rw_exit(&first_ire->ire_bucket->irb_lock);
2332 	ire_refrele(first_ire);
2333 	return (B_TRUE);
2334 }
2335 
2336 /*
2337  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2338  * calls this function.
2339  */
2340 static mblk_t *
2341 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2342 {
2343 	ipha_t *ipha;
2344 	icmph_t *icmph;
2345 	ipha_t *in_ipha;
2346 	int length;
2347 
2348 	ASSERT(mp->b_datap->db_type == M_DATA);
2349 
2350 	/*
2351 	 * For Self-encapsulated packets, we added an extra IP header
2352 	 * without the options. Inner IP header is the one from which
2353 	 * the outer IP header was formed. Thus, we need to remove the
2354 	 * outer IP header. To do this, we pullup the whole message
2355 	 * and overlay whatever follows the outer IP header over the
2356 	 * outer IP header.
2357 	 */
2358 
2359 	if (!pullupmsg(mp, -1))
2360 		return (NULL);
2361 
2362 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2363 	ipha = (ipha_t *)&icmph[1];
2364 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2365 
2366 	/*
2367 	 * The length that we want to overlay is following the inner
2368 	 * IP header. Subtracting the IP header + icmp header + outer
2369 	 * IP header's length should give us the length that we want to
2370 	 * overlay.
2371 	 */
2372 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2373 	    hdr_length;
2374 	/*
2375 	 * Overlay whatever follows the inner header over the
2376 	 * outer header.
2377 	 */
2378 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2379 
2380 	/* Set the wptr to account for the outer header */
2381 	mp->b_wptr -= hdr_length;
2382 	return (mp);
2383 }
2384 
2385 /*
2386  * Try to pass the ICMP message upstream in case the ULP cares.
2387  *
2388  * If the packet that caused the ICMP error is secure, we send
2389  * it to AH/ESP to make sure that the attached packet has a
2390  * valid association. ipha in the code below points to the
2391  * IP header of the packet that caused the error.
2392  *
2393  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2394  * in the context of IPsec. Normally we tell the upper layer
2395  * whenever we send the ire (including ip_bind), the IPsec header
2396  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2397  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2398  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2399  * same thing. As TCP has the IPsec options size that needs to be
2400  * adjusted, we just pass the MTU unchanged.
2401  *
2402  * IFN could have been generated locally or by some router.
2403  *
2404  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2405  *	    This happens because IP adjusted its value of MTU on an
2406  *	    earlier IFN message and could not tell the upper layer,
2407  *	    the new adjusted value of MTU e.g. Packet was encrypted
2408  *	    or there was not enough information to fanout to upper
2409  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2410  *	    generates the IFN, where IPsec processing has *not* been
2411  *	    done.
2412  *
2413  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2414  *	    could have generated this. This happens because ire_max_frag
2415  *	    value in IP was set to a new value, while the IPsec processing
2416  *	    was being done and after we made the fragmentation check in
2417  *	    ip_wput_ire. Thus on return from IPsec processing,
2418  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2419  *	    and generates the IFN. As IPsec processing is over, we fanout
2420  *	    to AH/ESP to remove the header.
2421  *
2422  *	    In both these cases, ipsec_in_loopback will be set indicating
2423  *	    that IFN was generated locally.
2424  *
2425  * ROUTER : IFN could be secure or non-secure.
2426  *
2427  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2428  *	      packet in error has AH/ESP headers to validate the AH/ESP
2429  *	      headers. AH/ESP will verify whether there is a valid SA or
2430  *	      not and send it back. We will fanout again if we have more
2431  *	      data in the packet.
2432  *
2433  *	      If the packet in error does not have AH/ESP, we handle it
2434  *	      like any other case.
2435  *
2436  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2437  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2438  *	      for validation. AH/ESP will verify whether there is a
2439  *	      valid SA or not and send it back. We will fanout again if
2440  *	      we have more data in the packet.
2441  *
2442  *	      If the packet in error does not have AH/ESP, we handle it
2443  *	      like any other case.
2444  */
2445 static void
2446 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2447     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2448     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2449     zoneid_t zoneid)
2450 {
2451 	uint16_t *up;	/* Pointer to ports in ULP header */
2452 	uint32_t ports;	/* reversed ports for fanout */
2453 	ipha_t ripha;	/* With reversed addresses */
2454 	mblk_t *first_mp;
2455 	ipsec_in_t *ii;
2456 	tcph_t	*tcph;
2457 	conn_t	*connp;
2458 	ip_stack_t *ipst;
2459 
2460 	ASSERT(ill != NULL);
2461 
2462 	ASSERT(recv_ill != NULL);
2463 	ipst = recv_ill->ill_ipst;
2464 
2465 	first_mp = mp;
2466 	if (mctl_present) {
2467 		mp = first_mp->b_cont;
2468 		ASSERT(mp != NULL);
2469 
2470 		ii = (ipsec_in_t *)first_mp->b_rptr;
2471 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2472 	} else {
2473 		ii = NULL;
2474 	}
2475 
2476 	switch (ipha->ipha_protocol) {
2477 	case IPPROTO_UDP:
2478 		/*
2479 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2480 		 * transport header.
2481 		 */
2482 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2483 		    mp->b_wptr) {
2484 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2485 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2486 				goto discard_pkt;
2487 			}
2488 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2489 			ipha = (ipha_t *)&icmph[1];
2490 		}
2491 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2492 
2493 		/*
2494 		 * Attempt to find a client stream based on port.
2495 		 * Note that we do a reverse lookup since the header is
2496 		 * in the form we sent it out.
2497 		 * The ripha header is only used for the IP_UDP_MATCH and we
2498 		 * only set the src and dst addresses and protocol.
2499 		 */
2500 		ripha.ipha_src = ipha->ipha_dst;
2501 		ripha.ipha_dst = ipha->ipha_src;
2502 		ripha.ipha_protocol = ipha->ipha_protocol;
2503 		((uint16_t *)&ports)[0] = up[1];
2504 		((uint16_t *)&ports)[1] = up[0];
2505 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2506 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2507 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2508 		    icmph->icmph_type, icmph->icmph_code));
2509 
2510 		/* Have to change db_type after any pullupmsg */
2511 		DB_TYPE(mp) = M_CTL;
2512 
2513 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2514 		    mctl_present, ip_policy, recv_ill, zoneid);
2515 		return;
2516 
2517 	case IPPROTO_TCP:
2518 		/*
2519 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2520 		 * transport header.
2521 		 */
2522 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2523 		    mp->b_wptr) {
2524 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2525 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2526 				goto discard_pkt;
2527 			}
2528 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2529 			ipha = (ipha_t *)&icmph[1];
2530 		}
2531 		/*
2532 		 * Find a TCP client stream for this packet.
2533 		 * Note that we do a reverse lookup since the header is
2534 		 * in the form we sent it out.
2535 		 */
2536 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2537 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2538 		    ipst);
2539 		if (connp == NULL)
2540 			goto discard_pkt;
2541 
2542 		/* Have to change db_type after any pullupmsg */
2543 		DB_TYPE(mp) = M_CTL;
2544 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2545 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2546 		return;
2547 
2548 	case IPPROTO_SCTP:
2549 		/*
2550 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2551 		 * transport header.
2552 		 */
2553 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2554 		    mp->b_wptr) {
2555 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2556 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2557 				goto discard_pkt;
2558 			}
2559 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2560 			ipha = (ipha_t *)&icmph[1];
2561 		}
2562 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2563 		/*
2564 		 * Find a SCTP client stream for this packet.
2565 		 * Note that we do a reverse lookup since the header is
2566 		 * in the form we sent it out.
2567 		 * The ripha header is only used for the matching and we
2568 		 * only set the src and dst addresses, protocol, and version.
2569 		 */
2570 		ripha.ipha_src = ipha->ipha_dst;
2571 		ripha.ipha_dst = ipha->ipha_src;
2572 		ripha.ipha_protocol = ipha->ipha_protocol;
2573 		ripha.ipha_version_and_hdr_length =
2574 		    ipha->ipha_version_and_hdr_length;
2575 		((uint16_t *)&ports)[0] = up[1];
2576 		((uint16_t *)&ports)[1] = up[0];
2577 
2578 		/* Have to change db_type after any pullupmsg */
2579 		DB_TYPE(mp) = M_CTL;
2580 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2581 		    mctl_present, ip_policy, zoneid);
2582 		return;
2583 
2584 	case IPPROTO_ESP:
2585 	case IPPROTO_AH: {
2586 		int ipsec_rc;
2587 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2588 
2589 		/*
2590 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2591 		 * We will re-use the IPSEC_IN if it is already present as
2592 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2593 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2594 		 * one and attach it in the front.
2595 		 */
2596 		if (ii != NULL) {
2597 			/*
2598 			 * ip_fanout_proto_again converts the ICMP errors
2599 			 * that come back from AH/ESP to M_DATA so that
2600 			 * if it is non-AH/ESP and we do a pullupmsg in
2601 			 * this function, it would work. Convert it back
2602 			 * to M_CTL before we send up as this is a ICMP
2603 			 * error. This could have been generated locally or
2604 			 * by some router. Validate the inner IPsec
2605 			 * headers.
2606 			 *
2607 			 * NOTE : ill_index is used by ip_fanout_proto_again
2608 			 * to locate the ill.
2609 			 */
2610 			ASSERT(ill != NULL);
2611 			ii->ipsec_in_ill_index =
2612 			    ill->ill_phyint->phyint_ifindex;
2613 			ii->ipsec_in_rill_index =
2614 			    recv_ill->ill_phyint->phyint_ifindex;
2615 			DB_TYPE(first_mp->b_cont) = M_CTL;
2616 		} else {
2617 			/*
2618 			 * IPSEC_IN is not present. We attach a ipsec_in
2619 			 * message and send up to IPsec for validating
2620 			 * and removing the IPsec headers. Clear
2621 			 * ipsec_in_secure so that when we return
2622 			 * from IPsec, we don't mistakenly think that this
2623 			 * is a secure packet came from the network.
2624 			 *
2625 			 * NOTE : ill_index is used by ip_fanout_proto_again
2626 			 * to locate the ill.
2627 			 */
2628 			ASSERT(first_mp == mp);
2629 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2630 			if (first_mp == NULL) {
2631 				freemsg(mp);
2632 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2633 				return;
2634 			}
2635 			ii = (ipsec_in_t *)first_mp->b_rptr;
2636 
2637 			/* This is not a secure packet */
2638 			ii->ipsec_in_secure = B_FALSE;
2639 			first_mp->b_cont = mp;
2640 			DB_TYPE(mp) = M_CTL;
2641 			ASSERT(ill != NULL);
2642 			ii->ipsec_in_ill_index =
2643 			    ill->ill_phyint->phyint_ifindex;
2644 			ii->ipsec_in_rill_index =
2645 			    recv_ill->ill_phyint->phyint_ifindex;
2646 		}
2647 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2648 
2649 		if (!ipsec_loaded(ipss)) {
2650 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2651 			return;
2652 		}
2653 
2654 		if (ipha->ipha_protocol == IPPROTO_ESP)
2655 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2656 		else
2657 			ipsec_rc = ipsecah_icmp_error(first_mp);
2658 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2659 			return;
2660 
2661 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2662 		return;
2663 	}
2664 	default:
2665 		/*
2666 		 * The ripha header is only used for the lookup and we
2667 		 * only set the src and dst addresses and protocol.
2668 		 */
2669 		ripha.ipha_src = ipha->ipha_dst;
2670 		ripha.ipha_dst = ipha->ipha_src;
2671 		ripha.ipha_protocol = ipha->ipha_protocol;
2672 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2673 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2674 		    ntohl(ipha->ipha_dst),
2675 		    icmph->icmph_type, icmph->icmph_code));
2676 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2677 			ipha_t *in_ipha;
2678 
2679 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2680 			    mp->b_wptr) {
2681 				if (!pullupmsg(mp, (uchar_t *)ipha +
2682 				    hdr_length + sizeof (ipha_t) -
2683 				    mp->b_rptr)) {
2684 					goto discard_pkt;
2685 				}
2686 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2687 				ipha = (ipha_t *)&icmph[1];
2688 			}
2689 			/*
2690 			 * Caller has verified that length has to be
2691 			 * at least the size of IP header.
2692 			 */
2693 			ASSERT(hdr_length >= sizeof (ipha_t));
2694 			/*
2695 			 * Check the sanity of the inner IP header like
2696 			 * we did for the outer header.
2697 			 */
2698 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2699 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2700 				goto discard_pkt;
2701 			}
2702 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2703 				goto discard_pkt;
2704 			}
2705 			/* Check for Self-encapsulated tunnels */
2706 			if (in_ipha->ipha_src == ipha->ipha_src &&
2707 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2708 
2709 				mp = icmp_inbound_self_encap_error(mp,
2710 				    iph_hdr_length, hdr_length);
2711 				if (mp == NULL)
2712 					goto discard_pkt;
2713 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2714 				ipha = (ipha_t *)&icmph[1];
2715 				hdr_length = IPH_HDR_LENGTH(ipha);
2716 				/*
2717 				 * The packet in error is self-encapsualted.
2718 				 * And we are finding it further encapsulated
2719 				 * which we could not have possibly generated.
2720 				 */
2721 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2722 					goto discard_pkt;
2723 				}
2724 				icmp_inbound_error_fanout(q, ill, first_mp,
2725 				    icmph, ipha, iph_hdr_length, hdr_length,
2726 				    mctl_present, ip_policy, recv_ill, zoneid);
2727 				return;
2728 			}
2729 		}
2730 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2731 		    ipha->ipha_protocol == IPPROTO_IPV6) &&
2732 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2733 		    ii != NULL &&
2734 		    ii->ipsec_in_loopback &&
2735 		    ii->ipsec_in_secure) {
2736 			/*
2737 			 * For IP tunnels that get a looped-back
2738 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2739 			 * reported new MTU to take into account the IPsec
2740 			 * headers protecting this configured tunnel.
2741 			 *
2742 			 * This allows the tunnel module (tun.c) to blindly
2743 			 * accept the MTU reported in an ICMP "too big"
2744 			 * message.
2745 			 *
2746 			 * Non-looped back ICMP messages will just be
2747 			 * handled by the security protocols (if needed),
2748 			 * and the first subsequent packet will hit this
2749 			 * path.
2750 			 */
2751 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2752 			    ipsec_in_extra_length(first_mp));
2753 		}
2754 		/* Have to change db_type after any pullupmsg */
2755 		DB_TYPE(mp) = M_CTL;
2756 
2757 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2758 		    ip_policy, recv_ill, zoneid);
2759 		return;
2760 	}
2761 	/* NOTREACHED */
2762 discard_pkt:
2763 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2764 drop_pkt:;
2765 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2766 	freemsg(first_mp);
2767 }
2768 
2769 /*
2770  * Common IP options parser.
2771  *
2772  * Setup routine: fill in *optp with options-parsing state, then
2773  * tail-call ipoptp_next to return the first option.
2774  */
2775 uint8_t
2776 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2777 {
2778 	uint32_t totallen; /* total length of all options */
2779 
2780 	totallen = ipha->ipha_version_and_hdr_length -
2781 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2782 	totallen <<= 2;
2783 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2784 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2785 	optp->ipoptp_flags = 0;
2786 	return (ipoptp_next(optp));
2787 }
2788 
2789 /*
2790  * Common IP options parser: extract next option.
2791  */
2792 uint8_t
2793 ipoptp_next(ipoptp_t *optp)
2794 {
2795 	uint8_t *end = optp->ipoptp_end;
2796 	uint8_t *cur = optp->ipoptp_next;
2797 	uint8_t opt, len, pointer;
2798 
2799 	/*
2800 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2801 	 * has been corrupted.
2802 	 */
2803 	ASSERT(cur <= end);
2804 
2805 	if (cur == end)
2806 		return (IPOPT_EOL);
2807 
2808 	opt = cur[IPOPT_OPTVAL];
2809 
2810 	/*
2811 	 * Skip any NOP options.
2812 	 */
2813 	while (opt == IPOPT_NOP) {
2814 		cur++;
2815 		if (cur == end)
2816 			return (IPOPT_EOL);
2817 		opt = cur[IPOPT_OPTVAL];
2818 	}
2819 
2820 	if (opt == IPOPT_EOL)
2821 		return (IPOPT_EOL);
2822 
2823 	/*
2824 	 * Option requiring a length.
2825 	 */
2826 	if ((cur + 1) >= end) {
2827 		optp->ipoptp_flags |= IPOPTP_ERROR;
2828 		return (IPOPT_EOL);
2829 	}
2830 	len = cur[IPOPT_OLEN];
2831 	if (len < 2) {
2832 		optp->ipoptp_flags |= IPOPTP_ERROR;
2833 		return (IPOPT_EOL);
2834 	}
2835 	optp->ipoptp_cur = cur;
2836 	optp->ipoptp_len = len;
2837 	optp->ipoptp_next = cur + len;
2838 	if (cur + len > end) {
2839 		optp->ipoptp_flags |= IPOPTP_ERROR;
2840 		return (IPOPT_EOL);
2841 	}
2842 
2843 	/*
2844 	 * For the options which require a pointer field, make sure
2845 	 * its there, and make sure it points to either something
2846 	 * inside this option, or the end of the option.
2847 	 */
2848 	switch (opt) {
2849 	case IPOPT_RR:
2850 	case IPOPT_TS:
2851 	case IPOPT_LSRR:
2852 	case IPOPT_SSRR:
2853 		if (len <= IPOPT_OFFSET) {
2854 			optp->ipoptp_flags |= IPOPTP_ERROR;
2855 			return (opt);
2856 		}
2857 		pointer = cur[IPOPT_OFFSET];
2858 		if (pointer - 1 > len) {
2859 			optp->ipoptp_flags |= IPOPTP_ERROR;
2860 			return (opt);
2861 		}
2862 		break;
2863 	}
2864 
2865 	/*
2866 	 * Sanity check the pointer field based on the type of the
2867 	 * option.
2868 	 */
2869 	switch (opt) {
2870 	case IPOPT_RR:
2871 	case IPOPT_SSRR:
2872 	case IPOPT_LSRR:
2873 		if (pointer < IPOPT_MINOFF_SR)
2874 			optp->ipoptp_flags |= IPOPTP_ERROR;
2875 		break;
2876 	case IPOPT_TS:
2877 		if (pointer < IPOPT_MINOFF_IT)
2878 			optp->ipoptp_flags |= IPOPTP_ERROR;
2879 		/*
2880 		 * Note that the Internet Timestamp option also
2881 		 * contains two four bit fields (the Overflow field,
2882 		 * and the Flag field), which follow the pointer
2883 		 * field.  We don't need to check that these fields
2884 		 * fall within the length of the option because this
2885 		 * was implicitely done above.  We've checked that the
2886 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2887 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2888 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2889 		 */
2890 		ASSERT(len > IPOPT_POS_OV_FLG);
2891 		break;
2892 	}
2893 
2894 	return (opt);
2895 }
2896 
2897 /*
2898  * Use the outgoing IP header to create an IP_OPTIONS option the way
2899  * it was passed down from the application.
2900  */
2901 int
2902 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2903 {
2904 	ipoptp_t	opts;
2905 	const uchar_t	*opt;
2906 	uint8_t		optval;
2907 	uint8_t		optlen;
2908 	uint32_t	len = 0;
2909 	uchar_t	*buf1 = buf;
2910 
2911 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2912 	len += IP_ADDR_LEN;
2913 	bzero(buf1, IP_ADDR_LEN);
2914 
2915 	/*
2916 	 * OK to cast away const here, as we don't store through the returned
2917 	 * opts.ipoptp_cur pointer.
2918 	 */
2919 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2920 	    optval != IPOPT_EOL;
2921 	    optval = ipoptp_next(&opts)) {
2922 		int	off;
2923 
2924 		opt = opts.ipoptp_cur;
2925 		optlen = opts.ipoptp_len;
2926 		switch (optval) {
2927 		case IPOPT_SSRR:
2928 		case IPOPT_LSRR:
2929 
2930 			/*
2931 			 * Insert ipha_dst as the first entry in the source
2932 			 * route and move down the entries on step.
2933 			 * The last entry gets placed at buf1.
2934 			 */
2935 			buf[IPOPT_OPTVAL] = optval;
2936 			buf[IPOPT_OLEN] = optlen;
2937 			buf[IPOPT_OFFSET] = optlen;
2938 
2939 			off = optlen - IP_ADDR_LEN;
2940 			if (off < 0) {
2941 				/* No entries in source route */
2942 				break;
2943 			}
2944 			/* Last entry in source route */
2945 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2946 			off -= IP_ADDR_LEN;
2947 
2948 			while (off > 0) {
2949 				bcopy(opt + off,
2950 				    buf + off + IP_ADDR_LEN,
2951 				    IP_ADDR_LEN);
2952 				off -= IP_ADDR_LEN;
2953 			}
2954 			/* ipha_dst into first slot */
2955 			bcopy(&ipha->ipha_dst,
2956 			    buf + off + IP_ADDR_LEN,
2957 			    IP_ADDR_LEN);
2958 			buf += optlen;
2959 			len += optlen;
2960 			break;
2961 
2962 		case IPOPT_COMSEC:
2963 		case IPOPT_SECURITY:
2964 			/* if passing up a label is not ok, then remove */
2965 			if (is_system_labeled())
2966 				break;
2967 			/* FALLTHROUGH */
2968 		default:
2969 			bcopy(opt, buf, optlen);
2970 			buf += optlen;
2971 			len += optlen;
2972 			break;
2973 		}
2974 	}
2975 done:
2976 	/* Pad the resulting options */
2977 	while (len & 0x3) {
2978 		*buf++ = IPOPT_EOL;
2979 		len++;
2980 	}
2981 	return (len);
2982 }
2983 
2984 /*
2985  * Update any record route or timestamp options to include this host.
2986  * Reverse any source route option.
2987  * This routine assumes that the options are well formed i.e. that they
2988  * have already been checked.
2989  */
2990 static void
2991 icmp_options_update(ipha_t *ipha)
2992 {
2993 	ipoptp_t	opts;
2994 	uchar_t		*opt;
2995 	uint8_t		optval;
2996 	ipaddr_t	src;		/* Our local address */
2997 	ipaddr_t	dst;
2998 
2999 	ip2dbg(("icmp_options_update\n"));
3000 	src = ipha->ipha_src;
3001 	dst = ipha->ipha_dst;
3002 
3003 	for (optval = ipoptp_first(&opts, ipha);
3004 	    optval != IPOPT_EOL;
3005 	    optval = ipoptp_next(&opts)) {
3006 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
3007 		opt = opts.ipoptp_cur;
3008 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
3009 		    optval, opts.ipoptp_len));
3010 		switch (optval) {
3011 			int off1, off2;
3012 		case IPOPT_SSRR:
3013 		case IPOPT_LSRR:
3014 			/*
3015 			 * Reverse the source route.  The first entry
3016 			 * should be the next to last one in the current
3017 			 * source route (the last entry is our address).
3018 			 * The last entry should be the final destination.
3019 			 */
3020 			off1 = IPOPT_MINOFF_SR - 1;
3021 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3022 			if (off2 < 0) {
3023 				/* No entries in source route */
3024 				ip1dbg((
3025 				    "icmp_options_update: bad src route\n"));
3026 				break;
3027 			}
3028 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3029 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3030 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3031 			off2 -= IP_ADDR_LEN;
3032 
3033 			while (off1 < off2) {
3034 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3035 				bcopy((char *)opt + off2, (char *)opt + off1,
3036 				    IP_ADDR_LEN);
3037 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3038 				off1 += IP_ADDR_LEN;
3039 				off2 -= IP_ADDR_LEN;
3040 			}
3041 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3042 			break;
3043 		}
3044 	}
3045 }
3046 
3047 /*
3048  * Process received ICMP Redirect messages.
3049  */
3050 static void
3051 icmp_redirect(ill_t *ill, mblk_t *mp)
3052 {
3053 	ipha_t	*ipha;
3054 	int	iph_hdr_length;
3055 	icmph_t	*icmph;
3056 	ipha_t	*ipha_err;
3057 	ire_t	*ire;
3058 	ire_t	*prev_ire;
3059 	ire_t	*save_ire;
3060 	ipaddr_t  src, dst, gateway;
3061 	iulp_t	ulp_info = { 0 };
3062 	int	error;
3063 	ip_stack_t *ipst;
3064 
3065 	ASSERT(ill != NULL);
3066 	ipst = ill->ill_ipst;
3067 
3068 	ipha = (ipha_t *)mp->b_rptr;
3069 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3070 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3071 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3072 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3073 		freemsg(mp);
3074 		return;
3075 	}
3076 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3077 	ipha_err = (ipha_t *)&icmph[1];
3078 	src = ipha->ipha_src;
3079 	dst = ipha_err->ipha_dst;
3080 	gateway = icmph->icmph_rd_gateway;
3081 	/* Make sure the new gateway is reachable somehow. */
3082 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3083 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3084 	/*
3085 	 * Make sure we had a route for the dest in question and that
3086 	 * that route was pointing to the old gateway (the source of the
3087 	 * redirect packet.)
3088 	 */
3089 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3090 	    NULL, MATCH_IRE_GW, ipst);
3091 	/*
3092 	 * Check that
3093 	 *	the redirect was not from ourselves
3094 	 *	the new gateway and the old gateway are directly reachable
3095 	 */
3096 	if (!prev_ire ||
3097 	    !ire ||
3098 	    ire->ire_type == IRE_LOCAL) {
3099 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3100 		freemsg(mp);
3101 		if (ire != NULL)
3102 			ire_refrele(ire);
3103 		if (prev_ire != NULL)
3104 			ire_refrele(prev_ire);
3105 		return;
3106 	}
3107 
3108 	/*
3109 	 * Should we use the old ULP info to create the new gateway?  From
3110 	 * a user's perspective, we should inherit the info so that it
3111 	 * is a "smooth" transition.  If we do not do that, then new
3112 	 * connections going thru the new gateway will have no route metrics,
3113 	 * which is counter-intuitive to user.  From a network point of
3114 	 * view, this may or may not make sense even though the new gateway
3115 	 * is still directly connected to us so the route metrics should not
3116 	 * change much.
3117 	 *
3118 	 * But if the old ire_uinfo is not initialized, we do another
3119 	 * recursive lookup on the dest using the new gateway.  There may
3120 	 * be a route to that.  If so, use it to initialize the redirect
3121 	 * route.
3122 	 */
3123 	if (prev_ire->ire_uinfo.iulp_set) {
3124 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3125 	} else {
3126 		ire_t *tmp_ire;
3127 		ire_t *sire;
3128 
3129 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3130 		    ALL_ZONES, 0, NULL,
3131 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3132 		    ipst);
3133 		if (sire != NULL) {
3134 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3135 			/*
3136 			 * If sire != NULL, ire_ftable_lookup() should not
3137 			 * return a NULL value.
3138 			 */
3139 			ASSERT(tmp_ire != NULL);
3140 			ire_refrele(tmp_ire);
3141 			ire_refrele(sire);
3142 		} else if (tmp_ire != NULL) {
3143 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3144 			    sizeof (iulp_t));
3145 			ire_refrele(tmp_ire);
3146 		}
3147 	}
3148 	if (prev_ire->ire_type == IRE_CACHE)
3149 		ire_delete(prev_ire);
3150 	ire_refrele(prev_ire);
3151 	/*
3152 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3153 	 * require TOS routing
3154 	 */
3155 	switch (icmph->icmph_code) {
3156 	case 0:
3157 	case 1:
3158 		/* TODO: TOS specificity for cases 2 and 3 */
3159 	case 2:
3160 	case 3:
3161 		break;
3162 	default:
3163 		freemsg(mp);
3164 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3165 		ire_refrele(ire);
3166 		return;
3167 	}
3168 	/*
3169 	 * Create a Route Association.  This will allow us to remember that
3170 	 * someone we believe told us to use the particular gateway.
3171 	 */
3172 	save_ire = ire;
3173 	ire = ire_create(
3174 	    (uchar_t *)&dst,			/* dest addr */
3175 	    (uchar_t *)&ip_g_all_ones,		/* mask */
3176 	    (uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3177 	    (uchar_t *)&gateway,		/* gateway addr */
3178 	    &save_ire->ire_max_frag,		/* max frag */
3179 	    NULL,				/* no src nce */
3180 	    NULL,				/* no rfq */
3181 	    NULL,				/* no stq */
3182 	    IRE_HOST,
3183 	    NULL,				/* ipif */
3184 	    0,					/* cmask */
3185 	    0,					/* phandle */
3186 	    0,					/* ihandle */
3187 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3188 	    &ulp_info,
3189 	    NULL,				/* tsol_gc_t */
3190 	    NULL,				/* gcgrp */
3191 	    ipst);
3192 
3193 	if (ire == NULL) {
3194 		freemsg(mp);
3195 		ire_refrele(save_ire);
3196 		return;
3197 	}
3198 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3199 	ire_refrele(save_ire);
3200 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3201 
3202 	if (error == 0) {
3203 		ire_refrele(ire);		/* Held in ire_add_v4 */
3204 		/* tell routing sockets that we received a redirect */
3205 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3206 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3207 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3208 	}
3209 
3210 	/*
3211 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3212 	 * This together with the added IRE has the effect of
3213 	 * modifying an existing redirect.
3214 	 */
3215 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3216 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3217 	if (prev_ire != NULL) {
3218 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3219 			ire_delete(prev_ire);
3220 		ire_refrele(prev_ire);
3221 	}
3222 
3223 	freemsg(mp);
3224 }
3225 
3226 /*
3227  * Generate an ICMP parameter problem message.
3228  */
3229 static void
3230 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3231 	ip_stack_t *ipst)
3232 {
3233 	icmph_t	icmph;
3234 	boolean_t mctl_present;
3235 	mblk_t *first_mp;
3236 
3237 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3238 
3239 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3240 		if (mctl_present)
3241 			freeb(first_mp);
3242 		return;
3243 	}
3244 
3245 	bzero(&icmph, sizeof (icmph_t));
3246 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3247 	icmph.icmph_pp_ptr = ptr;
3248 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3249 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3250 	    ipst);
3251 }
3252 
3253 /*
3254  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3255  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3256  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3257  * an icmp error packet can be sent.
3258  * Assigns an appropriate source address to the packet. If ipha_dst is
3259  * one of our addresses use it for source. Otherwise pick a source based
3260  * on a route lookup back to ipha_src.
3261  * Note that ipha_src must be set here since the
3262  * packet is likely to arrive on an ill queue in ip_wput() which will
3263  * not set a source address.
3264  */
3265 static void
3266 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3267     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3268 {
3269 	ipaddr_t dst;
3270 	icmph_t	*icmph;
3271 	ipha_t	*ipha;
3272 	uint_t	len_needed;
3273 	size_t	msg_len;
3274 	mblk_t	*mp1;
3275 	ipaddr_t src;
3276 	ire_t	*ire;
3277 	mblk_t *ipsec_mp;
3278 	ipsec_out_t	*io = NULL;
3279 
3280 	if (mctl_present) {
3281 		/*
3282 		 * If it is :
3283 		 *
3284 		 * 1) a IPSEC_OUT, then this is caused by outbound
3285 		 *    datagram originating on this host. IPsec processing
3286 		 *    may or may not have been done. Refer to comments above
3287 		 *    icmp_inbound_error_fanout for details.
3288 		 *
3289 		 * 2) a IPSEC_IN if we are generating a icmp_message
3290 		 *    for an incoming datagram destined for us i.e called
3291 		 *    from ip_fanout_send_icmp.
3292 		 */
3293 		ipsec_info_t *in;
3294 		ipsec_mp = mp;
3295 		mp = ipsec_mp->b_cont;
3296 
3297 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3298 		ipha = (ipha_t *)mp->b_rptr;
3299 
3300 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3301 		    in->ipsec_info_type == IPSEC_IN);
3302 
3303 		if (in->ipsec_info_type == IPSEC_IN) {
3304 			/*
3305 			 * Convert the IPSEC_IN to IPSEC_OUT.
3306 			 */
3307 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3308 				BUMP_MIB(&ipst->ips_ip_mib,
3309 				    ipIfStatsOutDiscards);
3310 				return;
3311 			}
3312 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3313 		} else {
3314 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3315 			io = (ipsec_out_t *)in;
3316 			/*
3317 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3318 			 * ire lookup.
3319 			 */
3320 			io->ipsec_out_proc_begin = B_FALSE;
3321 		}
3322 		ASSERT(zoneid == io->ipsec_out_zoneid);
3323 		ASSERT(zoneid != ALL_ZONES);
3324 	} else {
3325 		/*
3326 		 * This is in clear. The icmp message we are building
3327 		 * here should go out in clear.
3328 		 *
3329 		 * Pardon the convolution of it all, but it's easier to
3330 		 * allocate a "use cleartext" IPSEC_IN message and convert
3331 		 * it than it is to allocate a new one.
3332 		 */
3333 		ipsec_in_t *ii;
3334 		ASSERT(DB_TYPE(mp) == M_DATA);
3335 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3336 		if (ipsec_mp == NULL) {
3337 			freemsg(mp);
3338 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3339 			return;
3340 		}
3341 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3342 
3343 		/* This is not a secure packet */
3344 		ii->ipsec_in_secure = B_FALSE;
3345 		/*
3346 		 * For trusted extensions using a shared IP address we can
3347 		 * send using any zoneid.
3348 		 */
3349 		if (zoneid == ALL_ZONES)
3350 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3351 		else
3352 			ii->ipsec_in_zoneid = zoneid;
3353 		ipsec_mp->b_cont = mp;
3354 		ipha = (ipha_t *)mp->b_rptr;
3355 		/*
3356 		 * Convert the IPSEC_IN to IPSEC_OUT.
3357 		 */
3358 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3359 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3360 			return;
3361 		}
3362 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3363 	}
3364 
3365 	/* Remember our eventual destination */
3366 	dst = ipha->ipha_src;
3367 
3368 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3369 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3370 	if (ire != NULL &&
3371 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3372 		src = ipha->ipha_dst;
3373 	} else {
3374 		if (ire != NULL)
3375 			ire_refrele(ire);
3376 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3377 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3378 		    ipst);
3379 		if (ire == NULL) {
3380 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3381 			freemsg(ipsec_mp);
3382 			return;
3383 		}
3384 		src = ire->ire_src_addr;
3385 	}
3386 
3387 	if (ire != NULL)
3388 		ire_refrele(ire);
3389 
3390 	/*
3391 	 * Check if we can send back more then 8 bytes in addition to
3392 	 * the IP header.  We try to send 64 bytes of data and the internal
3393 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3394 	 */
3395 	len_needed = IPH_HDR_LENGTH(ipha);
3396 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3397 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3398 
3399 		if (!pullupmsg(mp, -1)) {
3400 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3401 			freemsg(ipsec_mp);
3402 			return;
3403 		}
3404 		ipha = (ipha_t *)mp->b_rptr;
3405 
3406 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3407 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3408 			    len_needed));
3409 		} else {
3410 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3411 
3412 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3413 			len_needed += ip_hdr_length_v6(mp, ip6h);
3414 		}
3415 	}
3416 	len_needed += ipst->ips_ip_icmp_return;
3417 	msg_len = msgdsize(mp);
3418 	if (msg_len > len_needed) {
3419 		(void) adjmsg(mp, len_needed - msg_len);
3420 		msg_len = len_needed;
3421 	}
3422 	mp1 = allocb_tmpl(sizeof (icmp_ipha) + len, mp);
3423 	if (mp1 == NULL) {
3424 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3425 		freemsg(ipsec_mp);
3426 		return;
3427 	}
3428 	mp1->b_cont = mp;
3429 	mp = mp1;
3430 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3431 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3432 	    io->ipsec_out_type == IPSEC_OUT);
3433 	ipsec_mp->b_cont = mp;
3434 
3435 	/*
3436 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3437 	 * node generates be accepted in peace by all on-host destinations.
3438 	 * If we do NOT assume that all on-host destinations trust
3439 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3440 	 * (Look for ipsec_out_icmp_loopback).
3441 	 */
3442 	io->ipsec_out_icmp_loopback = B_TRUE;
3443 
3444 	ipha = (ipha_t *)mp->b_rptr;
3445 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3446 	*ipha = icmp_ipha;
3447 	ipha->ipha_src = src;
3448 	ipha->ipha_dst = dst;
3449 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3450 	msg_len += sizeof (icmp_ipha) + len;
3451 	if (msg_len > IP_MAXPACKET) {
3452 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3453 		msg_len = IP_MAXPACKET;
3454 	}
3455 	ipha->ipha_length = htons((uint16_t)msg_len);
3456 	icmph = (icmph_t *)&ipha[1];
3457 	bcopy(stuff, icmph, len);
3458 	icmph->icmph_checksum = 0;
3459 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3460 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3461 	put(q, ipsec_mp);
3462 }
3463 
3464 /*
3465  * Determine if an ICMP error packet can be sent given the rate limit.
3466  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3467  * in milliseconds) and a burst size. Burst size number of packets can
3468  * be sent arbitrarely closely spaced.
3469  * The state is tracked using two variables to implement an approximate
3470  * token bucket filter:
3471  *	icmp_pkt_err_last - lbolt value when the last burst started
3472  *	icmp_pkt_err_sent - number of packets sent in current burst
3473  */
3474 boolean_t
3475 icmp_err_rate_limit(ip_stack_t *ipst)
3476 {
3477 	clock_t now = TICK_TO_MSEC(lbolt);
3478 	uint_t refilled; /* Number of packets refilled in tbf since last */
3479 	/* Guard against changes by loading into local variable */
3480 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3481 
3482 	if (err_interval == 0)
3483 		return (B_FALSE);
3484 
3485 	if (ipst->ips_icmp_pkt_err_last > now) {
3486 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3487 		ipst->ips_icmp_pkt_err_last = 0;
3488 		ipst->ips_icmp_pkt_err_sent = 0;
3489 	}
3490 	/*
3491 	 * If we are in a burst update the token bucket filter.
3492 	 * Update the "last" time to be close to "now" but make sure
3493 	 * we don't loose precision.
3494 	 */
3495 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3496 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3497 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3498 			ipst->ips_icmp_pkt_err_sent = 0;
3499 		} else {
3500 			ipst->ips_icmp_pkt_err_sent -= refilled;
3501 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3502 		}
3503 	}
3504 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3505 		/* Start of new burst */
3506 		ipst->ips_icmp_pkt_err_last = now;
3507 	}
3508 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3509 		ipst->ips_icmp_pkt_err_sent++;
3510 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3511 		    ipst->ips_icmp_pkt_err_sent));
3512 		return (B_FALSE);
3513 	}
3514 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3515 	return (B_TRUE);
3516 }
3517 
3518 /*
3519  * Check if it is ok to send an IPv4 ICMP error packet in
3520  * response to the IPv4 packet in mp.
3521  * Free the message and return null if no
3522  * ICMP error packet should be sent.
3523  */
3524 static mblk_t *
3525 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3526 {
3527 	icmph_t	*icmph;
3528 	ipha_t	*ipha;
3529 	uint_t	len_needed;
3530 	ire_t	*src_ire;
3531 	ire_t	*dst_ire;
3532 
3533 	if (!mp)
3534 		return (NULL);
3535 	ipha = (ipha_t *)mp->b_rptr;
3536 	if (ip_csum_hdr(ipha)) {
3537 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3538 		freemsg(mp);
3539 		return (NULL);
3540 	}
3541 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3542 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3543 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3544 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3545 	if (src_ire != NULL || dst_ire != NULL ||
3546 	    CLASSD(ipha->ipha_dst) ||
3547 	    CLASSD(ipha->ipha_src) ||
3548 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3549 		/* Note: only errors to the fragment with offset 0 */
3550 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3551 		freemsg(mp);
3552 		if (src_ire != NULL)
3553 			ire_refrele(src_ire);
3554 		if (dst_ire != NULL)
3555 			ire_refrele(dst_ire);
3556 		return (NULL);
3557 	}
3558 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3559 		/*
3560 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3561 		 * errors in response to any ICMP errors.
3562 		 */
3563 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3564 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3565 			if (!pullupmsg(mp, len_needed)) {
3566 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3567 				freemsg(mp);
3568 				return (NULL);
3569 			}
3570 			ipha = (ipha_t *)mp->b_rptr;
3571 		}
3572 		icmph = (icmph_t *)
3573 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3574 		switch (icmph->icmph_type) {
3575 		case ICMP_DEST_UNREACHABLE:
3576 		case ICMP_SOURCE_QUENCH:
3577 		case ICMP_TIME_EXCEEDED:
3578 		case ICMP_PARAM_PROBLEM:
3579 		case ICMP_REDIRECT:
3580 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3581 			freemsg(mp);
3582 			return (NULL);
3583 		default:
3584 			break;
3585 		}
3586 	}
3587 	/*
3588 	 * If this is a labeled system, then check to see if we're allowed to
3589 	 * send a response to this particular sender.  If not, then just drop.
3590 	 */
3591 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3592 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3593 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3594 		freemsg(mp);
3595 		return (NULL);
3596 	}
3597 	if (icmp_err_rate_limit(ipst)) {
3598 		/*
3599 		 * Only send ICMP error packets every so often.
3600 		 * This should be done on a per port/source basis,
3601 		 * but for now this will suffice.
3602 		 */
3603 		freemsg(mp);
3604 		return (NULL);
3605 	}
3606 	return (mp);
3607 }
3608 
3609 /*
3610  * Generate an ICMP redirect message.
3611  */
3612 static void
3613 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3614 {
3615 	icmph_t	icmph;
3616 
3617 	/*
3618 	 * We are called from ip_rput where we could
3619 	 * not have attached an IPSEC_IN.
3620 	 */
3621 	ASSERT(mp->b_datap->db_type == M_DATA);
3622 
3623 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3624 		return;
3625 	}
3626 
3627 	bzero(&icmph, sizeof (icmph_t));
3628 	icmph.icmph_type = ICMP_REDIRECT;
3629 	icmph.icmph_code = 1;
3630 	icmph.icmph_rd_gateway = gateway;
3631 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3632 	/* Redirects sent by router, and router is global zone */
3633 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3634 }
3635 
3636 /*
3637  * Generate an ICMP time exceeded message.
3638  */
3639 void
3640 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3641     ip_stack_t *ipst)
3642 {
3643 	icmph_t	icmph;
3644 	boolean_t mctl_present;
3645 	mblk_t *first_mp;
3646 
3647 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3648 
3649 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3650 		if (mctl_present)
3651 			freeb(first_mp);
3652 		return;
3653 	}
3654 
3655 	bzero(&icmph, sizeof (icmph_t));
3656 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3657 	icmph.icmph_code = code;
3658 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3659 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3660 	    ipst);
3661 }
3662 
3663 /*
3664  * Generate an ICMP unreachable message.
3665  */
3666 void
3667 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3668     ip_stack_t *ipst)
3669 {
3670 	icmph_t	icmph;
3671 	mblk_t *first_mp;
3672 	boolean_t mctl_present;
3673 
3674 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3675 
3676 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3677 		if (mctl_present)
3678 			freeb(first_mp);
3679 		return;
3680 	}
3681 
3682 	bzero(&icmph, sizeof (icmph_t));
3683 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3684 	icmph.icmph_code = code;
3685 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3686 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3687 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3688 	    zoneid, ipst);
3689 }
3690 
3691 /*
3692  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3693  * duplicate.  As long as someone else holds the address, the interface will
3694  * stay down.  When that conflict goes away, the interface is brought back up.
3695  * This is done so that accidental shutdowns of addresses aren't made
3696  * permanent.  Your server will recover from a failure.
3697  *
3698  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3699  * user space process (dhcpagent).
3700  *
3701  * Recovery completes if ARP reports that the address is now ours (via
3702  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3703  *
3704  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3705  */
3706 static void
3707 ipif_dup_recovery(void *arg)
3708 {
3709 	ipif_t *ipif = arg;
3710 	ill_t *ill = ipif->ipif_ill;
3711 	mblk_t *arp_add_mp;
3712 	mblk_t *arp_del_mp;
3713 	area_t *area;
3714 	ip_stack_t *ipst = ill->ill_ipst;
3715 
3716 	ipif->ipif_recovery_id = 0;
3717 
3718 	/*
3719 	 * No lock needed for moving or condemned check, as this is just an
3720 	 * optimization.
3721 	 */
3722 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3723 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3724 	    (ipif->ipif_state_flags & (IPIF_MOVING | IPIF_CONDEMNED))) {
3725 		/* No reason to try to bring this address back. */
3726 		return;
3727 	}
3728 
3729 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3730 		goto alloc_fail;
3731 
3732 	if (ipif->ipif_arp_del_mp == NULL) {
3733 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3734 			goto alloc_fail;
3735 		ipif->ipif_arp_del_mp = arp_del_mp;
3736 	}
3737 
3738 	/* Setting the 'unverified' flag restarts DAD */
3739 	area = (area_t *)arp_add_mp->b_rptr;
3740 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3741 	    ACE_F_UNVERIFIED;
3742 	putnext(ill->ill_rq, arp_add_mp);
3743 	return;
3744 
3745 alloc_fail:
3746 	/*
3747 	 * On allocation failure, just restart the timer.  Note that the ipif
3748 	 * is down here, so no other thread could be trying to start a recovery
3749 	 * timer.  The ill_lock protects the condemned flag and the recovery
3750 	 * timer ID.
3751 	 */
3752 	freemsg(arp_add_mp);
3753 	mutex_enter(&ill->ill_lock);
3754 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3755 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3756 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3757 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3758 	}
3759 	mutex_exit(&ill->ill_lock);
3760 }
3761 
3762 /*
3763  * This is for exclusive changes due to ARP.  Either tear down an interface due
3764  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3765  */
3766 /* ARGSUSED */
3767 static void
3768 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3769 {
3770 	ill_t	*ill = rq->q_ptr;
3771 	arh_t *arh;
3772 	ipaddr_t src;
3773 	ipif_t	*ipif;
3774 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3775 	char hbuf[MAC_STR_LEN];
3776 	char sbuf[INET_ADDRSTRLEN];
3777 	const char *failtype;
3778 	boolean_t bring_up;
3779 	ip_stack_t *ipst = ill->ill_ipst;
3780 
3781 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3782 	case AR_CN_READY:
3783 		failtype = NULL;
3784 		bring_up = B_TRUE;
3785 		break;
3786 	case AR_CN_FAILED:
3787 		failtype = "in use";
3788 		bring_up = B_FALSE;
3789 		break;
3790 	default:
3791 		failtype = "claimed";
3792 		bring_up = B_FALSE;
3793 		break;
3794 	}
3795 
3796 	arh = (arh_t *)mp->b_cont->b_rptr;
3797 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3798 
3799 	/* Handle failures due to probes */
3800 	if (src == 0) {
3801 		bcopy((char *)&arh[1] + 2 * arh->arh_hlen + IP_ADDR_LEN, &src,
3802 		    IP_ADDR_LEN);
3803 	}
3804 
3805 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3806 	    sizeof (hbuf));
3807 	(void) ip_dot_addr(src, sbuf);
3808 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3809 
3810 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3811 		    ipif->ipif_lcl_addr != src) {
3812 			continue;
3813 		}
3814 
3815 		/*
3816 		 * If we failed on a recovery probe, then restart the timer to
3817 		 * try again later.
3818 		 */
3819 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3820 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3821 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3822 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3823 		    ipst->ips_ip_dup_recovery > 0 &&
3824 		    ipif->ipif_recovery_id == 0) {
3825 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3826 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3827 			continue;
3828 		}
3829 
3830 		/*
3831 		 * If what we're trying to do has already been done, then do
3832 		 * nothing.
3833 		 */
3834 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3835 			continue;
3836 
3837 		ipif_get_name(ipif, ibuf, sizeof (ibuf));
3838 
3839 		if (failtype == NULL) {
3840 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3841 			    ibuf);
3842 		} else {
3843 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3844 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3845 		}
3846 
3847 		if (bring_up) {
3848 			ASSERT(ill->ill_dl_up);
3849 			/*
3850 			 * Free up the ARP delete message so we can allocate
3851 			 * a fresh one through the normal path.
3852 			 */
3853 			freemsg(ipif->ipif_arp_del_mp);
3854 			ipif->ipif_arp_del_mp = NULL;
3855 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3856 			    EINPROGRESS) {
3857 				ipif->ipif_addr_ready = 1;
3858 				(void) ipif_up_done(ipif);
3859 			}
3860 			continue;
3861 		}
3862 
3863 		mutex_enter(&ill->ill_lock);
3864 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3865 		ipif->ipif_flags |= IPIF_DUPLICATE;
3866 		ill->ill_ipif_dup_count++;
3867 		mutex_exit(&ill->ill_lock);
3868 		/*
3869 		 * Already exclusive on the ill; no need to handle deferred
3870 		 * processing here.
3871 		 */
3872 		(void) ipif_down(ipif, NULL, NULL);
3873 		ipif_down_tail(ipif);
3874 		mutex_enter(&ill->ill_lock);
3875 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3876 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3877 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3878 		    ipst->ips_ip_dup_recovery > 0) {
3879 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3880 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3881 		}
3882 		mutex_exit(&ill->ill_lock);
3883 	}
3884 	freemsg(mp);
3885 }
3886 
3887 /* ARGSUSED */
3888 static void
3889 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3890 {
3891 	ill_t	*ill = rq->q_ptr;
3892 	arh_t *arh;
3893 	ipaddr_t src;
3894 	ipif_t	*ipif;
3895 
3896 	arh = (arh_t *)mp->b_cont->b_rptr;
3897 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3898 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3899 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3900 			(void) ipif_resolver_up(ipif, Res_act_defend);
3901 	}
3902 	freemsg(mp);
3903 }
3904 
3905 /*
3906  * News from ARP.  ARP sends notification of interesting events down
3907  * to its clients using M_CTL messages with the interesting ARP packet
3908  * attached via b_cont.
3909  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3910  * queue as opposed to ARP sending the message to all the clients, i.e. all
3911  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3912  * table if a cache IRE is found to delete all the entries for the address in
3913  * the packet.
3914  */
3915 static void
3916 ip_arp_news(queue_t *q, mblk_t *mp)
3917 {
3918 	arcn_t		*arcn;
3919 	arh_t		*arh;
3920 	ire_t		*ire = NULL;
3921 	char		hbuf[MAC_STR_LEN];
3922 	char		sbuf[INET_ADDRSTRLEN];
3923 	ipaddr_t	src;
3924 	in6_addr_t	v6src;
3925 	boolean_t	isv6 = B_FALSE;
3926 	ipif_t		*ipif;
3927 	ill_t		*ill;
3928 	ip_stack_t	*ipst;
3929 
3930 	if (CONN_Q(q)) {
3931 		conn_t *connp = Q_TO_CONN(q);
3932 
3933 		ipst = connp->conn_netstack->netstack_ip;
3934 	} else {
3935 		ill_t *ill = (ill_t *)q->q_ptr;
3936 
3937 		ipst = ill->ill_ipst;
3938 	}
3939 
3940 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3941 		if (q->q_next) {
3942 			putnext(q, mp);
3943 		} else
3944 			freemsg(mp);
3945 		return;
3946 	}
3947 	arh = (arh_t *)mp->b_cont->b_rptr;
3948 	/* Is it one we are interested in? */
3949 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3950 		isv6 = B_TRUE;
3951 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3952 		    IPV6_ADDR_LEN);
3953 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3954 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3955 		    IP_ADDR_LEN);
3956 	} else {
3957 		freemsg(mp);
3958 		return;
3959 	}
3960 
3961 	ill = q->q_ptr;
3962 
3963 	arcn = (arcn_t *)mp->b_rptr;
3964 	switch (arcn->arcn_code) {
3965 	case AR_CN_BOGON:
3966 		/*
3967 		 * Someone is sending ARP packets with a source protocol
3968 		 * address that we have published and for which we believe our
3969 		 * entry is authoritative and (when ill_arp_extend is set)
3970 		 * verified to be unique on the network.
3971 		 *
3972 		 * The ARP module internally handles the cases where the sender
3973 		 * is just probing (for DAD) and where the hardware address of
3974 		 * a non-authoritative entry has changed.  Thus, these are the
3975 		 * real conflicts, and we have to do resolution.
3976 		 *
3977 		 * We back away quickly from the address if it's from DHCP or
3978 		 * otherwise temporary and hasn't been used recently (or at
3979 		 * all).  We'd like to include "deprecated" addresses here as
3980 		 * well (as there's no real reason to defend something we're
3981 		 * discarding), but IPMP "reuses" this flag to mean something
3982 		 * other than the standard meaning.
3983 		 *
3984 		 * If the ARP module above is not extended (meaning that it
3985 		 * doesn't know how to defend the address), then we just log
3986 		 * the problem as we always did and continue on.  It's not
3987 		 * right, but there's little else we can do, and those old ATM
3988 		 * users are going away anyway.
3989 		 */
3990 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
3991 		    hbuf, sizeof (hbuf));
3992 		(void) ip_dot_addr(src, sbuf);
3993 		if (isv6) {
3994 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
3995 			    ipst);
3996 		} else {
3997 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
3998 		}
3999 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
4000 			uint32_t now;
4001 			uint32_t maxage;
4002 			clock_t lused;
4003 			uint_t maxdefense;
4004 			uint_t defs;
4005 
4006 			/*
4007 			 * First, figure out if this address hasn't been used
4008 			 * in a while.  If it hasn't, then it's a better
4009 			 * candidate for abandoning.
4010 			 */
4011 			ipif = ire->ire_ipif;
4012 			ASSERT(ipif != NULL);
4013 			now = gethrestime_sec();
4014 			maxage = now - ire->ire_create_time;
4015 			if (maxage > ipst->ips_ip_max_temp_idle)
4016 				maxage = ipst->ips_ip_max_temp_idle;
4017 			lused = drv_hztousec(ddi_get_lbolt() -
4018 			    ire->ire_last_used_time) / MICROSEC + 1;
4019 			if (lused >= maxage && (ipif->ipif_flags &
4020 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4021 				maxdefense = ipst->ips_ip_max_temp_defend;
4022 			else
4023 				maxdefense = ipst->ips_ip_max_defend;
4024 
4025 			/*
4026 			 * Now figure out how many times we've defended
4027 			 * ourselves.  Ignore defenses that happened long in
4028 			 * the past.
4029 			 */
4030 			mutex_enter(&ire->ire_lock);
4031 			if ((defs = ire->ire_defense_count) > 0 &&
4032 			    now - ire->ire_defense_time >
4033 			    ipst->ips_ip_defend_interval) {
4034 				ire->ire_defense_count = defs = 0;
4035 			}
4036 			ire->ire_defense_count++;
4037 			ire->ire_defense_time = now;
4038 			mutex_exit(&ire->ire_lock);
4039 			ill_refhold(ill);
4040 			ire_refrele(ire);
4041 
4042 			/*
4043 			 * If we've defended ourselves too many times already,
4044 			 * then give up and tear down the interface(s) using
4045 			 * this address.  Otherwise, defend by sending out a
4046 			 * gratuitous ARP.
4047 			 */
4048 			if (defs >= maxdefense && ill->ill_arp_extend) {
4049 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4050 				    B_FALSE);
4051 			} else {
4052 				cmn_err(CE_WARN,
4053 				    "node %s is using our IP address %s on %s",
4054 				    hbuf, sbuf, ill->ill_name);
4055 				/*
4056 				 * If this is an old (ATM) ARP module, then
4057 				 * don't try to defend the address.  Remain
4058 				 * compatible with the old behavior.  Defend
4059 				 * only with new ARP.
4060 				 */
4061 				if (ill->ill_arp_extend) {
4062 					qwriter_ip(ill, q, mp, ip_arp_defend,
4063 					    NEW_OP, B_FALSE);
4064 				} else {
4065 					ill_refrele(ill);
4066 				}
4067 			}
4068 			return;
4069 		}
4070 		cmn_err(CE_WARN,
4071 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4072 		    hbuf, sbuf, ill->ill_name);
4073 		if (ire != NULL)
4074 			ire_refrele(ire);
4075 		break;
4076 	case AR_CN_ANNOUNCE:
4077 		if (isv6) {
4078 			/*
4079 			 * For XRESOLV interfaces.
4080 			 * Delete the IRE cache entry and NCE for this
4081 			 * v6 address
4082 			 */
4083 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4084 			/*
4085 			 * If v6src is a non-zero, it's a router address
4086 			 * as below. Do the same sort of thing to clean
4087 			 * out off-net IRE_CACHE entries that go through
4088 			 * the router.
4089 			 */
4090 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4091 				ire_walk_v6(ire_delete_cache_gw_v6,
4092 				    (char *)&v6src, ALL_ZONES, ipst);
4093 			}
4094 		} else {
4095 			nce_hw_map_t hwm;
4096 
4097 			/*
4098 			 * ARP gives us a copy of any packet where it thinks
4099 			 * the address has changed, so that we can update our
4100 			 * caches.  We're responsible for caching known answers
4101 			 * in the current design.  We check whether the
4102 			 * hardware address really has changed in all of our
4103 			 * entries that have cached this mapping, and if so, we
4104 			 * blow them away.  This way we will immediately pick
4105 			 * up the rare case of a host changing hardware
4106 			 * address.
4107 			 */
4108 			if (src == 0)
4109 				break;
4110 			hwm.hwm_addr = src;
4111 			hwm.hwm_hwlen = arh->arh_hlen;
4112 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4113 			NDP_HW_CHANGE_INCR(ipst->ips_ndp4);
4114 			ndp_walk_common(ipst->ips_ndp4, NULL,
4115 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4116 			NDP_HW_CHANGE_DECR(ipst->ips_ndp4);
4117 		}
4118 		break;
4119 	case AR_CN_READY:
4120 		/* No external v6 resolver has a contract to use this */
4121 		if (isv6)
4122 			break;
4123 		/* If the link is down, we'll retry this later */
4124 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4125 			break;
4126 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4127 		    NULL, NULL, ipst);
4128 		if (ipif != NULL) {
4129 			/*
4130 			 * If this is a duplicate recovery, then we now need to
4131 			 * go exclusive to bring this thing back up.
4132 			 */
4133 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4134 			    IPIF_DUPLICATE) {
4135 				ipif_refrele(ipif);
4136 				ill_refhold(ill);
4137 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4138 				    B_FALSE);
4139 				return;
4140 			}
4141 			/*
4142 			 * If this is the first notice that this address is
4143 			 * ready, then let the user know now.
4144 			 */
4145 			if ((ipif->ipif_flags & IPIF_UP) &&
4146 			    !ipif->ipif_addr_ready) {
4147 				ipif_mask_reply(ipif);
4148 				ip_rts_ifmsg(ipif);
4149 				ip_rts_newaddrmsg(RTM_ADD, 0, ipif);
4150 				sctp_update_ipif(ipif, SCTP_IPIF_UP);
4151 			}
4152 			ipif->ipif_addr_ready = 1;
4153 			ipif_refrele(ipif);
4154 		}
4155 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp), ipst);
4156 		if (ire != NULL) {
4157 			ire->ire_defense_count = 0;
4158 			ire_refrele(ire);
4159 		}
4160 		break;
4161 	case AR_CN_FAILED:
4162 		/* No external v6 resolver has a contract to use this */
4163 		if (isv6)
4164 			break;
4165 		ill_refhold(ill);
4166 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, B_FALSE);
4167 		return;
4168 	}
4169 	freemsg(mp);
4170 }
4171 
4172 /*
4173  * Create a mblk suitable for carrying the interface index and/or source link
4174  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4175  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4176  * application.
4177  */
4178 mblk_t *
4179 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4180     ip_stack_t *ipst)
4181 {
4182 	mblk_t		*mp;
4183 	ip_pktinfo_t	*pinfo;
4184 	ipha_t *ipha;
4185 	struct ether_header *pether;
4186 
4187 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4188 	if (mp == NULL) {
4189 		ip1dbg(("ip_add_info: allocation failure.\n"));
4190 		return (data_mp);
4191 	}
4192 
4193 	ipha	= (ipha_t *)data_mp->b_rptr;
4194 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4195 	bzero(pinfo, sizeof (ip_pktinfo_t));
4196 	pinfo->ip_pkt_flags = (uchar_t)flags;
4197 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4198 
4199 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4200 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4201 	if (flags & IPF_RECVADDR) {
4202 		ipif_t	*ipif;
4203 		ire_t	*ire;
4204 
4205 		/*
4206 		 * Only valid for V4
4207 		 */
4208 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4209 		    (IPV4_VERSION << 4));
4210 
4211 		ipif = ipif_get_next_ipif(NULL, ill);
4212 		if (ipif != NULL) {
4213 			/*
4214 			 * Since a decision has already been made to deliver the
4215 			 * packet, there is no need to test for SECATTR and
4216 			 * ZONEONLY.
4217 			 * When a multicast packet is transmitted
4218 			 * a cache entry is created for the multicast address.
4219 			 * When delivering a copy of the packet or when new
4220 			 * packets are received we do not want to match on the
4221 			 * cached entry so explicitly match on
4222 			 * IRE_LOCAL and IRE_LOOPBACK
4223 			 */
4224 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4225 			    IRE_LOCAL | IRE_LOOPBACK,
4226 			    ipif, zoneid, NULL,
4227 			    MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP, ipst);
4228 			if (ire == NULL) {
4229 				/*
4230 				 * packet must have come on a different
4231 				 * interface.
4232 				 * Since a decision has already been made to
4233 				 * deliver the packet, there is no need to test
4234 				 * for SECATTR and ZONEONLY.
4235 				 * Only match on local and broadcast ire's.
4236 				 * See detailed comment above.
4237 				 */
4238 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4239 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4240 				    NULL, MATCH_IRE_TYPE, ipst);
4241 			}
4242 
4243 			if (ire == NULL) {
4244 				/*
4245 				 * This is either a multicast packet or
4246 				 * the address has been removed since
4247 				 * the packet was received.
4248 				 * Return INADDR_ANY so that normal source
4249 				 * selection occurs for the response.
4250 				 */
4251 
4252 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4253 			} else {
4254 				pinfo->ip_pkt_match_addr.s_addr =
4255 				    ire->ire_src_addr;
4256 				ire_refrele(ire);
4257 			}
4258 			ipif_refrele(ipif);
4259 		} else {
4260 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4261 		}
4262 	}
4263 
4264 	pether = (struct ether_header *)((char *)ipha
4265 	    - sizeof (struct ether_header));
4266 	/*
4267 	 * Make sure the interface is an ethernet type, since this option
4268 	 * is currently supported only on this type of interface. Also make
4269 	 * sure we are pointing correctly above db_base.
4270 	 */
4271 
4272 	if ((flags & IPF_RECVSLLA) &&
4273 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4274 	    (ill->ill_type == IFT_ETHER) &&
4275 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4276 
4277 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4278 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4279 		    (uchar_t *)pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4280 	} else {
4281 		/*
4282 		 * Clear the bit. Indicate to upper layer that IP is not
4283 		 * sending this ancillary info.
4284 		 */
4285 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4286 	}
4287 
4288 	mp->b_datap->db_type = M_CTL;
4289 	mp->b_wptr += sizeof (ip_pktinfo_t);
4290 	mp->b_cont = data_mp;
4291 
4292 	return (mp);
4293 }
4294 
4295 /*
4296  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4297  * part of the bind request.
4298  */
4299 
4300 boolean_t
4301 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4302 {
4303 	ipsec_in_t *ii;
4304 
4305 	ASSERT(policy_mp != NULL);
4306 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4307 
4308 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4309 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4310 
4311 	connp->conn_policy = ii->ipsec_in_policy;
4312 	ii->ipsec_in_policy = NULL;
4313 
4314 	if (ii->ipsec_in_action != NULL) {
4315 		if (connp->conn_latch == NULL) {
4316 			connp->conn_latch = iplatch_create();
4317 			if (connp->conn_latch == NULL)
4318 				return (B_FALSE);
4319 		}
4320 		ipsec_latch_inbound(connp->conn_latch, ii);
4321 	}
4322 	return (B_TRUE);
4323 }
4324 
4325 /*
4326  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4327  * and to arrange for power-fanout assist.  The ULP is identified by
4328  * adding a single byte at the end of the original bind message.
4329  * A ULP other than UDP or TCP that wishes to be recognized passes
4330  * down a bind with a zero length address.
4331  *
4332  * The binding works as follows:
4333  * - A zero byte address means just bind to the protocol.
4334  * - A four byte address is treated as a request to validate
4335  *   that the address is a valid local address, appropriate for
4336  *   an application to bind to. This does not affect any fanout
4337  *   information in IP.
4338  * - A sizeof sin_t byte address is used to bind to only the local address
4339  *   and port.
4340  * - A sizeof ipa_conn_t byte address contains complete fanout information
4341  *   consisting of local and remote addresses and ports.  In
4342  *   this case, the addresses are both validated as appropriate
4343  *   for this operation, and, if so, the information is retained
4344  *   for use in the inbound fanout.
4345  *
4346  * The ULP (except in the zero-length bind) can append an
4347  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4348  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4349  * a copy of the source or destination IRE (source for local bind;
4350  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4351  * policy information contained should be copied on to the conn.
4352  *
4353  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4354  */
4355 mblk_t *
4356 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4357 {
4358 	ssize_t		len;
4359 	struct T_bind_req	*tbr;
4360 	sin_t		*sin;
4361 	ipa_conn_t	*ac;
4362 	uchar_t		*ucp;
4363 	mblk_t		*mp1;
4364 	boolean_t	ire_requested;
4365 	boolean_t	ipsec_policy_set = B_FALSE;
4366 	int		error = 0;
4367 	int		protocol;
4368 	ipa_conn_x_t	*acx;
4369 
4370 	ASSERT(!connp->conn_af_isv6);
4371 	connp->conn_pkt_isv6 = B_FALSE;
4372 
4373 	len = MBLKL(mp);
4374 	if (len < (sizeof (*tbr) + 1)) {
4375 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4376 		    "ip_bind: bogus msg, len %ld", len);
4377 		/* XXX: Need to return something better */
4378 		goto bad_addr;
4379 	}
4380 	/* Back up and extract the protocol identifier. */
4381 	mp->b_wptr--;
4382 	protocol = *mp->b_wptr & 0xFF;
4383 	tbr = (struct T_bind_req *)mp->b_rptr;
4384 	/* Reset the message type in preparation for shipping it back. */
4385 	DB_TYPE(mp) = M_PCPROTO;
4386 
4387 	connp->conn_ulp = (uint8_t)protocol;
4388 
4389 	/*
4390 	 * Check for a zero length address.  This is from a protocol that
4391 	 * wants to register to receive all packets of its type.
4392 	 */
4393 	if (tbr->ADDR_length == 0) {
4394 		/*
4395 		 * These protocols are now intercepted in ip_bind_v6().
4396 		 * Reject protocol-level binds here for now.
4397 		 *
4398 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4399 		 * so that the protocol type cannot be SCTP.
4400 		 */
4401 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4402 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4403 			goto bad_addr;
4404 		}
4405 
4406 		/*
4407 		 *
4408 		 * The udp module never sends down a zero-length address,
4409 		 * and allowing this on a labeled system will break MLP
4410 		 * functionality.
4411 		 */
4412 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4413 			goto bad_addr;
4414 
4415 		if (connp->conn_mac_exempt)
4416 			goto bad_addr;
4417 
4418 		/* No hash here really.  The table is big enough. */
4419 		connp->conn_srcv6 = ipv6_all_zeros;
4420 
4421 		ipcl_proto_insert(connp, protocol);
4422 
4423 		tbr->PRIM_type = T_BIND_ACK;
4424 		return (mp);
4425 	}
4426 
4427 	/* Extract the address pointer from the message. */
4428 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4429 	    tbr->ADDR_length);
4430 	if (ucp == NULL) {
4431 		ip1dbg(("ip_bind: no address\n"));
4432 		goto bad_addr;
4433 	}
4434 	if (!OK_32PTR(ucp)) {
4435 		ip1dbg(("ip_bind: unaligned address\n"));
4436 		goto bad_addr;
4437 	}
4438 	/*
4439 	 * Check for trailing mps.
4440 	 */
4441 
4442 	mp1 = mp->b_cont;
4443 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4444 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4445 
4446 	switch (tbr->ADDR_length) {
4447 	default:
4448 		ip1dbg(("ip_bind: bad address length %d\n",
4449 		    (int)tbr->ADDR_length));
4450 		goto bad_addr;
4451 
4452 	case IP_ADDR_LEN:
4453 		/* Verification of local address only */
4454 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4455 		    ire_requested, ipsec_policy_set, B_FALSE);
4456 		break;
4457 
4458 	case sizeof (sin_t):
4459 		sin = (sin_t *)ucp;
4460 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4461 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4462 		break;
4463 
4464 	case sizeof (ipa_conn_t):
4465 		ac = (ipa_conn_t *)ucp;
4466 		/* For raw socket, the local port is not set. */
4467 		if (ac->ac_lport == 0)
4468 			ac->ac_lport = connp->conn_lport;
4469 		/* Always verify destination reachability. */
4470 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4471 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4472 		    ipsec_policy_set, B_TRUE, B_TRUE);
4473 		break;
4474 
4475 	case sizeof (ipa_conn_x_t):
4476 		acx = (ipa_conn_x_t *)ucp;
4477 		/*
4478 		 * Whether or not to verify destination reachability depends
4479 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4480 		 */
4481 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4482 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4483 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4484 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4485 		break;
4486 	}
4487 	if (error == EINPROGRESS)
4488 		return (NULL);
4489 	else if (error != 0)
4490 		goto bad_addr;
4491 	/*
4492 	 * Pass the IPsec headers size in ire_ipsec_overhead.
4493 	 * We can't do this in ip_bind_insert_ire because the policy
4494 	 * may not have been inherited at that point in time and hence
4495 	 * conn_out_enforce_policy may not be set.
4496 	 */
4497 	mp1 = mp->b_cont;
4498 	if (ire_requested && connp->conn_out_enforce_policy &&
4499 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4500 		ire_t *ire = (ire_t *)mp1->b_rptr;
4501 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4502 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4503 	}
4504 
4505 	/* Send it home. */
4506 	mp->b_datap->db_type = M_PCPROTO;
4507 	tbr->PRIM_type = T_BIND_ACK;
4508 	return (mp);
4509 
4510 bad_addr:
4511 	/*
4512 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4513 	 * a unix errno.
4514 	 */
4515 	if (error > 0)
4516 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4517 	else
4518 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4519 	return (mp);
4520 }
4521 
4522 /*
4523  * Here address is verified to be a valid local address.
4524  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4525  * address is also considered a valid local address.
4526  * In the case of a broadcast/multicast address, however, the
4527  * upper protocol is expected to reset the src address
4528  * to 0 if it sees a IRE_BROADCAST type returned so that
4529  * no packets are emitted with broadcast/multicast address as
4530  * source address (that violates hosts requirements RFC1122)
4531  * The addresses valid for bind are:
4532  *	(1) - INADDR_ANY (0)
4533  *	(2) - IP address of an UP interface
4534  *	(3) - IP address of a DOWN interface
4535  *	(4) - valid local IP broadcast addresses. In this case
4536  *	the conn will only receive packets destined to
4537  *	the specified broadcast address.
4538  *	(5) - a multicast address. In this case
4539  *	the conn will only receive packets destined to
4540  *	the specified multicast address. Note: the
4541  *	application still has to issue an
4542  *	IP_ADD_MEMBERSHIP socket option.
4543  *
4544  * On error, return -1 for TBADADDR otherwise pass the
4545  * errno with TSYSERR reply.
4546  *
4547  * In all the above cases, the bound address must be valid in the current zone.
4548  * When the address is loopback, multicast or broadcast, there might be many
4549  * matching IREs so bind has to look up based on the zone.
4550  *
4551  * Note: lport is in network byte order.
4552  */
4553 int
4554 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4555     boolean_t ire_requested, boolean_t ipsec_policy_set,
4556     boolean_t fanout_insert)
4557 {
4558 	int		error = 0;
4559 	ire_t		*src_ire;
4560 	mblk_t		*policy_mp;
4561 	ipif_t		*ipif;
4562 	zoneid_t	zoneid;
4563 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4564 
4565 	if (ipsec_policy_set) {
4566 		policy_mp = mp->b_cont;
4567 	}
4568 
4569 	/*
4570 	 * If it was previously connected, conn_fully_bound would have
4571 	 * been set.
4572 	 */
4573 	connp->conn_fully_bound = B_FALSE;
4574 
4575 	src_ire = NULL;
4576 	ipif = NULL;
4577 
4578 	zoneid = IPCL_ZONEID(connp);
4579 
4580 	if (src_addr) {
4581 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4582 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4583 		/*
4584 		 * If an address other than 0.0.0.0 is requested,
4585 		 * we verify that it is a valid address for bind
4586 		 * Note: Following code is in if-else-if form for
4587 		 * readability compared to a condition check.
4588 		 */
4589 		/* LINTED - statement has no consequent */
4590 		if (IRE_IS_LOCAL(src_ire)) {
4591 			/*
4592 			 * (2) Bind to address of local UP interface
4593 			 */
4594 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4595 			/*
4596 			 * (4) Bind to broadcast address
4597 			 * Note: permitted only from transports that
4598 			 * request IRE
4599 			 */
4600 			if (!ire_requested)
4601 				error = EADDRNOTAVAIL;
4602 		} else {
4603 			/*
4604 			 * (3) Bind to address of local DOWN interface
4605 			 * (ipif_lookup_addr() looks up all interfaces
4606 			 * but we do not get here for UP interfaces
4607 			 * - case (2) above)
4608 			 * We put the protocol byte back into the mblk
4609 			 * since we may come back via ip_wput_nondata()
4610 			 * later with this mblk if ipif_lookup_addr chooses
4611 			 * to defer processing.
4612 			 */
4613 			*mp->b_wptr++ = (char)connp->conn_ulp;
4614 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4615 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4616 			    &error, ipst)) != NULL) {
4617 				ipif_refrele(ipif);
4618 			} else if (error == EINPROGRESS) {
4619 				if (src_ire != NULL)
4620 					ire_refrele(src_ire);
4621 				return (EINPROGRESS);
4622 			} else if (CLASSD(src_addr)) {
4623 				error = 0;
4624 				if (src_ire != NULL)
4625 					ire_refrele(src_ire);
4626 				/*
4627 				 * (5) bind to multicast address.
4628 				 * Fake out the IRE returned to upper
4629 				 * layer to be a broadcast IRE.
4630 				 */
4631 				src_ire = ire_ctable_lookup(
4632 				    INADDR_BROADCAST, INADDR_ANY,
4633 				    IRE_BROADCAST, NULL, zoneid, NULL,
4634 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4635 				    ipst);
4636 				if (src_ire == NULL || !ire_requested)
4637 					error = EADDRNOTAVAIL;
4638 			} else {
4639 				/*
4640 				 * Not a valid address for bind
4641 				 */
4642 				error = EADDRNOTAVAIL;
4643 			}
4644 			/*
4645 			 * Just to keep it consistent with the processing in
4646 			 * ip_bind_v4()
4647 			 */
4648 			mp->b_wptr--;
4649 		}
4650 		if (error) {
4651 			/* Red Alert!  Attempting to be a bogon! */
4652 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4653 			    ntohl(src_addr)));
4654 			goto bad_addr;
4655 		}
4656 	}
4657 
4658 	/*
4659 	 * Allow setting new policies. For example, disconnects come
4660 	 * down as ipa_t bind. As we would have set conn_policy_cached
4661 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4662 	 * can change after the disconnect.
4663 	 */
4664 	connp->conn_policy_cached = B_FALSE;
4665 
4666 	/*
4667 	 * If not fanout_insert this was just an address verification
4668 	 */
4669 	if (fanout_insert) {
4670 		/*
4671 		 * The addresses have been verified. Time to insert in
4672 		 * the correct fanout list.
4673 		 */
4674 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4675 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4676 		connp->conn_lport = lport;
4677 		connp->conn_fport = 0;
4678 		/*
4679 		 * Do we need to add a check to reject Multicast packets
4680 		 */
4681 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4682 	}
4683 
4684 	if (error == 0) {
4685 		if (ire_requested) {
4686 			if (!ip_bind_insert_ire(mp, src_ire, NULL, ipst)) {
4687 				error = -1;
4688 				/* Falls through to bad_addr */
4689 			}
4690 		} else if (ipsec_policy_set) {
4691 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4692 				error = -1;
4693 				/* Falls through to bad_addr */
4694 			}
4695 		}
4696 	}
4697 bad_addr:
4698 	if (error != 0) {
4699 		if (connp->conn_anon_port) {
4700 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4701 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4702 			    B_FALSE);
4703 		}
4704 		connp->conn_mlp_type = mlptSingle;
4705 	}
4706 	if (src_ire != NULL)
4707 		IRE_REFRELE(src_ire);
4708 	if (ipsec_policy_set) {
4709 		ASSERT(policy_mp == mp->b_cont);
4710 		ASSERT(policy_mp != NULL);
4711 		freeb(policy_mp);
4712 		/*
4713 		 * As of now assume that nothing else accompanies
4714 		 * IPSEC_POLICY_SET.
4715 		 */
4716 		mp->b_cont = NULL;
4717 	}
4718 	return (error);
4719 }
4720 
4721 /*
4722  * Verify that both the source and destination addresses
4723  * are valid.  If verify_dst is false, then the destination address may be
4724  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4725  * destination reachability, while tunnels do not.
4726  * Note that we allow connect to broadcast and multicast
4727  * addresses when ire_requested is set. Thus the ULP
4728  * has to check for IRE_BROADCAST and multicast.
4729  *
4730  * Returns zero if ok.
4731  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4732  * (for use with TSYSERR reply).
4733  *
4734  * Note: lport and fport are in network byte order.
4735  */
4736 int
4737 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4738     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4739     boolean_t ire_requested, boolean_t ipsec_policy_set,
4740     boolean_t fanout_insert, boolean_t verify_dst)
4741 {
4742 	ire_t		*src_ire;
4743 	ire_t		*dst_ire;
4744 	int		error = 0;
4745 	int 		protocol;
4746 	mblk_t		*policy_mp;
4747 	ire_t		*sire = NULL;
4748 	ire_t		*md_dst_ire = NULL;
4749 	ire_t		*lso_dst_ire = NULL;
4750 	ill_t		*ill = NULL;
4751 	zoneid_t	zoneid;
4752 	ipaddr_t	src_addr = *src_addrp;
4753 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4754 
4755 	src_ire = dst_ire = NULL;
4756 	protocol = *mp->b_wptr & 0xFF;
4757 
4758 	/*
4759 	 * If we never got a disconnect before, clear it now.
4760 	 */
4761 	connp->conn_fully_bound = B_FALSE;
4762 
4763 	if (ipsec_policy_set) {
4764 		policy_mp = mp->b_cont;
4765 	}
4766 
4767 	zoneid = IPCL_ZONEID(connp);
4768 
4769 	if (CLASSD(dst_addr)) {
4770 		/* Pick up an IRE_BROADCAST */
4771 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4772 		    NULL, zoneid, MBLK_GETLABEL(mp),
4773 		    (MATCH_IRE_RECURSIVE |
4774 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4775 		    MATCH_IRE_SECATTR), ipst);
4776 	} else {
4777 		/*
4778 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4779 		 * and onlink ipif is not found set ENETUNREACH error.
4780 		 */
4781 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4782 			ipif_t *ipif;
4783 
4784 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4785 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4786 			if (ipif == NULL) {
4787 				error = ENETUNREACH;
4788 				goto bad_addr;
4789 			}
4790 			ipif_refrele(ipif);
4791 		}
4792 
4793 		if (connp->conn_nexthop_set) {
4794 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4795 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4796 			    MATCH_IRE_SECATTR, ipst);
4797 		} else {
4798 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4799 			    &sire, zoneid, MBLK_GETLABEL(mp),
4800 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4801 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4802 			    MATCH_IRE_SECATTR), ipst);
4803 		}
4804 	}
4805 	/*
4806 	 * dst_ire can't be a broadcast when not ire_requested.
4807 	 * We also prevent ire's with src address INADDR_ANY to
4808 	 * be used, which are created temporarily for
4809 	 * sending out packets from endpoints that have
4810 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4811 	 * reachable.  If verify_dst is false, the destination needn't be
4812 	 * reachable.
4813 	 *
4814 	 * If we match on a reject or black hole, then we've got a
4815 	 * local failure.  May as well fail out the connect() attempt,
4816 	 * since it's never going to succeed.
4817 	 */
4818 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4819 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4820 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4821 		/*
4822 		 * If we're verifying destination reachability, we always want
4823 		 * to complain here.
4824 		 *
4825 		 * If we're not verifying destination reachability but the
4826 		 * destination has a route, we still want to fail on the
4827 		 * temporary address and broadcast address tests.
4828 		 */
4829 		if (verify_dst || (dst_ire != NULL)) {
4830 			if (ip_debug > 2) {
4831 				pr_addr_dbg("ip_bind_connected: bad connected "
4832 				    "dst %s\n", AF_INET, &dst_addr);
4833 			}
4834 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4835 				error = ENETUNREACH;
4836 			else
4837 				error = EHOSTUNREACH;
4838 			goto bad_addr;
4839 		}
4840 	}
4841 
4842 	/*
4843 	 * We now know that routing will allow us to reach the destination.
4844 	 * Check whether Trusted Solaris policy allows communication with this
4845 	 * host, and pretend that the destination is unreachable if not.
4846 	 *
4847 	 * This is never a problem for TCP, since that transport is known to
4848 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4849 	 * handling.  If the remote is unreachable, it will be detected at that
4850 	 * point, so there's no reason to check it here.
4851 	 *
4852 	 * Note that for sendto (and other datagram-oriented friends), this
4853 	 * check is done as part of the data path label computation instead.
4854 	 * The check here is just to make non-TCP connect() report the right
4855 	 * error.
4856 	 */
4857 	if (dst_ire != NULL && is_system_labeled() &&
4858 	    !IPCL_IS_TCP(connp) &&
4859 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4860 	    connp->conn_mac_exempt, ipst) != 0) {
4861 		error = EHOSTUNREACH;
4862 		if (ip_debug > 2) {
4863 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4864 			    AF_INET, &dst_addr);
4865 		}
4866 		goto bad_addr;
4867 	}
4868 
4869 	/*
4870 	 * If the app does a connect(), it means that it will most likely
4871 	 * send more than 1 packet to the destination.  It makes sense
4872 	 * to clear the temporary flag.
4873 	 */
4874 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4875 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4876 		irb_t *irb = dst_ire->ire_bucket;
4877 
4878 		rw_enter(&irb->irb_lock, RW_WRITER);
4879 		/*
4880 		 * We need to recheck for IRE_MARK_TEMPORARY after acquiring
4881 		 * the lock to guarantee irb_tmp_ire_cnt.
4882 		 */
4883 		if (dst_ire->ire_marks & IRE_MARK_TEMPORARY) {
4884 			dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4885 			irb->irb_tmp_ire_cnt--;
4886 		}
4887 		rw_exit(&irb->irb_lock);
4888 	}
4889 
4890 	/*
4891 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4892 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4893 	 * eligibility tests for passive connects are handled separately
4894 	 * through tcp_adapt_ire().  We do this before the source address
4895 	 * selection, because dst_ire may change after a call to
4896 	 * ipif_select_source().  This is a best-effort check, as the
4897 	 * packet for this connection may not actually go through
4898 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4899 	 * calling ip_newroute().  This is why we further check on the
4900 	 * IRE during LSO/Multidata packet transmission in
4901 	 * tcp_lsosend()/tcp_multisend().
4902 	 */
4903 	if (!ipsec_policy_set && dst_ire != NULL &&
4904 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4905 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4906 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4907 			lso_dst_ire = dst_ire;
4908 			IRE_REFHOLD(lso_dst_ire);
4909 		} else if (ipst->ips_ip_multidata_outbound &&
4910 		    ILL_MDT_CAPABLE(ill)) {
4911 			md_dst_ire = dst_ire;
4912 			IRE_REFHOLD(md_dst_ire);
4913 		}
4914 	}
4915 
4916 	if (dst_ire != NULL &&
4917 	    dst_ire->ire_type == IRE_LOCAL &&
4918 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4919 		/*
4920 		 * If the IRE belongs to a different zone, look for a matching
4921 		 * route in the forwarding table and use the source address from
4922 		 * that route.
4923 		 */
4924 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4925 		    zoneid, 0, NULL,
4926 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4927 		    MATCH_IRE_RJ_BHOLE, ipst);
4928 		if (src_ire == NULL) {
4929 			error = EHOSTUNREACH;
4930 			goto bad_addr;
4931 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4932 			if (!(src_ire->ire_type & IRE_HOST))
4933 				error = ENETUNREACH;
4934 			else
4935 				error = EHOSTUNREACH;
4936 			goto bad_addr;
4937 		}
4938 		if (src_addr == INADDR_ANY)
4939 			src_addr = src_ire->ire_src_addr;
4940 		ire_refrele(src_ire);
4941 		src_ire = NULL;
4942 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4943 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4944 			src_addr = sire->ire_src_addr;
4945 			ire_refrele(dst_ire);
4946 			dst_ire = sire;
4947 			sire = NULL;
4948 		} else {
4949 			/*
4950 			 * Pick a source address so that a proper inbound
4951 			 * load spreading would happen.
4952 			 */
4953 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4954 			ipif_t *src_ipif = NULL;
4955 			ire_t *ipif_ire;
4956 
4957 			/*
4958 			 * Supply a local source address such that inbound
4959 			 * load spreading happens.
4960 			 *
4961 			 * Determine the best source address on this ill for
4962 			 * the destination.
4963 			 *
4964 			 * 1) For broadcast, we should return a broadcast ire
4965 			 *    found above so that upper layers know that the
4966 			 *    destination address is a broadcast address.
4967 			 *
4968 			 * 2) If this is part of a group, select a better
4969 			 *    source address so that better inbound load
4970 			 *    balancing happens. Do the same if the ipif
4971 			 *    is DEPRECATED.
4972 			 *
4973 			 * 3) If the outgoing interface is part of a usesrc
4974 			 *    group, then try selecting a source address from
4975 			 *    the usesrc ILL.
4976 			 */
4977 			if ((dst_ire->ire_zoneid != zoneid &&
4978 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4979 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4980 			    ((dst_ill->ill_group != NULL) ||
4981 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4982 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4983 				/*
4984 				 * If the destination is reachable via a
4985 				 * given gateway, the selected source address
4986 				 * should be in the same subnet as the gateway.
4987 				 * Otherwise, the destination is not reachable.
4988 				 *
4989 				 * If there are no interfaces on the same subnet
4990 				 * as the destination, ipif_select_source gives
4991 				 * first non-deprecated interface which might be
4992 				 * on a different subnet than the gateway.
4993 				 * This is not desirable. Hence pass the dst_ire
4994 				 * source address to ipif_select_source.
4995 				 * It is sure that the destination is reachable
4996 				 * with the dst_ire source address subnet.
4997 				 * So passing dst_ire source address to
4998 				 * ipif_select_source will make sure that the
4999 				 * selected source will be on the same subnet
5000 				 * as dst_ire source address.
5001 				 */
5002 				ipaddr_t saddr =
5003 				    dst_ire->ire_ipif->ipif_src_addr;
5004 				src_ipif = ipif_select_source(dst_ill,
5005 				    saddr, zoneid);
5006 				if (src_ipif != NULL) {
5007 					if (IS_VNI(src_ipif->ipif_ill)) {
5008 						/*
5009 						 * For VNI there is no
5010 						 * interface route
5011 						 */
5012 						src_addr =
5013 						    src_ipif->ipif_src_addr;
5014 					} else {
5015 						ipif_ire =
5016 						    ipif_to_ire(src_ipif);
5017 						if (ipif_ire != NULL) {
5018 							IRE_REFRELE(dst_ire);
5019 							dst_ire = ipif_ire;
5020 						}
5021 						src_addr =
5022 						    dst_ire->ire_src_addr;
5023 					}
5024 					ipif_refrele(src_ipif);
5025 				} else {
5026 					src_addr = dst_ire->ire_src_addr;
5027 				}
5028 			} else {
5029 				src_addr = dst_ire->ire_src_addr;
5030 			}
5031 		}
5032 	}
5033 
5034 	/*
5035 	 * We do ire_route_lookup() here (and not
5036 	 * interface lookup as we assert that
5037 	 * src_addr should only come from an
5038 	 * UP interface for hard binding.
5039 	 */
5040 	ASSERT(src_ire == NULL);
5041 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5042 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5043 	/* src_ire must be a local|loopback */
5044 	if (!IRE_IS_LOCAL(src_ire)) {
5045 		if (ip_debug > 2) {
5046 			pr_addr_dbg("ip_bind_connected: bad connected "
5047 			    "src %s\n", AF_INET, &src_addr);
5048 		}
5049 		error = EADDRNOTAVAIL;
5050 		goto bad_addr;
5051 	}
5052 
5053 	/*
5054 	 * If the source address is a loopback address, the
5055 	 * destination had best be local or multicast.
5056 	 * The transports that can't handle multicast will reject
5057 	 * those addresses.
5058 	 */
5059 	if (src_ire->ire_type == IRE_LOOPBACK &&
5060 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5061 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5062 		error = -1;
5063 		goto bad_addr;
5064 	}
5065 
5066 	/*
5067 	 * Allow setting new policies. For example, disconnects come
5068 	 * down as ipa_t bind. As we would have set conn_policy_cached
5069 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5070 	 * can change after the disconnect.
5071 	 */
5072 	connp->conn_policy_cached = B_FALSE;
5073 
5074 	/*
5075 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5076 	 * can handle their passed-in conn's.
5077 	 */
5078 
5079 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5080 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5081 	connp->conn_lport = lport;
5082 	connp->conn_fport = fport;
5083 	*src_addrp = src_addr;
5084 
5085 	ASSERT(!(ipsec_policy_set && ire_requested));
5086 	if (ire_requested) {
5087 		iulp_t *ulp_info = NULL;
5088 
5089 		/*
5090 		 * Note that sire will not be NULL if this is an off-link
5091 		 * connection and there is not cache for that dest yet.
5092 		 *
5093 		 * XXX Because of an existing bug, if there are multiple
5094 		 * default routes, the IRE returned now may not be the actual
5095 		 * default route used (default routes are chosen in a
5096 		 * round robin fashion).  So if the metrics for different
5097 		 * default routes are different, we may return the wrong
5098 		 * metrics.  This will not be a problem if the existing
5099 		 * bug is fixed.
5100 		 */
5101 		if (sire != NULL) {
5102 			ulp_info = &(sire->ire_uinfo);
5103 		}
5104 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info, ipst)) {
5105 			error = -1;
5106 			goto bad_addr;
5107 		}
5108 	} else if (ipsec_policy_set) {
5109 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5110 			error = -1;
5111 			goto bad_addr;
5112 		}
5113 	}
5114 
5115 	/*
5116 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5117 	 * we'll cache that.  If we don't, we'll inherit global policy.
5118 	 *
5119 	 * We can't insert until the conn reflects the policy. Note that
5120 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5121 	 * connections where we don't have a policy. This is to prevent
5122 	 * global policy lookups in the inbound path.
5123 	 *
5124 	 * If we insert before we set conn_policy_cached,
5125 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5126 	 * because global policy cound be non-empty. We normally call
5127 	 * ipsec_check_policy() for conn_policy_cached connections only if
5128 	 * ipc_in_enforce_policy is set. But in this case,
5129 	 * conn_policy_cached can get set anytime since we made the
5130 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5131 	 * called, which will make the above assumption false.  Thus, we
5132 	 * need to insert after we set conn_policy_cached.
5133 	 */
5134 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5135 		goto bad_addr;
5136 
5137 	if (fanout_insert) {
5138 		/*
5139 		 * The addresses have been verified. Time to insert in
5140 		 * the correct fanout list.
5141 		 */
5142 		error = ipcl_conn_insert(connp, protocol, src_addr,
5143 		    dst_addr, connp->conn_ports);
5144 	}
5145 
5146 	if (error == 0) {
5147 		connp->conn_fully_bound = B_TRUE;
5148 		/*
5149 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5150 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5151 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5152 		 * ip_xxinfo_return(), which performs further checks
5153 		 * against them and upon success, returns the LSO/MDT info
5154 		 * mblk which we will attach to the bind acknowledgment.
5155 		 */
5156 		if (lso_dst_ire != NULL) {
5157 			mblk_t *lsoinfo_mp;
5158 
5159 			ASSERT(ill->ill_lso_capab != NULL);
5160 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5161 			    ill->ill_name, ill->ill_lso_capab)) != NULL)
5162 				linkb(mp, lsoinfo_mp);
5163 		} else if (md_dst_ire != NULL) {
5164 			mblk_t *mdinfo_mp;
5165 
5166 			ASSERT(ill->ill_mdt_capab != NULL);
5167 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5168 			    ill->ill_name, ill->ill_mdt_capab)) != NULL)
5169 				linkb(mp, mdinfo_mp);
5170 		}
5171 	}
5172 bad_addr:
5173 	if (ipsec_policy_set) {
5174 		ASSERT(policy_mp == mp->b_cont);
5175 		ASSERT(policy_mp != NULL);
5176 		freeb(policy_mp);
5177 		/*
5178 		 * As of now assume that nothing else accompanies
5179 		 * IPSEC_POLICY_SET.
5180 		 */
5181 		mp->b_cont = NULL;
5182 	}
5183 	if (src_ire != NULL)
5184 		IRE_REFRELE(src_ire);
5185 	if (dst_ire != NULL)
5186 		IRE_REFRELE(dst_ire);
5187 	if (sire != NULL)
5188 		IRE_REFRELE(sire);
5189 	if (md_dst_ire != NULL)
5190 		IRE_REFRELE(md_dst_ire);
5191 	if (lso_dst_ire != NULL)
5192 		IRE_REFRELE(lso_dst_ire);
5193 	return (error);
5194 }
5195 
5196 /*
5197  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5198  * Prefers dst_ire over src_ire.
5199  */
5200 static boolean_t
5201 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5202 {
5203 	mblk_t	*mp1;
5204 	ire_t *ret_ire = NULL;
5205 
5206 	mp1 = mp->b_cont;
5207 	ASSERT(mp1 != NULL);
5208 
5209 	if (ire != NULL) {
5210 		/*
5211 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5212 		 * appended mblk. Its <upper protocol>'s
5213 		 * job to make sure there is room.
5214 		 */
5215 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5216 			return (0);
5217 
5218 		mp1->b_datap->db_type = IRE_DB_TYPE;
5219 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5220 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5221 		ret_ire = (ire_t *)mp1->b_rptr;
5222 		/*
5223 		 * Pass the latest setting of the ip_path_mtu_discovery and
5224 		 * copy the ulp info if any.
5225 		 */
5226 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5227 		    IPH_DF : 0;
5228 		if (ulp_info != NULL) {
5229 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5230 			    sizeof (iulp_t));
5231 		}
5232 		ret_ire->ire_mp = mp1;
5233 	} else {
5234 		/*
5235 		 * No IRE was found. Remove IRE mblk.
5236 		 */
5237 		mp->b_cont = mp1->b_cont;
5238 		freeb(mp1);
5239 	}
5240 
5241 	return (1);
5242 }
5243 
5244 /*
5245  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5246  * the final piece where we don't.  Return a pointer to the first mblk in the
5247  * result, and update the pointer to the next mblk to chew on.  If anything
5248  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5249  * NULL pointer.
5250  */
5251 mblk_t *
5252 ip_carve_mp(mblk_t **mpp, ssize_t len)
5253 {
5254 	mblk_t	*mp0;
5255 	mblk_t	*mp1;
5256 	mblk_t	*mp2;
5257 
5258 	if (!len || !mpp || !(mp0 = *mpp))
5259 		return (NULL);
5260 	/* If we aren't going to consume the first mblk, we need a dup. */
5261 	if (mp0->b_wptr - mp0->b_rptr > len) {
5262 		mp1 = dupb(mp0);
5263 		if (mp1) {
5264 			/* Partition the data between the two mblks. */
5265 			mp1->b_wptr = mp1->b_rptr + len;
5266 			mp0->b_rptr = mp1->b_wptr;
5267 			/*
5268 			 * after adjustments if mblk not consumed is now
5269 			 * unaligned, try to align it. If this fails free
5270 			 * all messages and let upper layer recover.
5271 			 */
5272 			if (!OK_32PTR(mp0->b_rptr)) {
5273 				if (!pullupmsg(mp0, -1)) {
5274 					freemsg(mp0);
5275 					freemsg(mp1);
5276 					*mpp = NULL;
5277 					return (NULL);
5278 				}
5279 			}
5280 		}
5281 		return (mp1);
5282 	}
5283 	/* Eat through as many mblks as we need to get len bytes. */
5284 	len -= mp0->b_wptr - mp0->b_rptr;
5285 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5286 		if (mp2->b_wptr - mp2->b_rptr > len) {
5287 			/*
5288 			 * We won't consume the entire last mblk.  Like
5289 			 * above, dup and partition it.
5290 			 */
5291 			mp1->b_cont = dupb(mp2);
5292 			mp1 = mp1->b_cont;
5293 			if (!mp1) {
5294 				/*
5295 				 * Trouble.  Rather than go to a lot of
5296 				 * trouble to clean up, we free the messages.
5297 				 * This won't be any worse than losing it on
5298 				 * the wire.
5299 				 */
5300 				freemsg(mp0);
5301 				freemsg(mp2);
5302 				*mpp = NULL;
5303 				return (NULL);
5304 			}
5305 			mp1->b_wptr = mp1->b_rptr + len;
5306 			mp2->b_rptr = mp1->b_wptr;
5307 			/*
5308 			 * after adjustments if mblk not consumed is now
5309 			 * unaligned, try to align it. If this fails free
5310 			 * all messages and let upper layer recover.
5311 			 */
5312 			if (!OK_32PTR(mp2->b_rptr)) {
5313 				if (!pullupmsg(mp2, -1)) {
5314 					freemsg(mp0);
5315 					freemsg(mp2);
5316 					*mpp = NULL;
5317 					return (NULL);
5318 				}
5319 			}
5320 			*mpp = mp2;
5321 			return (mp0);
5322 		}
5323 		/* Decrement len by the amount we just got. */
5324 		len -= mp2->b_wptr - mp2->b_rptr;
5325 	}
5326 	/*
5327 	 * len should be reduced to zero now.  If not our caller has
5328 	 * screwed up.
5329 	 */
5330 	if (len) {
5331 		/* Shouldn't happen! */
5332 		freemsg(mp0);
5333 		*mpp = NULL;
5334 		return (NULL);
5335 	}
5336 	/*
5337 	 * We consumed up to exactly the end of an mblk.  Detach the part
5338 	 * we are returning from the rest of the chain.
5339 	 */
5340 	mp1->b_cont = NULL;
5341 	*mpp = mp2;
5342 	return (mp0);
5343 }
5344 
5345 /* The ill stream is being unplumbed. Called from ip_close */
5346 int
5347 ip_modclose(ill_t *ill)
5348 {
5349 	boolean_t success;
5350 	ipsq_t	*ipsq;
5351 	ipif_t	*ipif;
5352 	queue_t	*q = ill->ill_rq;
5353 	ip_stack_t	*ipst = ill->ill_ipst;
5354 	clock_t timeout;
5355 
5356 	/*
5357 	 * Wait for the ACKs of all deferred control messages to be processed.
5358 	 * In particular, we wait for a potential capability reset initiated
5359 	 * in ip_sioctl_plink() to complete before proceeding.
5360 	 *
5361 	 * Note: we wait for at most ip_modclose_ackwait_ms (by default 3000 ms)
5362 	 * in case the driver never replies.
5363 	 */
5364 	timeout = lbolt + MSEC_TO_TICK(ip_modclose_ackwait_ms);
5365 	mutex_enter(&ill->ill_lock);
5366 	while (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
5367 		if (cv_timedwait(&ill->ill_cv, &ill->ill_lock, timeout) < 0) {
5368 			/* Timeout */
5369 			break;
5370 		}
5371 	}
5372 	mutex_exit(&ill->ill_lock);
5373 
5374 	/*
5375 	 * Forcibly enter the ipsq after some delay. This is to take
5376 	 * care of the case when some ioctl does not complete because
5377 	 * we sent a control message to the driver and it did not
5378 	 * send us a reply. We want to be able to at least unplumb
5379 	 * and replumb rather than force the user to reboot the system.
5380 	 */
5381 	success = ipsq_enter(ill, B_FALSE);
5382 
5383 	/*
5384 	 * Open/close/push/pop is guaranteed to be single threaded
5385 	 * per stream by STREAMS. FS guarantees that all references
5386 	 * from top are gone before close is called. So there can't
5387 	 * be another close thread that has set CONDEMNED on this ill.
5388 	 * and cause ipsq_enter to return failure.
5389 	 */
5390 	ASSERT(success);
5391 	ipsq = ill->ill_phyint->phyint_ipsq;
5392 
5393 	/*
5394 	 * Mark it condemned. No new reference will be made to this ill.
5395 	 * Lookup functions will return an error. Threads that try to
5396 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5397 	 * that the refcnt will drop down to zero.
5398 	 */
5399 	mutex_enter(&ill->ill_lock);
5400 	ill->ill_state_flags |= ILL_CONDEMNED;
5401 	for (ipif = ill->ill_ipif; ipif != NULL;
5402 	    ipif = ipif->ipif_next) {
5403 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5404 	}
5405 	/*
5406 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5407 	 * returns  error if ILL_CONDEMNED is set
5408 	 */
5409 	cv_broadcast(&ill->ill_cv);
5410 	mutex_exit(&ill->ill_lock);
5411 
5412 	/*
5413 	 * Send all the deferred DLPI messages downstream which came in
5414 	 * during the small window right before ipsq_enter(). We do this
5415 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5416 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5417 	 */
5418 	ill_dlpi_send_deferred(ill);
5419 
5420 	/*
5421 	 * Shut down fragmentation reassembly.
5422 	 * ill_frag_timer won't start a timer again.
5423 	 * Now cancel any existing timer
5424 	 */
5425 	(void) untimeout(ill->ill_frag_timer_id);
5426 	(void) ill_frag_timeout(ill, 0);
5427 
5428 	/*
5429 	 * If MOVE was in progress, clear the
5430 	 * move_in_progress fields also.
5431 	 */
5432 	if (ill->ill_move_in_progress) {
5433 		ILL_CLEAR_MOVE(ill);
5434 	}
5435 
5436 	/*
5437 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5438 	 * this ill. Then wait for the refcnts to drop to zero.
5439 	 * ill_is_quiescent checks whether the ill is really quiescent.
5440 	 * Then make sure that threads that are waiting to enter the
5441 	 * ipsq have seen the error returned by ipsq_enter and have
5442 	 * gone away. Then we call ill_delete_tail which does the
5443 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5444 	 */
5445 	ill_delete(ill);
5446 	mutex_enter(&ill->ill_lock);
5447 	while (!ill_is_quiescent(ill))
5448 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5449 	while (ill->ill_waiters)
5450 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5451 
5452 	mutex_exit(&ill->ill_lock);
5453 
5454 	/*
5455 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5456 	 * it held until the end of the function since the cleanup
5457 	 * below needs to be able to use the ip_stack_t.
5458 	 */
5459 	netstack_hold(ipst->ips_netstack);
5460 
5461 	/* qprocsoff is called in ill_delete_tail */
5462 	ill_delete_tail(ill);
5463 	ASSERT(ill->ill_ipst == NULL);
5464 
5465 	/*
5466 	 * Walk through all upper (conn) streams and qenable
5467 	 * those that have queued data.
5468 	 * close synchronization needs this to
5469 	 * be done to ensure that all upper layers blocked
5470 	 * due to flow control to the closing device
5471 	 * get unblocked.
5472 	 */
5473 	ip1dbg(("ip_wsrv: walking\n"));
5474 	conn_walk_drain(ipst);
5475 
5476 	mutex_enter(&ipst->ips_ip_mi_lock);
5477 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5478 	mutex_exit(&ipst->ips_ip_mi_lock);
5479 
5480 	/*
5481 	 * credp could be null if the open didn't succeed and ip_modopen
5482 	 * itself calls ip_close.
5483 	 */
5484 	if (ill->ill_credp != NULL)
5485 		crfree(ill->ill_credp);
5486 
5487 	mutex_enter(&ill->ill_lock);
5488 	ill_nic_info_dispatch(ill);
5489 	mutex_exit(&ill->ill_lock);
5490 
5491 	/*
5492 	 * Now we are done with the module close pieces that
5493 	 * need the netstack_t.
5494 	 */
5495 	netstack_rele(ipst->ips_netstack);
5496 
5497 	mi_close_free((IDP)ill);
5498 	q->q_ptr = WR(q)->q_ptr = NULL;
5499 
5500 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5501 
5502 	return (0);
5503 }
5504 
5505 /*
5506  * This is called as part of close() for IP, UDP, ICMP, and RTS
5507  * in order to quiesce the conn.
5508  */
5509 void
5510 ip_quiesce_conn(conn_t *connp)
5511 {
5512 	boolean_t	drain_cleanup_reqd = B_FALSE;
5513 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5514 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5515 	ip_stack_t	*ipst;
5516 
5517 	ASSERT(!IPCL_IS_TCP(connp));
5518 	ipst = connp->conn_netstack->netstack_ip;
5519 
5520 	/*
5521 	 * Mark the conn as closing, and this conn must not be
5522 	 * inserted in future into any list. Eg. conn_drain_insert(),
5523 	 * won't insert this conn into the conn_drain_list.
5524 	 * Similarly ill_pending_mp_add() will not add any mp to
5525 	 * the pending mp list, after this conn has started closing.
5526 	 *
5527 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5528 	 * cannot get set henceforth.
5529 	 */
5530 	mutex_enter(&connp->conn_lock);
5531 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5532 	connp->conn_state_flags |= CONN_CLOSING;
5533 	if (connp->conn_idl != NULL)
5534 		drain_cleanup_reqd = B_TRUE;
5535 	if (connp->conn_oper_pending_ill != NULL)
5536 		conn_ioctl_cleanup_reqd = B_TRUE;
5537 	if (connp->conn_dhcpinit_ill != NULL) {
5538 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
5539 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
5540 		connp->conn_dhcpinit_ill = NULL;
5541 	}
5542 	if (connp->conn_ilg_inuse != 0)
5543 		ilg_cleanup_reqd = B_TRUE;
5544 	mutex_exit(&connp->conn_lock);
5545 
5546 	if (conn_ioctl_cleanup_reqd)
5547 		conn_ioctl_cleanup(connp);
5548 
5549 	if (is_system_labeled() && connp->conn_anon_port) {
5550 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5551 		    connp->conn_mlp_type, connp->conn_ulp,
5552 		    ntohs(connp->conn_lport), B_FALSE);
5553 		connp->conn_anon_port = 0;
5554 	}
5555 	connp->conn_mlp_type = mlptSingle;
5556 
5557 	/*
5558 	 * Remove this conn from any fanout list it is on.
5559 	 * and then wait for any threads currently operating
5560 	 * on this endpoint to finish
5561 	 */
5562 	ipcl_hash_remove(connp);
5563 
5564 	/*
5565 	 * Remove this conn from the drain list, and do
5566 	 * any other cleanup that may be required.
5567 	 * (Only non-tcp streams may have a non-null conn_idl.
5568 	 * TCP streams are never flow controlled, and
5569 	 * conn_idl will be null)
5570 	 */
5571 	if (drain_cleanup_reqd)
5572 		conn_drain_tail(connp, B_TRUE);
5573 
5574 	if (connp == ipst->ips_ip_g_mrouter)
5575 		(void) ip_mrouter_done(NULL, ipst);
5576 
5577 	if (ilg_cleanup_reqd)
5578 		ilg_delete_all(connp);
5579 
5580 	conn_delete_ire(connp, NULL);
5581 
5582 	/*
5583 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5584 	 * callers from write side can't be there now because close
5585 	 * is in progress. The only other caller is ipcl_walk
5586 	 * which checks for the condemned flag.
5587 	 */
5588 	mutex_enter(&connp->conn_lock);
5589 	connp->conn_state_flags |= CONN_CONDEMNED;
5590 	while (connp->conn_ref != 1)
5591 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5592 	connp->conn_state_flags |= CONN_QUIESCED;
5593 	mutex_exit(&connp->conn_lock);
5594 }
5595 
5596 /* ARGSUSED */
5597 int
5598 ip_close(queue_t *q, int flags)
5599 {
5600 	conn_t		*connp;
5601 
5602 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5603 
5604 	/*
5605 	 * Call the appropriate delete routine depending on whether this is
5606 	 * a module or device.
5607 	 */
5608 	if (WR(q)->q_next != NULL) {
5609 		/* This is a module close */
5610 		return (ip_modclose((ill_t *)q->q_ptr));
5611 	}
5612 
5613 	connp = q->q_ptr;
5614 	ip_quiesce_conn(connp);
5615 
5616 	qprocsoff(q);
5617 
5618 	/*
5619 	 * Now we are truly single threaded on this stream, and can
5620 	 * delete the things hanging off the connp, and finally the connp.
5621 	 * We removed this connp from the fanout list, it cannot be
5622 	 * accessed thru the fanouts, and we already waited for the
5623 	 * conn_ref to drop to 0. We are already in close, so
5624 	 * there cannot be any other thread from the top. qprocsoff
5625 	 * has completed, and service has completed or won't run in
5626 	 * future.
5627 	 */
5628 	ASSERT(connp->conn_ref == 1);
5629 
5630 	inet_minor_free(ip_minor_arena, connp->conn_dev);
5631 
5632 	connp->conn_ref--;
5633 	ipcl_conn_destroy(connp);
5634 
5635 	q->q_ptr = WR(q)->q_ptr = NULL;
5636 	return (0);
5637 }
5638 
5639 /*
5640  * Wapper around putnext() so that ip_rts_request can merely use
5641  * conn_recv.
5642  */
5643 /*ARGSUSED2*/
5644 static void
5645 ip_conn_input(void *arg1, mblk_t *mp, void *arg2)
5646 {
5647 	conn_t *connp = (conn_t *)arg1;
5648 
5649 	putnext(connp->conn_rq, mp);
5650 }
5651 
5652 /* Return the IP checksum for the IP header at "iph". */
5653 uint16_t
5654 ip_csum_hdr(ipha_t *ipha)
5655 {
5656 	uint16_t	*uph;
5657 	uint32_t	sum;
5658 	int		opt_len;
5659 
5660 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5661 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5662 	uph = (uint16_t *)ipha;
5663 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5664 	    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5665 	if (opt_len > 0) {
5666 		do {
5667 			sum += uph[10];
5668 			sum += uph[11];
5669 			uph += 2;
5670 		} while (--opt_len);
5671 	}
5672 	sum = (sum & 0xFFFF) + (sum >> 16);
5673 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5674 	if (sum == 0xffff)
5675 		sum = 0;
5676 	return ((uint16_t)sum);
5677 }
5678 
5679 /*
5680  * Called when the module is about to be unloaded
5681  */
5682 void
5683 ip_ddi_destroy(void)
5684 {
5685 	tnet_fini();
5686 
5687 	icmp_ddi_destroy();
5688 	rts_ddi_destroy();
5689 	udp_ddi_destroy();
5690 	sctp_ddi_g_destroy();
5691 	tcp_ddi_g_destroy();
5692 	ipsec_policy_g_destroy();
5693 	ipcl_g_destroy();
5694 	ip_net_g_destroy();
5695 	ip_ire_g_fini();
5696 	inet_minor_destroy(ip_minor_arena);
5697 
5698 #ifdef DEBUG
5699 	list_destroy(&ip_thread_list);
5700 	rw_destroy(&ip_thread_rwlock);
5701 	tsd_destroy(&ip_thread_data);
5702 #endif
5703 
5704 	netstack_unregister(NS_IP);
5705 }
5706 
5707 /*
5708  * First step in cleanup.
5709  */
5710 /* ARGSUSED */
5711 static void
5712 ip_stack_shutdown(netstackid_t stackid, void *arg)
5713 {
5714 	ip_stack_t *ipst = (ip_stack_t *)arg;
5715 
5716 #ifdef NS_DEBUG
5717 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5718 #endif
5719 
5720 	/* Get rid of loopback interfaces and their IREs */
5721 	ip_loopback_cleanup(ipst);
5722 }
5723 
5724 /*
5725  * Free the IP stack instance.
5726  */
5727 static void
5728 ip_stack_fini(netstackid_t stackid, void *arg)
5729 {
5730 	ip_stack_t *ipst = (ip_stack_t *)arg;
5731 	int ret;
5732 
5733 #ifdef NS_DEBUG
5734 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5735 #endif
5736 	ipv4_hook_destroy(ipst);
5737 	ipv6_hook_destroy(ipst);
5738 	ip_net_destroy(ipst);
5739 
5740 	rw_destroy(&ipst->ips_srcid_lock);
5741 
5742 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5743 	ipst->ips_ip_mibkp = NULL;
5744 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5745 	ipst->ips_icmp_mibkp = NULL;
5746 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5747 	ipst->ips_ip_kstat = NULL;
5748 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5749 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5750 	ipst->ips_ip6_kstat = NULL;
5751 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5752 
5753 	nd_free(&ipst->ips_ip_g_nd);
5754 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5755 	ipst->ips_param_arr = NULL;
5756 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5757 	ipst->ips_ndp_arr = NULL;
5758 
5759 	ip_mrouter_stack_destroy(ipst);
5760 
5761 	mutex_destroy(&ipst->ips_ip_mi_lock);
5762 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5763 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5764 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5765 
5766 	ret = untimeout(ipst->ips_igmp_timeout_id);
5767 	if (ret == -1) {
5768 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5769 	} else {
5770 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5771 		ipst->ips_igmp_timeout_id = 0;
5772 	}
5773 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5774 	if (ret == -1) {
5775 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5776 	} else {
5777 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5778 		ipst->ips_igmp_slowtimeout_id = 0;
5779 	}
5780 	ret = untimeout(ipst->ips_mld_timeout_id);
5781 	if (ret == -1) {
5782 		ASSERT(ipst->ips_mld_timeout_id == 0);
5783 	} else {
5784 		ASSERT(ipst->ips_mld_timeout_id != 0);
5785 		ipst->ips_mld_timeout_id = 0;
5786 	}
5787 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5788 	if (ret == -1) {
5789 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5790 	} else {
5791 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5792 		ipst->ips_mld_slowtimeout_id = 0;
5793 	}
5794 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5795 	if (ret == -1) {
5796 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5797 	} else {
5798 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5799 		ipst->ips_ip_ire_expire_id = 0;
5800 	}
5801 
5802 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5803 	mutex_destroy(&ipst->ips_mld_timer_lock);
5804 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5805 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5806 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5807 	rw_destroy(&ipst->ips_ill_g_lock);
5808 
5809 	ip_ire_fini(ipst);
5810 	ip6_asp_free(ipst);
5811 	conn_drain_fini(ipst);
5812 	ipcl_destroy(ipst);
5813 
5814 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5815 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5816 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5817 	ipst->ips_ndp4 = NULL;
5818 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5819 	ipst->ips_ndp6 = NULL;
5820 
5821 	if (ipst->ips_loopback_ksp != NULL) {
5822 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5823 		ipst->ips_loopback_ksp = NULL;
5824 	}
5825 
5826 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5827 	ipst->ips_phyint_g_list = NULL;
5828 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5829 	ipst->ips_ill_g_heads = NULL;
5830 
5831 	kmem_free(ipst, sizeof (*ipst));
5832 }
5833 
5834 /*
5835  * This function is called from the TSD destructor, and is used to debug
5836  * reference count issues in IP. See block comment in <inet/ip_if.h> for
5837  * details.
5838  */
5839 static void
5840 ip_thread_exit(void *phash)
5841 {
5842 	th_hash_t *thh = phash;
5843 
5844 	rw_enter(&ip_thread_rwlock, RW_WRITER);
5845 	list_remove(&ip_thread_list, thh);
5846 	rw_exit(&ip_thread_rwlock);
5847 	mod_hash_destroy_hash(thh->thh_hash);
5848 	kmem_free(thh, sizeof (*thh));
5849 }
5850 
5851 /*
5852  * Called when the IP kernel module is loaded into the kernel
5853  */
5854 void
5855 ip_ddi_init(void)
5856 {
5857 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5858 
5859 	/*
5860 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5861 	 * initial devices: ip, ip6, tcp, tcp6.
5862 	 */
5863 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
5864 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
5865 		cmn_err(CE_PANIC,
5866 		    "ip_ddi_init: ip_minor_arena creation failed\n");
5867 	}
5868 
5869 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5870 
5871 	ipcl_g_init();
5872 	ip_ire_g_init();
5873 	ip_net_g_init();
5874 
5875 #ifdef DEBUG
5876 	tsd_create(&ip_thread_data, ip_thread_exit);
5877 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
5878 	list_create(&ip_thread_list, sizeof (th_hash_t),
5879 	    offsetof(th_hash_t, thh_link));
5880 #endif
5881 
5882 	/*
5883 	 * We want to be informed each time a stack is created or
5884 	 * destroyed in the kernel, so we can maintain the
5885 	 * set of udp_stack_t's.
5886 	 */
5887 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5888 	    ip_stack_fini);
5889 
5890 	ipsec_policy_g_init();
5891 	tcp_ddi_g_init();
5892 	sctp_ddi_g_init();
5893 
5894 	tnet_init();
5895 
5896 	udp_ddi_init();
5897 	rts_ddi_init();
5898 	icmp_ddi_init();
5899 }
5900 
5901 /*
5902  * Initialize the IP stack instance.
5903  */
5904 static void *
5905 ip_stack_init(netstackid_t stackid, netstack_t *ns)
5906 {
5907 	ip_stack_t	*ipst;
5908 	ipparam_t	*pa;
5909 	ipndp_t		*na;
5910 
5911 #ifdef NS_DEBUG
5912 	printf("ip_stack_init(stack %d)\n", stackid);
5913 #endif
5914 
5915 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
5916 	ipst->ips_netstack = ns;
5917 
5918 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
5919 	    KM_SLEEP);
5920 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
5921 	    KM_SLEEP);
5922 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5923 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5924 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5925 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5926 
5927 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5928 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5929 	ipst->ips_igmp_deferred_next = INFINITY;
5930 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5931 	ipst->ips_mld_deferred_next = INFINITY;
5932 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5933 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5934 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5935 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5936 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
5937 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5938 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5939 
5940 	ipcl_init(ipst);
5941 	ip_ire_init(ipst);
5942 	ip6_asp_init(ipst);
5943 	ipif_init(ipst);
5944 	conn_drain_init(ipst);
5945 	ip_mrouter_stack_init(ipst);
5946 
5947 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
5948 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
5949 
5950 	ipst->ips_ip_multirt_log_interval = 1000;
5951 
5952 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
5953 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
5954 	ipst->ips_ill_index = 1;
5955 
5956 	ipst->ips_saved_ip_g_forward = -1;
5957 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
5958 
5959 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
5960 	ipst->ips_param_arr = pa;
5961 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
5962 
5963 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
5964 	ipst->ips_ndp_arr = na;
5965 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5966 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
5967 	    (caddr_t)&ipst->ips_ip_g_forward;
5968 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
5969 	    (caddr_t)&ipst->ips_ipv6_forward;
5970 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
5971 	    "ip_cgtp_filter") == 0);
5972 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
5973 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
5974 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_name,
5975 	    "ipmp_hook_emulation") == 0);
5976 	ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_data =
5977 	    (caddr_t)&ipst->ips_ipmp_hook_emulation;
5978 
5979 	(void) ip_param_register(&ipst->ips_ip_g_nd,
5980 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
5981 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
5982 
5983 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
5984 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
5985 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
5986 	ipst->ips_ip6_kstat =
5987 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
5988 
5989 	ipst->ips_ipmp_enable_failback = B_TRUE;
5990 
5991 	ipst->ips_ip_src_id = 1;
5992 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
5993 
5994 	ip_net_init(ipst, ns);
5995 	ipv4_hook_init(ipst);
5996 	ipv6_hook_init(ipst);
5997 
5998 	return (ipst);
5999 }
6000 
6001 /*
6002  * Allocate and initialize a DLPI template of the specified length.  (May be
6003  * called as writer.)
6004  */
6005 mblk_t *
6006 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6007 {
6008 	mblk_t	*mp;
6009 
6010 	mp = allocb(len, BPRI_MED);
6011 	if (!mp)
6012 		return (NULL);
6013 
6014 	/*
6015 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6016 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6017 	 * that other DLPI are M_PROTO.
6018 	 */
6019 	if (prim == DL_INFO_REQ) {
6020 		mp->b_datap->db_type = M_PCPROTO;
6021 	} else {
6022 		mp->b_datap->db_type = M_PROTO;
6023 	}
6024 
6025 	mp->b_wptr = mp->b_rptr + len;
6026 	bzero(mp->b_rptr, len);
6027 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6028 	return (mp);
6029 }
6030 
6031 const char *
6032 dlpi_prim_str(int prim)
6033 {
6034 	switch (prim) {
6035 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
6036 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
6037 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
6038 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
6039 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
6040 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
6041 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
6042 	case DL_OK_ACK:		return ("DL_OK_ACK");
6043 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
6044 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
6045 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
6046 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
6047 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
6048 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
6049 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
6050 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
6051 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
6052 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
6053 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
6054 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
6055 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
6056 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
6057 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
6058 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
6059 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
6060 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
6061 	default:		return ("<unknown primitive>");
6062 	}
6063 }
6064 
6065 const char *
6066 dlpi_err_str(int err)
6067 {
6068 	switch (err) {
6069 	case DL_ACCESS:		return ("DL_ACCESS");
6070 	case DL_BADADDR:	return ("DL_BADADDR");
6071 	case DL_BADCORR:	return ("DL_BADCORR");
6072 	case DL_BADDATA:	return ("DL_BADDATA");
6073 	case DL_BADPPA:		return ("DL_BADPPA");
6074 	case DL_BADPRIM:	return ("DL_BADPRIM");
6075 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
6076 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
6077 	case DL_BADSAP:		return ("DL_BADSAP");
6078 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
6079 	case DL_BOUND:		return ("DL_BOUND");
6080 	case DL_INITFAILED:	return ("DL_INITFAILED");
6081 	case DL_NOADDR:		return ("DL_NOADDR");
6082 	case DL_NOTINIT:	return ("DL_NOTINIT");
6083 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
6084 	case DL_SYSERR:		return ("DL_SYSERR");
6085 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
6086 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
6087 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
6088 	case DL_TOOMANY:	return ("DL_TOOMANY");
6089 	case DL_NOTENAB:	return ("DL_NOTENAB");
6090 	case DL_BUSY:		return ("DL_BUSY");
6091 	case DL_NOAUTO:		return ("DL_NOAUTO");
6092 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
6093 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
6094 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
6095 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
6096 	case DL_PENDING:	return ("DL_PENDING");
6097 	default:		return ("<unknown error>");
6098 	}
6099 }
6100 
6101 /*
6102  * Debug formatting routine.  Returns a character string representation of the
6103  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6104  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6105  *
6106  * Once the ndd table-printing interfaces are removed, this can be changed to
6107  * standard dotted-decimal form.
6108  */
6109 char *
6110 ip_dot_addr(ipaddr_t addr, char *buf)
6111 {
6112 	uint8_t *ap = (uint8_t *)&addr;
6113 
6114 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6115 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6116 	return (buf);
6117 }
6118 
6119 /*
6120  * Write the given MAC address as a printable string in the usual colon-
6121  * separated format.
6122  */
6123 const char *
6124 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6125 {
6126 	char *bp;
6127 
6128 	if (alen == 0 || buflen < 4)
6129 		return ("?");
6130 	bp = buf;
6131 	for (;;) {
6132 		/*
6133 		 * If there are more MAC address bytes available, but we won't
6134 		 * have any room to print them, then add "..." to the string
6135 		 * instead.  See below for the 'magic number' explanation.
6136 		 */
6137 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6138 			(void) strcpy(bp, "...");
6139 			break;
6140 		}
6141 		(void) sprintf(bp, "%02x", *addr++);
6142 		bp += 2;
6143 		if (--alen == 0)
6144 			break;
6145 		*bp++ = ':';
6146 		buflen -= 3;
6147 		/*
6148 		 * At this point, based on the first 'if' statement above,
6149 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6150 		 * buflen >= 4.  The first case leaves room for the final "xx"
6151 		 * number and trailing NUL byte.  The second leaves room for at
6152 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6153 		 * that statement.
6154 		 */
6155 	}
6156 	return (buf);
6157 }
6158 
6159 /*
6160  * Send an ICMP error after patching up the packet appropriately.  Returns
6161  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6162  */
6163 static boolean_t
6164 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6165     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6166     zoneid_t zoneid, ip_stack_t *ipst)
6167 {
6168 	ipha_t *ipha;
6169 	mblk_t *first_mp;
6170 	boolean_t secure;
6171 	unsigned char db_type;
6172 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6173 
6174 	first_mp = mp;
6175 	if (mctl_present) {
6176 		mp = mp->b_cont;
6177 		secure = ipsec_in_is_secure(first_mp);
6178 		ASSERT(mp != NULL);
6179 	} else {
6180 		/*
6181 		 * If this is an ICMP error being reported - which goes
6182 		 * up as M_CTLs, we need to convert them to M_DATA till
6183 		 * we finish checking with global policy because
6184 		 * ipsec_check_global_policy() assumes M_DATA as clear
6185 		 * and M_CTL as secure.
6186 		 */
6187 		db_type = DB_TYPE(mp);
6188 		DB_TYPE(mp) = M_DATA;
6189 		secure = B_FALSE;
6190 	}
6191 	/*
6192 	 * We are generating an icmp error for some inbound packet.
6193 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6194 	 * Before we generate an error, check with global policy
6195 	 * to see whether this is allowed to enter the system. As
6196 	 * there is no "conn", we are checking with global policy.
6197 	 */
6198 	ipha = (ipha_t *)mp->b_rptr;
6199 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6200 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6201 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6202 		if (first_mp == NULL)
6203 			return (B_FALSE);
6204 	}
6205 
6206 	if (!mctl_present)
6207 		DB_TYPE(mp) = db_type;
6208 
6209 	if (flags & IP_FF_SEND_ICMP) {
6210 		if (flags & IP_FF_HDR_COMPLETE) {
6211 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6212 				freemsg(first_mp);
6213 				return (B_TRUE);
6214 			}
6215 		}
6216 		if (flags & IP_FF_CKSUM) {
6217 			/*
6218 			 * Have to correct checksum since
6219 			 * the packet might have been
6220 			 * fragmented and the reassembly code in ip_rput
6221 			 * does not restore the IP checksum.
6222 			 */
6223 			ipha->ipha_hdr_checksum = 0;
6224 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6225 		}
6226 		switch (icmp_type) {
6227 		case ICMP_DEST_UNREACHABLE:
6228 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6229 			    ipst);
6230 			break;
6231 		default:
6232 			freemsg(first_mp);
6233 			break;
6234 		}
6235 	} else {
6236 		freemsg(first_mp);
6237 		return (B_FALSE);
6238 	}
6239 
6240 	return (B_TRUE);
6241 }
6242 
6243 /*
6244  * Used to send an ICMP error message when a packet is received for
6245  * a protocol that is not supported. The mblk passed as argument
6246  * is consumed by this function.
6247  */
6248 void
6249 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6250     ip_stack_t *ipst)
6251 {
6252 	mblk_t *mp;
6253 	ipha_t *ipha;
6254 	ill_t *ill;
6255 	ipsec_in_t *ii;
6256 
6257 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6258 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6259 
6260 	mp = ipsec_mp->b_cont;
6261 	ipsec_mp->b_cont = NULL;
6262 	ipha = (ipha_t *)mp->b_rptr;
6263 	/* Get ill from index in ipsec_in_t. */
6264 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6265 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6266 	    ipst);
6267 	if (ill != NULL) {
6268 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6269 			if (ip_fanout_send_icmp(q, mp, flags,
6270 			    ICMP_DEST_UNREACHABLE,
6271 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6272 				BUMP_MIB(ill->ill_ip_mib,
6273 				    ipIfStatsInUnknownProtos);
6274 			}
6275 		} else {
6276 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6277 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6278 			    0, B_FALSE, zoneid, ipst)) {
6279 				BUMP_MIB(ill->ill_ip_mib,
6280 				    ipIfStatsInUnknownProtos);
6281 			}
6282 		}
6283 		ill_refrele(ill);
6284 	} else { /* re-link for the freemsg() below. */
6285 		ipsec_mp->b_cont = mp;
6286 	}
6287 
6288 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6289 	freemsg(ipsec_mp);
6290 }
6291 
6292 /*
6293  * See if the inbound datagram has had IPsec processing applied to it.
6294  */
6295 boolean_t
6296 ipsec_in_is_secure(mblk_t *ipsec_mp)
6297 {
6298 	ipsec_in_t *ii;
6299 
6300 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6301 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6302 
6303 	if (ii->ipsec_in_loopback) {
6304 		return (ii->ipsec_in_secure);
6305 	} else {
6306 		return (ii->ipsec_in_ah_sa != NULL ||
6307 		    ii->ipsec_in_esp_sa != NULL ||
6308 		    ii->ipsec_in_decaps);
6309 	}
6310 }
6311 
6312 /*
6313  * Handle protocols with which IP is less intimate.  There
6314  * can be more than one stream bound to a particular
6315  * protocol.  When this is the case, normally each one gets a copy
6316  * of any incoming packets.
6317  *
6318  * IPsec NOTE :
6319  *
6320  * Don't allow a secure packet going up a non-secure connection.
6321  * We don't allow this because
6322  *
6323  * 1) Reply might go out in clear which will be dropped at
6324  *    the sending side.
6325  * 2) If the reply goes out in clear it will give the
6326  *    adversary enough information for getting the key in
6327  *    most of the cases.
6328  *
6329  * Moreover getting a secure packet when we expect clear
6330  * implies that SA's were added without checking for
6331  * policy on both ends. This should not happen once ISAKMP
6332  * is used to negotiate SAs as SAs will be added only after
6333  * verifying the policy.
6334  *
6335  * NOTE : If the packet was tunneled and not multicast we only send
6336  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6337  * back to delivering packets to AF_INET6 raw sockets.
6338  *
6339  * IPQoS Notes:
6340  * Once we have determined the client, invoke IPPF processing.
6341  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6342  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6343  * ip_policy will be false.
6344  *
6345  * Zones notes:
6346  * Currently only applications in the global zone can create raw sockets for
6347  * protocols other than ICMP. So unlike the broadcast / multicast case of
6348  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6349  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6350  */
6351 static void
6352 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6353     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6354     zoneid_t zoneid)
6355 {
6356 	queue_t	*rq;
6357 	mblk_t	*mp1, *first_mp1;
6358 	uint_t	protocol = ipha->ipha_protocol;
6359 	ipaddr_t dst;
6360 	boolean_t one_only;
6361 	mblk_t *first_mp = mp;
6362 	boolean_t secure;
6363 	uint32_t ill_index;
6364 	conn_t	*connp, *first_connp, *next_connp;
6365 	connf_t	*connfp;
6366 	boolean_t shared_addr;
6367 	mib2_ipIfStatsEntry_t *mibptr;
6368 	ip_stack_t *ipst = recv_ill->ill_ipst;
6369 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6370 
6371 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6372 	if (mctl_present) {
6373 		mp = first_mp->b_cont;
6374 		secure = ipsec_in_is_secure(first_mp);
6375 		ASSERT(mp != NULL);
6376 	} else {
6377 		secure = B_FALSE;
6378 	}
6379 	dst = ipha->ipha_dst;
6380 	/*
6381 	 * If the packet was tunneled and not multicast we only send to it
6382 	 * the first match.
6383 	 */
6384 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6385 	    !CLASSD(dst));
6386 
6387 	shared_addr = (zoneid == ALL_ZONES);
6388 	if (shared_addr) {
6389 		/*
6390 		 * We don't allow multilevel ports for raw IP, so no need to
6391 		 * check for that here.
6392 		 */
6393 		zoneid = tsol_packet_to_zoneid(mp);
6394 	}
6395 
6396 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6397 	mutex_enter(&connfp->connf_lock);
6398 	connp = connfp->connf_head;
6399 	for (connp = connfp->connf_head; connp != NULL;
6400 	    connp = connp->conn_next) {
6401 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6402 		    zoneid) &&
6403 		    (!is_system_labeled() ||
6404 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6405 		    connp))) {
6406 			break;
6407 		}
6408 	}
6409 
6410 	if (connp == NULL || connp->conn_upq == NULL) {
6411 		/*
6412 		 * No one bound to these addresses.  Is
6413 		 * there a client that wants all
6414 		 * unclaimed datagrams?
6415 		 */
6416 		mutex_exit(&connfp->connf_lock);
6417 		/*
6418 		 * Check for IPPROTO_ENCAP...
6419 		 */
6420 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6421 			/*
6422 			 * If an IPsec mblk is here on a multicast
6423 			 * tunnel (using ip_mroute stuff), check policy here,
6424 			 * THEN ship off to ip_mroute_decap().
6425 			 *
6426 			 * BTW,  If I match a configured IP-in-IP
6427 			 * tunnel, this path will not be reached, and
6428 			 * ip_mroute_decap will never be called.
6429 			 */
6430 			first_mp = ipsec_check_global_policy(first_mp, connp,
6431 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6432 			if (first_mp != NULL) {
6433 				if (mctl_present)
6434 					freeb(first_mp);
6435 				ip_mroute_decap(q, mp, ill);
6436 			} /* Else we already freed everything! */
6437 		} else {
6438 			/*
6439 			 * Otherwise send an ICMP protocol unreachable.
6440 			 */
6441 			if (ip_fanout_send_icmp(q, first_mp, flags,
6442 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6443 			    mctl_present, zoneid, ipst)) {
6444 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6445 			}
6446 		}
6447 		return;
6448 	}
6449 	CONN_INC_REF(connp);
6450 	first_connp = connp;
6451 
6452 	/*
6453 	 * Only send message to one tunnel driver by immediately
6454 	 * terminating the loop.
6455 	 */
6456 	connp = one_only ? NULL : connp->conn_next;
6457 
6458 	for (;;) {
6459 		while (connp != NULL) {
6460 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6461 			    flags, zoneid) &&
6462 			    (!is_system_labeled() ||
6463 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6464 			    shared_addr, connp)))
6465 				break;
6466 			connp = connp->conn_next;
6467 		}
6468 
6469 		/*
6470 		 * Copy the packet.
6471 		 */
6472 		if (connp == NULL || connp->conn_upq == NULL ||
6473 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6474 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6475 			/*
6476 			 * No more interested clients or memory
6477 			 * allocation failed
6478 			 */
6479 			connp = first_connp;
6480 			break;
6481 		}
6482 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6483 		CONN_INC_REF(connp);
6484 		mutex_exit(&connfp->connf_lock);
6485 		rq = connp->conn_rq;
6486 		if (!canputnext(rq)) {
6487 			if (flags & IP_FF_RAWIP) {
6488 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6489 			} else {
6490 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6491 			}
6492 
6493 			freemsg(first_mp1);
6494 		} else {
6495 			/*
6496 			 * Don't enforce here if we're an actual tunnel -
6497 			 * let "tun" do it instead.
6498 			 */
6499 			if (!IPCL_IS_IPTUN(connp) &&
6500 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6501 			    secure)) {
6502 				first_mp1 = ipsec_check_inbound_policy
6503 				    (first_mp1, connp, ipha, NULL,
6504 				    mctl_present);
6505 			}
6506 			if (first_mp1 != NULL) {
6507 				int in_flags = 0;
6508 				/*
6509 				 * ip_fanout_proto also gets called from
6510 				 * icmp_inbound_error_fanout, in which case
6511 				 * the msg type is M_CTL.  Don't add info
6512 				 * in this case for the time being. In future
6513 				 * when there is a need for knowing the
6514 				 * inbound iface index for ICMP error msgs,
6515 				 * then this can be changed.
6516 				 */
6517 				if (connp->conn_recvif)
6518 					in_flags = IPF_RECVIF;
6519 				/*
6520 				 * The ULP may support IP_RECVPKTINFO for both
6521 				 * IP v4 and v6 so pass the appropriate argument
6522 				 * based on conn IP version.
6523 				 */
6524 				if (connp->conn_ip_recvpktinfo) {
6525 					if (connp->conn_af_isv6) {
6526 						/*
6527 						 * V6 only needs index
6528 						 */
6529 						in_flags |= IPF_RECVIF;
6530 					} else {
6531 						/*
6532 						 * V4 needs index +
6533 						 * matching address.
6534 						 */
6535 						in_flags |= IPF_RECVADDR;
6536 					}
6537 				}
6538 				if ((in_flags != 0) &&
6539 				    (mp->b_datap->db_type != M_CTL)) {
6540 					/*
6541 					 * the actual data will be
6542 					 * contained in b_cont upon
6543 					 * successful return of the
6544 					 * following call else
6545 					 * original mblk is returned
6546 					 */
6547 					ASSERT(recv_ill != NULL);
6548 					mp1 = ip_add_info(mp1, recv_ill,
6549 					    in_flags, IPCL_ZONEID(connp), ipst);
6550 				}
6551 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6552 				if (mctl_present)
6553 					freeb(first_mp1);
6554 				(connp->conn_recv)(connp, mp1, NULL);
6555 			}
6556 		}
6557 		mutex_enter(&connfp->connf_lock);
6558 		/* Follow the next pointer before releasing the conn. */
6559 		next_connp = connp->conn_next;
6560 		CONN_DEC_REF(connp);
6561 		connp = next_connp;
6562 	}
6563 
6564 	/* Last one.  Send it upstream. */
6565 	mutex_exit(&connfp->connf_lock);
6566 
6567 	/*
6568 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6569 	 * will be set to false.
6570 	 */
6571 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6572 		ill_index = ill->ill_phyint->phyint_ifindex;
6573 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6574 		if (mp == NULL) {
6575 			CONN_DEC_REF(connp);
6576 			if (mctl_present) {
6577 				freeb(first_mp);
6578 			}
6579 			return;
6580 		}
6581 	}
6582 
6583 	rq = connp->conn_rq;
6584 	if (!canputnext(rq)) {
6585 		if (flags & IP_FF_RAWIP) {
6586 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6587 		} else {
6588 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6589 		}
6590 
6591 		freemsg(first_mp);
6592 	} else {
6593 		if (IPCL_IS_IPTUN(connp)) {
6594 			/*
6595 			 * Tunneled packet.  We enforce policy in the tunnel
6596 			 * module itself.
6597 			 *
6598 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6599 			 * a policy check.
6600 			 * FIXME to use conn_recv for tun later.
6601 			 */
6602 			putnext(rq, first_mp);
6603 			CONN_DEC_REF(connp);
6604 			return;
6605 		}
6606 
6607 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6608 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6609 			    ipha, NULL, mctl_present);
6610 		}
6611 
6612 		if (first_mp != NULL) {
6613 			int in_flags = 0;
6614 
6615 			/*
6616 			 * ip_fanout_proto also gets called
6617 			 * from icmp_inbound_error_fanout, in
6618 			 * which case the msg type is M_CTL.
6619 			 * Don't add info in this case for time
6620 			 * being. In future when there is a
6621 			 * need for knowing the inbound iface
6622 			 * index for ICMP error msgs, then this
6623 			 * can be changed
6624 			 */
6625 			if (connp->conn_recvif)
6626 				in_flags = IPF_RECVIF;
6627 			if (connp->conn_ip_recvpktinfo) {
6628 				if (connp->conn_af_isv6) {
6629 					/*
6630 					 * V6 only needs index
6631 					 */
6632 					in_flags |= IPF_RECVIF;
6633 				} else {
6634 					/*
6635 					 * V4 needs index +
6636 					 * matching address.
6637 					 */
6638 					in_flags |= IPF_RECVADDR;
6639 				}
6640 			}
6641 			if ((in_flags != 0) &&
6642 			    (mp->b_datap->db_type != M_CTL)) {
6643 
6644 				/*
6645 				 * the actual data will be contained in
6646 				 * b_cont upon successful return
6647 				 * of the following call else original
6648 				 * mblk is returned
6649 				 */
6650 				ASSERT(recv_ill != NULL);
6651 				mp = ip_add_info(mp, recv_ill,
6652 				    in_flags, IPCL_ZONEID(connp), ipst);
6653 			}
6654 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6655 			(connp->conn_recv)(connp, mp, NULL);
6656 			if (mctl_present)
6657 				freeb(first_mp);
6658 		}
6659 	}
6660 	CONN_DEC_REF(connp);
6661 }
6662 
6663 /*
6664  * Fanout for TCP packets
6665  * The caller puts <fport, lport> in the ports parameter.
6666  *
6667  * IPQoS Notes
6668  * Before sending it to the client, invoke IPPF processing.
6669  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6670  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6671  * ip_policy is false.
6672  */
6673 static void
6674 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6675     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6676 {
6677 	mblk_t  *first_mp;
6678 	boolean_t secure;
6679 	uint32_t ill_index;
6680 	int	ip_hdr_len;
6681 	tcph_t	*tcph;
6682 	boolean_t syn_present = B_FALSE;
6683 	conn_t	*connp;
6684 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6685 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6686 
6687 	ASSERT(recv_ill != NULL);
6688 
6689 	first_mp = mp;
6690 	if (mctl_present) {
6691 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6692 		mp = first_mp->b_cont;
6693 		secure = ipsec_in_is_secure(first_mp);
6694 		ASSERT(mp != NULL);
6695 	} else {
6696 		secure = B_FALSE;
6697 	}
6698 
6699 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6700 
6701 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6702 	    zoneid, ipst)) == NULL) {
6703 		/*
6704 		 * No connected connection or listener. Send a
6705 		 * TH_RST via tcp_xmit_listeners_reset.
6706 		 */
6707 
6708 		/* Initiate IPPf processing, if needed. */
6709 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6710 			uint32_t ill_index;
6711 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6712 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6713 			if (first_mp == NULL)
6714 				return;
6715 		}
6716 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6717 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6718 		    zoneid));
6719 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6720 		    ipst->ips_netstack->netstack_tcp, NULL);
6721 		return;
6722 	}
6723 
6724 	/*
6725 	 * Allocate the SYN for the TCP connection here itself
6726 	 */
6727 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6728 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6729 		if (IPCL_IS_TCP(connp)) {
6730 			squeue_t *sqp;
6731 
6732 			/*
6733 			 * For fused tcp loopback, assign the eager's
6734 			 * squeue to be that of the active connect's.
6735 			 * Note that we don't check for IP_FF_LOOPBACK
6736 			 * here since this routine gets called only
6737 			 * for loopback (unlike the IPv6 counterpart).
6738 			 */
6739 			ASSERT(Q_TO_CONN(q) != NULL);
6740 			if (do_tcp_fusion &&
6741 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6742 			    !secure &&
6743 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6744 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6745 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6746 				sqp = Q_TO_CONN(q)->conn_sqp;
6747 			} else {
6748 				sqp = IP_SQUEUE_GET(lbolt);
6749 			}
6750 
6751 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6752 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6753 			syn_present = B_TRUE;
6754 		}
6755 	}
6756 
6757 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6758 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6759 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6760 		if ((flags & TH_RST) || (flags & TH_URG)) {
6761 			CONN_DEC_REF(connp);
6762 			freemsg(first_mp);
6763 			return;
6764 		}
6765 		if (flags & TH_ACK) {
6766 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6767 			    ipst->ips_netstack->netstack_tcp, connp);
6768 			CONN_DEC_REF(connp);
6769 			return;
6770 		}
6771 
6772 		CONN_DEC_REF(connp);
6773 		freemsg(first_mp);
6774 		return;
6775 	}
6776 
6777 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6778 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6779 		    NULL, mctl_present);
6780 		if (first_mp == NULL) {
6781 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6782 			CONN_DEC_REF(connp);
6783 			return;
6784 		}
6785 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6786 			ASSERT(syn_present);
6787 			if (mctl_present) {
6788 				ASSERT(first_mp != mp);
6789 				first_mp->b_datap->db_struioflag |=
6790 				    STRUIO_POLICY;
6791 			} else {
6792 				ASSERT(first_mp == mp);
6793 				mp->b_datap->db_struioflag &=
6794 				    ~STRUIO_EAGER;
6795 				mp->b_datap->db_struioflag |=
6796 				    STRUIO_POLICY;
6797 			}
6798 		} else {
6799 			/*
6800 			 * Discard first_mp early since we're dealing with a
6801 			 * fully-connected conn_t and tcp doesn't do policy in
6802 			 * this case.
6803 			 */
6804 			if (mctl_present) {
6805 				freeb(first_mp);
6806 				mctl_present = B_FALSE;
6807 			}
6808 			first_mp = mp;
6809 		}
6810 	}
6811 
6812 	/*
6813 	 * Initiate policy processing here if needed. If we get here from
6814 	 * icmp_inbound_error_fanout, ip_policy is false.
6815 	 */
6816 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6817 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6818 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6819 		if (mp == NULL) {
6820 			CONN_DEC_REF(connp);
6821 			if (mctl_present)
6822 				freeb(first_mp);
6823 			return;
6824 		} else if (mctl_present) {
6825 			ASSERT(first_mp != mp);
6826 			first_mp->b_cont = mp;
6827 		} else {
6828 			first_mp = mp;
6829 		}
6830 	}
6831 
6832 
6833 
6834 	/* Handle socket options. */
6835 	if (!syn_present &&
6836 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6837 		/* Add header */
6838 		ASSERT(recv_ill != NULL);
6839 		/*
6840 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6841 		 * IPF_RECVIF.
6842 		 */
6843 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6844 		    ipst);
6845 		if (mp == NULL) {
6846 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6847 			CONN_DEC_REF(connp);
6848 			if (mctl_present)
6849 				freeb(first_mp);
6850 			return;
6851 		} else if (mctl_present) {
6852 			/*
6853 			 * ip_add_info might return a new mp.
6854 			 */
6855 			ASSERT(first_mp != mp);
6856 			first_mp->b_cont = mp;
6857 		} else {
6858 			first_mp = mp;
6859 		}
6860 	}
6861 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6862 	if (IPCL_IS_TCP(connp)) {
6863 		/* do not drain, certain use cases can blow the stack */
6864 		squeue_enter_nodrain(connp->conn_sqp, first_mp,
6865 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6866 	} else {
6867 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
6868 		(connp->conn_recv)(connp, first_mp, NULL);
6869 		CONN_DEC_REF(connp);
6870 	}
6871 }
6872 
6873 /*
6874  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
6875  * pass it along to ESP if the SPI is non-zero.  Returns TRUE if the mblk
6876  * is not consumed.
6877  *
6878  * One of four things can happen, all of which affect the passed-in mblk:
6879  *
6880  * 1.) ICMP messages that go through here just get returned TRUE.
6881  *
6882  * 2.) The packet is stock UDP and gets its zero-SPI stripped.  Return TRUE.
6883  *
6884  * 3.) The packet is ESP-in-UDP, gets transformed into an equivalent
6885  *     ESP packet, and is passed along to ESP for consumption.  Return FALSE.
6886  *
6887  * 4.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
6888  */
6889 static boolean_t
6890 zero_spi_check(queue_t *q, mblk_t *mp, ire_t *ire, ill_t *recv_ill,
6891     ipsec_stack_t *ipss)
6892 {
6893 	int shift, plen, iph_len;
6894 	ipha_t *ipha;
6895 	udpha_t *udpha;
6896 	uint32_t *spi;
6897 	uint8_t *orptr;
6898 	boolean_t udp_pkt, free_ire;
6899 
6900 	if (DB_TYPE(mp) == M_CTL) {
6901 		/*
6902 		 * ICMP message with UDP inside.  Don't bother stripping, just
6903 		 * send it up.
6904 		 *
6905 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
6906 		 * to ignore errors set by ICMP anyway ('cause they might be
6907 		 * forged), but that's the app's decision, not ours.
6908 		 */
6909 
6910 		/* Bunch of reality checks for DEBUG kernels... */
6911 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
6912 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
6913 
6914 		return (B_TRUE);
6915 	}
6916 
6917 	ipha = (ipha_t *)mp->b_rptr;
6918 	iph_len = IPH_HDR_LENGTH(ipha);
6919 	plen = ntohs(ipha->ipha_length);
6920 
6921 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
6922 		/*
6923 		 * Most likely a keepalive for the benefit of an intervening
6924 		 * NAT.  These aren't for us, per se, so drop it.
6925 		 *
6926 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
6927 		 * byte packets (keepalives are 1-byte), but we'll drop them
6928 		 * also.
6929 		 */
6930 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6931 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
6932 		return (B_FALSE);
6933 	}
6934 
6935 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
6936 		/* might as well pull it all up - it might be ESP. */
6937 		if (!pullupmsg(mp, -1)) {
6938 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6939 			    DROPPER(ipss, ipds_esp_nomem),
6940 			    &ipss->ipsec_dropper);
6941 			return (B_FALSE);
6942 		}
6943 
6944 		ipha = (ipha_t *)mp->b_rptr;
6945 	}
6946 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
6947 	if (*spi == 0) {
6948 		/* UDP packet - remove 0-spi. */
6949 		shift = sizeof (uint32_t);
6950 	} else {
6951 		/* ESP-in-UDP packet - reduce to ESP. */
6952 		ipha->ipha_protocol = IPPROTO_ESP;
6953 		shift = sizeof (udpha_t);
6954 	}
6955 
6956 	/* Fix IP header */
6957 	ipha->ipha_length = htons(plen - shift);
6958 	ipha->ipha_hdr_checksum = 0;
6959 
6960 	orptr = mp->b_rptr;
6961 	mp->b_rptr += shift;
6962 
6963 	if (*spi == 0) {
6964 		ASSERT((uint8_t *)ipha == orptr);
6965 		udpha = (udpha_t *)(orptr + iph_len);
6966 		udpha->uha_length = htons(plen - shift - iph_len);
6967 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
6968 		udp_pkt = B_TRUE;
6969 	} else {
6970 		udp_pkt = B_FALSE;
6971 	}
6972 	ovbcopy(orptr, orptr + shift, iph_len);
6973 	if (!udp_pkt) /* Punt up for ESP processing. */ {
6974 		ipha = (ipha_t *)(orptr + shift);
6975 
6976 		free_ire = (ire == NULL);
6977 		if (free_ire) {
6978 			/* Re-acquire ire. */
6979 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
6980 			    ipss->ipsec_netstack->netstack_ip);
6981 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
6982 				if (ire != NULL)
6983 					ire_refrele(ire);
6984 				/*
6985 				 * Do a regular freemsg(), as this is an IP
6986 				 * error (no local route) not an IPsec one.
6987 				 */
6988 				freemsg(mp);
6989 			}
6990 		}
6991 
6992 		ip_proto_input(q, mp, ipha, ire, recv_ill, B_TRUE);
6993 		if (free_ire)
6994 			ire_refrele(ire);
6995 	}
6996 
6997 	return (udp_pkt);
6998 }
6999 
7000 /*
7001  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
7002  * We are responsible for disposing of mp, such as by freemsg() or putnext()
7003  * Caller is responsible for dropping references to the conn, and freeing
7004  * first_mp.
7005  *
7006  * IPQoS Notes
7007  * Before sending it to the client, invoke IPPF processing. Policy processing
7008  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
7009  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
7010  * ip_wput_local, ip_policy is false.
7011  */
7012 static void
7013 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
7014     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
7015     boolean_t ip_policy)
7016 {
7017 	boolean_t	mctl_present = (first_mp != NULL);
7018 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
7019 	uint32_t	ill_index;
7020 	ip_stack_t	*ipst = recv_ill->ill_ipst;
7021 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
7022 
7023 	ASSERT(ill != NULL);
7024 
7025 	if (mctl_present)
7026 		first_mp->b_cont = mp;
7027 	else
7028 		first_mp = mp;
7029 
7030 	if (CONN_UDP_FLOWCTLD(connp)) {
7031 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
7032 		freemsg(first_mp);
7033 		return;
7034 	}
7035 
7036 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
7037 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
7038 		    NULL, mctl_present);
7039 		if (first_mp == NULL) {
7040 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7041 			return;	/* Freed by ipsec_check_inbound_policy(). */
7042 		}
7043 	}
7044 	if (mctl_present)
7045 		freeb(first_mp);
7046 
7047 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
7048 	if (connp->conn_udp->udp_nat_t_endpoint) {
7049 		if (mctl_present) {
7050 			/* mctl_present *shouldn't* happen. */
7051 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
7052 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
7053 			    &ipss->ipsec_dropper);
7054 			return;
7055 		}
7056 
7057 		if (!zero_spi_check(ill->ill_rq, mp, NULL, recv_ill, ipss))
7058 			return;
7059 	}
7060 
7061 	/* Handle options. */
7062 	if (connp->conn_recvif)
7063 		in_flags = IPF_RECVIF;
7064 	/*
7065 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7066 	 * passed to ip_add_info is based on IP version of connp.
7067 	 */
7068 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7069 		if (connp->conn_af_isv6) {
7070 			/*
7071 			 * V6 only needs index
7072 			 */
7073 			in_flags |= IPF_RECVIF;
7074 		} else {
7075 			/*
7076 			 * V4 needs index + matching address.
7077 			 */
7078 			in_flags |= IPF_RECVADDR;
7079 		}
7080 	}
7081 
7082 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7083 		in_flags |= IPF_RECVSLLA;
7084 
7085 	/*
7086 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7087 	 * freed if the packet is dropped. The caller will do so.
7088 	 */
7089 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7090 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7091 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7092 		if (mp == NULL) {
7093 			return;
7094 		}
7095 	}
7096 	if ((in_flags != 0) &&
7097 	    (mp->b_datap->db_type != M_CTL)) {
7098 		/*
7099 		 * The actual data will be contained in b_cont
7100 		 * upon successful return of the following call
7101 		 * else original mblk is returned
7102 		 */
7103 		ASSERT(recv_ill != NULL);
7104 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7105 		    ipst);
7106 	}
7107 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7108 	/* Send it upstream */
7109 	(connp->conn_recv)(connp, mp, NULL);
7110 }
7111 
7112 /*
7113  * Fanout for UDP packets.
7114  * The caller puts <fport, lport> in the ports parameter.
7115  *
7116  * If SO_REUSEADDR is set all multicast and broadcast packets
7117  * will be delivered to all streams bound to the same port.
7118  *
7119  * Zones notes:
7120  * Multicast and broadcast packets will be distributed to streams in all zones.
7121  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7122  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7123  * packets. To maintain this behavior with multiple zones, the conns are grouped
7124  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7125  * each zone. If unset, all the following conns in the same zone are skipped.
7126  */
7127 static void
7128 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7129     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7130     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7131 {
7132 	uint32_t	dstport, srcport;
7133 	ipaddr_t	dst;
7134 	mblk_t		*first_mp;
7135 	boolean_t	secure;
7136 	in6_addr_t	v6src;
7137 	conn_t		*connp;
7138 	connf_t		*connfp;
7139 	conn_t		*first_connp;
7140 	conn_t		*next_connp;
7141 	mblk_t		*mp1, *first_mp1;
7142 	ipaddr_t	src;
7143 	zoneid_t	last_zoneid;
7144 	boolean_t	reuseaddr;
7145 	boolean_t	shared_addr;
7146 	ip_stack_t	*ipst;
7147 
7148 	ASSERT(recv_ill != NULL);
7149 	ipst = recv_ill->ill_ipst;
7150 
7151 	first_mp = mp;
7152 	if (mctl_present) {
7153 		mp = first_mp->b_cont;
7154 		first_mp->b_cont = NULL;
7155 		secure = ipsec_in_is_secure(first_mp);
7156 		ASSERT(mp != NULL);
7157 	} else {
7158 		first_mp = NULL;
7159 		secure = B_FALSE;
7160 	}
7161 
7162 	/* Extract ports in net byte order */
7163 	dstport = htons(ntohl(ports) & 0xFFFF);
7164 	srcport = htons(ntohl(ports) >> 16);
7165 	dst = ipha->ipha_dst;
7166 	src = ipha->ipha_src;
7167 
7168 	shared_addr = (zoneid == ALL_ZONES);
7169 	if (shared_addr) {
7170 		/*
7171 		 * No need to handle exclusive-stack zones since ALL_ZONES
7172 		 * only applies to the shared stack.
7173 		 */
7174 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7175 		if (zoneid == ALL_ZONES)
7176 			zoneid = tsol_packet_to_zoneid(mp);
7177 	}
7178 
7179 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7180 	mutex_enter(&connfp->connf_lock);
7181 	connp = connfp->connf_head;
7182 	if (!broadcast && !CLASSD(dst)) {
7183 		/*
7184 		 * Not broadcast or multicast. Send to the one (first)
7185 		 * client we find. No need to check conn_wantpacket()
7186 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7187 		 * IPv4 unicast packets.
7188 		 */
7189 		while ((connp != NULL) &&
7190 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7191 		    !IPCL_ZONE_MATCH(connp, zoneid))) {
7192 			connp = connp->conn_next;
7193 		}
7194 
7195 		if (connp == NULL || connp->conn_upq == NULL)
7196 			goto notfound;
7197 
7198 		if (is_system_labeled() &&
7199 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7200 		    connp))
7201 			goto notfound;
7202 
7203 		CONN_INC_REF(connp);
7204 		mutex_exit(&connfp->connf_lock);
7205 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7206 		    flags, recv_ill, ip_policy);
7207 		IP_STAT(ipst, ip_udp_fannorm);
7208 		CONN_DEC_REF(connp);
7209 		return;
7210 	}
7211 
7212 	/*
7213 	 * Broadcast and multicast case
7214 	 *
7215 	 * Need to check conn_wantpacket().
7216 	 * If SO_REUSEADDR has been set on the first we send the
7217 	 * packet to all clients that have joined the group and
7218 	 * match the port.
7219 	 */
7220 
7221 	while (connp != NULL) {
7222 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7223 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7224 		    (!is_system_labeled() ||
7225 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7226 		    connp)))
7227 			break;
7228 		connp = connp->conn_next;
7229 	}
7230 
7231 	if (connp == NULL || connp->conn_upq == NULL)
7232 		goto notfound;
7233 
7234 	first_connp = connp;
7235 	/*
7236 	 * When SO_REUSEADDR is not set, send the packet only to the first
7237 	 * matching connection in its zone by keeping track of the zoneid.
7238 	 */
7239 	reuseaddr = first_connp->conn_reuseaddr;
7240 	last_zoneid = first_connp->conn_zoneid;
7241 
7242 	CONN_INC_REF(connp);
7243 	connp = connp->conn_next;
7244 	for (;;) {
7245 		while (connp != NULL) {
7246 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7247 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7248 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7249 			    (!is_system_labeled() ||
7250 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7251 			    shared_addr, connp)))
7252 				break;
7253 			connp = connp->conn_next;
7254 		}
7255 		/*
7256 		 * Just copy the data part alone. The mctl part is
7257 		 * needed just for verifying policy and it is never
7258 		 * sent up.
7259 		 */
7260 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7261 		    ((mp1 = copymsg(mp)) == NULL))) {
7262 			/*
7263 			 * No more interested clients or memory
7264 			 * allocation failed
7265 			 */
7266 			connp = first_connp;
7267 			break;
7268 		}
7269 		if (connp->conn_zoneid != last_zoneid) {
7270 			/*
7271 			 * Update the zoneid so that the packet isn't sent to
7272 			 * any more conns in the same zone unless SO_REUSEADDR
7273 			 * is set.
7274 			 */
7275 			reuseaddr = connp->conn_reuseaddr;
7276 			last_zoneid = connp->conn_zoneid;
7277 		}
7278 		if (first_mp != NULL) {
7279 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7280 			    ipsec_info_type == IPSEC_IN);
7281 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7282 			    ipst->ips_netstack);
7283 			if (first_mp1 == NULL) {
7284 				freemsg(mp1);
7285 				connp = first_connp;
7286 				break;
7287 			}
7288 		} else {
7289 			first_mp1 = NULL;
7290 		}
7291 		CONN_INC_REF(connp);
7292 		mutex_exit(&connfp->connf_lock);
7293 		/*
7294 		 * IPQoS notes: We don't send the packet for policy
7295 		 * processing here, will do it for the last one (below).
7296 		 * i.e. we do it per-packet now, but if we do policy
7297 		 * processing per-conn, then we would need to do it
7298 		 * here too.
7299 		 */
7300 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7301 		    ipha, flags, recv_ill, B_FALSE);
7302 		mutex_enter(&connfp->connf_lock);
7303 		/* Follow the next pointer before releasing the conn. */
7304 		next_connp = connp->conn_next;
7305 		IP_STAT(ipst, ip_udp_fanmb);
7306 		CONN_DEC_REF(connp);
7307 		connp = next_connp;
7308 	}
7309 
7310 	/* Last one.  Send it upstream. */
7311 	mutex_exit(&connfp->connf_lock);
7312 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7313 	    recv_ill, ip_policy);
7314 	IP_STAT(ipst, ip_udp_fanmb);
7315 	CONN_DEC_REF(connp);
7316 	return;
7317 
7318 notfound:
7319 
7320 	mutex_exit(&connfp->connf_lock);
7321 	IP_STAT(ipst, ip_udp_fanothers);
7322 	/*
7323 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7324 	 * have already been matched above, since they live in the IPv4
7325 	 * fanout tables. This implies we only need to
7326 	 * check for IPv6 in6addr_any endpoints here.
7327 	 * Thus we compare using ipv6_all_zeros instead of the destination
7328 	 * address, except for the multicast group membership lookup which
7329 	 * uses the IPv4 destination.
7330 	 */
7331 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7332 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7333 	mutex_enter(&connfp->connf_lock);
7334 	connp = connfp->connf_head;
7335 	if (!broadcast && !CLASSD(dst)) {
7336 		while (connp != NULL) {
7337 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7338 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7339 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7340 			    !connp->conn_ipv6_v6only)
7341 				break;
7342 			connp = connp->conn_next;
7343 		}
7344 
7345 		if (connp != NULL && is_system_labeled() &&
7346 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7347 		    connp))
7348 			connp = NULL;
7349 
7350 		if (connp == NULL || connp->conn_upq == NULL) {
7351 			/*
7352 			 * No one bound to this port.  Is
7353 			 * there a client that wants all
7354 			 * unclaimed datagrams?
7355 			 */
7356 			mutex_exit(&connfp->connf_lock);
7357 
7358 			if (mctl_present)
7359 				first_mp->b_cont = mp;
7360 			else
7361 				first_mp = mp;
7362 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7363 			    connf_head != NULL) {
7364 				ip_fanout_proto(q, first_mp, ill, ipha,
7365 				    flags | IP_FF_RAWIP, mctl_present,
7366 				    ip_policy, recv_ill, zoneid);
7367 			} else {
7368 				if (ip_fanout_send_icmp(q, first_mp, flags,
7369 				    ICMP_DEST_UNREACHABLE,
7370 				    ICMP_PORT_UNREACHABLE,
7371 				    mctl_present, zoneid, ipst)) {
7372 					BUMP_MIB(ill->ill_ip_mib,
7373 					    udpIfStatsNoPorts);
7374 				}
7375 			}
7376 			return;
7377 		}
7378 
7379 		CONN_INC_REF(connp);
7380 		mutex_exit(&connfp->connf_lock);
7381 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7382 		    flags, recv_ill, ip_policy);
7383 		CONN_DEC_REF(connp);
7384 		return;
7385 	}
7386 	/*
7387 	 * IPv4 multicast packet being delivered to an AF_INET6
7388 	 * in6addr_any endpoint.
7389 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7390 	 * and not conn_wantpacket_v6() since any multicast membership is
7391 	 * for an IPv4-mapped multicast address.
7392 	 * The packet is sent to all clients in all zones that have joined the
7393 	 * group and match the port.
7394 	 */
7395 	while (connp != NULL) {
7396 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7397 		    srcport, v6src) &&
7398 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7399 		    (!is_system_labeled() ||
7400 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7401 		    connp)))
7402 			break;
7403 		connp = connp->conn_next;
7404 	}
7405 
7406 	if (connp == NULL || connp->conn_upq == NULL) {
7407 		/*
7408 		 * No one bound to this port.  Is
7409 		 * there a client that wants all
7410 		 * unclaimed datagrams?
7411 		 */
7412 		mutex_exit(&connfp->connf_lock);
7413 
7414 		if (mctl_present)
7415 			first_mp->b_cont = mp;
7416 		else
7417 			first_mp = mp;
7418 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7419 		    NULL) {
7420 			ip_fanout_proto(q, first_mp, ill, ipha,
7421 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7422 			    recv_ill, zoneid);
7423 		} else {
7424 			/*
7425 			 * We used to attempt to send an icmp error here, but
7426 			 * since this is known to be a multicast packet
7427 			 * and we don't send icmp errors in response to
7428 			 * multicast, just drop the packet and give up sooner.
7429 			 */
7430 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7431 			freemsg(first_mp);
7432 		}
7433 		return;
7434 	}
7435 
7436 	first_connp = connp;
7437 
7438 	CONN_INC_REF(connp);
7439 	connp = connp->conn_next;
7440 	for (;;) {
7441 		while (connp != NULL) {
7442 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7443 			    ipv6_all_zeros, srcport, v6src) &&
7444 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7445 			    (!is_system_labeled() ||
7446 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7447 			    shared_addr, connp)))
7448 				break;
7449 			connp = connp->conn_next;
7450 		}
7451 		/*
7452 		 * Just copy the data part alone. The mctl part is
7453 		 * needed just for verifying policy and it is never
7454 		 * sent up.
7455 		 */
7456 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7457 		    ((mp1 = copymsg(mp)) == NULL))) {
7458 			/*
7459 			 * No more intested clients or memory
7460 			 * allocation failed
7461 			 */
7462 			connp = first_connp;
7463 			break;
7464 		}
7465 		if (first_mp != NULL) {
7466 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7467 			    ipsec_info_type == IPSEC_IN);
7468 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7469 			    ipst->ips_netstack);
7470 			if (first_mp1 == NULL) {
7471 				freemsg(mp1);
7472 				connp = first_connp;
7473 				break;
7474 			}
7475 		} else {
7476 			first_mp1 = NULL;
7477 		}
7478 		CONN_INC_REF(connp);
7479 		mutex_exit(&connfp->connf_lock);
7480 		/*
7481 		 * IPQoS notes: We don't send the packet for policy
7482 		 * processing here, will do it for the last one (below).
7483 		 * i.e. we do it per-packet now, but if we do policy
7484 		 * processing per-conn, then we would need to do it
7485 		 * here too.
7486 		 */
7487 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7488 		    ipha, flags, recv_ill, B_FALSE);
7489 		mutex_enter(&connfp->connf_lock);
7490 		/* Follow the next pointer before releasing the conn. */
7491 		next_connp = connp->conn_next;
7492 		CONN_DEC_REF(connp);
7493 		connp = next_connp;
7494 	}
7495 
7496 	/* Last one.  Send it upstream. */
7497 	mutex_exit(&connfp->connf_lock);
7498 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7499 	    recv_ill, ip_policy);
7500 	CONN_DEC_REF(connp);
7501 }
7502 
7503 /*
7504  * Complete the ip_wput header so that it
7505  * is possible to generate ICMP
7506  * errors.
7507  */
7508 int
7509 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7510 {
7511 	ire_t *ire;
7512 
7513 	if (ipha->ipha_src == INADDR_ANY) {
7514 		ire = ire_lookup_local(zoneid, ipst);
7515 		if (ire == NULL) {
7516 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7517 			return (1);
7518 		}
7519 		ipha->ipha_src = ire->ire_addr;
7520 		ire_refrele(ire);
7521 	}
7522 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7523 	ipha->ipha_hdr_checksum = 0;
7524 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7525 	return (0);
7526 }
7527 
7528 /*
7529  * Nobody should be sending
7530  * packets up this stream
7531  */
7532 static void
7533 ip_lrput(queue_t *q, mblk_t *mp)
7534 {
7535 	mblk_t *mp1;
7536 
7537 	switch (mp->b_datap->db_type) {
7538 	case M_FLUSH:
7539 		/* Turn around */
7540 		if (*mp->b_rptr & FLUSHW) {
7541 			*mp->b_rptr &= ~FLUSHR;
7542 			qreply(q, mp);
7543 			return;
7544 		}
7545 		break;
7546 	}
7547 	/* Could receive messages that passed through ar_rput */
7548 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7549 		mp1->b_prev = mp1->b_next = NULL;
7550 	freemsg(mp);
7551 }
7552 
7553 /* Nobody should be sending packets down this stream */
7554 /* ARGSUSED */
7555 void
7556 ip_lwput(queue_t *q, mblk_t *mp)
7557 {
7558 	freemsg(mp);
7559 }
7560 
7561 /*
7562  * Move the first hop in any source route to ipha_dst and remove that part of
7563  * the source route.  Called by other protocols.  Errors in option formatting
7564  * are ignored - will be handled by ip_wput_options Return the final
7565  * destination (either ipha_dst or the last entry in a source route.)
7566  */
7567 ipaddr_t
7568 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7569 {
7570 	ipoptp_t	opts;
7571 	uchar_t		*opt;
7572 	uint8_t		optval;
7573 	uint8_t		optlen;
7574 	ipaddr_t	dst;
7575 	int		i;
7576 	ire_t		*ire;
7577 	ip_stack_t	*ipst = ns->netstack_ip;
7578 
7579 	ip2dbg(("ip_massage_options\n"));
7580 	dst = ipha->ipha_dst;
7581 	for (optval = ipoptp_first(&opts, ipha);
7582 	    optval != IPOPT_EOL;
7583 	    optval = ipoptp_next(&opts)) {
7584 		opt = opts.ipoptp_cur;
7585 		switch (optval) {
7586 			uint8_t off;
7587 		case IPOPT_SSRR:
7588 		case IPOPT_LSRR:
7589 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7590 				ip1dbg(("ip_massage_options: bad src route\n"));
7591 				break;
7592 			}
7593 			optlen = opts.ipoptp_len;
7594 			off = opt[IPOPT_OFFSET];
7595 			off--;
7596 		redo_srr:
7597 			if (optlen < IP_ADDR_LEN ||
7598 			    off > optlen - IP_ADDR_LEN) {
7599 				/* End of source route */
7600 				ip1dbg(("ip_massage_options: end of SR\n"));
7601 				break;
7602 			}
7603 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7604 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7605 			    ntohl(dst)));
7606 			/*
7607 			 * Check if our address is present more than
7608 			 * once as consecutive hops in source route.
7609 			 * XXX verify per-interface ip_forwarding
7610 			 * for source route?
7611 			 */
7612 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7613 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7614 			if (ire != NULL) {
7615 				ire_refrele(ire);
7616 				off += IP_ADDR_LEN;
7617 				goto redo_srr;
7618 			}
7619 			if (dst == htonl(INADDR_LOOPBACK)) {
7620 				ip1dbg(("ip_massage_options: loopback addr in "
7621 				    "source route!\n"));
7622 				break;
7623 			}
7624 			/*
7625 			 * Update ipha_dst to be the first hop and remove the
7626 			 * first hop from the source route (by overwriting
7627 			 * part of the option with NOP options).
7628 			 */
7629 			ipha->ipha_dst = dst;
7630 			/* Put the last entry in dst */
7631 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7632 			    3;
7633 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7634 
7635 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7636 			    ntohl(dst)));
7637 			/* Move down and overwrite */
7638 			opt[IP_ADDR_LEN] = opt[0];
7639 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7640 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7641 			for (i = 0; i < IP_ADDR_LEN; i++)
7642 				opt[i] = IPOPT_NOP;
7643 			break;
7644 		}
7645 	}
7646 	return (dst);
7647 }
7648 
7649 /*
7650  * Return the network mask
7651  * associated with the specified address.
7652  */
7653 ipaddr_t
7654 ip_net_mask(ipaddr_t addr)
7655 {
7656 	uchar_t	*up = (uchar_t *)&addr;
7657 	ipaddr_t mask = 0;
7658 	uchar_t	*maskp = (uchar_t *)&mask;
7659 
7660 #if defined(__i386) || defined(__amd64)
7661 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7662 #endif
7663 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7664 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7665 #endif
7666 	if (CLASSD(addr)) {
7667 		maskp[0] = 0xF0;
7668 		return (mask);
7669 	}
7670 	if (addr == 0)
7671 		return (0);
7672 	maskp[0] = 0xFF;
7673 	if ((up[0] & 0x80) == 0)
7674 		return (mask);
7675 
7676 	maskp[1] = 0xFF;
7677 	if ((up[0] & 0xC0) == 0x80)
7678 		return (mask);
7679 
7680 	maskp[2] = 0xFF;
7681 	if ((up[0] & 0xE0) == 0xC0)
7682 		return (mask);
7683 
7684 	/* Must be experimental or multicast, indicate as much */
7685 	return ((ipaddr_t)0);
7686 }
7687 
7688 /*
7689  * Select an ill for the packet by considering load spreading across
7690  * a different ill in the group if dst_ill is part of some group.
7691  */
7692 ill_t *
7693 ip_newroute_get_dst_ill(ill_t *dst_ill)
7694 {
7695 	ill_t *ill;
7696 
7697 	/*
7698 	 * We schedule irrespective of whether the source address is
7699 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7700 	 */
7701 	ill = illgrp_scheduler(dst_ill);
7702 	if (ill == NULL)
7703 		return (NULL);
7704 
7705 	/*
7706 	 * For groups with names ip_sioctl_groupname ensures that all
7707 	 * ills are of same type. For groups without names, ifgrp_insert
7708 	 * ensures this.
7709 	 */
7710 	ASSERT(dst_ill->ill_type == ill->ill_type);
7711 
7712 	return (ill);
7713 }
7714 
7715 /*
7716  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7717  */
7718 ill_t *
7719 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6,
7720     ip_stack_t *ipst)
7721 {
7722 	ill_t *ret_ill;
7723 
7724 	ASSERT(ifindex != 0);
7725 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7726 	    ipst);
7727 	if (ret_ill == NULL ||
7728 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7729 		if (isv6) {
7730 			if (ill != NULL) {
7731 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7732 			} else {
7733 				BUMP_MIB(&ipst->ips_ip6_mib,
7734 				    ipIfStatsOutDiscards);
7735 			}
7736 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7737 			    "bad ifindex %d.\n", ifindex));
7738 		} else {
7739 			if (ill != NULL) {
7740 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7741 			} else {
7742 				BUMP_MIB(&ipst->ips_ip_mib,
7743 				    ipIfStatsOutDiscards);
7744 			}
7745 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7746 			    "bad ifindex %d.\n", ifindex));
7747 		}
7748 		if (ret_ill != NULL)
7749 			ill_refrele(ret_ill);
7750 		freemsg(first_mp);
7751 		return (NULL);
7752 	}
7753 
7754 	return (ret_ill);
7755 }
7756 
7757 /*
7758  * IPv4 -
7759  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7760  * out a packet to a destination address for which we do not have specific
7761  * (or sufficient) routing information.
7762  *
7763  * NOTE : These are the scopes of some of the variables that point at IRE,
7764  *	  which needs to be followed while making any future modifications
7765  *	  to avoid memory leaks.
7766  *
7767  *	- ire and sire are the entries looked up initially by
7768  *	  ire_ftable_lookup.
7769  *	- ipif_ire is used to hold the interface ire associated with
7770  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7771  *	  it before branching out to error paths.
7772  *	- save_ire is initialized before ire_create, so that ire returned
7773  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7774  *	  before breaking out of the switch.
7775  *
7776  *	Thus on failures, we have to REFRELE only ire and sire, if they
7777  *	are not NULL.
7778  */
7779 void
7780 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7781     zoneid_t zoneid, ip_stack_t *ipst)
7782 {
7783 	areq_t	*areq;
7784 	ipaddr_t gw = 0;
7785 	ire_t	*ire = NULL;
7786 	mblk_t	*res_mp;
7787 	ipaddr_t *addrp;
7788 	ipaddr_t nexthop_addr;
7789 	ipif_t  *src_ipif = NULL;
7790 	ill_t	*dst_ill = NULL;
7791 	ipha_t  *ipha;
7792 	ire_t	*sire = NULL;
7793 	mblk_t	*first_mp;
7794 	ire_t	*save_ire;
7795 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7796 	ushort_t ire_marks = 0;
7797 	boolean_t mctl_present;
7798 	ipsec_out_t *io;
7799 	mblk_t	*saved_mp;
7800 	ire_t	*first_sire = NULL;
7801 	mblk_t	*copy_mp = NULL;
7802 	mblk_t	*xmit_mp = NULL;
7803 	ipaddr_t save_dst;
7804 	uint32_t multirt_flags =
7805 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7806 	boolean_t multirt_is_resolvable;
7807 	boolean_t multirt_resolve_next;
7808 	boolean_t unspec_src;
7809 	boolean_t do_attach_ill = B_FALSE;
7810 	boolean_t ip_nexthop = B_FALSE;
7811 	tsol_ire_gw_secattr_t *attrp = NULL;
7812 	tsol_gcgrp_t *gcgrp = NULL;
7813 	tsol_gcgrp_addr_t ga;
7814 
7815 	if (ip_debug > 2) {
7816 		/* ip1dbg */
7817 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7818 	}
7819 
7820 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7821 	if (mctl_present) {
7822 		io = (ipsec_out_t *)first_mp->b_rptr;
7823 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7824 		ASSERT(zoneid == io->ipsec_out_zoneid);
7825 		ASSERT(zoneid != ALL_ZONES);
7826 	}
7827 
7828 	ipha = (ipha_t *)mp->b_rptr;
7829 
7830 	/* All multicast lookups come through ip_newroute_ipif() */
7831 	if (CLASSD(dst)) {
7832 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7833 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7834 		freemsg(first_mp);
7835 		return;
7836 	}
7837 
7838 	if (mctl_present && io->ipsec_out_attach_if) {
7839 		/* ip_grab_attach_ill returns a held ill */
7840 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7841 		    io->ipsec_out_ill_index, B_FALSE, ipst);
7842 
7843 		/* Failure case frees things for us. */
7844 		if (attach_ill == NULL)
7845 			return;
7846 
7847 		/*
7848 		 * Check if we need an ire that will not be
7849 		 * looked up by anybody else i.e. HIDDEN.
7850 		 */
7851 		if (ill_is_probeonly(attach_ill))
7852 			ire_marks = IRE_MARK_HIDDEN;
7853 	}
7854 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7855 		ip_nexthop = B_TRUE;
7856 		nexthop_addr = io->ipsec_out_nexthop_addr;
7857 	}
7858 	/*
7859 	 * If this IRE is created for forwarding or it is not for
7860 	 * traffic for congestion controlled protocols, mark it as temporary.
7861 	 */
7862 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7863 		ire_marks |= IRE_MARK_TEMPORARY;
7864 
7865 	/*
7866 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7867 	 * chain until it gets the most specific information available.
7868 	 * For example, we know that there is no IRE_CACHE for this dest,
7869 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7870 	 * ire_ftable_lookup will look up the gateway, etc.
7871 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7872 	 * to the destination, of equal netmask length in the forward table,
7873 	 * will be recursively explored. If no information is available
7874 	 * for the final gateway of that route, we force the returned ire
7875 	 * to be equal to sire using MATCH_IRE_PARENT.
7876 	 * At least, in this case we have a starting point (in the buckets)
7877 	 * to look for other routes to the destination in the forward table.
7878 	 * This is actually used only for multirouting, where a list
7879 	 * of routes has to be processed in sequence.
7880 	 *
7881 	 * In the process of coming up with the most specific information,
7882 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7883 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7884 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7885 	 * Two caveats when handling incomplete ire's in ip_newroute:
7886 	 * - we should be careful when accessing its ire_nce (specifically
7887 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7888 	 * - not all legacy code path callers are prepared to handle
7889 	 *   incomplete ire's, so we should not create/add incomplete
7890 	 *   ire_cache entries here. (See discussion about temporary solution
7891 	 *   further below).
7892 	 *
7893 	 * In order to minimize packet dropping, and to preserve existing
7894 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7895 	 * gateway, and instead use the IF_RESOLVER ire to send out
7896 	 * another request to ARP (this is achieved by passing the
7897 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7898 	 * arp response comes back in ip_wput_nondata, we will create
7899 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7900 	 *
7901 	 * Note that this is a temporary solution; the correct solution is
7902 	 * to create an incomplete  per-dst ire_cache entry, and send the
7903 	 * packet out when the gw's nce is resolved. In order to achieve this,
7904 	 * all packet processing must have been completed prior to calling
7905 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7906 	 * to be modified to accomodate this solution.
7907 	 */
7908 	if (ip_nexthop) {
7909 		/*
7910 		 * The first time we come here, we look for an IRE_INTERFACE
7911 		 * entry for the specified nexthop, set the dst to be the
7912 		 * nexthop address and create an IRE_CACHE entry for the
7913 		 * nexthop. The next time around, we are able to find an
7914 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7915 		 * nexthop address and create an IRE_CACHE entry for the
7916 		 * destination address via the specified nexthop.
7917 		 */
7918 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7919 		    MBLK_GETLABEL(mp), ipst);
7920 		if (ire != NULL) {
7921 			gw = nexthop_addr;
7922 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7923 		} else {
7924 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7925 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7926 			    MBLK_GETLABEL(mp),
7927 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
7928 			    ipst);
7929 			if (ire != NULL) {
7930 				dst = nexthop_addr;
7931 			}
7932 		}
7933 	} else if (attach_ill == NULL) {
7934 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7935 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
7936 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7937 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7938 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
7939 		    ipst);
7940 	} else {
7941 		/*
7942 		 * attach_ill is set only for communicating with
7943 		 * on-link hosts. So, don't look for DEFAULT.
7944 		 */
7945 		ipif_t	*attach_ipif;
7946 
7947 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
7948 		if (attach_ipif == NULL) {
7949 			ill_refrele(attach_ill);
7950 			goto icmp_err_ret;
7951 		}
7952 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
7953 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
7954 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
7955 		    MATCH_IRE_SECATTR, ipst);
7956 		ipif_refrele(attach_ipif);
7957 	}
7958 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7959 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7960 
7961 	/*
7962 	 * This loop is run only once in most cases.
7963 	 * We loop to resolve further routes only when the destination
7964 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7965 	 */
7966 	do {
7967 		/* Clear the previous iteration's values */
7968 		if (src_ipif != NULL) {
7969 			ipif_refrele(src_ipif);
7970 			src_ipif = NULL;
7971 		}
7972 		if (dst_ill != NULL) {
7973 			ill_refrele(dst_ill);
7974 			dst_ill = NULL;
7975 		}
7976 
7977 		multirt_resolve_next = B_FALSE;
7978 		/*
7979 		 * We check if packets have to be multirouted.
7980 		 * In this case, given the current <ire, sire> couple,
7981 		 * we look for the next suitable <ire, sire>.
7982 		 * This check is done in ire_multirt_lookup(),
7983 		 * which applies various criteria to find the next route
7984 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7985 		 * unchanged if it detects it has not been tried yet.
7986 		 */
7987 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7988 			ip3dbg(("ip_newroute: starting next_resolution "
7989 			    "with first_mp %p, tag %d\n",
7990 			    (void *)first_mp,
7991 			    MULTIRT_DEBUG_TAGGED(first_mp)));
7992 
7993 			ASSERT(sire != NULL);
7994 			multirt_is_resolvable =
7995 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
7996 			    MBLK_GETLABEL(mp), ipst);
7997 
7998 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
7999 			    "ire %p, sire %p\n",
8000 			    multirt_is_resolvable,
8001 			    (void *)ire, (void *)sire));
8002 
8003 			if (!multirt_is_resolvable) {
8004 				/*
8005 				 * No more multirt route to resolve; give up
8006 				 * (all routes resolved or no more
8007 				 * resolvable routes).
8008 				 */
8009 				if (ire != NULL) {
8010 					ire_refrele(ire);
8011 					ire = NULL;
8012 				}
8013 			} else {
8014 				ASSERT(sire != NULL);
8015 				ASSERT(ire != NULL);
8016 				/*
8017 				 * We simply use first_sire as a flag that
8018 				 * indicates if a resolvable multirt route
8019 				 * has already been found.
8020 				 * If it is not the case, we may have to send
8021 				 * an ICMP error to report that the
8022 				 * destination is unreachable.
8023 				 * We do not IRE_REFHOLD first_sire.
8024 				 */
8025 				if (first_sire == NULL) {
8026 					first_sire = sire;
8027 				}
8028 			}
8029 		}
8030 		if (ire == NULL) {
8031 			if (ip_debug > 3) {
8032 				/* ip2dbg */
8033 				pr_addr_dbg("ip_newroute: "
8034 				    "can't resolve %s\n", AF_INET, &dst);
8035 			}
8036 			ip3dbg(("ip_newroute: "
8037 			    "ire %p, sire %p, first_sire %p\n",
8038 			    (void *)ire, (void *)sire, (void *)first_sire));
8039 
8040 			if (sire != NULL) {
8041 				ire_refrele(sire);
8042 				sire = NULL;
8043 			}
8044 
8045 			if (first_sire != NULL) {
8046 				/*
8047 				 * At least one multirt route has been found
8048 				 * in the same call to ip_newroute();
8049 				 * there is no need to report an ICMP error.
8050 				 * first_sire was not IRE_REFHOLDed.
8051 				 */
8052 				MULTIRT_DEBUG_UNTAG(first_mp);
8053 				freemsg(first_mp);
8054 				return;
8055 			}
8056 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8057 			    RTA_DST, ipst);
8058 			if (attach_ill != NULL)
8059 				ill_refrele(attach_ill);
8060 			goto icmp_err_ret;
8061 		}
8062 
8063 		/*
8064 		 * Verify that the returned IRE does not have either
8065 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8066 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8067 		 */
8068 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8069 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8070 			if (attach_ill != NULL)
8071 				ill_refrele(attach_ill);
8072 			goto icmp_err_ret;
8073 		}
8074 		/*
8075 		 * Increment the ire_ob_pkt_count field for ire if it is an
8076 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8077 		 * increment the same for the parent IRE, sire, if it is some
8078 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8079 		 */
8080 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8081 			UPDATE_OB_PKT_COUNT(ire);
8082 			ire->ire_last_used_time = lbolt;
8083 		}
8084 
8085 		if (sire != NULL) {
8086 			gw = sire->ire_gateway_addr;
8087 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8088 			    IRE_INTERFACE)) == 0);
8089 			UPDATE_OB_PKT_COUNT(sire);
8090 			sire->ire_last_used_time = lbolt;
8091 		}
8092 		/*
8093 		 * We have a route to reach the destination.
8094 		 *
8095 		 * 1) If the interface is part of ill group, try to get a new
8096 		 *    ill taking load spreading into account.
8097 		 *
8098 		 * 2) After selecting the ill, get a source address that
8099 		 *    might create good inbound load spreading.
8100 		 *    ipif_select_source does this for us.
8101 		 *
8102 		 * If the application specified the ill (ifindex), we still
8103 		 * load spread. Only if the packets needs to go out
8104 		 * specifically on a given ill e.g. binding to
8105 		 * IPIF_NOFAILOVER address, then we don't try to use a
8106 		 * different ill for load spreading.
8107 		 */
8108 		if (attach_ill == NULL) {
8109 			/*
8110 			 * Don't perform outbound load spreading in the
8111 			 * case of an RTF_MULTIRT route, as we actually
8112 			 * typically want to replicate outgoing packets
8113 			 * through particular interfaces.
8114 			 */
8115 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8116 				dst_ill = ire->ire_ipif->ipif_ill;
8117 				/* for uniformity */
8118 				ill_refhold(dst_ill);
8119 			} else {
8120 				/*
8121 				 * If we are here trying to create an IRE_CACHE
8122 				 * for an offlink destination and have the
8123 				 * IRE_CACHE for the next hop and the latter is
8124 				 * using virtual IP source address selection i.e
8125 				 * it's ire->ire_ipif is pointing to a virtual
8126 				 * network interface (vni) then
8127 				 * ip_newroute_get_dst_ll() will return the vni
8128 				 * interface as the dst_ill. Since the vni is
8129 				 * virtual i.e not associated with any physical
8130 				 * interface, it cannot be the dst_ill, hence
8131 				 * in such a case call ip_newroute_get_dst_ll()
8132 				 * with the stq_ill instead of the ire_ipif ILL.
8133 				 * The function returns a refheld ill.
8134 				 */
8135 				if ((ire->ire_type == IRE_CACHE) &&
8136 				    IS_VNI(ire->ire_ipif->ipif_ill))
8137 					dst_ill = ip_newroute_get_dst_ill(
8138 					    ire->ire_stq->q_ptr);
8139 				else
8140 					dst_ill = ip_newroute_get_dst_ill(
8141 					    ire->ire_ipif->ipif_ill);
8142 			}
8143 			if (dst_ill == NULL) {
8144 				if (ip_debug > 2) {
8145 					pr_addr_dbg("ip_newroute: "
8146 					    "no dst ill for dst"
8147 					    " %s\n", AF_INET, &dst);
8148 				}
8149 				goto icmp_err_ret;
8150 			}
8151 		} else {
8152 			dst_ill = ire->ire_ipif->ipif_ill;
8153 			/* for uniformity */
8154 			ill_refhold(dst_ill);
8155 			/*
8156 			 * We should have found a route matching ill as we
8157 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
8158 			 * Rather than asserting, when there is a mismatch,
8159 			 * we just drop the packet.
8160 			 */
8161 			if (dst_ill != attach_ill) {
8162 				ip0dbg(("ip_newroute: Packet dropped as "
8163 				    "IPIF_NOFAILOVER ill is %s, "
8164 				    "ire->ire_ipif->ipif_ill is %s\n",
8165 				    attach_ill->ill_name,
8166 				    dst_ill->ill_name));
8167 				ill_refrele(attach_ill);
8168 				goto icmp_err_ret;
8169 			}
8170 		}
8171 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
8172 		if (attach_ill != NULL) {
8173 			ill_refrele(attach_ill);
8174 			attach_ill = NULL;
8175 			do_attach_ill = B_TRUE;
8176 		}
8177 		ASSERT(dst_ill != NULL);
8178 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8179 
8180 		/*
8181 		 * Pick the best source address from dst_ill.
8182 		 *
8183 		 * 1) If it is part of a multipathing group, we would
8184 		 *    like to spread the inbound packets across different
8185 		 *    interfaces. ipif_select_source picks a random source
8186 		 *    across the different ills in the group.
8187 		 *
8188 		 * 2) If it is not part of a multipathing group, we try
8189 		 *    to pick the source address from the destination
8190 		 *    route. Clustering assumes that when we have multiple
8191 		 *    prefixes hosted on an interface, the prefix of the
8192 		 *    source address matches the prefix of the destination
8193 		 *    route. We do this only if the address is not
8194 		 *    DEPRECATED.
8195 		 *
8196 		 * 3) If the conn is in a different zone than the ire, we
8197 		 *    need to pick a source address from the right zone.
8198 		 *
8199 		 * NOTE : If we hit case (1) above, the prefix of the source
8200 		 *	  address picked may not match the prefix of the
8201 		 *	  destination routes prefix as ipif_select_source
8202 		 *	  does not look at "dst" while picking a source
8203 		 *	  address.
8204 		 *	  If we want the same behavior as (2), we will need
8205 		 *	  to change the behavior of ipif_select_source.
8206 		 */
8207 		ASSERT(src_ipif == NULL);
8208 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8209 			/*
8210 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8211 			 * Check that the ipif matching the requested source
8212 			 * address still exists.
8213 			 */
8214 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8215 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8216 		}
8217 
8218 		unspec_src = (connp != NULL && connp->conn_unspec_src);
8219 
8220 		if (src_ipif == NULL &&
8221 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
8222 			ire_marks |= IRE_MARK_USESRC_CHECK;
8223 			if ((dst_ill->ill_group != NULL) ||
8224 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8225 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8226 			    ire->ire_zoneid != ALL_ZONES) ||
8227 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8228 				/*
8229 				 * If the destination is reachable via a
8230 				 * given gateway, the selected source address
8231 				 * should be in the same subnet as the gateway.
8232 				 * Otherwise, the destination is not reachable.
8233 				 *
8234 				 * If there are no interfaces on the same subnet
8235 				 * as the destination, ipif_select_source gives
8236 				 * first non-deprecated interface which might be
8237 				 * on a different subnet than the gateway.
8238 				 * This is not desirable. Hence pass the dst_ire
8239 				 * source address to ipif_select_source.
8240 				 * It is sure that the destination is reachable
8241 				 * with the dst_ire source address subnet.
8242 				 * So passing dst_ire source address to
8243 				 * ipif_select_source will make sure that the
8244 				 * selected source will be on the same subnet
8245 				 * as dst_ire source address.
8246 				 */
8247 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8248 				src_ipif = ipif_select_source(dst_ill, saddr,
8249 				    zoneid);
8250 				if (src_ipif == NULL) {
8251 					if (ip_debug > 2) {
8252 						pr_addr_dbg("ip_newroute: "
8253 						    "no src for dst %s ",
8254 						    AF_INET, &dst);
8255 						printf("through interface %s\n",
8256 						    dst_ill->ill_name);
8257 					}
8258 					goto icmp_err_ret;
8259 				}
8260 			} else {
8261 				src_ipif = ire->ire_ipif;
8262 				ASSERT(src_ipif != NULL);
8263 				/* hold src_ipif for uniformity */
8264 				ipif_refhold(src_ipif);
8265 			}
8266 		}
8267 
8268 		/*
8269 		 * Assign a source address while we have the conn.
8270 		 * We can't have ip_wput_ire pick a source address when the
8271 		 * packet returns from arp since we need to look at
8272 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8273 		 * going through arp.
8274 		 *
8275 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8276 		 *	  it uses ip6i to store this information.
8277 		 */
8278 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
8279 			ipha->ipha_src = src_ipif->ipif_src_addr;
8280 
8281 		if (ip_debug > 3) {
8282 			/* ip2dbg */
8283 			pr_addr_dbg("ip_newroute: first hop %s\n",
8284 			    AF_INET, &gw);
8285 		}
8286 		ip2dbg(("\tire type %s (%d)\n",
8287 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8288 
8289 		/*
8290 		 * The TTL of multirouted packets is bounded by the
8291 		 * ip_multirt_ttl ndd variable.
8292 		 */
8293 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8294 			/* Force TTL of multirouted packets */
8295 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8296 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8297 				ip2dbg(("ip_newroute: forcing multirt TTL "
8298 				    "to %d (was %d), dst 0x%08x\n",
8299 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8300 				    ntohl(sire->ire_addr)));
8301 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8302 			}
8303 		}
8304 		/*
8305 		 * At this point in ip_newroute(), ire is either the
8306 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8307 		 * destination or an IRE_INTERFACE type that should be used
8308 		 * to resolve an on-subnet destination or an on-subnet
8309 		 * next-hop gateway.
8310 		 *
8311 		 * In the IRE_CACHE case, we have the following :
8312 		 *
8313 		 * 1) src_ipif - used for getting a source address.
8314 		 *
8315 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8316 		 *    means packets using this IRE_CACHE will go out on
8317 		 *    dst_ill.
8318 		 *
8319 		 * 3) The IRE sire will point to the prefix that is the
8320 		 *    longest  matching route for the destination. These
8321 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8322 		 *
8323 		 *    The newly created IRE_CACHE entry for the off-subnet
8324 		 *    destination is tied to both the prefix route and the
8325 		 *    interface route used to resolve the next-hop gateway
8326 		 *    via the ire_phandle and ire_ihandle fields,
8327 		 *    respectively.
8328 		 *
8329 		 * In the IRE_INTERFACE case, we have the following :
8330 		 *
8331 		 * 1) src_ipif - used for getting a source address.
8332 		 *
8333 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8334 		 *    means packets using the IRE_CACHE that we will build
8335 		 *    here will go out on dst_ill.
8336 		 *
8337 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8338 		 *    to be created will only be tied to the IRE_INTERFACE
8339 		 *    that was derived from the ire_ihandle field.
8340 		 *
8341 		 *    If sire is non-NULL, it means the destination is
8342 		 *    off-link and we will first create the IRE_CACHE for the
8343 		 *    gateway. Next time through ip_newroute, we will create
8344 		 *    the IRE_CACHE for the final destination as described
8345 		 *    above.
8346 		 *
8347 		 * In both cases, after the current resolution has been
8348 		 * completed (or possibly initialised, in the IRE_INTERFACE
8349 		 * case), the loop may be re-entered to attempt the resolution
8350 		 * of another RTF_MULTIRT route.
8351 		 *
8352 		 * When an IRE_CACHE entry for the off-subnet destination is
8353 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8354 		 * for further processing in emission loops.
8355 		 */
8356 		save_ire = ire;
8357 		switch (ire->ire_type) {
8358 		case IRE_CACHE: {
8359 			ire_t	*ipif_ire;
8360 
8361 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8362 			if (gw == 0)
8363 				gw = ire->ire_gateway_addr;
8364 			/*
8365 			 * We need 3 ire's to create a new cache ire for an
8366 			 * off-link destination from the cache ire of the
8367 			 * gateway.
8368 			 *
8369 			 *	1. The prefix ire 'sire' (Note that this does
8370 			 *	   not apply to the conn_nexthop_set case)
8371 			 *	2. The cache ire of the gateway 'ire'
8372 			 *	3. The interface ire 'ipif_ire'
8373 			 *
8374 			 * We have (1) and (2). We lookup (3) below.
8375 			 *
8376 			 * If there is no interface route to the gateway,
8377 			 * it is a race condition, where we found the cache
8378 			 * but the interface route has been deleted.
8379 			 */
8380 			if (ip_nexthop) {
8381 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8382 			} else {
8383 				ipif_ire =
8384 				    ire_ihandle_lookup_offlink(ire, sire);
8385 			}
8386 			if (ipif_ire == NULL) {
8387 				ip1dbg(("ip_newroute: "
8388 				    "ire_ihandle_lookup_offlink failed\n"));
8389 				goto icmp_err_ret;
8390 			}
8391 
8392 			/*
8393 			 * Check cached gateway IRE for any security
8394 			 * attributes; if found, associate the gateway
8395 			 * credentials group to the destination IRE.
8396 			 */
8397 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8398 				mutex_enter(&attrp->igsa_lock);
8399 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8400 					GCGRP_REFHOLD(gcgrp);
8401 				mutex_exit(&attrp->igsa_lock);
8402 			}
8403 
8404 			/*
8405 			 * XXX For the source of the resolver mp,
8406 			 * we are using the same DL_UNITDATA_REQ
8407 			 * (from save_ire->ire_nce->nce_res_mp)
8408 			 * though the save_ire is not pointing at the same ill.
8409 			 * This is incorrect. We need to send it up to the
8410 			 * resolver to get the right res_mp. For ethernets
8411 			 * this may be okay (ill_type == DL_ETHER).
8412 			 */
8413 
8414 			ire = ire_create(
8415 			    (uchar_t *)&dst,		/* dest address */
8416 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8417 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8418 			    (uchar_t *)&gw,		/* gateway address */
8419 			    &save_ire->ire_max_frag,
8420 			    save_ire->ire_nce,		/* src nce */
8421 			    dst_ill->ill_rq,		/* recv-from queue */
8422 			    dst_ill->ill_wq,		/* send-to queue */
8423 			    IRE_CACHE,			/* IRE type */
8424 			    src_ipif,
8425 			    (sire != NULL) ?
8426 			    sire->ire_mask : 0, 	/* Parent mask */
8427 			    (sire != NULL) ?
8428 			    sire->ire_phandle : 0,	/* Parent handle */
8429 			    ipif_ire->ire_ihandle,	/* Interface handle */
8430 			    (sire != NULL) ? (sire->ire_flags &
8431 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8432 			    (sire != NULL) ?
8433 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8434 			    NULL,
8435 			    gcgrp,
8436 			    ipst);
8437 
8438 			if (ire == NULL) {
8439 				if (gcgrp != NULL) {
8440 					GCGRP_REFRELE(gcgrp);
8441 					gcgrp = NULL;
8442 				}
8443 				ire_refrele(ipif_ire);
8444 				ire_refrele(save_ire);
8445 				break;
8446 			}
8447 
8448 			/* reference now held by IRE */
8449 			gcgrp = NULL;
8450 
8451 			ire->ire_marks |= ire_marks;
8452 
8453 			/*
8454 			 * Prevent sire and ipif_ire from getting deleted.
8455 			 * The newly created ire is tied to both of them via
8456 			 * the phandle and ihandle respectively.
8457 			 */
8458 			if (sire != NULL) {
8459 				IRB_REFHOLD(sire->ire_bucket);
8460 				/* Has it been removed already ? */
8461 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8462 					IRB_REFRELE(sire->ire_bucket);
8463 					ire_refrele(ipif_ire);
8464 					ire_refrele(save_ire);
8465 					break;
8466 				}
8467 			}
8468 
8469 			IRB_REFHOLD(ipif_ire->ire_bucket);
8470 			/* Has it been removed already ? */
8471 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8472 				IRB_REFRELE(ipif_ire->ire_bucket);
8473 				if (sire != NULL)
8474 					IRB_REFRELE(sire->ire_bucket);
8475 				ire_refrele(ipif_ire);
8476 				ire_refrele(save_ire);
8477 				break;
8478 			}
8479 
8480 			xmit_mp = first_mp;
8481 			/*
8482 			 * In the case of multirouting, a copy
8483 			 * of the packet is done before its sending.
8484 			 * The copy is used to attempt another
8485 			 * route resolution, in a next loop.
8486 			 */
8487 			if (ire->ire_flags & RTF_MULTIRT) {
8488 				copy_mp = copymsg(first_mp);
8489 				if (copy_mp != NULL) {
8490 					xmit_mp = copy_mp;
8491 					MULTIRT_DEBUG_TAG(first_mp);
8492 				}
8493 			}
8494 			ire_add_then_send(q, ire, xmit_mp);
8495 			ire_refrele(save_ire);
8496 
8497 			/* Assert that sire is not deleted yet. */
8498 			if (sire != NULL) {
8499 				ASSERT(sire->ire_ptpn != NULL);
8500 				IRB_REFRELE(sire->ire_bucket);
8501 			}
8502 
8503 			/* Assert that ipif_ire is not deleted yet. */
8504 			ASSERT(ipif_ire->ire_ptpn != NULL);
8505 			IRB_REFRELE(ipif_ire->ire_bucket);
8506 			ire_refrele(ipif_ire);
8507 
8508 			/*
8509 			 * If copy_mp is not NULL, multirouting was
8510 			 * requested. We loop to initiate a next
8511 			 * route resolution attempt, starting from sire.
8512 			 */
8513 			if (copy_mp != NULL) {
8514 				/*
8515 				 * Search for the next unresolved
8516 				 * multirt route.
8517 				 */
8518 				copy_mp = NULL;
8519 				ipif_ire = NULL;
8520 				ire = NULL;
8521 				multirt_resolve_next = B_TRUE;
8522 				continue;
8523 			}
8524 			if (sire != NULL)
8525 				ire_refrele(sire);
8526 			ipif_refrele(src_ipif);
8527 			ill_refrele(dst_ill);
8528 			return;
8529 		}
8530 		case IRE_IF_NORESOLVER: {
8531 
8532 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8533 			    dst_ill->ill_resolver_mp == NULL) {
8534 				ip1dbg(("ip_newroute: dst_ill %p "
8535 				    "for IRE_IF_NORESOLVER ire %p has "
8536 				    "no ill_resolver_mp\n",
8537 				    (void *)dst_ill, (void *)ire));
8538 				break;
8539 			}
8540 
8541 			/*
8542 			 * TSol note: We are creating the ire cache for the
8543 			 * destination 'dst'. If 'dst' is offlink, going
8544 			 * through the first hop 'gw', the security attributes
8545 			 * of 'dst' must be set to point to the gateway
8546 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8547 			 * is possible that 'dst' is a potential gateway that is
8548 			 * referenced by some route that has some security
8549 			 * attributes. Thus in the former case, we need to do a
8550 			 * gcgrp_lookup of 'gw' while in the latter case we
8551 			 * need to do gcgrp_lookup of 'dst' itself.
8552 			 */
8553 			ga.ga_af = AF_INET;
8554 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8555 			    &ga.ga_addr);
8556 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8557 
8558 			ire = ire_create(
8559 			    (uchar_t *)&dst,		/* dest address */
8560 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8561 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8562 			    (uchar_t *)&gw,		/* gateway address */
8563 			    &save_ire->ire_max_frag,
8564 			    NULL,			/* no src nce */
8565 			    dst_ill->ill_rq,		/* recv-from queue */
8566 			    dst_ill->ill_wq,		/* send-to queue */
8567 			    IRE_CACHE,
8568 			    src_ipif,
8569 			    save_ire->ire_mask,		/* Parent mask */
8570 			    (sire != NULL) ?		/* Parent handle */
8571 			    sire->ire_phandle : 0,
8572 			    save_ire->ire_ihandle,	/* Interface handle */
8573 			    (sire != NULL) ? sire->ire_flags &
8574 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8575 			    &(save_ire->ire_uinfo),
8576 			    NULL,
8577 			    gcgrp,
8578 			    ipst);
8579 
8580 			if (ire == NULL) {
8581 				if (gcgrp != NULL) {
8582 					GCGRP_REFRELE(gcgrp);
8583 					gcgrp = NULL;
8584 				}
8585 				ire_refrele(save_ire);
8586 				break;
8587 			}
8588 
8589 			/* reference now held by IRE */
8590 			gcgrp = NULL;
8591 
8592 			ire->ire_marks |= ire_marks;
8593 
8594 			/* Prevent save_ire from getting deleted */
8595 			IRB_REFHOLD(save_ire->ire_bucket);
8596 			/* Has it been removed already ? */
8597 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8598 				IRB_REFRELE(save_ire->ire_bucket);
8599 				ire_refrele(save_ire);
8600 				break;
8601 			}
8602 
8603 			/*
8604 			 * In the case of multirouting, a copy
8605 			 * of the packet is made before it is sent.
8606 			 * The copy is used in the next
8607 			 * loop to attempt another resolution.
8608 			 */
8609 			xmit_mp = first_mp;
8610 			if ((sire != NULL) &&
8611 			    (sire->ire_flags & RTF_MULTIRT)) {
8612 				copy_mp = copymsg(first_mp);
8613 				if (copy_mp != NULL) {
8614 					xmit_mp = copy_mp;
8615 					MULTIRT_DEBUG_TAG(first_mp);
8616 				}
8617 			}
8618 			ire_add_then_send(q, ire, xmit_mp);
8619 
8620 			/* Assert that it is not deleted yet. */
8621 			ASSERT(save_ire->ire_ptpn != NULL);
8622 			IRB_REFRELE(save_ire->ire_bucket);
8623 			ire_refrele(save_ire);
8624 
8625 			if (copy_mp != NULL) {
8626 				/*
8627 				 * If we found a (no)resolver, we ignore any
8628 				 * trailing top priority IRE_CACHE in further
8629 				 * loops. This ensures that we do not omit any
8630 				 * (no)resolver.
8631 				 * This IRE_CACHE, if any, will be processed
8632 				 * by another thread entering ip_newroute().
8633 				 * IRE_CACHE entries, if any, will be processed
8634 				 * by another thread entering ip_newroute(),
8635 				 * (upon resolver response, for instance).
8636 				 * This aims to force parallel multirt
8637 				 * resolutions as soon as a packet must be sent.
8638 				 * In the best case, after the tx of only one
8639 				 * packet, all reachable routes are resolved.
8640 				 * Otherwise, the resolution of all RTF_MULTIRT
8641 				 * routes would require several emissions.
8642 				 */
8643 				multirt_flags &= ~MULTIRT_CACHEGW;
8644 
8645 				/*
8646 				 * Search for the next unresolved multirt
8647 				 * route.
8648 				 */
8649 				copy_mp = NULL;
8650 				save_ire = NULL;
8651 				ire = NULL;
8652 				multirt_resolve_next = B_TRUE;
8653 				continue;
8654 			}
8655 
8656 			/*
8657 			 * Don't need sire anymore
8658 			 */
8659 			if (sire != NULL)
8660 				ire_refrele(sire);
8661 
8662 			ipif_refrele(src_ipif);
8663 			ill_refrele(dst_ill);
8664 			return;
8665 		}
8666 		case IRE_IF_RESOLVER:
8667 			/*
8668 			 * We can't build an IRE_CACHE yet, but at least we
8669 			 * found a resolver that can help.
8670 			 */
8671 			res_mp = dst_ill->ill_resolver_mp;
8672 			if (!OK_RESOLVER_MP(res_mp))
8673 				break;
8674 
8675 			/*
8676 			 * To be at this point in the code with a non-zero gw
8677 			 * means that dst is reachable through a gateway that
8678 			 * we have never resolved.  By changing dst to the gw
8679 			 * addr we resolve the gateway first.
8680 			 * When ire_add_then_send() tries to put the IP dg
8681 			 * to dst, it will reenter ip_newroute() at which
8682 			 * time we will find the IRE_CACHE for the gw and
8683 			 * create another IRE_CACHE in case IRE_CACHE above.
8684 			 */
8685 			if (gw != INADDR_ANY) {
8686 				/*
8687 				 * The source ipif that was determined above was
8688 				 * relative to the destination address, not the
8689 				 * gateway's. If src_ipif was not taken out of
8690 				 * the IRE_IF_RESOLVER entry, we'll need to call
8691 				 * ipif_select_source() again.
8692 				 */
8693 				if (src_ipif != ire->ire_ipif) {
8694 					ipif_refrele(src_ipif);
8695 					src_ipif = ipif_select_source(dst_ill,
8696 					    gw, zoneid);
8697 					if (src_ipif == NULL) {
8698 						if (ip_debug > 2) {
8699 							pr_addr_dbg(
8700 							    "ip_newroute: no "
8701 							    "src for gw %s ",
8702 							    AF_INET, &gw);
8703 							printf("through "
8704 							    "interface %s\n",
8705 							    dst_ill->ill_name);
8706 						}
8707 						goto icmp_err_ret;
8708 					}
8709 				}
8710 				save_dst = dst;
8711 				dst = gw;
8712 				gw = INADDR_ANY;
8713 			}
8714 
8715 			/*
8716 			 * We obtain a partial IRE_CACHE which we will pass
8717 			 * along with the resolver query.  When the response
8718 			 * comes back it will be there ready for us to add.
8719 			 * The ire_max_frag is atomically set under the
8720 			 * irebucket lock in ire_add_v[46].
8721 			 */
8722 
8723 			ire = ire_create_mp(
8724 			    (uchar_t *)&dst,		/* dest address */
8725 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8726 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8727 			    (uchar_t *)&gw,		/* gateway address */
8728 			    NULL,			/* ire_max_frag */
8729 			    NULL,			/* no src nce */
8730 			    dst_ill->ill_rq,		/* recv-from queue */
8731 			    dst_ill->ill_wq,		/* send-to queue */
8732 			    IRE_CACHE,
8733 			    src_ipif,			/* Interface ipif */
8734 			    save_ire->ire_mask,		/* Parent mask */
8735 			    0,
8736 			    save_ire->ire_ihandle,	/* Interface handle */
8737 			    0,				/* flags if any */
8738 			    &(save_ire->ire_uinfo),
8739 			    NULL,
8740 			    NULL,
8741 			    ipst);
8742 
8743 			if (ire == NULL) {
8744 				ire_refrele(save_ire);
8745 				break;
8746 			}
8747 
8748 			if ((sire != NULL) &&
8749 			    (sire->ire_flags & RTF_MULTIRT)) {
8750 				copy_mp = copymsg(first_mp);
8751 				if (copy_mp != NULL)
8752 					MULTIRT_DEBUG_TAG(copy_mp);
8753 			}
8754 
8755 			ire->ire_marks |= ire_marks;
8756 
8757 			/*
8758 			 * Construct message chain for the resolver
8759 			 * of the form:
8760 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8761 			 * Packet could contain a IPSEC_OUT mp.
8762 			 *
8763 			 * NOTE : ire will be added later when the response
8764 			 * comes back from ARP. If the response does not
8765 			 * come back, ARP frees the packet. For this reason,
8766 			 * we can't REFHOLD the bucket of save_ire to prevent
8767 			 * deletions. We may not be able to REFRELE the bucket
8768 			 * if the response never comes back. Thus, before
8769 			 * adding the ire, ire_add_v4 will make sure that the
8770 			 * interface route does not get deleted. This is the
8771 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8772 			 * where we can always prevent deletions because of
8773 			 * the synchronous nature of adding IRES i.e
8774 			 * ire_add_then_send is called after creating the IRE.
8775 			 */
8776 			ASSERT(ire->ire_mp != NULL);
8777 			ire->ire_mp->b_cont = first_mp;
8778 			/* Have saved_mp handy, for cleanup if canput fails */
8779 			saved_mp = mp;
8780 			mp = copyb(res_mp);
8781 			if (mp == NULL) {
8782 				/* Prepare for cleanup */
8783 				mp = saved_mp; /* pkt */
8784 				ire_delete(ire); /* ire_mp */
8785 				ire = NULL;
8786 				ire_refrele(save_ire);
8787 				if (copy_mp != NULL) {
8788 					MULTIRT_DEBUG_UNTAG(copy_mp);
8789 					freemsg(copy_mp);
8790 					copy_mp = NULL;
8791 				}
8792 				break;
8793 			}
8794 			linkb(mp, ire->ire_mp);
8795 
8796 			/*
8797 			 * Fill in the source and dest addrs for the resolver.
8798 			 * NOTE: this depends on memory layouts imposed by
8799 			 * ill_init().
8800 			 */
8801 			areq = (areq_t *)mp->b_rptr;
8802 			addrp = (ipaddr_t *)((char *)areq +
8803 			    areq->areq_sender_addr_offset);
8804 			if (do_attach_ill) {
8805 				/*
8806 				 * This is bind to no failover case.
8807 				 * arp packet also must go out on attach_ill.
8808 				 */
8809 				ASSERT(ipha->ipha_src != NULL);
8810 				*addrp = ipha->ipha_src;
8811 			} else {
8812 				*addrp = save_ire->ire_src_addr;
8813 			}
8814 
8815 			ire_refrele(save_ire);
8816 			addrp = (ipaddr_t *)((char *)areq +
8817 			    areq->areq_target_addr_offset);
8818 			*addrp = dst;
8819 			/* Up to the resolver. */
8820 			if (canputnext(dst_ill->ill_rq) &&
8821 			    !(dst_ill->ill_arp_closing)) {
8822 				putnext(dst_ill->ill_rq, mp);
8823 				ire = NULL;
8824 				if (copy_mp != NULL) {
8825 					/*
8826 					 * If we found a resolver, we ignore
8827 					 * any trailing top priority IRE_CACHE
8828 					 * in the further loops. This ensures
8829 					 * that we do not omit any resolver.
8830 					 * IRE_CACHE entries, if any, will be
8831 					 * processed next time we enter
8832 					 * ip_newroute().
8833 					 */
8834 					multirt_flags &= ~MULTIRT_CACHEGW;
8835 					/*
8836 					 * Search for the next unresolved
8837 					 * multirt route.
8838 					 */
8839 					first_mp = copy_mp;
8840 					copy_mp = NULL;
8841 					/* Prepare the next resolution loop. */
8842 					mp = first_mp;
8843 					EXTRACT_PKT_MP(mp, first_mp,
8844 					    mctl_present);
8845 					if (mctl_present)
8846 						io = (ipsec_out_t *)
8847 						    first_mp->b_rptr;
8848 					ipha = (ipha_t *)mp->b_rptr;
8849 
8850 					ASSERT(sire != NULL);
8851 
8852 					dst = save_dst;
8853 					multirt_resolve_next = B_TRUE;
8854 					continue;
8855 				}
8856 
8857 				if (sire != NULL)
8858 					ire_refrele(sire);
8859 
8860 				/*
8861 				 * The response will come back in ip_wput
8862 				 * with db_type IRE_DB_TYPE.
8863 				 */
8864 				ipif_refrele(src_ipif);
8865 				ill_refrele(dst_ill);
8866 				return;
8867 			} else {
8868 				/* Prepare for cleanup */
8869 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8870 				    mp);
8871 				mp->b_cont = NULL;
8872 				freeb(mp); /* areq */
8873 				/*
8874 				 * this is an ire that is not added to the
8875 				 * cache. ire_freemblk will handle the release
8876 				 * of any resources associated with the ire.
8877 				 */
8878 				ire_delete(ire); /* ire_mp */
8879 				mp = saved_mp; /* pkt */
8880 				ire = NULL;
8881 				if (copy_mp != NULL) {
8882 					MULTIRT_DEBUG_UNTAG(copy_mp);
8883 					freemsg(copy_mp);
8884 					copy_mp = NULL;
8885 				}
8886 				break;
8887 			}
8888 		default:
8889 			break;
8890 		}
8891 	} while (multirt_resolve_next);
8892 
8893 	ip1dbg(("ip_newroute: dropped\n"));
8894 	/* Did this packet originate externally? */
8895 	if (mp->b_prev) {
8896 		mp->b_next = NULL;
8897 		mp->b_prev = NULL;
8898 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8899 	} else {
8900 		if (dst_ill != NULL) {
8901 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8902 		} else {
8903 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8904 		}
8905 	}
8906 	ASSERT(copy_mp == NULL);
8907 	MULTIRT_DEBUG_UNTAG(first_mp);
8908 	freemsg(first_mp);
8909 	if (ire != NULL)
8910 		ire_refrele(ire);
8911 	if (sire != NULL)
8912 		ire_refrele(sire);
8913 	if (src_ipif != NULL)
8914 		ipif_refrele(src_ipif);
8915 	if (dst_ill != NULL)
8916 		ill_refrele(dst_ill);
8917 	return;
8918 
8919 icmp_err_ret:
8920 	ip1dbg(("ip_newroute: no route\n"));
8921 	if (src_ipif != NULL)
8922 		ipif_refrele(src_ipif);
8923 	if (dst_ill != NULL)
8924 		ill_refrele(dst_ill);
8925 	if (sire != NULL)
8926 		ire_refrele(sire);
8927 	/* Did this packet originate externally? */
8928 	if (mp->b_prev) {
8929 		mp->b_next = NULL;
8930 		mp->b_prev = NULL;
8931 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8932 		q = WR(q);
8933 	} else {
8934 		/*
8935 		 * There is no outgoing ill, so just increment the
8936 		 * system MIB.
8937 		 */
8938 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
8939 		/*
8940 		 * Since ip_wput() isn't close to finished, we fill
8941 		 * in enough of the header for credible error reporting.
8942 		 */
8943 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
8944 			/* Failed */
8945 			MULTIRT_DEBUG_UNTAG(first_mp);
8946 			freemsg(first_mp);
8947 			if (ire != NULL)
8948 				ire_refrele(ire);
8949 			return;
8950 		}
8951 	}
8952 
8953 	/*
8954 	 * At this point we will have ire only if RTF_BLACKHOLE
8955 	 * or RTF_REJECT flags are set on the IRE. It will not
8956 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8957 	 */
8958 	if (ire != NULL) {
8959 		if (ire->ire_flags & RTF_BLACKHOLE) {
8960 			ire_refrele(ire);
8961 			MULTIRT_DEBUG_UNTAG(first_mp);
8962 			freemsg(first_mp);
8963 			return;
8964 		}
8965 		ire_refrele(ire);
8966 	}
8967 	if (ip_source_routed(ipha, ipst)) {
8968 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8969 		    zoneid, ipst);
8970 		return;
8971 	}
8972 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
8973 }
8974 
8975 ip_opt_info_t zero_info;
8976 
8977 /*
8978  * IPv4 -
8979  * ip_newroute_ipif is called by ip_wput_multicast and
8980  * ip_rput_forward_multicast whenever we need to send
8981  * out a packet to a destination address for which we do not have specific
8982  * routing information. It is used when the packet will be sent out
8983  * on a specific interface. It is also called by ip_wput() when IP_BOUND_IF
8984  * socket option is set or icmp error message wants to go out on a particular
8985  * interface for a unicast packet.
8986  *
8987  * In most cases, the destination address is resolved thanks to the ipif
8988  * intrinsic resolver. However, there are some cases where the call to
8989  * ip_newroute_ipif must take into account the potential presence of
8990  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8991  * that uses the interface. This is specified through flags,
8992  * which can be a combination of:
8993  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8994  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
8995  *   and flags. Additionally, the packet source address has to be set to
8996  *   the specified address. The caller is thus expected to set this flag
8997  *   if the packet has no specific source address yet.
8998  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
8999  *   flag, the resulting ire will inherit the flag. All unresolved routes
9000  *   to the destination must be explored in the same call to
9001  *   ip_newroute_ipif().
9002  */
9003 static void
9004 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
9005     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
9006 {
9007 	areq_t	*areq;
9008 	ire_t	*ire = NULL;
9009 	mblk_t	*res_mp;
9010 	ipaddr_t *addrp;
9011 	mblk_t *first_mp;
9012 	ire_t	*save_ire = NULL;
9013 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
9014 	ipif_t	*src_ipif = NULL;
9015 	ushort_t ire_marks = 0;
9016 	ill_t	*dst_ill = NULL;
9017 	boolean_t mctl_present;
9018 	ipsec_out_t *io;
9019 	ipha_t *ipha;
9020 	int	ihandle = 0;
9021 	mblk_t	*saved_mp;
9022 	ire_t   *fire = NULL;
9023 	mblk_t  *copy_mp = NULL;
9024 	boolean_t multirt_resolve_next;
9025 	boolean_t unspec_src;
9026 	ipaddr_t ipha_dst;
9027 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
9028 
9029 	/*
9030 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9031 	 * here for uniformity
9032 	 */
9033 	ipif_refhold(ipif);
9034 
9035 	/*
9036 	 * This loop is run only once in most cases.
9037 	 * We loop to resolve further routes only when the destination
9038 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9039 	 */
9040 	do {
9041 		if (dst_ill != NULL) {
9042 			ill_refrele(dst_ill);
9043 			dst_ill = NULL;
9044 		}
9045 		if (src_ipif != NULL) {
9046 			ipif_refrele(src_ipif);
9047 			src_ipif = NULL;
9048 		}
9049 		multirt_resolve_next = B_FALSE;
9050 
9051 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9052 		    ipif->ipif_ill->ill_name));
9053 
9054 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
9055 		if (mctl_present)
9056 			io = (ipsec_out_t *)first_mp->b_rptr;
9057 
9058 		ipha = (ipha_t *)mp->b_rptr;
9059 
9060 		/*
9061 		 * Save the packet destination address, we may need it after
9062 		 * the packet has been consumed.
9063 		 */
9064 		ipha_dst = ipha->ipha_dst;
9065 
9066 		/*
9067 		 * If the interface is a pt-pt interface we look for an
9068 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9069 		 * local_address and the pt-pt destination address. Otherwise
9070 		 * we just match the local address.
9071 		 * NOTE: dst could be different than ipha->ipha_dst in case
9072 		 * of sending igmp multicast packets over a point-to-point
9073 		 * connection.
9074 		 * Thus we must be careful enough to check ipha_dst to be a
9075 		 * multicast address, otherwise it will take xmit_if path for
9076 		 * multicast packets resulting into kernel stack overflow by
9077 		 * repeated calls to ip_newroute_ipif from ire_send().
9078 		 */
9079 		if (CLASSD(ipha_dst) &&
9080 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9081 			goto err_ret;
9082 		}
9083 
9084 		/*
9085 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9086 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9087 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9088 		 * propagate its flags to the new ire.
9089 		 */
9090 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9091 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9092 			ip2dbg(("ip_newroute_ipif: "
9093 			    "ipif_lookup_multi_ire("
9094 			    "ipif %p, dst %08x) = fire %p\n",
9095 			    (void *)ipif, ntohl(dst), (void *)fire));
9096 		}
9097 
9098 		if (mctl_present && io->ipsec_out_attach_if) {
9099 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
9100 			    io->ipsec_out_ill_index, B_FALSE, ipst);
9101 
9102 			/* Failure case frees things for us. */
9103 			if (attach_ill == NULL) {
9104 				ipif_refrele(ipif);
9105 				if (fire != NULL)
9106 					ire_refrele(fire);
9107 				return;
9108 			}
9109 
9110 			/*
9111 			 * Check if we need an ire that will not be
9112 			 * looked up by anybody else i.e. HIDDEN.
9113 			 */
9114 			if (ill_is_probeonly(attach_ill)) {
9115 				ire_marks = IRE_MARK_HIDDEN;
9116 			}
9117 			/*
9118 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
9119 			 * case.
9120 			 */
9121 			dst_ill = ipif->ipif_ill;
9122 			/* attach_ill has been refheld by ip_grab_attach_ill */
9123 			ASSERT(dst_ill == attach_ill);
9124 		} else {
9125 			/*
9126 			 * If the interface belongs to an interface group,
9127 			 * make sure the next possible interface in the group
9128 			 * is used.  This encourages load spreading among
9129 			 * peers in an interface group.
9130 			 * Note: load spreading is disabled for RTF_MULTIRT
9131 			 * routes.
9132 			 */
9133 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9134 			    (fire->ire_flags & RTF_MULTIRT)) {
9135 				/*
9136 				 * Don't perform outbound load spreading
9137 				 * in the case of an RTF_MULTIRT issued route,
9138 				 * we actually typically want to replicate
9139 				 * outgoing packets through particular
9140 				 * interfaces.
9141 				 */
9142 				dst_ill = ipif->ipif_ill;
9143 				ill_refhold(dst_ill);
9144 			} else {
9145 				dst_ill = ip_newroute_get_dst_ill(
9146 				    ipif->ipif_ill);
9147 			}
9148 			if (dst_ill == NULL) {
9149 				if (ip_debug > 2) {
9150 					pr_addr_dbg("ip_newroute_ipif: "
9151 					    "no dst ill for dst %s\n",
9152 					    AF_INET, &dst);
9153 				}
9154 				goto err_ret;
9155 			}
9156 		}
9157 
9158 		/*
9159 		 * Pick a source address preferring non-deprecated ones.
9160 		 * Unlike ip_newroute, we don't do any source address
9161 		 * selection here since for multicast it really does not help
9162 		 * in inbound load spreading as in the unicast case.
9163 		 */
9164 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9165 		    (fire->ire_flags & RTF_SETSRC)) {
9166 			/*
9167 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9168 			 * on that interface. This ire has RTF_SETSRC flag, so
9169 			 * the source address of the packet must be changed.
9170 			 * Check that the ipif matching the requested source
9171 			 * address still exists.
9172 			 */
9173 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9174 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9175 		}
9176 
9177 		unspec_src = (connp != NULL && connp->conn_unspec_src);
9178 
9179 		if (((!ipif->ipif_isv6 && ipif->ipif_lcl_addr == INADDR_ANY) ||
9180 		    (ipif->ipif_flags & (IPIF_DEPRECATED|IPIF_UP)) != IPIF_UP ||
9181 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9182 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9183 		    (src_ipif == NULL) &&
9184 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
9185 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9186 			if (src_ipif == NULL) {
9187 				if (ip_debug > 2) {
9188 					/* ip1dbg */
9189 					pr_addr_dbg("ip_newroute_ipif: "
9190 					    "no src for dst %s",
9191 					    AF_INET, &dst);
9192 				}
9193 				ip1dbg((" through interface %s\n",
9194 				    dst_ill->ill_name));
9195 				goto err_ret;
9196 			}
9197 			ipif_refrele(ipif);
9198 			ipif = src_ipif;
9199 			ipif_refhold(ipif);
9200 		}
9201 		if (src_ipif == NULL) {
9202 			src_ipif = ipif;
9203 			ipif_refhold(src_ipif);
9204 		}
9205 
9206 		/*
9207 		 * Assign a source address while we have the conn.
9208 		 * We can't have ip_wput_ire pick a source address when the
9209 		 * packet returns from arp since conn_unspec_src might be set
9210 		 * and we lose the conn when going through arp.
9211 		 */
9212 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
9213 			ipha->ipha_src = src_ipif->ipif_src_addr;
9214 
9215 		/*
9216 		 * In the case of IP_BOUND_IF and IP_PKTINFO, it is possible
9217 		 * that the outgoing interface does not have an interface ire.
9218 		 */
9219 		if (CLASSD(ipha_dst) && (connp == NULL ||
9220 		    connp->conn_outgoing_ill == NULL) &&
9221 		    infop->ip_opt_ill_index == 0) {
9222 			/* ipif_to_ire returns an held ire */
9223 			ire = ipif_to_ire(ipif);
9224 			if (ire == NULL)
9225 				goto err_ret;
9226 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9227 				goto err_ret;
9228 			/*
9229 			 * ihandle is needed when the ire is added to
9230 			 * cache table.
9231 			 */
9232 			save_ire = ire;
9233 			ihandle = save_ire->ire_ihandle;
9234 
9235 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9236 			    "flags %04x\n",
9237 			    (void *)ire, (void *)ipif, flags));
9238 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9239 			    (fire->ire_flags & RTF_MULTIRT)) {
9240 				/*
9241 				 * As requested by flags, an IRE_OFFSUBNET was
9242 				 * looked up on that interface. This ire has
9243 				 * RTF_MULTIRT flag, so the resolution loop will
9244 				 * be re-entered to resolve additional routes on
9245 				 * other interfaces. For that purpose, a copy of
9246 				 * the packet is performed at this point.
9247 				 */
9248 				fire->ire_last_used_time = lbolt;
9249 				copy_mp = copymsg(first_mp);
9250 				if (copy_mp) {
9251 					MULTIRT_DEBUG_TAG(copy_mp);
9252 				}
9253 			}
9254 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9255 			    (fire->ire_flags & RTF_SETSRC)) {
9256 				/*
9257 				 * As requested by flags, an IRE_OFFSUBET was
9258 				 * looked up on that interface. This ire has
9259 				 * RTF_SETSRC flag, so the source address of the
9260 				 * packet must be changed.
9261 				 */
9262 				ipha->ipha_src = fire->ire_src_addr;
9263 			}
9264 		} else {
9265 			ASSERT((connp == NULL) ||
9266 			    (connp->conn_outgoing_ill != NULL) ||
9267 			    (connp->conn_dontroute) ||
9268 			    infop->ip_opt_ill_index != 0);
9269 			/*
9270 			 * The only ways we can come here are:
9271 			 * 1) IP_BOUND_IF socket option is set
9272 			 * 2) SO_DONTROUTE socket option is set
9273 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9274 			 * In all cases, the new ire will not be added
9275 			 * into cache table.
9276 			 */
9277 			ire_marks |= IRE_MARK_NOADD;
9278 		}
9279 
9280 		switch (ipif->ipif_net_type) {
9281 		case IRE_IF_NORESOLVER: {
9282 			/* We have what we need to build an IRE_CACHE. */
9283 
9284 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9285 			    (dst_ill->ill_resolver_mp == NULL)) {
9286 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9287 				    "for IRE_IF_NORESOLVER ire %p has "
9288 				    "no ill_resolver_mp\n",
9289 				    (void *)dst_ill, (void *)ire));
9290 				break;
9291 			}
9292 
9293 			/*
9294 			 * The new ire inherits the IRE_OFFSUBNET flags
9295 			 * and source address, if this was requested.
9296 			 */
9297 			ire = ire_create(
9298 			    (uchar_t *)&dst,		/* dest address */
9299 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9300 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9301 			    NULL,			/* gateway address */
9302 			    &ipif->ipif_mtu,
9303 			    NULL,			/* no src nce */
9304 			    dst_ill->ill_rq,		/* recv-from queue */
9305 			    dst_ill->ill_wq,		/* send-to queue */
9306 			    IRE_CACHE,
9307 			    src_ipif,
9308 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9309 			    (fire != NULL) ?		/* Parent handle */
9310 			    fire->ire_phandle : 0,
9311 			    ihandle,			/* Interface handle */
9312 			    (fire != NULL) ?
9313 			    (fire->ire_flags &
9314 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9315 			    (save_ire == NULL ? &ire_uinfo_null :
9316 			    &save_ire->ire_uinfo),
9317 			    NULL,
9318 			    NULL,
9319 			    ipst);
9320 
9321 			if (ire == NULL) {
9322 				if (save_ire != NULL)
9323 					ire_refrele(save_ire);
9324 				break;
9325 			}
9326 
9327 			ire->ire_marks |= ire_marks;
9328 
9329 			/*
9330 			 * If IRE_MARK_NOADD is set then we need to convert
9331 			 * the max_fragp to a useable value now. This is
9332 			 * normally done in ire_add_v[46]. We also need to
9333 			 * associate the ire with an nce (normally would be
9334 			 * done in ip_wput_nondata()).
9335 			 *
9336 			 * Note that IRE_MARK_NOADD packets created here
9337 			 * do not have a non-null ire_mp pointer. The null
9338 			 * value of ire_bucket indicates that they were
9339 			 * never added.
9340 			 */
9341 			if (ire->ire_marks & IRE_MARK_NOADD) {
9342 				uint_t  max_frag;
9343 
9344 				max_frag = *ire->ire_max_fragp;
9345 				ire->ire_max_fragp = NULL;
9346 				ire->ire_max_frag = max_frag;
9347 
9348 				if ((ire->ire_nce = ndp_lookup_v4(
9349 				    ire_to_ill(ire),
9350 				    (ire->ire_gateway_addr != INADDR_ANY ?
9351 				    &ire->ire_gateway_addr : &ire->ire_addr),
9352 				    B_FALSE)) == NULL) {
9353 					if (save_ire != NULL)
9354 						ire_refrele(save_ire);
9355 					break;
9356 				}
9357 				ASSERT(ire->ire_nce->nce_state ==
9358 				    ND_REACHABLE);
9359 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9360 			}
9361 
9362 			/* Prevent save_ire from getting deleted */
9363 			if (save_ire != NULL) {
9364 				IRB_REFHOLD(save_ire->ire_bucket);
9365 				/* Has it been removed already ? */
9366 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9367 					IRB_REFRELE(save_ire->ire_bucket);
9368 					ire_refrele(save_ire);
9369 					break;
9370 				}
9371 			}
9372 
9373 			ire_add_then_send(q, ire, first_mp);
9374 
9375 			/* Assert that save_ire is not deleted yet. */
9376 			if (save_ire != NULL) {
9377 				ASSERT(save_ire->ire_ptpn != NULL);
9378 				IRB_REFRELE(save_ire->ire_bucket);
9379 				ire_refrele(save_ire);
9380 				save_ire = NULL;
9381 			}
9382 			if (fire != NULL) {
9383 				ire_refrele(fire);
9384 				fire = NULL;
9385 			}
9386 
9387 			/*
9388 			 * the resolution loop is re-entered if this
9389 			 * was requested through flags and if we
9390 			 * actually are in a multirouting case.
9391 			 */
9392 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9393 				boolean_t need_resolve =
9394 				    ire_multirt_need_resolve(ipha_dst,
9395 				    MBLK_GETLABEL(copy_mp), ipst);
9396 				if (!need_resolve) {
9397 					MULTIRT_DEBUG_UNTAG(copy_mp);
9398 					freemsg(copy_mp);
9399 					copy_mp = NULL;
9400 				} else {
9401 					/*
9402 					 * ipif_lookup_group() calls
9403 					 * ire_lookup_multi() that uses
9404 					 * ire_ftable_lookup() to find
9405 					 * an IRE_INTERFACE for the group.
9406 					 * In the multirt case,
9407 					 * ire_lookup_multi() then invokes
9408 					 * ire_multirt_lookup() to find
9409 					 * the next resolvable ire.
9410 					 * As a result, we obtain an new
9411 					 * interface, derived from the
9412 					 * next ire.
9413 					 */
9414 					ipif_refrele(ipif);
9415 					ipif = ipif_lookup_group(ipha_dst,
9416 					    zoneid, ipst);
9417 					ip2dbg(("ip_newroute_ipif: "
9418 					    "multirt dst %08x, ipif %p\n",
9419 					    htonl(dst), (void *)ipif));
9420 					if (ipif != NULL) {
9421 						mp = copy_mp;
9422 						copy_mp = NULL;
9423 						multirt_resolve_next = B_TRUE;
9424 						continue;
9425 					} else {
9426 						freemsg(copy_mp);
9427 					}
9428 				}
9429 			}
9430 			if (ipif != NULL)
9431 				ipif_refrele(ipif);
9432 			ill_refrele(dst_ill);
9433 			ipif_refrele(src_ipif);
9434 			return;
9435 		}
9436 		case IRE_IF_RESOLVER:
9437 			/*
9438 			 * We can't build an IRE_CACHE yet, but at least
9439 			 * we found a resolver that can help.
9440 			 */
9441 			res_mp = dst_ill->ill_resolver_mp;
9442 			if (!OK_RESOLVER_MP(res_mp))
9443 				break;
9444 
9445 			/*
9446 			 * We obtain a partial IRE_CACHE which we will pass
9447 			 * along with the resolver query.  When the response
9448 			 * comes back it will be there ready for us to add.
9449 			 * The new ire inherits the IRE_OFFSUBNET flags
9450 			 * and source address, if this was requested.
9451 			 * The ire_max_frag is atomically set under the
9452 			 * irebucket lock in ire_add_v[46]. Only in the
9453 			 * case of IRE_MARK_NOADD, we set it here itself.
9454 			 */
9455 			ire = ire_create_mp(
9456 			    (uchar_t *)&dst,		/* dest address */
9457 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9458 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9459 			    NULL,			/* gateway address */
9460 			    (ire_marks & IRE_MARK_NOADD) ?
9461 			    ipif->ipif_mtu : 0,		/* max_frag */
9462 			    NULL,			/* no src nce */
9463 			    dst_ill->ill_rq,		/* recv-from queue */
9464 			    dst_ill->ill_wq,		/* send-to queue */
9465 			    IRE_CACHE,
9466 			    src_ipif,
9467 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9468 			    (fire != NULL) ?		/* Parent handle */
9469 			    fire->ire_phandle : 0,
9470 			    ihandle,			/* Interface handle */
9471 			    (fire != NULL) ?		/* flags if any */
9472 			    (fire->ire_flags &
9473 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9474 			    (save_ire == NULL ? &ire_uinfo_null :
9475 			    &save_ire->ire_uinfo),
9476 			    NULL,
9477 			    NULL,
9478 			    ipst);
9479 
9480 			if (save_ire != NULL) {
9481 				ire_refrele(save_ire);
9482 				save_ire = NULL;
9483 			}
9484 			if (ire == NULL)
9485 				break;
9486 
9487 			ire->ire_marks |= ire_marks;
9488 			/*
9489 			 * Construct message chain for the resolver of the
9490 			 * form:
9491 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9492 			 *
9493 			 * NOTE : ire will be added later when the response
9494 			 * comes back from ARP. If the response does not
9495 			 * come back, ARP frees the packet. For this reason,
9496 			 * we can't REFHOLD the bucket of save_ire to prevent
9497 			 * deletions. We may not be able to REFRELE the
9498 			 * bucket if the response never comes back.
9499 			 * Thus, before adding the ire, ire_add_v4 will make
9500 			 * sure that the interface route does not get deleted.
9501 			 * This is the only case unlike ip_newroute_v6,
9502 			 * ip_newroute_ipif_v6 where we can always prevent
9503 			 * deletions because ire_add_then_send is called after
9504 			 * creating the IRE.
9505 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9506 			 * does not add this IRE into the IRE CACHE.
9507 			 */
9508 			ASSERT(ire->ire_mp != NULL);
9509 			ire->ire_mp->b_cont = first_mp;
9510 			/* Have saved_mp handy, for cleanup if canput fails */
9511 			saved_mp = mp;
9512 			mp = copyb(res_mp);
9513 			if (mp == NULL) {
9514 				/* Prepare for cleanup */
9515 				mp = saved_mp; /* pkt */
9516 				ire_delete(ire); /* ire_mp */
9517 				ire = NULL;
9518 				if (copy_mp != NULL) {
9519 					MULTIRT_DEBUG_UNTAG(copy_mp);
9520 					freemsg(copy_mp);
9521 					copy_mp = NULL;
9522 				}
9523 				break;
9524 			}
9525 			linkb(mp, ire->ire_mp);
9526 
9527 			/*
9528 			 * Fill in the source and dest addrs for the resolver.
9529 			 * NOTE: this depends on memory layouts imposed by
9530 			 * ill_init().
9531 			 */
9532 			areq = (areq_t *)mp->b_rptr;
9533 			addrp = (ipaddr_t *)((char *)areq +
9534 			    areq->areq_sender_addr_offset);
9535 			*addrp = ire->ire_src_addr;
9536 			addrp = (ipaddr_t *)((char *)areq +
9537 			    areq->areq_target_addr_offset);
9538 			*addrp = dst;
9539 			/* Up to the resolver. */
9540 			if (canputnext(dst_ill->ill_rq) &&
9541 			    !(dst_ill->ill_arp_closing)) {
9542 				putnext(dst_ill->ill_rq, mp);
9543 				/*
9544 				 * The response will come back in ip_wput
9545 				 * with db_type IRE_DB_TYPE.
9546 				 */
9547 			} else {
9548 				mp->b_cont = NULL;
9549 				freeb(mp); /* areq */
9550 				ire_delete(ire); /* ire_mp */
9551 				saved_mp->b_next = NULL;
9552 				saved_mp->b_prev = NULL;
9553 				freemsg(first_mp); /* pkt */
9554 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9555 			}
9556 
9557 			if (fire != NULL) {
9558 				ire_refrele(fire);
9559 				fire = NULL;
9560 			}
9561 
9562 
9563 			/*
9564 			 * The resolution loop is re-entered if this was
9565 			 * requested through flags and we actually are
9566 			 * in a multirouting case.
9567 			 */
9568 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9569 				boolean_t need_resolve =
9570 				    ire_multirt_need_resolve(ipha_dst,
9571 				    MBLK_GETLABEL(copy_mp), ipst);
9572 				if (!need_resolve) {
9573 					MULTIRT_DEBUG_UNTAG(copy_mp);
9574 					freemsg(copy_mp);
9575 					copy_mp = NULL;
9576 				} else {
9577 					/*
9578 					 * ipif_lookup_group() calls
9579 					 * ire_lookup_multi() that uses
9580 					 * ire_ftable_lookup() to find
9581 					 * an IRE_INTERFACE for the group.
9582 					 * In the multirt case,
9583 					 * ire_lookup_multi() then invokes
9584 					 * ire_multirt_lookup() to find
9585 					 * the next resolvable ire.
9586 					 * As a result, we obtain an new
9587 					 * interface, derived from the
9588 					 * next ire.
9589 					 */
9590 					ipif_refrele(ipif);
9591 					ipif = ipif_lookup_group(ipha_dst,
9592 					    zoneid, ipst);
9593 					if (ipif != NULL) {
9594 						mp = copy_mp;
9595 						copy_mp = NULL;
9596 						multirt_resolve_next = B_TRUE;
9597 						continue;
9598 					} else {
9599 						freemsg(copy_mp);
9600 					}
9601 				}
9602 			}
9603 			if (ipif != NULL)
9604 				ipif_refrele(ipif);
9605 			ill_refrele(dst_ill);
9606 			ipif_refrele(src_ipif);
9607 			return;
9608 		default:
9609 			break;
9610 		}
9611 	} while (multirt_resolve_next);
9612 
9613 err_ret:
9614 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9615 	if (fire != NULL)
9616 		ire_refrele(fire);
9617 	ipif_refrele(ipif);
9618 	/* Did this packet originate externally? */
9619 	if (dst_ill != NULL)
9620 		ill_refrele(dst_ill);
9621 	if (src_ipif != NULL)
9622 		ipif_refrele(src_ipif);
9623 	if (mp->b_prev || mp->b_next) {
9624 		mp->b_next = NULL;
9625 		mp->b_prev = NULL;
9626 	} else {
9627 		/*
9628 		 * Since ip_wput() isn't close to finished, we fill
9629 		 * in enough of the header for credible error reporting.
9630 		 */
9631 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9632 			/* Failed */
9633 			freemsg(first_mp);
9634 			if (ire != NULL)
9635 				ire_refrele(ire);
9636 			return;
9637 		}
9638 	}
9639 	/*
9640 	 * At this point we will have ire only if RTF_BLACKHOLE
9641 	 * or RTF_REJECT flags are set on the IRE. It will not
9642 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9643 	 */
9644 	if (ire != NULL) {
9645 		if (ire->ire_flags & RTF_BLACKHOLE) {
9646 			ire_refrele(ire);
9647 			freemsg(first_mp);
9648 			return;
9649 		}
9650 		ire_refrele(ire);
9651 	}
9652 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9653 }
9654 
9655 /* Name/Value Table Lookup Routine */
9656 char *
9657 ip_nv_lookup(nv_t *nv, int value)
9658 {
9659 	if (!nv)
9660 		return (NULL);
9661 	for (; nv->nv_name; nv++) {
9662 		if (nv->nv_value == value)
9663 			return (nv->nv_name);
9664 	}
9665 	return ("unknown");
9666 }
9667 
9668 /*
9669  * This is a module open, i.e. this is a control stream for access
9670  * to a DLPI device.  We allocate an ill_t as the instance data in
9671  * this case.
9672  */
9673 int
9674 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9675 {
9676 	ill_t	*ill;
9677 	int	err;
9678 	zoneid_t zoneid;
9679 	netstack_t *ns;
9680 	ip_stack_t *ipst;
9681 
9682 	/*
9683 	 * Prevent unprivileged processes from pushing IP so that
9684 	 * they can't send raw IP.
9685 	 */
9686 	if (secpolicy_net_rawaccess(credp) != 0)
9687 		return (EPERM);
9688 
9689 	ns = netstack_find_by_cred(credp);
9690 	ASSERT(ns != NULL);
9691 	ipst = ns->netstack_ip;
9692 	ASSERT(ipst != NULL);
9693 
9694 	/*
9695 	 * For exclusive stacks we set the zoneid to zero
9696 	 * to make IP operate as if in the global zone.
9697 	 */
9698 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9699 		zoneid = GLOBAL_ZONEID;
9700 	else
9701 		zoneid = crgetzoneid(credp);
9702 
9703 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9704 	q->q_ptr = WR(q)->q_ptr = ill;
9705 	ill->ill_ipst = ipst;
9706 	ill->ill_zoneid = zoneid;
9707 
9708 	/*
9709 	 * ill_init initializes the ill fields and then sends down
9710 	 * down a DL_INFO_REQ after calling qprocson.
9711 	 */
9712 	err = ill_init(q, ill);
9713 	if (err != 0) {
9714 		mi_free(ill);
9715 		netstack_rele(ipst->ips_netstack);
9716 		q->q_ptr = NULL;
9717 		WR(q)->q_ptr = NULL;
9718 		return (err);
9719 	}
9720 
9721 	/* ill_init initializes the ipsq marking this thread as writer */
9722 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9723 	/* Wait for the DL_INFO_ACK */
9724 	mutex_enter(&ill->ill_lock);
9725 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9726 		/*
9727 		 * Return value of 0 indicates a pending signal.
9728 		 */
9729 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9730 		if (err == 0) {
9731 			mutex_exit(&ill->ill_lock);
9732 			(void) ip_close(q, 0);
9733 			return (EINTR);
9734 		}
9735 	}
9736 	mutex_exit(&ill->ill_lock);
9737 
9738 	/*
9739 	 * ip_rput_other could have set an error  in ill_error on
9740 	 * receipt of M_ERROR.
9741 	 */
9742 
9743 	err = ill->ill_error;
9744 	if (err != 0) {
9745 		(void) ip_close(q, 0);
9746 		return (err);
9747 	}
9748 
9749 	ill->ill_credp = credp;
9750 	crhold(credp);
9751 
9752 	mutex_enter(&ipst->ips_ip_mi_lock);
9753 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9754 	    credp);
9755 	mutex_exit(&ipst->ips_ip_mi_lock);
9756 	if (err) {
9757 		(void) ip_close(q, 0);
9758 		return (err);
9759 	}
9760 	return (0);
9761 }
9762 
9763 /* For /dev/ip aka AF_INET open */
9764 int
9765 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9766 {
9767 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
9768 }
9769 
9770 /* For /dev/ip6 aka AF_INET6 open */
9771 int
9772 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9773 {
9774 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
9775 }
9776 
9777 /* IP open routine. */
9778 int
9779 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9780     boolean_t isv6)
9781 {
9782 	conn_t 		*connp;
9783 	major_t		maj;
9784 	zoneid_t	zoneid;
9785 	netstack_t	*ns;
9786 	ip_stack_t	*ipst;
9787 
9788 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9789 
9790 	/* Allow reopen. */
9791 	if (q->q_ptr != NULL)
9792 		return (0);
9793 
9794 	if (sflag & MODOPEN) {
9795 		/* This is a module open */
9796 		return (ip_modopen(q, devp, flag, sflag, credp));
9797 	}
9798 
9799 	ns = netstack_find_by_cred(credp);
9800 	ASSERT(ns != NULL);
9801 	ipst = ns->netstack_ip;
9802 	ASSERT(ipst != NULL);
9803 
9804 	/*
9805 	 * For exclusive stacks we set the zoneid to zero
9806 	 * to make IP operate as if in the global zone.
9807 	 */
9808 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9809 		zoneid = GLOBAL_ZONEID;
9810 	else
9811 		zoneid = crgetzoneid(credp);
9812 
9813 	/*
9814 	 * We are opening as a device. This is an IP client stream, and we
9815 	 * allocate an conn_t as the instance data.
9816 	 */
9817 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9818 
9819 	/*
9820 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9821 	 * done by netstack_find_by_cred()
9822 	 */
9823 	netstack_rele(ipst->ips_netstack);
9824 
9825 	connp->conn_zoneid = zoneid;
9826 
9827 	connp->conn_upq = q;
9828 	q->q_ptr = WR(q)->q_ptr = connp;
9829 
9830 	if (flag & SO_SOCKSTR)
9831 		connp->conn_flags |= IPCL_SOCKET;
9832 
9833 	/* Minor tells us which /dev entry was opened */
9834 	if (isv6) {
9835 		connp->conn_flags |= IPCL_ISV6;
9836 		connp->conn_af_isv6 = B_TRUE;
9837 		ip_setpktversion(connp, isv6, B_FALSE, ipst);
9838 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9839 	} else {
9840 		connp->conn_af_isv6 = B_FALSE;
9841 		connp->conn_pkt_isv6 = B_FALSE;
9842 	}
9843 
9844 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
9845 		/* CONN_DEC_REF takes care of netstack_rele() */
9846 		q->q_ptr = WR(q)->q_ptr = NULL;
9847 		CONN_DEC_REF(connp);
9848 		return (EBUSY);
9849 	}
9850 
9851 	maj = getemajor(*devp);
9852 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9853 
9854 	/*
9855 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9856 	 */
9857 	connp->conn_cred = credp;
9858 
9859 	/*
9860 	 * Handle IP_RTS_REQUEST and other ioctls which use conn_recv
9861 	 */
9862 	connp->conn_recv = ip_conn_input;
9863 
9864 	crhold(connp->conn_cred);
9865 
9866 	/*
9867 	 * If the caller has the process-wide flag set, then default to MAC
9868 	 * exempt mode.  This allows read-down to unlabeled hosts.
9869 	 */
9870 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9871 		connp->conn_mac_exempt = B_TRUE;
9872 
9873 	connp->conn_rq = q;
9874 	connp->conn_wq = WR(q);
9875 
9876 	/* Non-zero default values */
9877 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9878 
9879 	/*
9880 	 * Make the conn globally visible to walkers
9881 	 */
9882 	ASSERT(connp->conn_ref == 1);
9883 	mutex_enter(&connp->conn_lock);
9884 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9885 	mutex_exit(&connp->conn_lock);
9886 
9887 	qprocson(q);
9888 
9889 	return (0);
9890 }
9891 
9892 /*
9893  * Change the output format (IPv4 vs. IPv6) for a conn_t.
9894  * Note that there is no race since either ip_output function works - it
9895  * is just an optimization to enter the best ip_output routine directly.
9896  */
9897 void
9898 ip_setpktversion(conn_t *connp, boolean_t isv6, boolean_t bump_mib,
9899     ip_stack_t *ipst)
9900 {
9901 	if (isv6)  {
9902 		if (bump_mib) {
9903 			BUMP_MIB(&ipst->ips_ip6_mib,
9904 			    ipIfStatsOutSwitchIPVersion);
9905 		}
9906 		connp->conn_send = ip_output_v6;
9907 		connp->conn_pkt_isv6 = B_TRUE;
9908 	} else {
9909 		if (bump_mib) {
9910 			BUMP_MIB(&ipst->ips_ip_mib,
9911 			    ipIfStatsOutSwitchIPVersion);
9912 		}
9913 		connp->conn_send = ip_output;
9914 		connp->conn_pkt_isv6 = B_FALSE;
9915 	}
9916 
9917 }
9918 
9919 /*
9920  * See if IPsec needs loading because of the options in mp.
9921  */
9922 static boolean_t
9923 ipsec_opt_present(mblk_t *mp)
9924 {
9925 	uint8_t *optcp, *next_optcp, *opt_endcp;
9926 	struct opthdr *opt;
9927 	struct T_opthdr *topt;
9928 	int opthdr_len;
9929 	t_uscalar_t optname, optlevel;
9930 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9931 	ipsec_req_t *ipsr;
9932 
9933 	/*
9934 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9935 	 * return TRUE.
9936 	 */
9937 
9938 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9939 	opt_endcp = optcp + tor->OPT_length;
9940 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9941 		opthdr_len = sizeof (struct T_opthdr);
9942 	} else {		/* O_OPTMGMT_REQ */
9943 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9944 		opthdr_len = sizeof (struct opthdr);
9945 	}
9946 	for (; optcp < opt_endcp; optcp = next_optcp) {
9947 		if (optcp + opthdr_len > opt_endcp)
9948 			return (B_FALSE);	/* Not enough option header. */
9949 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9950 			topt = (struct T_opthdr *)optcp;
9951 			optlevel = topt->level;
9952 			optname = topt->name;
9953 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9954 		} else {
9955 			opt = (struct opthdr *)optcp;
9956 			optlevel = opt->level;
9957 			optname = opt->name;
9958 			next_optcp = optcp + opthdr_len +
9959 			    _TPI_ALIGN_OPT(opt->len);
9960 		}
9961 		if ((next_optcp < optcp) || /* wraparound pointer space */
9962 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9963 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9964 			return (B_FALSE); /* bad option buffer */
9965 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9966 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9967 			/*
9968 			 * Check to see if it's an all-bypass or all-zeroes
9969 			 * IPsec request.  Don't bother loading IPsec if
9970 			 * the socket doesn't want to use it.  (A good example
9971 			 * is a bypass request.)
9972 			 *
9973 			 * Basically, if any of the non-NEVER bits are set,
9974 			 * load IPsec.
9975 			 */
9976 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9977 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9978 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9979 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9980 			    != 0)
9981 				return (B_TRUE);
9982 		}
9983 	}
9984 	return (B_FALSE);
9985 }
9986 
9987 /*
9988  * If conn is is waiting for ipsec to finish loading, kick it.
9989  */
9990 /* ARGSUSED */
9991 static void
9992 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9993 {
9994 	t_scalar_t	optreq_prim;
9995 	mblk_t		*mp;
9996 	cred_t		*cr;
9997 	int		err = 0;
9998 
9999 	/*
10000 	 * This function is called, after ipsec loading is complete.
10001 	 * Since IP checks exclusively and atomically (i.e it prevents
10002 	 * ipsec load from completing until ip_optcom_req completes)
10003 	 * whether ipsec load is complete, there cannot be a race with IP
10004 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
10005 	 */
10006 	mutex_enter(&connp->conn_lock);
10007 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
10008 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
10009 		mp = connp->conn_ipsec_opt_mp;
10010 		connp->conn_ipsec_opt_mp = NULL;
10011 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
10012 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
10013 		mutex_exit(&connp->conn_lock);
10014 
10015 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
10016 
10017 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
10018 		if (optreq_prim == T_OPTMGMT_REQ) {
10019 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10020 			    &ip_opt_obj, B_FALSE);
10021 		} else {
10022 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10023 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10024 			    &ip_opt_obj, B_FALSE);
10025 		}
10026 		if (err != EINPROGRESS)
10027 			CONN_OPER_PENDING_DONE(connp);
10028 		return;
10029 	}
10030 	mutex_exit(&connp->conn_lock);
10031 }
10032 
10033 /*
10034  * Called from the ipsec_loader thread, outside any perimeter, to tell
10035  * ip qenable any of the queues waiting for the ipsec loader to
10036  * complete.
10037  */
10038 void
10039 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10040 {
10041 	netstack_t *ns = ipss->ipsec_netstack;
10042 
10043 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10044 }
10045 
10046 /*
10047  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10048  * determines the grp on which it has to become exclusive, queues the mp
10049  * and sq draining restarts the optmgmt
10050  */
10051 static boolean_t
10052 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10053 {
10054 	conn_t *connp = Q_TO_CONN(q);
10055 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10056 
10057 	/*
10058 	 * Take IPsec requests and treat them special.
10059 	 */
10060 	if (ipsec_opt_present(mp)) {
10061 		/* First check if IPsec is loaded. */
10062 		mutex_enter(&ipss->ipsec_loader_lock);
10063 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10064 			mutex_exit(&ipss->ipsec_loader_lock);
10065 			return (B_FALSE);
10066 		}
10067 		mutex_enter(&connp->conn_lock);
10068 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10069 
10070 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10071 		connp->conn_ipsec_opt_mp = mp;
10072 		mutex_exit(&connp->conn_lock);
10073 		mutex_exit(&ipss->ipsec_loader_lock);
10074 
10075 		ipsec_loader_loadnow(ipss);
10076 		return (B_TRUE);
10077 	}
10078 	return (B_FALSE);
10079 }
10080 
10081 /*
10082  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10083  * all of them are copied to the conn_t. If the req is "zero", the policy is
10084  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10085  * fields.
10086  * We keep only the latest setting of the policy and thus policy setting
10087  * is not incremental/cumulative.
10088  *
10089  * Requests to set policies with multiple alternative actions will
10090  * go through a different API.
10091  */
10092 int
10093 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10094 {
10095 	uint_t ah_req = 0;
10096 	uint_t esp_req = 0;
10097 	uint_t se_req = 0;
10098 	ipsec_selkey_t sel;
10099 	ipsec_act_t *actp = NULL;
10100 	uint_t nact;
10101 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10102 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10103 	ipsec_policy_root_t *pr;
10104 	ipsec_policy_head_t *ph;
10105 	int fam;
10106 	boolean_t is_pol_reset;
10107 	int error = 0;
10108 	netstack_t	*ns = connp->conn_netstack;
10109 	ip_stack_t	*ipst = ns->netstack_ip;
10110 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10111 
10112 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10113 
10114 	/*
10115 	 * The IP_SEC_OPT option does not allow variable length parameters,
10116 	 * hence a request cannot be NULL.
10117 	 */
10118 	if (req == NULL)
10119 		return (EINVAL);
10120 
10121 	ah_req = req->ipsr_ah_req;
10122 	esp_req = req->ipsr_esp_req;
10123 	se_req = req->ipsr_self_encap_req;
10124 
10125 	/*
10126 	 * Are we dealing with a request to reset the policy (i.e.
10127 	 * zero requests).
10128 	 */
10129 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10130 	    (esp_req & REQ_MASK) == 0 &&
10131 	    (se_req & REQ_MASK) == 0);
10132 
10133 	if (!is_pol_reset) {
10134 		/*
10135 		 * If we couldn't load IPsec, fail with "protocol
10136 		 * not supported".
10137 		 * IPsec may not have been loaded for a request with zero
10138 		 * policies, so we don't fail in this case.
10139 		 */
10140 		mutex_enter(&ipss->ipsec_loader_lock);
10141 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10142 			mutex_exit(&ipss->ipsec_loader_lock);
10143 			return (EPROTONOSUPPORT);
10144 		}
10145 		mutex_exit(&ipss->ipsec_loader_lock);
10146 
10147 		/*
10148 		 * Test for valid requests. Invalid algorithms
10149 		 * need to be tested by IPsec code because new
10150 		 * algorithms can be added dynamically.
10151 		 */
10152 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10153 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10154 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10155 			return (EINVAL);
10156 		}
10157 
10158 		/*
10159 		 * Only privileged users can issue these
10160 		 * requests.
10161 		 */
10162 		if (((ah_req & IPSEC_PREF_NEVER) ||
10163 		    (esp_req & IPSEC_PREF_NEVER) ||
10164 		    (se_req & IPSEC_PREF_NEVER)) &&
10165 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10166 			return (EPERM);
10167 		}
10168 
10169 		/*
10170 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10171 		 * are mutually exclusive.
10172 		 */
10173 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10174 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10175 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10176 			/* Both of them are set */
10177 			return (EINVAL);
10178 		}
10179 	}
10180 
10181 	mutex_enter(&connp->conn_lock);
10182 
10183 	/*
10184 	 * If we have already cached policies in ip_bind_connected*(), don't
10185 	 * let them change now. We cache policies for connections
10186 	 * whose src,dst [addr, port] is known.
10187 	 */
10188 	if (connp->conn_policy_cached) {
10189 		mutex_exit(&connp->conn_lock);
10190 		return (EINVAL);
10191 	}
10192 
10193 	/*
10194 	 * We have a zero policies, reset the connection policy if already
10195 	 * set. This will cause the connection to inherit the
10196 	 * global policy, if any.
10197 	 */
10198 	if (is_pol_reset) {
10199 		if (connp->conn_policy != NULL) {
10200 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10201 			connp->conn_policy = NULL;
10202 		}
10203 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10204 		connp->conn_in_enforce_policy = B_FALSE;
10205 		connp->conn_out_enforce_policy = B_FALSE;
10206 		mutex_exit(&connp->conn_lock);
10207 		return (0);
10208 	}
10209 
10210 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10211 	    ipst->ips_netstack);
10212 	if (ph == NULL)
10213 		goto enomem;
10214 
10215 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10216 	if (actp == NULL)
10217 		goto enomem;
10218 
10219 	/*
10220 	 * Always allocate IPv4 policy entries, since they can also
10221 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10222 	 */
10223 	bzero(&sel, sizeof (sel));
10224 	sel.ipsl_valid = IPSL_IPV4;
10225 
10226 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10227 	    ipst->ips_netstack);
10228 	if (pin4 == NULL)
10229 		goto enomem;
10230 
10231 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10232 	    ipst->ips_netstack);
10233 	if (pout4 == NULL)
10234 		goto enomem;
10235 
10236 	if (connp->conn_af_isv6) {
10237 		/*
10238 		 * We're looking at a v6 socket, also allocate the
10239 		 * v6-specific entries...
10240 		 */
10241 		sel.ipsl_valid = IPSL_IPV6;
10242 		pin6 = ipsec_policy_create(&sel, actp, nact,
10243 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10244 		if (pin6 == NULL)
10245 			goto enomem;
10246 
10247 		pout6 = ipsec_policy_create(&sel, actp, nact,
10248 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10249 		if (pout6 == NULL)
10250 			goto enomem;
10251 
10252 		/*
10253 		 * .. and file them away in the right place.
10254 		 */
10255 		fam = IPSEC_AF_V6;
10256 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10257 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10258 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10259 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10260 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10261 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10262 	}
10263 
10264 	ipsec_actvec_free(actp, nact);
10265 
10266 	/*
10267 	 * File the v4 policies.
10268 	 */
10269 	fam = IPSEC_AF_V4;
10270 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10271 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10272 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10273 
10274 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10275 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10276 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10277 
10278 	/*
10279 	 * If the requests need security, set enforce_policy.
10280 	 * If the requests are IPSEC_PREF_NEVER, one should
10281 	 * still set conn_out_enforce_policy so that an ipsec_out
10282 	 * gets attached in ip_wput. This is needed so that
10283 	 * for connections that we don't cache policy in ip_bind,
10284 	 * if global policy matches in ip_wput_attach_policy, we
10285 	 * don't wrongly inherit global policy. Similarly, we need
10286 	 * to set conn_in_enforce_policy also so that we don't verify
10287 	 * policy wrongly.
10288 	 */
10289 	if ((ah_req & REQ_MASK) != 0 ||
10290 	    (esp_req & REQ_MASK) != 0 ||
10291 	    (se_req & REQ_MASK) != 0) {
10292 		connp->conn_in_enforce_policy = B_TRUE;
10293 		connp->conn_out_enforce_policy = B_TRUE;
10294 		connp->conn_flags |= IPCL_CHECK_POLICY;
10295 	}
10296 
10297 	mutex_exit(&connp->conn_lock);
10298 	return (error);
10299 #undef REQ_MASK
10300 
10301 	/*
10302 	 * Common memory-allocation-failure exit path.
10303 	 */
10304 enomem:
10305 	mutex_exit(&connp->conn_lock);
10306 	if (actp != NULL)
10307 		ipsec_actvec_free(actp, nact);
10308 	if (pin4 != NULL)
10309 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10310 	if (pout4 != NULL)
10311 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10312 	if (pin6 != NULL)
10313 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10314 	if (pout6 != NULL)
10315 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10316 	return (ENOMEM);
10317 }
10318 
10319 /*
10320  * Only for options that pass in an IP addr. Currently only V4 options
10321  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10322  * So this function assumes level is IPPROTO_IP
10323  */
10324 int
10325 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10326     mblk_t *first_mp)
10327 {
10328 	ipif_t *ipif = NULL;
10329 	int error;
10330 	ill_t *ill;
10331 	int zoneid;
10332 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10333 
10334 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10335 
10336 	if (addr != INADDR_ANY || checkonly) {
10337 		ASSERT(connp != NULL);
10338 		zoneid = IPCL_ZONEID(connp);
10339 		if (option == IP_NEXTHOP) {
10340 			ipif = ipif_lookup_onlink_addr(addr,
10341 			    connp->conn_zoneid, ipst);
10342 		} else {
10343 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10344 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10345 			    &error, ipst);
10346 		}
10347 		if (ipif == NULL) {
10348 			if (error == EINPROGRESS)
10349 				return (error);
10350 			else if ((option == IP_MULTICAST_IF) ||
10351 			    (option == IP_NEXTHOP))
10352 				return (EHOSTUNREACH);
10353 			else
10354 				return (EINVAL);
10355 		} else if (checkonly) {
10356 			if (option == IP_MULTICAST_IF) {
10357 				ill = ipif->ipif_ill;
10358 				/* not supported by the virtual network iface */
10359 				if (IS_VNI(ill)) {
10360 					ipif_refrele(ipif);
10361 					return (EINVAL);
10362 				}
10363 			}
10364 			ipif_refrele(ipif);
10365 			return (0);
10366 		}
10367 		ill = ipif->ipif_ill;
10368 		mutex_enter(&connp->conn_lock);
10369 		mutex_enter(&ill->ill_lock);
10370 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10371 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10372 			mutex_exit(&ill->ill_lock);
10373 			mutex_exit(&connp->conn_lock);
10374 			ipif_refrele(ipif);
10375 			return (option == IP_MULTICAST_IF ?
10376 			    EHOSTUNREACH : EINVAL);
10377 		}
10378 	} else {
10379 		mutex_enter(&connp->conn_lock);
10380 	}
10381 
10382 	/* None of the options below are supported on the VNI */
10383 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10384 		mutex_exit(&ill->ill_lock);
10385 		mutex_exit(&connp->conn_lock);
10386 		ipif_refrele(ipif);
10387 		return (EINVAL);
10388 	}
10389 
10390 	switch (option) {
10391 	case IP_DONTFAILOVER_IF:
10392 		/*
10393 		 * This option is used by in.mpathd to ensure
10394 		 * that IPMP probe packets only go out on the
10395 		 * test interfaces. in.mpathd sets this option
10396 		 * on the non-failover interfaces.
10397 		 * For backward compatibility, this option
10398 		 * implicitly sets IP_MULTICAST_IF, as used
10399 		 * be done in bind(), so that ip_wput gets
10400 		 * this ipif to send mcast packets.
10401 		 */
10402 		if (ipif != NULL) {
10403 			ASSERT(addr != INADDR_ANY);
10404 			connp->conn_nofailover_ill = ipif->ipif_ill;
10405 			connp->conn_multicast_ipif = ipif;
10406 		} else {
10407 			ASSERT(addr == INADDR_ANY);
10408 			connp->conn_nofailover_ill = NULL;
10409 			connp->conn_multicast_ipif = NULL;
10410 		}
10411 		break;
10412 
10413 	case IP_MULTICAST_IF:
10414 		connp->conn_multicast_ipif = ipif;
10415 		break;
10416 	case IP_NEXTHOP:
10417 		connp->conn_nexthop_v4 = addr;
10418 		connp->conn_nexthop_set = B_TRUE;
10419 		break;
10420 	}
10421 
10422 	if (ipif != NULL) {
10423 		mutex_exit(&ill->ill_lock);
10424 		mutex_exit(&connp->conn_lock);
10425 		ipif_refrele(ipif);
10426 		return (0);
10427 	}
10428 	mutex_exit(&connp->conn_lock);
10429 	/* We succeded in cleared the option */
10430 	return (0);
10431 }
10432 
10433 /*
10434  * For options that pass in an ifindex specifying the ill. V6 options always
10435  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10436  */
10437 int
10438 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10439     int level, int option, mblk_t *first_mp)
10440 {
10441 	ill_t *ill = NULL;
10442 	int error = 0;
10443 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10444 
10445 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10446 	if (ifindex != 0) {
10447 		ASSERT(connp != NULL);
10448 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10449 		    first_mp, ip_restart_optmgmt, &error, ipst);
10450 		if (ill != NULL) {
10451 			if (checkonly) {
10452 				/* not supported by the virtual network iface */
10453 				if (IS_VNI(ill)) {
10454 					ill_refrele(ill);
10455 					return (EINVAL);
10456 				}
10457 				ill_refrele(ill);
10458 				return (0);
10459 			}
10460 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10461 			    0, NULL)) {
10462 				ill_refrele(ill);
10463 				ill = NULL;
10464 				mutex_enter(&connp->conn_lock);
10465 				goto setit;
10466 			}
10467 			mutex_enter(&connp->conn_lock);
10468 			mutex_enter(&ill->ill_lock);
10469 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10470 				mutex_exit(&ill->ill_lock);
10471 				mutex_exit(&connp->conn_lock);
10472 				ill_refrele(ill);
10473 				ill = NULL;
10474 				mutex_enter(&connp->conn_lock);
10475 			}
10476 			goto setit;
10477 		} else if (error == EINPROGRESS) {
10478 			return (error);
10479 		} else {
10480 			error = 0;
10481 		}
10482 	}
10483 	mutex_enter(&connp->conn_lock);
10484 setit:
10485 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10486 
10487 	/*
10488 	 * The options below assume that the ILL (if any) transmits and/or
10489 	 * receives traffic. Neither of which is true for the virtual network
10490 	 * interface, so fail setting these on a VNI.
10491 	 */
10492 	if (IS_VNI(ill)) {
10493 		ASSERT(ill != NULL);
10494 		mutex_exit(&ill->ill_lock);
10495 		mutex_exit(&connp->conn_lock);
10496 		ill_refrele(ill);
10497 		return (EINVAL);
10498 	}
10499 
10500 	if (level == IPPROTO_IP) {
10501 		switch (option) {
10502 		case IP_BOUND_IF:
10503 			connp->conn_incoming_ill = ill;
10504 			connp->conn_outgoing_ill = ill;
10505 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10506 			    0 : ifindex;
10507 			break;
10508 
10509 		case IP_MULTICAST_IF:
10510 			/*
10511 			 * This option is an internal special. The socket
10512 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10513 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10514 			 * specifies an ifindex and we try first on V6 ill's.
10515 			 * If we don't find one, we they try using on v4 ill's
10516 			 * intenally and we come here.
10517 			 */
10518 			if (!checkonly && ill != NULL) {
10519 				ipif_t	*ipif;
10520 				ipif = ill->ill_ipif;
10521 
10522 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10523 					mutex_exit(&ill->ill_lock);
10524 					mutex_exit(&connp->conn_lock);
10525 					ill_refrele(ill);
10526 					ill = NULL;
10527 					mutex_enter(&connp->conn_lock);
10528 				} else {
10529 					connp->conn_multicast_ipif = ipif;
10530 				}
10531 			}
10532 			break;
10533 
10534 		case IP_DHCPINIT_IF:
10535 			if (connp->conn_dhcpinit_ill != NULL) {
10536 				/*
10537 				 * We've locked the conn so conn_cleanup_ill()
10538 				 * cannot clear conn_dhcpinit_ill -- so it's
10539 				 * safe to access the ill.
10540 				 */
10541 				ill_t *oill = connp->conn_dhcpinit_ill;
10542 
10543 				ASSERT(oill->ill_dhcpinit != 0);
10544 				atomic_dec_32(&oill->ill_dhcpinit);
10545 				connp->conn_dhcpinit_ill = NULL;
10546 			}
10547 
10548 			if (ill != NULL) {
10549 				connp->conn_dhcpinit_ill = ill;
10550 				atomic_inc_32(&ill->ill_dhcpinit);
10551 			}
10552 			break;
10553 		}
10554 	} else {
10555 		switch (option) {
10556 		case IPV6_BOUND_IF:
10557 			connp->conn_incoming_ill = ill;
10558 			connp->conn_outgoing_ill = ill;
10559 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10560 			    0 : ifindex;
10561 			break;
10562 
10563 		case IPV6_BOUND_PIF:
10564 			/*
10565 			 * Limit all transmit to this ill.
10566 			 * Unlike IPV6_BOUND_IF, using this option
10567 			 * prevents load spreading and failover from
10568 			 * happening when the interface is part of the
10569 			 * group. That's why we don't need to remember
10570 			 * the ifindex in orig_bound_ifindex as in
10571 			 * IPV6_BOUND_IF.
10572 			 */
10573 			connp->conn_outgoing_pill = ill;
10574 			break;
10575 
10576 		case IPV6_DONTFAILOVER_IF:
10577 			/*
10578 			 * This option is used by in.mpathd to ensure
10579 			 * that IPMP probe packets only go out on the
10580 			 * test interfaces. in.mpathd sets this option
10581 			 * on the non-failover interfaces.
10582 			 */
10583 			connp->conn_nofailover_ill = ill;
10584 			/*
10585 			 * For backward compatibility, this option
10586 			 * implicitly sets ip_multicast_ill as used in
10587 			 * IPV6_MULTICAST_IF so that ip_wput gets
10588 			 * this ill to send mcast packets.
10589 			 */
10590 			connp->conn_multicast_ill = ill;
10591 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10592 			    0 : ifindex;
10593 			break;
10594 
10595 		case IPV6_MULTICAST_IF:
10596 			/*
10597 			 * Set conn_multicast_ill to be the IPv6 ill.
10598 			 * Set conn_multicast_ipif to be an IPv4 ipif
10599 			 * for ifindex to make IPv4 mapped addresses
10600 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10601 			 * Even if no IPv6 ill exists for the ifindex
10602 			 * we need to check for an IPv4 ifindex in order
10603 			 * for this to work with mapped addresses. In that
10604 			 * case only set conn_multicast_ipif.
10605 			 */
10606 			if (!checkonly) {
10607 				if (ifindex == 0) {
10608 					connp->conn_multicast_ill = NULL;
10609 					connp->conn_orig_multicast_ifindex = 0;
10610 					connp->conn_multicast_ipif = NULL;
10611 				} else if (ill != NULL) {
10612 					connp->conn_multicast_ill = ill;
10613 					connp->conn_orig_multicast_ifindex =
10614 					    ifindex;
10615 				}
10616 			}
10617 			break;
10618 		}
10619 	}
10620 
10621 	if (ill != NULL) {
10622 		mutex_exit(&ill->ill_lock);
10623 		mutex_exit(&connp->conn_lock);
10624 		ill_refrele(ill);
10625 		return (0);
10626 	}
10627 	mutex_exit(&connp->conn_lock);
10628 	/*
10629 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10630 	 * locate the ill and could not set the option (ifindex != 0)
10631 	 */
10632 	return (ifindex == 0 ? 0 : EINVAL);
10633 }
10634 
10635 /* This routine sets socket options. */
10636 /* ARGSUSED */
10637 int
10638 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10639     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10640     void *dummy, cred_t *cr, mblk_t *first_mp)
10641 {
10642 	int		*i1 = (int *)invalp;
10643 	conn_t		*connp = Q_TO_CONN(q);
10644 	int		error = 0;
10645 	boolean_t	checkonly;
10646 	ire_t		*ire;
10647 	boolean_t	found;
10648 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10649 
10650 	switch (optset_context) {
10651 
10652 	case SETFN_OPTCOM_CHECKONLY:
10653 		checkonly = B_TRUE;
10654 		/*
10655 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10656 		 * inlen != 0 implies value supplied and
10657 		 * 	we have to "pretend" to set it.
10658 		 * inlen == 0 implies that there is no
10659 		 * 	value part in T_CHECK request and just validation
10660 		 * done elsewhere should be enough, we just return here.
10661 		 */
10662 		if (inlen == 0) {
10663 			*outlenp = 0;
10664 			return (0);
10665 		}
10666 		break;
10667 	case SETFN_OPTCOM_NEGOTIATE:
10668 	case SETFN_UD_NEGOTIATE:
10669 	case SETFN_CONN_NEGOTIATE:
10670 		checkonly = B_FALSE;
10671 		break;
10672 	default:
10673 		/*
10674 		 * We should never get here
10675 		 */
10676 		*outlenp = 0;
10677 		return (EINVAL);
10678 	}
10679 
10680 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10681 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10682 
10683 	/*
10684 	 * For fixed length options, no sanity check
10685 	 * of passed in length is done. It is assumed *_optcom_req()
10686 	 * routines do the right thing.
10687 	 */
10688 
10689 	switch (level) {
10690 	case SOL_SOCKET:
10691 		/*
10692 		 * conn_lock protects the bitfields, and is used to
10693 		 * set the fields atomically.
10694 		 */
10695 		switch (name) {
10696 		case SO_BROADCAST:
10697 			if (!checkonly) {
10698 				/* TODO: use value someplace? */
10699 				mutex_enter(&connp->conn_lock);
10700 				connp->conn_broadcast = *i1 ? 1 : 0;
10701 				mutex_exit(&connp->conn_lock);
10702 			}
10703 			break;	/* goto sizeof (int) option return */
10704 		case SO_USELOOPBACK:
10705 			if (!checkonly) {
10706 				/* TODO: use value someplace? */
10707 				mutex_enter(&connp->conn_lock);
10708 				connp->conn_loopback = *i1 ? 1 : 0;
10709 				mutex_exit(&connp->conn_lock);
10710 			}
10711 			break;	/* goto sizeof (int) option return */
10712 		case SO_DONTROUTE:
10713 			if (!checkonly) {
10714 				mutex_enter(&connp->conn_lock);
10715 				connp->conn_dontroute = *i1 ? 1 : 0;
10716 				mutex_exit(&connp->conn_lock);
10717 			}
10718 			break;	/* goto sizeof (int) option return */
10719 		case SO_REUSEADDR:
10720 			if (!checkonly) {
10721 				mutex_enter(&connp->conn_lock);
10722 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10723 				mutex_exit(&connp->conn_lock);
10724 			}
10725 			break;	/* goto sizeof (int) option return */
10726 		case SO_PROTOTYPE:
10727 			if (!checkonly) {
10728 				mutex_enter(&connp->conn_lock);
10729 				connp->conn_proto = *i1;
10730 				mutex_exit(&connp->conn_lock);
10731 			}
10732 			break;	/* goto sizeof (int) option return */
10733 		case SO_ALLZONES:
10734 			if (!checkonly) {
10735 				mutex_enter(&connp->conn_lock);
10736 				if (IPCL_IS_BOUND(connp)) {
10737 					mutex_exit(&connp->conn_lock);
10738 					return (EINVAL);
10739 				}
10740 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10741 				mutex_exit(&connp->conn_lock);
10742 			}
10743 			break;	/* goto sizeof (int) option return */
10744 		case SO_ANON_MLP:
10745 			if (!checkonly) {
10746 				mutex_enter(&connp->conn_lock);
10747 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10748 				mutex_exit(&connp->conn_lock);
10749 			}
10750 			break;	/* goto sizeof (int) option return */
10751 		case SO_MAC_EXEMPT:
10752 			if (secpolicy_net_mac_aware(cr) != 0 ||
10753 			    IPCL_IS_BOUND(connp))
10754 				return (EACCES);
10755 			if (!checkonly) {
10756 				mutex_enter(&connp->conn_lock);
10757 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10758 				mutex_exit(&connp->conn_lock);
10759 			}
10760 			break;	/* goto sizeof (int) option return */
10761 		default:
10762 			/*
10763 			 * "soft" error (negative)
10764 			 * option not handled at this level
10765 			 * Note: Do not modify *outlenp
10766 			 */
10767 			return (-EINVAL);
10768 		}
10769 		break;
10770 	case IPPROTO_IP:
10771 		switch (name) {
10772 		case IP_NEXTHOP:
10773 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10774 				return (EPERM);
10775 			/* FALLTHRU */
10776 		case IP_MULTICAST_IF:
10777 		case IP_DONTFAILOVER_IF: {
10778 			ipaddr_t addr = *i1;
10779 
10780 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10781 			    first_mp);
10782 			if (error != 0)
10783 				return (error);
10784 			break;	/* goto sizeof (int) option return */
10785 		}
10786 
10787 		case IP_MULTICAST_TTL:
10788 			/* Recorded in transport above IP */
10789 			*outvalp = *invalp;
10790 			*outlenp = sizeof (uchar_t);
10791 			return (0);
10792 		case IP_MULTICAST_LOOP:
10793 			if (!checkonly) {
10794 				mutex_enter(&connp->conn_lock);
10795 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10796 				mutex_exit(&connp->conn_lock);
10797 			}
10798 			*outvalp = *invalp;
10799 			*outlenp = sizeof (uchar_t);
10800 			return (0);
10801 		case IP_ADD_MEMBERSHIP:
10802 		case MCAST_JOIN_GROUP:
10803 		case IP_DROP_MEMBERSHIP:
10804 		case MCAST_LEAVE_GROUP: {
10805 			struct ip_mreq *mreqp;
10806 			struct group_req *greqp;
10807 			ire_t *ire;
10808 			boolean_t done = B_FALSE;
10809 			ipaddr_t group, ifaddr;
10810 			struct sockaddr_in *sin;
10811 			uint32_t *ifindexp;
10812 			boolean_t mcast_opt = B_TRUE;
10813 			mcast_record_t fmode;
10814 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10815 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10816 
10817 			switch (name) {
10818 			case IP_ADD_MEMBERSHIP:
10819 				mcast_opt = B_FALSE;
10820 				/* FALLTHRU */
10821 			case MCAST_JOIN_GROUP:
10822 				fmode = MODE_IS_EXCLUDE;
10823 				optfn = ip_opt_add_group;
10824 				break;
10825 
10826 			case IP_DROP_MEMBERSHIP:
10827 				mcast_opt = B_FALSE;
10828 				/* FALLTHRU */
10829 			case MCAST_LEAVE_GROUP:
10830 				fmode = MODE_IS_INCLUDE;
10831 				optfn = ip_opt_delete_group;
10832 				break;
10833 			}
10834 
10835 			if (mcast_opt) {
10836 				greqp = (struct group_req *)i1;
10837 				sin = (struct sockaddr_in *)&greqp->gr_group;
10838 				if (sin->sin_family != AF_INET) {
10839 					*outlenp = 0;
10840 					return (ENOPROTOOPT);
10841 				}
10842 				group = (ipaddr_t)sin->sin_addr.s_addr;
10843 				ifaddr = INADDR_ANY;
10844 				ifindexp = &greqp->gr_interface;
10845 			} else {
10846 				mreqp = (struct ip_mreq *)i1;
10847 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10848 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10849 				ifindexp = NULL;
10850 			}
10851 
10852 			/*
10853 			 * In the multirouting case, we need to replicate
10854 			 * the request on all interfaces that will take part
10855 			 * in replication.  We do so because multirouting is
10856 			 * reflective, thus we will probably receive multi-
10857 			 * casts on those interfaces.
10858 			 * The ip_multirt_apply_membership() succeeds if the
10859 			 * operation succeeds on at least one interface.
10860 			 */
10861 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10862 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10863 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10864 			if (ire != NULL) {
10865 				if (ire->ire_flags & RTF_MULTIRT) {
10866 					error = ip_multirt_apply_membership(
10867 					    optfn, ire, connp, checkonly, group,
10868 					    fmode, INADDR_ANY, first_mp);
10869 					done = B_TRUE;
10870 				}
10871 				ire_refrele(ire);
10872 			}
10873 			if (!done) {
10874 				error = optfn(connp, checkonly, group, ifaddr,
10875 				    ifindexp, fmode, INADDR_ANY, first_mp);
10876 			}
10877 			if (error) {
10878 				/*
10879 				 * EINPROGRESS is a soft error, needs retry
10880 				 * so don't make *outlenp zero.
10881 				 */
10882 				if (error != EINPROGRESS)
10883 					*outlenp = 0;
10884 				return (error);
10885 			}
10886 			/* OK return - copy input buffer into output buffer */
10887 			if (invalp != outvalp) {
10888 				/* don't trust bcopy for identical src/dst */
10889 				bcopy(invalp, outvalp, inlen);
10890 			}
10891 			*outlenp = inlen;
10892 			return (0);
10893 		}
10894 		case IP_BLOCK_SOURCE:
10895 		case IP_UNBLOCK_SOURCE:
10896 		case IP_ADD_SOURCE_MEMBERSHIP:
10897 		case IP_DROP_SOURCE_MEMBERSHIP:
10898 		case MCAST_BLOCK_SOURCE:
10899 		case MCAST_UNBLOCK_SOURCE:
10900 		case MCAST_JOIN_SOURCE_GROUP:
10901 		case MCAST_LEAVE_SOURCE_GROUP: {
10902 			struct ip_mreq_source *imreqp;
10903 			struct group_source_req *gsreqp;
10904 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10905 			uint32_t ifindex = 0;
10906 			mcast_record_t fmode;
10907 			struct sockaddr_in *sin;
10908 			ire_t *ire;
10909 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10910 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10911 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10912 
10913 			switch (name) {
10914 			case IP_BLOCK_SOURCE:
10915 				mcast_opt = B_FALSE;
10916 				/* FALLTHRU */
10917 			case MCAST_BLOCK_SOURCE:
10918 				fmode = MODE_IS_EXCLUDE;
10919 				optfn = ip_opt_add_group;
10920 				break;
10921 
10922 			case IP_UNBLOCK_SOURCE:
10923 				mcast_opt = B_FALSE;
10924 				/* FALLTHRU */
10925 			case MCAST_UNBLOCK_SOURCE:
10926 				fmode = MODE_IS_EXCLUDE;
10927 				optfn = ip_opt_delete_group;
10928 				break;
10929 
10930 			case IP_ADD_SOURCE_MEMBERSHIP:
10931 				mcast_opt = B_FALSE;
10932 				/* FALLTHRU */
10933 			case MCAST_JOIN_SOURCE_GROUP:
10934 				fmode = MODE_IS_INCLUDE;
10935 				optfn = ip_opt_add_group;
10936 				break;
10937 
10938 			case IP_DROP_SOURCE_MEMBERSHIP:
10939 				mcast_opt = B_FALSE;
10940 				/* FALLTHRU */
10941 			case MCAST_LEAVE_SOURCE_GROUP:
10942 				fmode = MODE_IS_INCLUDE;
10943 				optfn = ip_opt_delete_group;
10944 				break;
10945 			}
10946 
10947 			if (mcast_opt) {
10948 				gsreqp = (struct group_source_req *)i1;
10949 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10950 					*outlenp = 0;
10951 					return (ENOPROTOOPT);
10952 				}
10953 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10954 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10955 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10956 				src = (ipaddr_t)sin->sin_addr.s_addr;
10957 				ifindex = gsreqp->gsr_interface;
10958 			} else {
10959 				imreqp = (struct ip_mreq_source *)i1;
10960 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10961 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10962 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10963 			}
10964 
10965 			/*
10966 			 * In the multirouting case, we need to replicate
10967 			 * the request as noted in the mcast cases above.
10968 			 */
10969 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10970 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10971 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10972 			if (ire != NULL) {
10973 				if (ire->ire_flags & RTF_MULTIRT) {
10974 					error = ip_multirt_apply_membership(
10975 					    optfn, ire, connp, checkonly, grp,
10976 					    fmode, src, first_mp);
10977 					done = B_TRUE;
10978 				}
10979 				ire_refrele(ire);
10980 			}
10981 			if (!done) {
10982 				error = optfn(connp, checkonly, grp, ifaddr,
10983 				    &ifindex, fmode, src, first_mp);
10984 			}
10985 			if (error != 0) {
10986 				/*
10987 				 * EINPROGRESS is a soft error, needs retry
10988 				 * so don't make *outlenp zero.
10989 				 */
10990 				if (error != EINPROGRESS)
10991 					*outlenp = 0;
10992 				return (error);
10993 			}
10994 			/* OK return - copy input buffer into output buffer */
10995 			if (invalp != outvalp) {
10996 				bcopy(invalp, outvalp, inlen);
10997 			}
10998 			*outlenp = inlen;
10999 			return (0);
11000 		}
11001 		case IP_SEC_OPT:
11002 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11003 			if (error != 0) {
11004 				*outlenp = 0;
11005 				return (error);
11006 			}
11007 			break;
11008 		case IP_HDRINCL:
11009 		case IP_OPTIONS:
11010 		case T_IP_OPTIONS:
11011 		case IP_TOS:
11012 		case T_IP_TOS:
11013 		case IP_TTL:
11014 		case IP_RECVDSTADDR:
11015 		case IP_RECVOPTS:
11016 			/* OK return - copy input buffer into output buffer */
11017 			if (invalp != outvalp) {
11018 				/* don't trust bcopy for identical src/dst */
11019 				bcopy(invalp, outvalp, inlen);
11020 			}
11021 			*outlenp = inlen;
11022 			return (0);
11023 		case IP_RECVIF:
11024 			/* Retrieve the inbound interface index */
11025 			if (!checkonly) {
11026 				mutex_enter(&connp->conn_lock);
11027 				connp->conn_recvif = *i1 ? 1 : 0;
11028 				mutex_exit(&connp->conn_lock);
11029 			}
11030 			break;	/* goto sizeof (int) option return */
11031 		case IP_RECVPKTINFO:
11032 			if (!checkonly) {
11033 				mutex_enter(&connp->conn_lock);
11034 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11035 				mutex_exit(&connp->conn_lock);
11036 			}
11037 			break;	/* goto sizeof (int) option return */
11038 		case IP_RECVSLLA:
11039 			/* Retrieve the source link layer address */
11040 			if (!checkonly) {
11041 				mutex_enter(&connp->conn_lock);
11042 				connp->conn_recvslla = *i1 ? 1 : 0;
11043 				mutex_exit(&connp->conn_lock);
11044 			}
11045 			break;	/* goto sizeof (int) option return */
11046 		case MRT_INIT:
11047 		case MRT_DONE:
11048 		case MRT_ADD_VIF:
11049 		case MRT_DEL_VIF:
11050 		case MRT_ADD_MFC:
11051 		case MRT_DEL_MFC:
11052 		case MRT_ASSERT:
11053 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11054 				*outlenp = 0;
11055 				return (error);
11056 			}
11057 			error = ip_mrouter_set((int)name, q, checkonly,
11058 			    (uchar_t *)invalp, inlen, first_mp);
11059 			if (error) {
11060 				*outlenp = 0;
11061 				return (error);
11062 			}
11063 			/* OK return - copy input buffer into output buffer */
11064 			if (invalp != outvalp) {
11065 				/* don't trust bcopy for identical src/dst */
11066 				bcopy(invalp, outvalp, inlen);
11067 			}
11068 			*outlenp = inlen;
11069 			return (0);
11070 		case IP_BOUND_IF:
11071 		case IP_DHCPINIT_IF:
11072 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11073 			    level, name, first_mp);
11074 			if (error != 0)
11075 				return (error);
11076 			break; 		/* goto sizeof (int) option return */
11077 
11078 		case IP_UNSPEC_SRC:
11079 			/* Allow sending with a zero source address */
11080 			if (!checkonly) {
11081 				mutex_enter(&connp->conn_lock);
11082 				connp->conn_unspec_src = *i1 ? 1 : 0;
11083 				mutex_exit(&connp->conn_lock);
11084 			}
11085 			break;	/* goto sizeof (int) option return */
11086 		default:
11087 			/*
11088 			 * "soft" error (negative)
11089 			 * option not handled at this level
11090 			 * Note: Do not modify *outlenp
11091 			 */
11092 			return (-EINVAL);
11093 		}
11094 		break;
11095 	case IPPROTO_IPV6:
11096 		switch (name) {
11097 		case IPV6_BOUND_IF:
11098 		case IPV6_BOUND_PIF:
11099 		case IPV6_DONTFAILOVER_IF:
11100 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11101 			    level, name, first_mp);
11102 			if (error != 0)
11103 				return (error);
11104 			break; 		/* goto sizeof (int) option return */
11105 
11106 		case IPV6_MULTICAST_IF:
11107 			/*
11108 			 * The only possible errors are EINPROGRESS and
11109 			 * EINVAL. EINPROGRESS will be restarted and is not
11110 			 * a hard error. We call this option on both V4 and V6
11111 			 * If both return EINVAL, then this call returns
11112 			 * EINVAL. If at least one of them succeeds we
11113 			 * return success.
11114 			 */
11115 			found = B_FALSE;
11116 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11117 			    level, name, first_mp);
11118 			if (error == EINPROGRESS)
11119 				return (error);
11120 			if (error == 0)
11121 				found = B_TRUE;
11122 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11123 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11124 			if (error == 0)
11125 				found = B_TRUE;
11126 			if (!found)
11127 				return (error);
11128 			break; 		/* goto sizeof (int) option return */
11129 
11130 		case IPV6_MULTICAST_HOPS:
11131 			/* Recorded in transport above IP */
11132 			break;	/* goto sizeof (int) option return */
11133 		case IPV6_MULTICAST_LOOP:
11134 			if (!checkonly) {
11135 				mutex_enter(&connp->conn_lock);
11136 				connp->conn_multicast_loop = *i1;
11137 				mutex_exit(&connp->conn_lock);
11138 			}
11139 			break;	/* goto sizeof (int) option return */
11140 		case IPV6_JOIN_GROUP:
11141 		case MCAST_JOIN_GROUP:
11142 		case IPV6_LEAVE_GROUP:
11143 		case MCAST_LEAVE_GROUP: {
11144 			struct ipv6_mreq *ip_mreqp;
11145 			struct group_req *greqp;
11146 			ire_t *ire;
11147 			boolean_t done = B_FALSE;
11148 			in6_addr_t groupv6;
11149 			uint32_t ifindex;
11150 			boolean_t mcast_opt = B_TRUE;
11151 			mcast_record_t fmode;
11152 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11153 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11154 
11155 			switch (name) {
11156 			case IPV6_JOIN_GROUP:
11157 				mcast_opt = B_FALSE;
11158 				/* FALLTHRU */
11159 			case MCAST_JOIN_GROUP:
11160 				fmode = MODE_IS_EXCLUDE;
11161 				optfn = ip_opt_add_group_v6;
11162 				break;
11163 
11164 			case IPV6_LEAVE_GROUP:
11165 				mcast_opt = B_FALSE;
11166 				/* FALLTHRU */
11167 			case MCAST_LEAVE_GROUP:
11168 				fmode = MODE_IS_INCLUDE;
11169 				optfn = ip_opt_delete_group_v6;
11170 				break;
11171 			}
11172 
11173 			if (mcast_opt) {
11174 				struct sockaddr_in *sin;
11175 				struct sockaddr_in6 *sin6;
11176 				greqp = (struct group_req *)i1;
11177 				if (greqp->gr_group.ss_family == AF_INET) {
11178 					sin = (struct sockaddr_in *)
11179 					    &(greqp->gr_group);
11180 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11181 					    &groupv6);
11182 				} else {
11183 					sin6 = (struct sockaddr_in6 *)
11184 					    &(greqp->gr_group);
11185 					groupv6 = sin6->sin6_addr;
11186 				}
11187 				ifindex = greqp->gr_interface;
11188 			} else {
11189 				ip_mreqp = (struct ipv6_mreq *)i1;
11190 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11191 				ifindex = ip_mreqp->ipv6mr_interface;
11192 			}
11193 			/*
11194 			 * In the multirouting case, we need to replicate
11195 			 * the request on all interfaces that will take part
11196 			 * in replication.  We do so because multirouting is
11197 			 * reflective, thus we will probably receive multi-
11198 			 * casts on those interfaces.
11199 			 * The ip_multirt_apply_membership_v6() succeeds if
11200 			 * the operation succeeds on at least one interface.
11201 			 */
11202 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11203 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11204 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11205 			if (ire != NULL) {
11206 				if (ire->ire_flags & RTF_MULTIRT) {
11207 					error = ip_multirt_apply_membership_v6(
11208 					    optfn, ire, connp, checkonly,
11209 					    &groupv6, fmode, &ipv6_all_zeros,
11210 					    first_mp);
11211 					done = B_TRUE;
11212 				}
11213 				ire_refrele(ire);
11214 			}
11215 			if (!done) {
11216 				error = optfn(connp, checkonly, &groupv6,
11217 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11218 			}
11219 			if (error) {
11220 				/*
11221 				 * EINPROGRESS is a soft error, needs retry
11222 				 * so don't make *outlenp zero.
11223 				 */
11224 				if (error != EINPROGRESS)
11225 					*outlenp = 0;
11226 				return (error);
11227 			}
11228 			/* OK return - copy input buffer into output buffer */
11229 			if (invalp != outvalp) {
11230 				/* don't trust bcopy for identical src/dst */
11231 				bcopy(invalp, outvalp, inlen);
11232 			}
11233 			*outlenp = inlen;
11234 			return (0);
11235 		}
11236 		case MCAST_BLOCK_SOURCE:
11237 		case MCAST_UNBLOCK_SOURCE:
11238 		case MCAST_JOIN_SOURCE_GROUP:
11239 		case MCAST_LEAVE_SOURCE_GROUP: {
11240 			struct group_source_req *gsreqp;
11241 			in6_addr_t v6grp, v6src;
11242 			uint32_t ifindex;
11243 			mcast_record_t fmode;
11244 			ire_t *ire;
11245 			boolean_t done = B_FALSE;
11246 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11247 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11248 
11249 			switch (name) {
11250 			case MCAST_BLOCK_SOURCE:
11251 				fmode = MODE_IS_EXCLUDE;
11252 				optfn = ip_opt_add_group_v6;
11253 				break;
11254 			case MCAST_UNBLOCK_SOURCE:
11255 				fmode = MODE_IS_EXCLUDE;
11256 				optfn = ip_opt_delete_group_v6;
11257 				break;
11258 			case MCAST_JOIN_SOURCE_GROUP:
11259 				fmode = MODE_IS_INCLUDE;
11260 				optfn = ip_opt_add_group_v6;
11261 				break;
11262 			case MCAST_LEAVE_SOURCE_GROUP:
11263 				fmode = MODE_IS_INCLUDE;
11264 				optfn = ip_opt_delete_group_v6;
11265 				break;
11266 			}
11267 
11268 			gsreqp = (struct group_source_req *)i1;
11269 			ifindex = gsreqp->gsr_interface;
11270 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11271 				struct sockaddr_in *s;
11272 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11273 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11274 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11275 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11276 			} else {
11277 				struct sockaddr_in6 *s6;
11278 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11279 				v6grp = s6->sin6_addr;
11280 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11281 				v6src = s6->sin6_addr;
11282 			}
11283 
11284 			/*
11285 			 * In the multirouting case, we need to replicate
11286 			 * the request as noted in the mcast cases above.
11287 			 */
11288 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11289 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11290 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11291 			if (ire != NULL) {
11292 				if (ire->ire_flags & RTF_MULTIRT) {
11293 					error = ip_multirt_apply_membership_v6(
11294 					    optfn, ire, connp, checkonly,
11295 					    &v6grp, fmode, &v6src, first_mp);
11296 					done = B_TRUE;
11297 				}
11298 				ire_refrele(ire);
11299 			}
11300 			if (!done) {
11301 				error = optfn(connp, checkonly, &v6grp,
11302 				    ifindex, fmode, &v6src, first_mp);
11303 			}
11304 			if (error != 0) {
11305 				/*
11306 				 * EINPROGRESS is a soft error, needs retry
11307 				 * so don't make *outlenp zero.
11308 				 */
11309 				if (error != EINPROGRESS)
11310 					*outlenp = 0;
11311 				return (error);
11312 			}
11313 			/* OK return - copy input buffer into output buffer */
11314 			if (invalp != outvalp) {
11315 				bcopy(invalp, outvalp, inlen);
11316 			}
11317 			*outlenp = inlen;
11318 			return (0);
11319 		}
11320 		case IPV6_UNICAST_HOPS:
11321 			/* Recorded in transport above IP */
11322 			break;	/* goto sizeof (int) option return */
11323 		case IPV6_UNSPEC_SRC:
11324 			/* Allow sending with a zero source address */
11325 			if (!checkonly) {
11326 				mutex_enter(&connp->conn_lock);
11327 				connp->conn_unspec_src = *i1 ? 1 : 0;
11328 				mutex_exit(&connp->conn_lock);
11329 			}
11330 			break;	/* goto sizeof (int) option return */
11331 		case IPV6_RECVPKTINFO:
11332 			if (!checkonly) {
11333 				mutex_enter(&connp->conn_lock);
11334 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11335 				mutex_exit(&connp->conn_lock);
11336 			}
11337 			break;	/* goto sizeof (int) option return */
11338 		case IPV6_RECVTCLASS:
11339 			if (!checkonly) {
11340 				if (*i1 < 0 || *i1 > 1) {
11341 					return (EINVAL);
11342 				}
11343 				mutex_enter(&connp->conn_lock);
11344 				connp->conn_ipv6_recvtclass = *i1;
11345 				mutex_exit(&connp->conn_lock);
11346 			}
11347 			break;
11348 		case IPV6_RECVPATHMTU:
11349 			if (!checkonly) {
11350 				if (*i1 < 0 || *i1 > 1) {
11351 					return (EINVAL);
11352 				}
11353 				mutex_enter(&connp->conn_lock);
11354 				connp->conn_ipv6_recvpathmtu = *i1;
11355 				mutex_exit(&connp->conn_lock);
11356 			}
11357 			break;
11358 		case IPV6_RECVHOPLIMIT:
11359 			if (!checkonly) {
11360 				mutex_enter(&connp->conn_lock);
11361 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11362 				mutex_exit(&connp->conn_lock);
11363 			}
11364 			break;	/* goto sizeof (int) option return */
11365 		case IPV6_RECVHOPOPTS:
11366 			if (!checkonly) {
11367 				mutex_enter(&connp->conn_lock);
11368 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11369 				mutex_exit(&connp->conn_lock);
11370 			}
11371 			break;	/* goto sizeof (int) option return */
11372 		case IPV6_RECVDSTOPTS:
11373 			if (!checkonly) {
11374 				mutex_enter(&connp->conn_lock);
11375 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11376 				mutex_exit(&connp->conn_lock);
11377 			}
11378 			break;	/* goto sizeof (int) option return */
11379 		case IPV6_RECVRTHDR:
11380 			if (!checkonly) {
11381 				mutex_enter(&connp->conn_lock);
11382 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11383 				mutex_exit(&connp->conn_lock);
11384 			}
11385 			break;	/* goto sizeof (int) option return */
11386 		case IPV6_RECVRTHDRDSTOPTS:
11387 			if (!checkonly) {
11388 				mutex_enter(&connp->conn_lock);
11389 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11390 				mutex_exit(&connp->conn_lock);
11391 			}
11392 			break;	/* goto sizeof (int) option return */
11393 		case IPV6_PKTINFO:
11394 			if (inlen == 0)
11395 				return (-EINVAL);	/* clearing option */
11396 			error = ip6_set_pktinfo(cr, connp,
11397 			    (struct in6_pktinfo *)invalp, first_mp);
11398 			if (error != 0)
11399 				*outlenp = 0;
11400 			else
11401 				*outlenp = inlen;
11402 			return (error);
11403 		case IPV6_NEXTHOP: {
11404 			struct sockaddr_in6 *sin6;
11405 
11406 			/* Verify that the nexthop is reachable */
11407 			if (inlen == 0)
11408 				return (-EINVAL);	/* clearing option */
11409 
11410 			sin6 = (struct sockaddr_in6 *)invalp;
11411 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11412 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11413 			    NULL, MATCH_IRE_DEFAULT, ipst);
11414 
11415 			if (ire == NULL) {
11416 				*outlenp = 0;
11417 				return (EHOSTUNREACH);
11418 			}
11419 			ire_refrele(ire);
11420 			return (-EINVAL);
11421 		}
11422 		case IPV6_SEC_OPT:
11423 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11424 			if (error != 0) {
11425 				*outlenp = 0;
11426 				return (error);
11427 			}
11428 			break;
11429 		case IPV6_SRC_PREFERENCES: {
11430 			/*
11431 			 * This is implemented strictly in the ip module
11432 			 * (here and in tcp_opt_*() to accomodate tcp
11433 			 * sockets).  Modules above ip pass this option
11434 			 * down here since ip is the only one that needs to
11435 			 * be aware of source address preferences.
11436 			 *
11437 			 * This socket option only affects connected
11438 			 * sockets that haven't already bound to a specific
11439 			 * IPv6 address.  In other words, sockets that
11440 			 * don't call bind() with an address other than the
11441 			 * unspecified address and that call connect().
11442 			 * ip_bind_connected_v6() passes these preferences
11443 			 * to the ipif_select_source_v6() function.
11444 			 */
11445 			if (inlen != sizeof (uint32_t))
11446 				return (EINVAL);
11447 			error = ip6_set_src_preferences(connp,
11448 			    *(uint32_t *)invalp);
11449 			if (error != 0) {
11450 				*outlenp = 0;
11451 				return (error);
11452 			} else {
11453 				*outlenp = sizeof (uint32_t);
11454 			}
11455 			break;
11456 		}
11457 		case IPV6_V6ONLY:
11458 			if (*i1 < 0 || *i1 > 1) {
11459 				return (EINVAL);
11460 			}
11461 			mutex_enter(&connp->conn_lock);
11462 			connp->conn_ipv6_v6only = *i1;
11463 			mutex_exit(&connp->conn_lock);
11464 			break;
11465 		default:
11466 			return (-EINVAL);
11467 		}
11468 		break;
11469 	default:
11470 		/*
11471 		 * "soft" error (negative)
11472 		 * option not handled at this level
11473 		 * Note: Do not modify *outlenp
11474 		 */
11475 		return (-EINVAL);
11476 	}
11477 	/*
11478 	 * Common case of return from an option that is sizeof (int)
11479 	 */
11480 	*(int *)outvalp = *i1;
11481 	*outlenp = sizeof (int);
11482 	return (0);
11483 }
11484 
11485 /*
11486  * This routine gets default values of certain options whose default
11487  * values are maintained by protocol specific code
11488  */
11489 /* ARGSUSED */
11490 int
11491 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11492 {
11493 	int *i1 = (int *)ptr;
11494 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11495 
11496 	switch (level) {
11497 	case IPPROTO_IP:
11498 		switch (name) {
11499 		case IP_MULTICAST_TTL:
11500 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11501 			return (sizeof (uchar_t));
11502 		case IP_MULTICAST_LOOP:
11503 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11504 			return (sizeof (uchar_t));
11505 		default:
11506 			return (-1);
11507 		}
11508 	case IPPROTO_IPV6:
11509 		switch (name) {
11510 		case IPV6_UNICAST_HOPS:
11511 			*i1 = ipst->ips_ipv6_def_hops;
11512 			return (sizeof (int));
11513 		case IPV6_MULTICAST_HOPS:
11514 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11515 			return (sizeof (int));
11516 		case IPV6_MULTICAST_LOOP:
11517 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11518 			return (sizeof (int));
11519 		case IPV6_V6ONLY:
11520 			*i1 = 1;
11521 			return (sizeof (int));
11522 		default:
11523 			return (-1);
11524 		}
11525 	default:
11526 		return (-1);
11527 	}
11528 	/* NOTREACHED */
11529 }
11530 
11531 /*
11532  * Given a destination address and a pointer to where to put the information
11533  * this routine fills in the mtuinfo.
11534  */
11535 int
11536 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11537     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11538 {
11539 	ire_t *ire;
11540 	ip_stack_t	*ipst = ns->netstack_ip;
11541 
11542 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11543 		return (-1);
11544 
11545 	bzero(mtuinfo, sizeof (*mtuinfo));
11546 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11547 	mtuinfo->ip6m_addr.sin6_port = port;
11548 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11549 
11550 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11551 	if (ire != NULL) {
11552 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11553 		ire_refrele(ire);
11554 	} else {
11555 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11556 	}
11557 	return (sizeof (struct ip6_mtuinfo));
11558 }
11559 
11560 /*
11561  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11562  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11563  * isn't.  This doesn't matter as the error checking is done properly for the
11564  * other MRT options coming in through ip_opt_set.
11565  */
11566 int
11567 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11568 {
11569 	conn_t		*connp = Q_TO_CONN(q);
11570 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11571 
11572 	switch (level) {
11573 	case IPPROTO_IP:
11574 		switch (name) {
11575 		case MRT_VERSION:
11576 		case MRT_ASSERT:
11577 			(void) ip_mrouter_get(name, q, ptr);
11578 			return (sizeof (int));
11579 		case IP_SEC_OPT:
11580 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11581 		case IP_NEXTHOP:
11582 			if (connp->conn_nexthop_set) {
11583 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11584 				return (sizeof (ipaddr_t));
11585 			} else
11586 				return (0);
11587 		case IP_RECVPKTINFO:
11588 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11589 			return (sizeof (int));
11590 		default:
11591 			break;
11592 		}
11593 		break;
11594 	case IPPROTO_IPV6:
11595 		switch (name) {
11596 		case IPV6_SEC_OPT:
11597 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11598 		case IPV6_SRC_PREFERENCES: {
11599 			return (ip6_get_src_preferences(connp,
11600 			    (uint32_t *)ptr));
11601 		}
11602 		case IPV6_V6ONLY:
11603 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11604 			return (sizeof (int));
11605 		case IPV6_PATHMTU:
11606 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11607 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11608 		default:
11609 			break;
11610 		}
11611 		break;
11612 	default:
11613 		break;
11614 	}
11615 	return (-1);
11616 }
11617 
11618 /* Named Dispatch routine to get a current value out of our parameter table. */
11619 /* ARGSUSED */
11620 static int
11621 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11622 {
11623 	ipparam_t *ippa = (ipparam_t *)cp;
11624 
11625 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11626 	return (0);
11627 }
11628 
11629 /* ARGSUSED */
11630 static int
11631 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11632 {
11633 
11634 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11635 	return (0);
11636 }
11637 
11638 /*
11639  * Set ip{,6}_forwarding values.  This means walking through all of the
11640  * ill's and toggling their forwarding values.
11641  */
11642 /* ARGSUSED */
11643 static int
11644 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11645 {
11646 	long new_value;
11647 	int *forwarding_value = (int *)cp;
11648 	ill_t *ill;
11649 	boolean_t isv6;
11650 	ill_walk_context_t ctx;
11651 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11652 
11653 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11654 
11655 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11656 	    new_value < 0 || new_value > 1) {
11657 		return (EINVAL);
11658 	}
11659 
11660 	*forwarding_value = new_value;
11661 
11662 	/*
11663 	 * Regardless of the current value of ip_forwarding, set all per-ill
11664 	 * values of ip_forwarding to the value being set.
11665 	 *
11666 	 * Bring all the ill's up to date with the new global value.
11667 	 */
11668 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11669 
11670 	if (isv6)
11671 		ill = ILL_START_WALK_V6(&ctx, ipst);
11672 	else
11673 		ill = ILL_START_WALK_V4(&ctx, ipst);
11674 
11675 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11676 		(void) ill_forward_set(ill, new_value != 0);
11677 
11678 	rw_exit(&ipst->ips_ill_g_lock);
11679 	return (0);
11680 }
11681 
11682 /*
11683  * Walk through the param array specified registering each element with the
11684  * Named Dispatch handler. This is called only during init. So it is ok
11685  * not to acquire any locks
11686  */
11687 static boolean_t
11688 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11689     ipndp_t *ipnd, size_t ipnd_cnt)
11690 {
11691 	for (; ippa_cnt-- > 0; ippa++) {
11692 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11693 			if (!nd_load(ndp, ippa->ip_param_name,
11694 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11695 				nd_free(ndp);
11696 				return (B_FALSE);
11697 			}
11698 		}
11699 	}
11700 
11701 	for (; ipnd_cnt-- > 0; ipnd++) {
11702 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11703 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11704 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11705 			    ipnd->ip_ndp_data)) {
11706 				nd_free(ndp);
11707 				return (B_FALSE);
11708 			}
11709 		}
11710 	}
11711 
11712 	return (B_TRUE);
11713 }
11714 
11715 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11716 /* ARGSUSED */
11717 static int
11718 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11719 {
11720 	long		new_value;
11721 	ipparam_t	*ippa = (ipparam_t *)cp;
11722 
11723 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11724 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11725 		return (EINVAL);
11726 	}
11727 	ippa->ip_param_value = new_value;
11728 	return (0);
11729 }
11730 
11731 /*
11732  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11733  * When an ipf is passed here for the first time, if
11734  * we already have in-order fragments on the queue, we convert from the fast-
11735  * path reassembly scheme to the hard-case scheme.  From then on, additional
11736  * fragments are reassembled here.  We keep track of the start and end offsets
11737  * of each piece, and the number of holes in the chain.  When the hole count
11738  * goes to zero, we are done!
11739  *
11740  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11741  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11742  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11743  * after the call to ip_reassemble().
11744  */
11745 int
11746 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11747     size_t msg_len)
11748 {
11749 	uint_t	end;
11750 	mblk_t	*next_mp;
11751 	mblk_t	*mp1;
11752 	uint_t	offset;
11753 	boolean_t incr_dups = B_TRUE;
11754 	boolean_t offset_zero_seen = B_FALSE;
11755 	boolean_t pkt_boundary_checked = B_FALSE;
11756 
11757 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11758 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11759 
11760 	/* Add in byte count */
11761 	ipf->ipf_count += msg_len;
11762 	if (ipf->ipf_end) {
11763 		/*
11764 		 * We were part way through in-order reassembly, but now there
11765 		 * is a hole.  We walk through messages already queued, and
11766 		 * mark them for hard case reassembly.  We know that up till
11767 		 * now they were in order starting from offset zero.
11768 		 */
11769 		offset = 0;
11770 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11771 			IP_REASS_SET_START(mp1, offset);
11772 			if (offset == 0) {
11773 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11774 				offset = -ipf->ipf_nf_hdr_len;
11775 			}
11776 			offset += mp1->b_wptr - mp1->b_rptr;
11777 			IP_REASS_SET_END(mp1, offset);
11778 		}
11779 		/* One hole at the end. */
11780 		ipf->ipf_hole_cnt = 1;
11781 		/* Brand it as a hard case, forever. */
11782 		ipf->ipf_end = 0;
11783 	}
11784 	/* Walk through all the new pieces. */
11785 	do {
11786 		end = start + (mp->b_wptr - mp->b_rptr);
11787 		/*
11788 		 * If start is 0, decrease 'end' only for the first mblk of
11789 		 * the fragment. Otherwise 'end' can get wrong value in the
11790 		 * second pass of the loop if first mblk is exactly the
11791 		 * size of ipf_nf_hdr_len.
11792 		 */
11793 		if (start == 0 && !offset_zero_seen) {
11794 			/* First segment */
11795 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11796 			end -= ipf->ipf_nf_hdr_len;
11797 			offset_zero_seen = B_TRUE;
11798 		}
11799 		next_mp = mp->b_cont;
11800 		/*
11801 		 * We are checking to see if there is any interesing data
11802 		 * to process.  If there isn't and the mblk isn't the
11803 		 * one which carries the unfragmentable header then we
11804 		 * drop it.  It's possible to have just the unfragmentable
11805 		 * header come through without any data.  That needs to be
11806 		 * saved.
11807 		 *
11808 		 * If the assert at the top of this function holds then the
11809 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11810 		 * is infrequently traveled enough that the test is left in
11811 		 * to protect against future code changes which break that
11812 		 * invariant.
11813 		 */
11814 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11815 			/* Empty.  Blast it. */
11816 			IP_REASS_SET_START(mp, 0);
11817 			IP_REASS_SET_END(mp, 0);
11818 			/*
11819 			 * If the ipf points to the mblk we are about to free,
11820 			 * update ipf to point to the next mblk (or NULL
11821 			 * if none).
11822 			 */
11823 			if (ipf->ipf_mp->b_cont == mp)
11824 				ipf->ipf_mp->b_cont = next_mp;
11825 			freeb(mp);
11826 			continue;
11827 		}
11828 		mp->b_cont = NULL;
11829 		IP_REASS_SET_START(mp, start);
11830 		IP_REASS_SET_END(mp, end);
11831 		if (!ipf->ipf_tail_mp) {
11832 			ipf->ipf_tail_mp = mp;
11833 			ipf->ipf_mp->b_cont = mp;
11834 			if (start == 0 || !more) {
11835 				ipf->ipf_hole_cnt = 1;
11836 				/*
11837 				 * if the first fragment comes in more than one
11838 				 * mblk, this loop will be executed for each
11839 				 * mblk. Need to adjust hole count so exiting
11840 				 * this routine will leave hole count at 1.
11841 				 */
11842 				if (next_mp)
11843 					ipf->ipf_hole_cnt++;
11844 			} else
11845 				ipf->ipf_hole_cnt = 2;
11846 			continue;
11847 		} else if (ipf->ipf_last_frag_seen && !more &&
11848 		    !pkt_boundary_checked) {
11849 			/*
11850 			 * We check datagram boundary only if this fragment
11851 			 * claims to be the last fragment and we have seen a
11852 			 * last fragment in the past too. We do this only
11853 			 * once for a given fragment.
11854 			 *
11855 			 * start cannot be 0 here as fragments with start=0
11856 			 * and MF=0 gets handled as a complete packet. These
11857 			 * fragments should not reach here.
11858 			 */
11859 
11860 			if (start + msgdsize(mp) !=
11861 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11862 				/*
11863 				 * We have two fragments both of which claim
11864 				 * to be the last fragment but gives conflicting
11865 				 * information about the whole datagram size.
11866 				 * Something fishy is going on. Drop the
11867 				 * fragment and free up the reassembly list.
11868 				 */
11869 				return (IP_REASS_FAILED);
11870 			}
11871 
11872 			/*
11873 			 * We shouldn't come to this code block again for this
11874 			 * particular fragment.
11875 			 */
11876 			pkt_boundary_checked = B_TRUE;
11877 		}
11878 
11879 		/* New stuff at or beyond tail? */
11880 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11881 		if (start >= offset) {
11882 			if (ipf->ipf_last_frag_seen) {
11883 				/* current fragment is beyond last fragment */
11884 				return (IP_REASS_FAILED);
11885 			}
11886 			/* Link it on end. */
11887 			ipf->ipf_tail_mp->b_cont = mp;
11888 			ipf->ipf_tail_mp = mp;
11889 			if (more) {
11890 				if (start != offset)
11891 					ipf->ipf_hole_cnt++;
11892 			} else if (start == offset && next_mp == NULL)
11893 					ipf->ipf_hole_cnt--;
11894 			continue;
11895 		}
11896 		mp1 = ipf->ipf_mp->b_cont;
11897 		offset = IP_REASS_START(mp1);
11898 		/* New stuff at the front? */
11899 		if (start < offset) {
11900 			if (start == 0) {
11901 				if (end >= offset) {
11902 					/* Nailed the hole at the begining. */
11903 					ipf->ipf_hole_cnt--;
11904 				}
11905 			} else if (end < offset) {
11906 				/*
11907 				 * A hole, stuff, and a hole where there used
11908 				 * to be just a hole.
11909 				 */
11910 				ipf->ipf_hole_cnt++;
11911 			}
11912 			mp->b_cont = mp1;
11913 			/* Check for overlap. */
11914 			while (end > offset) {
11915 				if (end < IP_REASS_END(mp1)) {
11916 					mp->b_wptr -= end - offset;
11917 					IP_REASS_SET_END(mp, offset);
11918 					BUMP_MIB(ill->ill_ip_mib,
11919 					    ipIfStatsReasmPartDups);
11920 					break;
11921 				}
11922 				/* Did we cover another hole? */
11923 				if ((mp1->b_cont &&
11924 				    IP_REASS_END(mp1) !=
11925 				    IP_REASS_START(mp1->b_cont) &&
11926 				    end >= IP_REASS_START(mp1->b_cont)) ||
11927 				    (!ipf->ipf_last_frag_seen && !more)) {
11928 					ipf->ipf_hole_cnt--;
11929 				}
11930 				/* Clip out mp1. */
11931 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11932 					/*
11933 					 * After clipping out mp1, this guy
11934 					 * is now hanging off the end.
11935 					 */
11936 					ipf->ipf_tail_mp = mp;
11937 				}
11938 				IP_REASS_SET_START(mp1, 0);
11939 				IP_REASS_SET_END(mp1, 0);
11940 				/* Subtract byte count */
11941 				ipf->ipf_count -= mp1->b_datap->db_lim -
11942 				    mp1->b_datap->db_base;
11943 				freeb(mp1);
11944 				BUMP_MIB(ill->ill_ip_mib,
11945 				    ipIfStatsReasmPartDups);
11946 				mp1 = mp->b_cont;
11947 				if (!mp1)
11948 					break;
11949 				offset = IP_REASS_START(mp1);
11950 			}
11951 			ipf->ipf_mp->b_cont = mp;
11952 			continue;
11953 		}
11954 		/*
11955 		 * The new piece starts somewhere between the start of the head
11956 		 * and before the end of the tail.
11957 		 */
11958 		for (; mp1; mp1 = mp1->b_cont) {
11959 			offset = IP_REASS_END(mp1);
11960 			if (start < offset) {
11961 				if (end <= offset) {
11962 					/* Nothing new. */
11963 					IP_REASS_SET_START(mp, 0);
11964 					IP_REASS_SET_END(mp, 0);
11965 					/* Subtract byte count */
11966 					ipf->ipf_count -= mp->b_datap->db_lim -
11967 					    mp->b_datap->db_base;
11968 					if (incr_dups) {
11969 						ipf->ipf_num_dups++;
11970 						incr_dups = B_FALSE;
11971 					}
11972 					freeb(mp);
11973 					BUMP_MIB(ill->ill_ip_mib,
11974 					    ipIfStatsReasmDuplicates);
11975 					break;
11976 				}
11977 				/*
11978 				 * Trim redundant stuff off beginning of new
11979 				 * piece.
11980 				 */
11981 				IP_REASS_SET_START(mp, offset);
11982 				mp->b_rptr += offset - start;
11983 				BUMP_MIB(ill->ill_ip_mib,
11984 				    ipIfStatsReasmPartDups);
11985 				start = offset;
11986 				if (!mp1->b_cont) {
11987 					/*
11988 					 * After trimming, this guy is now
11989 					 * hanging off the end.
11990 					 */
11991 					mp1->b_cont = mp;
11992 					ipf->ipf_tail_mp = mp;
11993 					if (!more) {
11994 						ipf->ipf_hole_cnt--;
11995 					}
11996 					break;
11997 				}
11998 			}
11999 			if (start >= IP_REASS_START(mp1->b_cont))
12000 				continue;
12001 			/* Fill a hole */
12002 			if (start > offset)
12003 				ipf->ipf_hole_cnt++;
12004 			mp->b_cont = mp1->b_cont;
12005 			mp1->b_cont = mp;
12006 			mp1 = mp->b_cont;
12007 			offset = IP_REASS_START(mp1);
12008 			if (end >= offset) {
12009 				ipf->ipf_hole_cnt--;
12010 				/* Check for overlap. */
12011 				while (end > offset) {
12012 					if (end < IP_REASS_END(mp1)) {
12013 						mp->b_wptr -= end - offset;
12014 						IP_REASS_SET_END(mp, offset);
12015 						/*
12016 						 * TODO we might bump
12017 						 * this up twice if there is
12018 						 * overlap at both ends.
12019 						 */
12020 						BUMP_MIB(ill->ill_ip_mib,
12021 						    ipIfStatsReasmPartDups);
12022 						break;
12023 					}
12024 					/* Did we cover another hole? */
12025 					if ((mp1->b_cont &&
12026 					    IP_REASS_END(mp1)
12027 					    != IP_REASS_START(mp1->b_cont) &&
12028 					    end >=
12029 					    IP_REASS_START(mp1->b_cont)) ||
12030 					    (!ipf->ipf_last_frag_seen &&
12031 					    !more)) {
12032 						ipf->ipf_hole_cnt--;
12033 					}
12034 					/* Clip out mp1. */
12035 					if ((mp->b_cont = mp1->b_cont) ==
12036 					    NULL) {
12037 						/*
12038 						 * After clipping out mp1,
12039 						 * this guy is now hanging
12040 						 * off the end.
12041 						 */
12042 						ipf->ipf_tail_mp = mp;
12043 					}
12044 					IP_REASS_SET_START(mp1, 0);
12045 					IP_REASS_SET_END(mp1, 0);
12046 					/* Subtract byte count */
12047 					ipf->ipf_count -=
12048 					    mp1->b_datap->db_lim -
12049 					    mp1->b_datap->db_base;
12050 					freeb(mp1);
12051 					BUMP_MIB(ill->ill_ip_mib,
12052 					    ipIfStatsReasmPartDups);
12053 					mp1 = mp->b_cont;
12054 					if (!mp1)
12055 						break;
12056 					offset = IP_REASS_START(mp1);
12057 				}
12058 			}
12059 			break;
12060 		}
12061 	} while (start = end, mp = next_mp);
12062 
12063 	/* Fragment just processed could be the last one. Remember this fact */
12064 	if (!more)
12065 		ipf->ipf_last_frag_seen = B_TRUE;
12066 
12067 	/* Still got holes? */
12068 	if (ipf->ipf_hole_cnt)
12069 		return (IP_REASS_PARTIAL);
12070 	/* Clean up overloaded fields to avoid upstream disasters. */
12071 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12072 		IP_REASS_SET_START(mp1, 0);
12073 		IP_REASS_SET_END(mp1, 0);
12074 	}
12075 	return (IP_REASS_COMPLETE);
12076 }
12077 
12078 /*
12079  * ipsec processing for the fast path, used for input UDP Packets
12080  * Returns true if ready for passup to UDP.
12081  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
12082  * was an ESP-in-UDP packet, etc.).
12083  */
12084 static boolean_t
12085 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12086     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
12087 {
12088 	uint32_t	ill_index;
12089 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12090 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12091 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12092 	udp_t		*udp = connp->conn_udp;
12093 
12094 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12095 	/* The ill_index of the incoming ILL */
12096 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12097 
12098 	/* pass packet up to the transport */
12099 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12100 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12101 		    NULL, mctl_present);
12102 		if (*first_mpp == NULL) {
12103 			return (B_FALSE);
12104 		}
12105 	}
12106 
12107 	/* Initiate IPPF processing for fastpath UDP */
12108 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12109 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12110 		if (*mpp == NULL) {
12111 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12112 			    "deferred/dropped during IPPF processing\n"));
12113 			return (B_FALSE);
12114 		}
12115 	}
12116 	/*
12117 	 * Remove 0-spi if it's 0, or move everything behind
12118 	 * the UDP header over it and forward to ESP via
12119 	 * ip_proto_input().
12120 	 */
12121 	if (udp->udp_nat_t_endpoint) {
12122 		if (mctl_present) {
12123 			/* mctl_present *shouldn't* happen. */
12124 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
12125 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
12126 			    &ipss->ipsec_dropper);
12127 			*first_mpp = NULL;
12128 			return (B_FALSE);
12129 		}
12130 
12131 		/* "ill" is "recv_ill" in actuality. */
12132 		if (!zero_spi_check(q, *mpp, ire, ill, ipss))
12133 			return (B_FALSE);
12134 
12135 		/* Else continue like a normal UDP packet. */
12136 	}
12137 
12138 	/*
12139 	 * We make the checks as below since we are in the fast path
12140 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12141 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12142 	 */
12143 	if (connp->conn_recvif || connp->conn_recvslla ||
12144 	    connp->conn_ip_recvpktinfo) {
12145 		if (connp->conn_recvif) {
12146 			in_flags = IPF_RECVIF;
12147 		}
12148 		/*
12149 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12150 		 * so the flag passed to ip_add_info is based on IP version
12151 		 * of connp.
12152 		 */
12153 		if (connp->conn_ip_recvpktinfo) {
12154 			if (connp->conn_af_isv6) {
12155 				/*
12156 				 * V6 only needs index
12157 				 */
12158 				in_flags |= IPF_RECVIF;
12159 			} else {
12160 				/*
12161 				 * V4 needs index + matching address.
12162 				 */
12163 				in_flags |= IPF_RECVADDR;
12164 			}
12165 		}
12166 		if (connp->conn_recvslla) {
12167 			in_flags |= IPF_RECVSLLA;
12168 		}
12169 		/*
12170 		 * since in_flags are being set ill will be
12171 		 * referenced in ip_add_info, so it better not
12172 		 * be NULL.
12173 		 */
12174 		/*
12175 		 * the actual data will be contained in b_cont
12176 		 * upon successful return of the following call.
12177 		 * If the call fails then the original mblk is
12178 		 * returned.
12179 		 */
12180 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12181 		    ipst);
12182 	}
12183 
12184 	return (B_TRUE);
12185 }
12186 
12187 /*
12188  * Fragmentation reassembly.  Each ILL has a hash table for
12189  * queuing packets undergoing reassembly for all IPIFs
12190  * associated with the ILL.  The hash is based on the packet
12191  * IP ident field.  The ILL frag hash table was allocated
12192  * as a timer block at the time the ILL was created.  Whenever
12193  * there is anything on the reassembly queue, the timer will
12194  * be running.  Returns B_TRUE if successful else B_FALSE;
12195  * frees mp on failure.
12196  */
12197 static boolean_t
12198 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12199     uint32_t *cksum_val, uint16_t *cksum_flags)
12200 {
12201 	uint32_t	frag_offset_flags;
12202 	ill_t		*ill = (ill_t *)q->q_ptr;
12203 	mblk_t		*mp = *mpp;
12204 	mblk_t		*t_mp;
12205 	ipaddr_t	dst;
12206 	uint8_t		proto = ipha->ipha_protocol;
12207 	uint32_t	sum_val;
12208 	uint16_t	sum_flags;
12209 	ipf_t		*ipf;
12210 	ipf_t		**ipfp;
12211 	ipfb_t		*ipfb;
12212 	uint16_t	ident;
12213 	uint32_t	offset;
12214 	ipaddr_t	src;
12215 	uint_t		hdr_length;
12216 	uint32_t	end;
12217 	mblk_t		*mp1;
12218 	mblk_t		*tail_mp;
12219 	size_t		count;
12220 	size_t		msg_len;
12221 	uint8_t		ecn_info = 0;
12222 	uint32_t	packet_size;
12223 	boolean_t	pruned = B_FALSE;
12224 	ip_stack_t *ipst = ill->ill_ipst;
12225 
12226 	if (cksum_val != NULL)
12227 		*cksum_val = 0;
12228 	if (cksum_flags != NULL)
12229 		*cksum_flags = 0;
12230 
12231 	/*
12232 	 * Drop the fragmented as early as possible, if
12233 	 * we don't have resource(s) to re-assemble.
12234 	 */
12235 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12236 		freemsg(mp);
12237 		return (B_FALSE);
12238 	}
12239 
12240 	/* Check for fragmentation offset; return if there's none */
12241 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12242 	    (IPH_MF | IPH_OFFSET)) == 0)
12243 		return (B_TRUE);
12244 
12245 	/*
12246 	 * We utilize hardware computed checksum info only for UDP since
12247 	 * IP fragmentation is a normal occurence for the protocol.  In
12248 	 * addition, checksum offload support for IP fragments carrying
12249 	 * UDP payload is commonly implemented across network adapters.
12250 	 */
12251 	ASSERT(ill != NULL);
12252 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12253 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12254 		mblk_t *mp1 = mp->b_cont;
12255 		int32_t len;
12256 
12257 		/* Record checksum information from the packet */
12258 		sum_val = (uint32_t)DB_CKSUM16(mp);
12259 		sum_flags = DB_CKSUMFLAGS(mp);
12260 
12261 		/* IP payload offset from beginning of mblk */
12262 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12263 
12264 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12265 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12266 		    offset >= DB_CKSUMSTART(mp) &&
12267 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12268 			uint32_t adj;
12269 			/*
12270 			 * Partial checksum has been calculated by hardware
12271 			 * and attached to the packet; in addition, any
12272 			 * prepended extraneous data is even byte aligned.
12273 			 * If any such data exists, we adjust the checksum;
12274 			 * this would also handle any postpended data.
12275 			 */
12276 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12277 			    mp, mp1, len, adj);
12278 
12279 			/* One's complement subtract extraneous checksum */
12280 			if (adj >= sum_val)
12281 				sum_val = ~(adj - sum_val) & 0xFFFF;
12282 			else
12283 				sum_val -= adj;
12284 		}
12285 	} else {
12286 		sum_val = 0;
12287 		sum_flags = 0;
12288 	}
12289 
12290 	/* Clear hardware checksumming flag */
12291 	DB_CKSUMFLAGS(mp) = 0;
12292 
12293 	ident = ipha->ipha_ident;
12294 	offset = (frag_offset_flags << 3) & 0xFFFF;
12295 	src = ipha->ipha_src;
12296 	dst = ipha->ipha_dst;
12297 	hdr_length = IPH_HDR_LENGTH(ipha);
12298 	end = ntohs(ipha->ipha_length) - hdr_length;
12299 
12300 	/* If end == 0 then we have a packet with no data, so just free it */
12301 	if (end == 0) {
12302 		freemsg(mp);
12303 		return (B_FALSE);
12304 	}
12305 
12306 	/* Record the ECN field info. */
12307 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12308 	if (offset != 0) {
12309 		/*
12310 		 * If this isn't the first piece, strip the header, and
12311 		 * add the offset to the end value.
12312 		 */
12313 		mp->b_rptr += hdr_length;
12314 		end += offset;
12315 	}
12316 
12317 	msg_len = MBLKSIZE(mp);
12318 	tail_mp = mp;
12319 	while (tail_mp->b_cont != NULL) {
12320 		tail_mp = tail_mp->b_cont;
12321 		msg_len += MBLKSIZE(tail_mp);
12322 	}
12323 
12324 	/* If the reassembly list for this ILL will get too big, prune it */
12325 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12326 	    ipst->ips_ip_reass_queue_bytes) {
12327 		ill_frag_prune(ill,
12328 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12329 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12330 		pruned = B_TRUE;
12331 	}
12332 
12333 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12334 	mutex_enter(&ipfb->ipfb_lock);
12335 
12336 	ipfp = &ipfb->ipfb_ipf;
12337 	/* Try to find an existing fragment queue for this packet. */
12338 	for (;;) {
12339 		ipf = ipfp[0];
12340 		if (ipf != NULL) {
12341 			/*
12342 			 * It has to match on ident and src/dst address.
12343 			 */
12344 			if (ipf->ipf_ident == ident &&
12345 			    ipf->ipf_src == src &&
12346 			    ipf->ipf_dst == dst &&
12347 			    ipf->ipf_protocol == proto) {
12348 				/*
12349 				 * If we have received too many
12350 				 * duplicate fragments for this packet
12351 				 * free it.
12352 				 */
12353 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12354 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12355 					freemsg(mp);
12356 					mutex_exit(&ipfb->ipfb_lock);
12357 					return (B_FALSE);
12358 				}
12359 				/* Found it. */
12360 				break;
12361 			}
12362 			ipfp = &ipf->ipf_hash_next;
12363 			continue;
12364 		}
12365 
12366 		/*
12367 		 * If we pruned the list, do we want to store this new
12368 		 * fragment?. We apply an optimization here based on the
12369 		 * fact that most fragments will be received in order.
12370 		 * So if the offset of this incoming fragment is zero,
12371 		 * it is the first fragment of a new packet. We will
12372 		 * keep it.  Otherwise drop the fragment, as we have
12373 		 * probably pruned the packet already (since the
12374 		 * packet cannot be found).
12375 		 */
12376 		if (pruned && offset != 0) {
12377 			mutex_exit(&ipfb->ipfb_lock);
12378 			freemsg(mp);
12379 			return (B_FALSE);
12380 		}
12381 
12382 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12383 			/*
12384 			 * Too many fragmented packets in this hash
12385 			 * bucket. Free the oldest.
12386 			 */
12387 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12388 		}
12389 
12390 		/* New guy.  Allocate a frag message. */
12391 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12392 		if (mp1 == NULL) {
12393 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12394 			freemsg(mp);
12395 reass_done:
12396 			mutex_exit(&ipfb->ipfb_lock);
12397 			return (B_FALSE);
12398 		}
12399 
12400 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12401 		mp1->b_cont = mp;
12402 
12403 		/* Initialize the fragment header. */
12404 		ipf = (ipf_t *)mp1->b_rptr;
12405 		ipf->ipf_mp = mp1;
12406 		ipf->ipf_ptphn = ipfp;
12407 		ipfp[0] = ipf;
12408 		ipf->ipf_hash_next = NULL;
12409 		ipf->ipf_ident = ident;
12410 		ipf->ipf_protocol = proto;
12411 		ipf->ipf_src = src;
12412 		ipf->ipf_dst = dst;
12413 		ipf->ipf_nf_hdr_len = 0;
12414 		/* Record reassembly start time. */
12415 		ipf->ipf_timestamp = gethrestime_sec();
12416 		/* Record ipf generation and account for frag header */
12417 		ipf->ipf_gen = ill->ill_ipf_gen++;
12418 		ipf->ipf_count = MBLKSIZE(mp1);
12419 		ipf->ipf_last_frag_seen = B_FALSE;
12420 		ipf->ipf_ecn = ecn_info;
12421 		ipf->ipf_num_dups = 0;
12422 		ipfb->ipfb_frag_pkts++;
12423 		ipf->ipf_checksum = 0;
12424 		ipf->ipf_checksum_flags = 0;
12425 
12426 		/* Store checksum value in fragment header */
12427 		if (sum_flags != 0) {
12428 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12429 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12430 			ipf->ipf_checksum = sum_val;
12431 			ipf->ipf_checksum_flags = sum_flags;
12432 		}
12433 
12434 		/*
12435 		 * We handle reassembly two ways.  In the easy case,
12436 		 * where all the fragments show up in order, we do
12437 		 * minimal bookkeeping, and just clip new pieces on
12438 		 * the end.  If we ever see a hole, then we go off
12439 		 * to ip_reassemble which has to mark the pieces and
12440 		 * keep track of the number of holes, etc.  Obviously,
12441 		 * the point of having both mechanisms is so we can
12442 		 * handle the easy case as efficiently as possible.
12443 		 */
12444 		if (offset == 0) {
12445 			/* Easy case, in-order reassembly so far. */
12446 			ipf->ipf_count += msg_len;
12447 			ipf->ipf_tail_mp = tail_mp;
12448 			/*
12449 			 * Keep track of next expected offset in
12450 			 * ipf_end.
12451 			 */
12452 			ipf->ipf_end = end;
12453 			ipf->ipf_nf_hdr_len = hdr_length;
12454 		} else {
12455 			/* Hard case, hole at the beginning. */
12456 			ipf->ipf_tail_mp = NULL;
12457 			/*
12458 			 * ipf_end == 0 means that we have given up
12459 			 * on easy reassembly.
12460 			 */
12461 			ipf->ipf_end = 0;
12462 
12463 			/* Forget checksum offload from now on */
12464 			ipf->ipf_checksum_flags = 0;
12465 
12466 			/*
12467 			 * ipf_hole_cnt is set by ip_reassemble.
12468 			 * ipf_count is updated by ip_reassemble.
12469 			 * No need to check for return value here
12470 			 * as we don't expect reassembly to complete
12471 			 * or fail for the first fragment itself.
12472 			 */
12473 			(void) ip_reassemble(mp, ipf,
12474 			    (frag_offset_flags & IPH_OFFSET) << 3,
12475 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12476 		}
12477 		/* Update per ipfb and ill byte counts */
12478 		ipfb->ipfb_count += ipf->ipf_count;
12479 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12480 		ill->ill_frag_count += ipf->ipf_count;
12481 		/* If the frag timer wasn't already going, start it. */
12482 		mutex_enter(&ill->ill_lock);
12483 		ill_frag_timer_start(ill);
12484 		mutex_exit(&ill->ill_lock);
12485 		goto reass_done;
12486 	}
12487 
12488 	/*
12489 	 * If the packet's flag has changed (it could be coming up
12490 	 * from an interface different than the previous, therefore
12491 	 * possibly different checksum capability), then forget about
12492 	 * any stored checksum states.  Otherwise add the value to
12493 	 * the existing one stored in the fragment header.
12494 	 */
12495 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12496 		sum_val += ipf->ipf_checksum;
12497 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12498 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12499 		ipf->ipf_checksum = sum_val;
12500 	} else if (ipf->ipf_checksum_flags != 0) {
12501 		/* Forget checksum offload from now on */
12502 		ipf->ipf_checksum_flags = 0;
12503 	}
12504 
12505 	/*
12506 	 * We have a new piece of a datagram which is already being
12507 	 * reassembled.  Update the ECN info if all IP fragments
12508 	 * are ECN capable.  If there is one which is not, clear
12509 	 * all the info.  If there is at least one which has CE
12510 	 * code point, IP needs to report that up to transport.
12511 	 */
12512 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12513 		if (ecn_info == IPH_ECN_CE)
12514 			ipf->ipf_ecn = IPH_ECN_CE;
12515 	} else {
12516 		ipf->ipf_ecn = IPH_ECN_NECT;
12517 	}
12518 	if (offset && ipf->ipf_end == offset) {
12519 		/* The new fragment fits at the end */
12520 		ipf->ipf_tail_mp->b_cont = mp;
12521 		/* Update the byte count */
12522 		ipf->ipf_count += msg_len;
12523 		/* Update per ipfb and ill byte counts */
12524 		ipfb->ipfb_count += msg_len;
12525 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12526 		ill->ill_frag_count += msg_len;
12527 		if (frag_offset_flags & IPH_MF) {
12528 			/* More to come. */
12529 			ipf->ipf_end = end;
12530 			ipf->ipf_tail_mp = tail_mp;
12531 			goto reass_done;
12532 		}
12533 	} else {
12534 		/* Go do the hard cases. */
12535 		int ret;
12536 
12537 		if (offset == 0)
12538 			ipf->ipf_nf_hdr_len = hdr_length;
12539 
12540 		/* Save current byte count */
12541 		count = ipf->ipf_count;
12542 		ret = ip_reassemble(mp, ipf,
12543 		    (frag_offset_flags & IPH_OFFSET) << 3,
12544 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12545 		/* Count of bytes added and subtracted (freeb()ed) */
12546 		count = ipf->ipf_count - count;
12547 		if (count) {
12548 			/* Update per ipfb and ill byte counts */
12549 			ipfb->ipfb_count += count;
12550 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12551 			ill->ill_frag_count += count;
12552 		}
12553 		if (ret == IP_REASS_PARTIAL) {
12554 			goto reass_done;
12555 		} else if (ret == IP_REASS_FAILED) {
12556 			/* Reassembly failed. Free up all resources */
12557 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12558 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12559 				IP_REASS_SET_START(t_mp, 0);
12560 				IP_REASS_SET_END(t_mp, 0);
12561 			}
12562 			freemsg(mp);
12563 			goto reass_done;
12564 		}
12565 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12566 	}
12567 	/*
12568 	 * We have completed reassembly.  Unhook the frag header from
12569 	 * the reassembly list.
12570 	 *
12571 	 * Before we free the frag header, record the ECN info
12572 	 * to report back to the transport.
12573 	 */
12574 	ecn_info = ipf->ipf_ecn;
12575 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12576 	ipfp = ipf->ipf_ptphn;
12577 
12578 	/* We need to supply these to caller */
12579 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12580 		sum_val = ipf->ipf_checksum;
12581 	else
12582 		sum_val = 0;
12583 
12584 	mp1 = ipf->ipf_mp;
12585 	count = ipf->ipf_count;
12586 	ipf = ipf->ipf_hash_next;
12587 	if (ipf != NULL)
12588 		ipf->ipf_ptphn = ipfp;
12589 	ipfp[0] = ipf;
12590 	ill->ill_frag_count -= count;
12591 	ASSERT(ipfb->ipfb_count >= count);
12592 	ipfb->ipfb_count -= count;
12593 	ipfb->ipfb_frag_pkts--;
12594 	mutex_exit(&ipfb->ipfb_lock);
12595 	/* Ditch the frag header. */
12596 	mp = mp1->b_cont;
12597 
12598 	freeb(mp1);
12599 
12600 	/* Restore original IP length in header. */
12601 	packet_size = (uint32_t)msgdsize(mp);
12602 	if (packet_size > IP_MAXPACKET) {
12603 		freemsg(mp);
12604 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12605 		return (B_FALSE);
12606 	}
12607 
12608 	if (DB_REF(mp) > 1) {
12609 		mblk_t *mp2 = copymsg(mp);
12610 
12611 		freemsg(mp);
12612 		if (mp2 == NULL) {
12613 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12614 			return (B_FALSE);
12615 		}
12616 		mp = mp2;
12617 	}
12618 	ipha = (ipha_t *)mp->b_rptr;
12619 
12620 	ipha->ipha_length = htons((uint16_t)packet_size);
12621 	/* We're now complete, zip the frag state */
12622 	ipha->ipha_fragment_offset_and_flags = 0;
12623 	/* Record the ECN info. */
12624 	ipha->ipha_type_of_service &= 0xFC;
12625 	ipha->ipha_type_of_service |= ecn_info;
12626 	*mpp = mp;
12627 
12628 	/* Reassembly is successful; return checksum information if needed */
12629 	if (cksum_val != NULL)
12630 		*cksum_val = sum_val;
12631 	if (cksum_flags != NULL)
12632 		*cksum_flags = sum_flags;
12633 
12634 	return (B_TRUE);
12635 }
12636 
12637 /*
12638  * Perform ip header check sum update local options.
12639  * return B_TRUE if all is well, else return B_FALSE and release
12640  * the mp. caller is responsible for decrementing ire ref cnt.
12641  */
12642 static boolean_t
12643 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12644     ip_stack_t *ipst)
12645 {
12646 	mblk_t		*first_mp;
12647 	boolean_t	mctl_present;
12648 	uint16_t	sum;
12649 
12650 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12651 	/*
12652 	 * Don't do the checksum if it has gone through AH/ESP
12653 	 * processing.
12654 	 */
12655 	if (!mctl_present) {
12656 		sum = ip_csum_hdr(ipha);
12657 		if (sum != 0) {
12658 			if (ill != NULL) {
12659 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12660 			} else {
12661 				BUMP_MIB(&ipst->ips_ip_mib,
12662 				    ipIfStatsInCksumErrs);
12663 			}
12664 			freemsg(first_mp);
12665 			return (B_FALSE);
12666 		}
12667 	}
12668 
12669 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12670 		if (mctl_present)
12671 			freeb(first_mp);
12672 		return (B_FALSE);
12673 	}
12674 
12675 	return (B_TRUE);
12676 }
12677 
12678 /*
12679  * All udp packet are delivered to the local host via this routine.
12680  */
12681 void
12682 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12683     ill_t *recv_ill)
12684 {
12685 	uint32_t	sum;
12686 	uint32_t	u1;
12687 	boolean_t	mctl_present;
12688 	conn_t		*connp;
12689 	mblk_t		*first_mp;
12690 	uint16_t	*up;
12691 	ill_t		*ill = (ill_t *)q->q_ptr;
12692 	uint16_t	reass_hck_flags = 0;
12693 	ip_stack_t	*ipst;
12694 
12695 	ASSERT(recv_ill != NULL);
12696 	ipst = recv_ill->ill_ipst;
12697 
12698 #define	rptr    ((uchar_t *)ipha)
12699 
12700 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12701 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12702 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12703 	ASSERT(ill != NULL);
12704 
12705 	/*
12706 	 * FAST PATH for udp packets
12707 	 */
12708 
12709 	/* u1 is # words of IP options */
12710 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12711 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12712 
12713 	/* IP options present */
12714 	if (u1 != 0)
12715 		goto ipoptions;
12716 
12717 	/* Check the IP header checksum.  */
12718 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12719 		/* Clear the IP header h/w cksum flag */
12720 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12721 	} else if (!mctl_present) {
12722 		/*
12723 		 * Don't verify header checksum if this packet is coming
12724 		 * back from AH/ESP as we already did it.
12725 		 */
12726 #define	uph	((uint16_t *)ipha)
12727 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12728 		    uph[6] + uph[7] + uph[8] + uph[9];
12729 #undef	uph
12730 		/* finish doing IP checksum */
12731 		sum = (sum & 0xFFFF) + (sum >> 16);
12732 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12733 		if (sum != 0 && sum != 0xFFFF) {
12734 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12735 			freemsg(first_mp);
12736 			return;
12737 		}
12738 	}
12739 
12740 	/*
12741 	 * Count for SNMP of inbound packets for ire.
12742 	 * if mctl is present this might be a secure packet and
12743 	 * has already been counted for in ip_proto_input().
12744 	 */
12745 	if (!mctl_present) {
12746 		UPDATE_IB_PKT_COUNT(ire);
12747 		ire->ire_last_used_time = lbolt;
12748 	}
12749 
12750 	/* packet part of fragmented IP packet? */
12751 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12752 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12753 		goto fragmented;
12754 	}
12755 
12756 	/* u1 = IP header length (20 bytes) */
12757 	u1 = IP_SIMPLE_HDR_LENGTH;
12758 
12759 	/* packet does not contain complete IP & UDP headers */
12760 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12761 		goto udppullup;
12762 
12763 	/* up points to UDP header */
12764 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12765 #define	iphs    ((uint16_t *)ipha)
12766 
12767 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12768 	if (up[3] != 0) {
12769 		mblk_t *mp1 = mp->b_cont;
12770 		boolean_t cksum_err;
12771 		uint16_t hck_flags = 0;
12772 
12773 		/* Pseudo-header checksum */
12774 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12775 		    iphs[9] + up[2];
12776 
12777 		/*
12778 		 * Revert to software checksum calculation if the interface
12779 		 * isn't capable of checksum offload or if IPsec is present.
12780 		 */
12781 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12782 			hck_flags = DB_CKSUMFLAGS(mp);
12783 
12784 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12785 			IP_STAT(ipst, ip_in_sw_cksum);
12786 
12787 		IP_CKSUM_RECV(hck_flags, u1,
12788 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12789 		    (int32_t)((uchar_t *)up - rptr),
12790 		    mp, mp1, cksum_err);
12791 
12792 		if (cksum_err) {
12793 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12794 			if (hck_flags & HCK_FULLCKSUM)
12795 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12796 			else if (hck_flags & HCK_PARTIALCKSUM)
12797 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12798 			else
12799 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12800 
12801 			freemsg(first_mp);
12802 			return;
12803 		}
12804 	}
12805 
12806 	/* Non-fragmented broadcast or multicast packet? */
12807 	if (ire->ire_type == IRE_BROADCAST)
12808 		goto udpslowpath;
12809 
12810 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12811 	    ire->ire_zoneid, ipst)) != NULL) {
12812 		ASSERT(connp->conn_upq != NULL);
12813 		IP_STAT(ipst, ip_udp_fast_path);
12814 
12815 		if (CONN_UDP_FLOWCTLD(connp)) {
12816 			freemsg(mp);
12817 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12818 		} else {
12819 			if (!mctl_present) {
12820 				BUMP_MIB(ill->ill_ip_mib,
12821 				    ipIfStatsHCInDelivers);
12822 			}
12823 			/*
12824 			 * mp and first_mp can change.
12825 			 */
12826 			if (ip_udp_check(q, connp, recv_ill,
12827 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12828 				/* Send it upstream */
12829 				(connp->conn_recv)(connp, mp, NULL);
12830 			}
12831 		}
12832 		/*
12833 		 * freeb() cannot deal with null mblk being passed
12834 		 * in and first_mp can be set to null in the call
12835 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12836 		 */
12837 		if (mctl_present && first_mp != NULL) {
12838 			freeb(first_mp);
12839 		}
12840 		CONN_DEC_REF(connp);
12841 		return;
12842 	}
12843 
12844 	/*
12845 	 * if we got here we know the packet is not fragmented and
12846 	 * has no options. The classifier could not find a conn_t and
12847 	 * most likely its an icmp packet so send it through slow path.
12848 	 */
12849 
12850 	goto udpslowpath;
12851 
12852 ipoptions:
12853 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12854 		goto slow_done;
12855 	}
12856 
12857 	UPDATE_IB_PKT_COUNT(ire);
12858 	ire->ire_last_used_time = lbolt;
12859 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12860 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12861 fragmented:
12862 		/*
12863 		 * "sum" and "reass_hck_flags" are non-zero if the
12864 		 * reassembled packet has a valid hardware computed
12865 		 * checksum information associated with it.
12866 		 */
12867 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12868 			goto slow_done;
12869 		/*
12870 		 * Make sure that first_mp points back to mp as
12871 		 * the mp we came in with could have changed in
12872 		 * ip_rput_fragment().
12873 		 */
12874 		ASSERT(!mctl_present);
12875 		ipha = (ipha_t *)mp->b_rptr;
12876 		first_mp = mp;
12877 	}
12878 
12879 	/* Now we have a complete datagram, destined for this machine. */
12880 	u1 = IPH_HDR_LENGTH(ipha);
12881 	/* Pull up the UDP header, if necessary. */
12882 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12883 udppullup:
12884 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12885 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12886 			freemsg(first_mp);
12887 			goto slow_done;
12888 		}
12889 		ipha = (ipha_t *)mp->b_rptr;
12890 	}
12891 
12892 	/*
12893 	 * Validate the checksum for the reassembled packet; for the
12894 	 * pullup case we calculate the payload checksum in software.
12895 	 */
12896 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12897 	if (up[3] != 0) {
12898 		boolean_t cksum_err;
12899 
12900 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12901 			IP_STAT(ipst, ip_in_sw_cksum);
12902 
12903 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12904 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12905 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12906 		    iphs[9] + up[2], sum, cksum_err);
12907 
12908 		if (cksum_err) {
12909 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12910 
12911 			if (reass_hck_flags & HCK_FULLCKSUM)
12912 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12913 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12914 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12915 			else
12916 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12917 
12918 			freemsg(first_mp);
12919 			goto slow_done;
12920 		}
12921 	}
12922 udpslowpath:
12923 
12924 	/* Clear hardware checksum flag to be safe */
12925 	DB_CKSUMFLAGS(mp) = 0;
12926 
12927 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12928 	    (ire->ire_type == IRE_BROADCAST),
12929 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12930 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12931 
12932 slow_done:
12933 	IP_STAT(ipst, ip_udp_slow_path);
12934 	return;
12935 
12936 #undef  iphs
12937 #undef  rptr
12938 }
12939 
12940 /* ARGSUSED */
12941 static mblk_t *
12942 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12943     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12944     ill_rx_ring_t *ill_ring)
12945 {
12946 	conn_t		*connp;
12947 	uint32_t	sum;
12948 	uint32_t	u1;
12949 	uint16_t	*up;
12950 	int		offset;
12951 	ssize_t		len;
12952 	mblk_t		*mp1;
12953 	boolean_t	syn_present = B_FALSE;
12954 	tcph_t		*tcph;
12955 	uint_t		ip_hdr_len;
12956 	ill_t		*ill = (ill_t *)q->q_ptr;
12957 	zoneid_t	zoneid = ire->ire_zoneid;
12958 	boolean_t	cksum_err;
12959 	uint16_t	hck_flags = 0;
12960 	ip_stack_t	*ipst = recv_ill->ill_ipst;
12961 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12962 
12963 #define	rptr	((uchar_t *)ipha)
12964 
12965 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12966 	ASSERT(ill != NULL);
12967 
12968 	/*
12969 	 * FAST PATH for tcp packets
12970 	 */
12971 
12972 	/* u1 is # words of IP options */
12973 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12974 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12975 
12976 	/* IP options present */
12977 	if (u1) {
12978 		goto ipoptions;
12979 	} else if (!mctl_present) {
12980 		/* Check the IP header checksum.  */
12981 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12982 			/* Clear the IP header h/w cksum flag */
12983 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12984 		} else if (!mctl_present) {
12985 			/*
12986 			 * Don't verify header checksum if this packet
12987 			 * is coming back from AH/ESP as we already did it.
12988 			 */
12989 #define	uph	((uint16_t *)ipha)
12990 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12991 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12992 #undef	uph
12993 			/* finish doing IP checksum */
12994 			sum = (sum & 0xFFFF) + (sum >> 16);
12995 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12996 			if (sum != 0 && sum != 0xFFFF) {
12997 				BUMP_MIB(ill->ill_ip_mib,
12998 				    ipIfStatsInCksumErrs);
12999 				goto error;
13000 			}
13001 		}
13002 	}
13003 
13004 	if (!mctl_present) {
13005 		UPDATE_IB_PKT_COUNT(ire);
13006 		ire->ire_last_used_time = lbolt;
13007 	}
13008 
13009 	/* packet part of fragmented IP packet? */
13010 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13011 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13012 		goto fragmented;
13013 	}
13014 
13015 	/* u1 = IP header length (20 bytes) */
13016 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
13017 
13018 	/* does packet contain IP+TCP headers? */
13019 	len = mp->b_wptr - rptr;
13020 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
13021 		IP_STAT(ipst, ip_tcppullup);
13022 		goto tcppullup;
13023 	}
13024 
13025 	/* TCP options present? */
13026 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
13027 
13028 	/*
13029 	 * If options need to be pulled up, then goto tcpoptions.
13030 	 * otherwise we are still in the fast path
13031 	 */
13032 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
13033 		IP_STAT(ipst, ip_tcpoptions);
13034 		goto tcpoptions;
13035 	}
13036 
13037 	/* multiple mblks of tcp data? */
13038 	if ((mp1 = mp->b_cont) != NULL) {
13039 		/* more then two? */
13040 		if (mp1->b_cont != NULL) {
13041 			IP_STAT(ipst, ip_multipkttcp);
13042 			goto multipkttcp;
13043 		}
13044 		len += mp1->b_wptr - mp1->b_rptr;
13045 	}
13046 
13047 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13048 
13049 	/* part of pseudo checksum */
13050 
13051 	/* TCP datagram length */
13052 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13053 
13054 #define	iphs    ((uint16_t *)ipha)
13055 
13056 #ifdef	_BIG_ENDIAN
13057 	u1 += IPPROTO_TCP;
13058 #else
13059 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13060 #endif
13061 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13062 
13063 	/*
13064 	 * Revert to software checksum calculation if the interface
13065 	 * isn't capable of checksum offload or if IPsec is present.
13066 	 */
13067 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
13068 		hck_flags = DB_CKSUMFLAGS(mp);
13069 
13070 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13071 		IP_STAT(ipst, ip_in_sw_cksum);
13072 
13073 	IP_CKSUM_RECV(hck_flags, u1,
13074 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13075 	    (int32_t)((uchar_t *)up - rptr),
13076 	    mp, mp1, cksum_err);
13077 
13078 	if (cksum_err) {
13079 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13080 
13081 		if (hck_flags & HCK_FULLCKSUM)
13082 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13083 		else if (hck_flags & HCK_PARTIALCKSUM)
13084 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13085 		else
13086 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13087 
13088 		goto error;
13089 	}
13090 
13091 try_again:
13092 
13093 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13094 	    zoneid, ipst)) == NULL) {
13095 		/* Send the TH_RST */
13096 		goto no_conn;
13097 	}
13098 
13099 	/*
13100 	 * TCP FAST PATH for AF_INET socket.
13101 	 *
13102 	 * TCP fast path to avoid extra work. An AF_INET socket type
13103 	 * does not have facility to receive extra information via
13104 	 * ip_process or ip_add_info. Also, when the connection was
13105 	 * established, we made a check if this connection is impacted
13106 	 * by any global IPsec policy or per connection policy (a
13107 	 * policy that comes in effect later will not apply to this
13108 	 * connection). Since all this can be determined at the
13109 	 * connection establishment time, a quick check of flags
13110 	 * can avoid extra work.
13111 	 */
13112 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13113 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13114 		ASSERT(first_mp == mp);
13115 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13116 		SET_SQUEUE(mp, tcp_rput_data, connp);
13117 		return (mp);
13118 	}
13119 
13120 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13121 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
13122 		if (IPCL_IS_TCP(connp)) {
13123 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13124 			DB_CKSUMSTART(mp) =
13125 			    (intptr_t)ip_squeue_get(ill_ring);
13126 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13127 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13128 				BUMP_MIB(ill->ill_ip_mib,
13129 				    ipIfStatsHCInDelivers);
13130 				SET_SQUEUE(mp, connp->conn_recv, connp);
13131 				return (mp);
13132 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13133 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13134 				BUMP_MIB(ill->ill_ip_mib,
13135 				    ipIfStatsHCInDelivers);
13136 				ip_squeue_enter_unbound++;
13137 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13138 				    connp);
13139 				return (mp);
13140 			}
13141 			syn_present = B_TRUE;
13142 		}
13143 
13144 	}
13145 
13146 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13147 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13148 
13149 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13150 		/* No need to send this packet to TCP */
13151 		if ((flags & TH_RST) || (flags & TH_URG)) {
13152 			CONN_DEC_REF(connp);
13153 			freemsg(first_mp);
13154 			return (NULL);
13155 		}
13156 		if (flags & TH_ACK) {
13157 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
13158 			    ipst->ips_netstack->netstack_tcp, connp);
13159 			CONN_DEC_REF(connp);
13160 			return (NULL);
13161 		}
13162 
13163 		CONN_DEC_REF(connp);
13164 		freemsg(first_mp);
13165 		return (NULL);
13166 	}
13167 
13168 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13169 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13170 		    ipha, NULL, mctl_present);
13171 		if (first_mp == NULL) {
13172 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13173 			CONN_DEC_REF(connp);
13174 			return (NULL);
13175 		}
13176 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13177 			ASSERT(syn_present);
13178 			if (mctl_present) {
13179 				ASSERT(first_mp != mp);
13180 				first_mp->b_datap->db_struioflag |=
13181 				    STRUIO_POLICY;
13182 			} else {
13183 				ASSERT(first_mp == mp);
13184 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13185 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13186 			}
13187 		} else {
13188 			/*
13189 			 * Discard first_mp early since we're dealing with a
13190 			 * fully-connected conn_t and tcp doesn't do policy in
13191 			 * this case.
13192 			 */
13193 			if (mctl_present) {
13194 				freeb(first_mp);
13195 				mctl_present = B_FALSE;
13196 			}
13197 			first_mp = mp;
13198 		}
13199 	}
13200 
13201 	/* Initiate IPPF processing for fastpath */
13202 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13203 		uint32_t	ill_index;
13204 
13205 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13206 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13207 		if (mp == NULL) {
13208 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13209 			    "deferred/dropped during IPPF processing\n"));
13210 			CONN_DEC_REF(connp);
13211 			if (mctl_present)
13212 				freeb(first_mp);
13213 			return (NULL);
13214 		} else if (mctl_present) {
13215 			/*
13216 			 * ip_process might return a new mp.
13217 			 */
13218 			ASSERT(first_mp != mp);
13219 			first_mp->b_cont = mp;
13220 		} else {
13221 			first_mp = mp;
13222 		}
13223 
13224 	}
13225 
13226 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13227 		/*
13228 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13229 		 * make sure IPF_RECVIF is passed to ip_add_info.
13230 		 */
13231 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13232 		    IPCL_ZONEID(connp), ipst);
13233 		if (mp == NULL) {
13234 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13235 			CONN_DEC_REF(connp);
13236 			if (mctl_present)
13237 				freeb(first_mp);
13238 			return (NULL);
13239 		} else if (mctl_present) {
13240 			/*
13241 			 * ip_add_info might return a new mp.
13242 			 */
13243 			ASSERT(first_mp != mp);
13244 			first_mp->b_cont = mp;
13245 		} else {
13246 			first_mp = mp;
13247 		}
13248 	}
13249 
13250 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13251 	if (IPCL_IS_TCP(connp)) {
13252 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13253 		return (first_mp);
13254 	} else {
13255 		/* SOCK_RAW, IPPROTO_TCP case */
13256 		(connp->conn_recv)(connp, first_mp, NULL);
13257 		CONN_DEC_REF(connp);
13258 		return (NULL);
13259 	}
13260 
13261 no_conn:
13262 	/* Initiate IPPf processing, if needed. */
13263 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13264 		uint32_t ill_index;
13265 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13266 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13267 		if (first_mp == NULL) {
13268 			return (NULL);
13269 		}
13270 	}
13271 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13272 
13273 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13274 	    ipst->ips_netstack->netstack_tcp, NULL);
13275 	return (NULL);
13276 ipoptions:
13277 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13278 		goto slow_done;
13279 	}
13280 
13281 	UPDATE_IB_PKT_COUNT(ire);
13282 	ire->ire_last_used_time = lbolt;
13283 
13284 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13285 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13286 fragmented:
13287 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13288 			if (mctl_present)
13289 				freeb(first_mp);
13290 			goto slow_done;
13291 		}
13292 		/*
13293 		 * Make sure that first_mp points back to mp as
13294 		 * the mp we came in with could have changed in
13295 		 * ip_rput_fragment().
13296 		 */
13297 		ASSERT(!mctl_present);
13298 		ipha = (ipha_t *)mp->b_rptr;
13299 		first_mp = mp;
13300 	}
13301 
13302 	/* Now we have a complete datagram, destined for this machine. */
13303 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13304 
13305 	len = mp->b_wptr - mp->b_rptr;
13306 	/* Pull up a minimal TCP header, if necessary. */
13307 	if (len < (u1 + 20)) {
13308 tcppullup:
13309 		if (!pullupmsg(mp, u1 + 20)) {
13310 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13311 			goto error;
13312 		}
13313 		ipha = (ipha_t *)mp->b_rptr;
13314 		len = mp->b_wptr - mp->b_rptr;
13315 	}
13316 
13317 	/*
13318 	 * Extract the offset field from the TCP header.  As usual, we
13319 	 * try to help the compiler more than the reader.
13320 	 */
13321 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13322 	if (offset != 5) {
13323 tcpoptions:
13324 		if (offset < 5) {
13325 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13326 			goto error;
13327 		}
13328 		/*
13329 		 * There must be TCP options.
13330 		 * Make sure we can grab them.
13331 		 */
13332 		offset <<= 2;
13333 		offset += u1;
13334 		if (len < offset) {
13335 			if (!pullupmsg(mp, offset)) {
13336 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13337 				goto error;
13338 			}
13339 			ipha = (ipha_t *)mp->b_rptr;
13340 			len = mp->b_wptr - rptr;
13341 		}
13342 	}
13343 
13344 	/* Get the total packet length in len, including headers. */
13345 	if (mp->b_cont) {
13346 multipkttcp:
13347 		len = msgdsize(mp);
13348 	}
13349 
13350 	/*
13351 	 * Check the TCP checksum by pulling together the pseudo-
13352 	 * header checksum, and passing it to ip_csum to be added in
13353 	 * with the TCP datagram.
13354 	 *
13355 	 * Since we are not using the hwcksum if available we must
13356 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13357 	 * If either of these fails along the way the mblk is freed.
13358 	 * If this logic ever changes and mblk is reused to say send
13359 	 * ICMP's back, then this flag may need to be cleared in
13360 	 * other places as well.
13361 	 */
13362 	DB_CKSUMFLAGS(mp) = 0;
13363 
13364 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13365 
13366 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13367 #ifdef	_BIG_ENDIAN
13368 	u1 += IPPROTO_TCP;
13369 #else
13370 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13371 #endif
13372 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13373 	/*
13374 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13375 	 */
13376 	IP_STAT(ipst, ip_in_sw_cksum);
13377 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13378 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13379 		goto error;
13380 	}
13381 
13382 	IP_STAT(ipst, ip_tcp_slow_path);
13383 	goto try_again;
13384 #undef  iphs
13385 #undef  rptr
13386 
13387 error:
13388 	freemsg(first_mp);
13389 slow_done:
13390 	return (NULL);
13391 }
13392 
13393 /* ARGSUSED */
13394 static void
13395 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13396     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13397 {
13398 	conn_t		*connp;
13399 	uint32_t	sum;
13400 	uint32_t	u1;
13401 	ssize_t		len;
13402 	sctp_hdr_t	*sctph;
13403 	zoneid_t	zoneid = ire->ire_zoneid;
13404 	uint32_t	pktsum;
13405 	uint32_t	calcsum;
13406 	uint32_t	ports;
13407 	in6_addr_t	map_src, map_dst;
13408 	ill_t		*ill = (ill_t *)q->q_ptr;
13409 	ip_stack_t	*ipst;
13410 	sctp_stack_t	*sctps;
13411 
13412 	ASSERT(recv_ill != NULL);
13413 	ipst = recv_ill->ill_ipst;
13414 	sctps = ipst->ips_netstack->netstack_sctp;
13415 
13416 #define	rptr	((uchar_t *)ipha)
13417 
13418 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13419 	ASSERT(ill != NULL);
13420 
13421 	/* u1 is # words of IP options */
13422 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13423 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13424 
13425 	/* IP options present */
13426 	if (u1 > 0) {
13427 		goto ipoptions;
13428 	} else {
13429 		/* Check the IP header checksum.  */
13430 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill) &&
13431 		    !mctl_present) {
13432 #define	uph	((uint16_t *)ipha)
13433 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13434 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13435 #undef	uph
13436 			/* finish doing IP checksum */
13437 			sum = (sum & 0xFFFF) + (sum >> 16);
13438 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13439 			/*
13440 			 * Don't verify header checksum if this packet
13441 			 * is coming back from AH/ESP as we already did it.
13442 			 */
13443 			if (sum != 0 && sum != 0xFFFF) {
13444 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13445 				goto error;
13446 			}
13447 		}
13448 		/*
13449 		 * Since there is no SCTP h/w cksum support yet, just
13450 		 * clear the flag.
13451 		 */
13452 		DB_CKSUMFLAGS(mp) = 0;
13453 	}
13454 
13455 	/*
13456 	 * Don't verify header checksum if this packet is coming
13457 	 * back from AH/ESP as we already did it.
13458 	 */
13459 	if (!mctl_present) {
13460 		UPDATE_IB_PKT_COUNT(ire);
13461 		ire->ire_last_used_time = lbolt;
13462 	}
13463 
13464 	/* packet part of fragmented IP packet? */
13465 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13466 	if (u1 & (IPH_MF | IPH_OFFSET))
13467 		goto fragmented;
13468 
13469 	/* u1 = IP header length (20 bytes) */
13470 	u1 = IP_SIMPLE_HDR_LENGTH;
13471 
13472 find_sctp_client:
13473 	/* Pullup if we don't have the sctp common header. */
13474 	len = MBLKL(mp);
13475 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13476 		if (mp->b_cont == NULL ||
13477 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13478 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13479 			goto error;
13480 		}
13481 		ipha = (ipha_t *)mp->b_rptr;
13482 		len = MBLKL(mp);
13483 	}
13484 
13485 	sctph = (sctp_hdr_t *)(rptr + u1);
13486 #ifdef	DEBUG
13487 	if (!skip_sctp_cksum) {
13488 #endif
13489 		pktsum = sctph->sh_chksum;
13490 		sctph->sh_chksum = 0;
13491 		calcsum = sctp_cksum(mp, u1);
13492 		if (calcsum != pktsum) {
13493 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
13494 			goto error;
13495 		}
13496 		sctph->sh_chksum = pktsum;
13497 #ifdef	DEBUG	/* skip_sctp_cksum */
13498 	}
13499 #endif
13500 	/* get the ports */
13501 	ports = *(uint32_t *)&sctph->sh_sport;
13502 
13503 	IRE_REFRELE(ire);
13504 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13505 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13506 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13507 	    sctps)) == NULL) {
13508 		/* Check for raw socket or OOTB handling */
13509 		goto no_conn;
13510 	}
13511 
13512 	/* Found a client; up it goes */
13513 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13514 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13515 	return;
13516 
13517 no_conn:
13518 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13519 	    ports, mctl_present, flags, B_TRUE, zoneid);
13520 	return;
13521 
13522 ipoptions:
13523 	DB_CKSUMFLAGS(mp) = 0;
13524 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13525 		goto slow_done;
13526 
13527 	UPDATE_IB_PKT_COUNT(ire);
13528 	ire->ire_last_used_time = lbolt;
13529 
13530 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13531 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13532 fragmented:
13533 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13534 			goto slow_done;
13535 		/*
13536 		 * Make sure that first_mp points back to mp as
13537 		 * the mp we came in with could have changed in
13538 		 * ip_rput_fragment().
13539 		 */
13540 		ASSERT(!mctl_present);
13541 		ipha = (ipha_t *)mp->b_rptr;
13542 		first_mp = mp;
13543 	}
13544 
13545 	/* Now we have a complete datagram, destined for this machine. */
13546 	u1 = IPH_HDR_LENGTH(ipha);
13547 	goto find_sctp_client;
13548 #undef  iphs
13549 #undef  rptr
13550 
13551 error:
13552 	freemsg(first_mp);
13553 slow_done:
13554 	IRE_REFRELE(ire);
13555 }
13556 
13557 #define	VER_BITS	0xF0
13558 #define	VERSION_6	0x60
13559 
13560 static boolean_t
13561 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13562     ipaddr_t *dstp, ip_stack_t *ipst)
13563 {
13564 	uint_t	opt_len;
13565 	ipha_t *ipha;
13566 	ssize_t len;
13567 	uint_t	pkt_len;
13568 
13569 	ASSERT(ill != NULL);
13570 	IP_STAT(ipst, ip_ipoptions);
13571 	ipha = *iphapp;
13572 
13573 #define	rptr    ((uchar_t *)ipha)
13574 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13575 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13576 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13577 		freemsg(mp);
13578 		return (B_FALSE);
13579 	}
13580 
13581 	/* multiple mblk or too short */
13582 	pkt_len = ntohs(ipha->ipha_length);
13583 
13584 	/* Get the number of words of IP options in the IP header. */
13585 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13586 	if (opt_len) {
13587 		/* IP Options present!  Validate and process. */
13588 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13589 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13590 			goto done;
13591 		}
13592 		/*
13593 		 * Recompute complete header length and make sure we
13594 		 * have access to all of it.
13595 		 */
13596 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13597 		if (len > (mp->b_wptr - rptr)) {
13598 			if (len > pkt_len) {
13599 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13600 				goto done;
13601 			}
13602 			if (!pullupmsg(mp, len)) {
13603 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13604 				goto done;
13605 			}
13606 			ipha = (ipha_t *)mp->b_rptr;
13607 		}
13608 		/*
13609 		 * Go off to ip_rput_options which returns the next hop
13610 		 * destination address, which may have been affected
13611 		 * by source routing.
13612 		 */
13613 		IP_STAT(ipst, ip_opt);
13614 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13615 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13616 			return (B_FALSE);
13617 		}
13618 	}
13619 	*iphapp = ipha;
13620 	return (B_TRUE);
13621 done:
13622 	/* clear b_prev - used by ip_mroute_decap */
13623 	mp->b_prev = NULL;
13624 	freemsg(mp);
13625 	return (B_FALSE);
13626 #undef  rptr
13627 }
13628 
13629 /*
13630  * Deal with the fact that there is no ire for the destination.
13631  */
13632 static ire_t *
13633 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13634 {
13635 	ipha_t	*ipha;
13636 	ill_t	*ill;
13637 	ire_t	*ire;
13638 	boolean_t	check_multirt = B_FALSE;
13639 	ip_stack_t *ipst;
13640 
13641 	ipha = (ipha_t *)mp->b_rptr;
13642 	ill = (ill_t *)q->q_ptr;
13643 
13644 	ASSERT(ill != NULL);
13645 	ipst = ill->ill_ipst;
13646 
13647 	/*
13648 	 * No IRE for this destination, so it can't be for us.
13649 	 * Unless we are forwarding, drop the packet.
13650 	 * We have to let source routed packets through
13651 	 * since we don't yet know if they are 'ping -l'
13652 	 * packets i.e. if they will go out over the
13653 	 * same interface as they came in on.
13654 	 */
13655 	if (ll_multicast) {
13656 		freemsg(mp);
13657 		return (NULL);
13658 	}
13659 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13660 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13661 		freemsg(mp);
13662 		return (NULL);
13663 	}
13664 
13665 	/*
13666 	 * Mark this packet as having originated externally.
13667 	 *
13668 	 * For non-forwarding code path, ire_send later double
13669 	 * checks this interface to see if it is still exists
13670 	 * post-ARP resolution.
13671 	 *
13672 	 * Also, IPQOS uses this to differentiate between
13673 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13674 	 * QOS packet processing in ip_wput_attach_llhdr().
13675 	 * The QoS module can mark the b_band for a fastpath message
13676 	 * or the dl_priority field in a unitdata_req header for
13677 	 * CoS marking. This info can only be found in
13678 	 * ip_wput_attach_llhdr().
13679 	 */
13680 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13681 	/*
13682 	 * Clear the indication that this may have a hardware checksum
13683 	 * as we are not using it
13684 	 */
13685 	DB_CKSUMFLAGS(mp) = 0;
13686 
13687 	ire = ire_forward(dst, &check_multirt, NULL, NULL,
13688 	    MBLK_GETLABEL(mp), ipst);
13689 
13690 	if (ire == NULL && check_multirt) {
13691 		/* Let ip_newroute handle CGTP  */
13692 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13693 		return (NULL);
13694 	}
13695 
13696 	if (ire != NULL)
13697 		return (ire);
13698 
13699 	mp->b_prev = mp->b_next = 0;
13700 	/* send icmp unreachable */
13701 	q = WR(q);
13702 	/* Sent by forwarding path, and router is global zone */
13703 	if (ip_source_routed(ipha, ipst)) {
13704 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13705 		    GLOBAL_ZONEID, ipst);
13706 	} else {
13707 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13708 		    ipst);
13709 	}
13710 
13711 	return (NULL);
13712 
13713 }
13714 
13715 /*
13716  * check ip header length and align it.
13717  */
13718 static boolean_t
13719 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13720 {
13721 	ssize_t len;
13722 	ill_t *ill;
13723 	ipha_t	*ipha;
13724 
13725 	len = MBLKL(mp);
13726 
13727 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13728 		ill = (ill_t *)q->q_ptr;
13729 
13730 		if (!OK_32PTR(mp->b_rptr))
13731 			IP_STAT(ipst, ip_notaligned1);
13732 		else
13733 			IP_STAT(ipst, ip_notaligned2);
13734 		/* Guard against bogus device drivers */
13735 		if (len < 0) {
13736 			/* clear b_prev - used by ip_mroute_decap */
13737 			mp->b_prev = NULL;
13738 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13739 			freemsg(mp);
13740 			return (B_FALSE);
13741 		}
13742 
13743 		if (ip_rput_pullups++ == 0) {
13744 			ipha = (ipha_t *)mp->b_rptr;
13745 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13746 			    "ip_check_and_align_header: %s forced us to "
13747 			    " pullup pkt, hdr len %ld, hdr addr %p",
13748 			    ill->ill_name, len, ipha);
13749 		}
13750 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13751 			/* clear b_prev - used by ip_mroute_decap */
13752 			mp->b_prev = NULL;
13753 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13754 			freemsg(mp);
13755 			return (B_FALSE);
13756 		}
13757 	}
13758 	return (B_TRUE);
13759 }
13760 
13761 ire_t *
13762 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13763 {
13764 	ire_t		*new_ire;
13765 	ill_t		*ire_ill;
13766 	uint_t		ifindex;
13767 	ip_stack_t	*ipst = ill->ill_ipst;
13768 	boolean_t	strict_check = B_FALSE;
13769 
13770 	/*
13771 	 * This packet came in on an interface other than the one associated
13772 	 * with the first ire we found for the destination address. We do
13773 	 * another ire lookup here, using the ingress ill, to see if the
13774 	 * interface is in an interface group.
13775 	 * As long as the ills belong to the same group, we don't consider
13776 	 * them to be arriving on the wrong interface. Thus, if the switch
13777 	 * is doing inbound load spreading, we won't drop packets when the
13778 	 * ip*_strict_dst_multihoming switch is on. Note, the same holds true
13779 	 * for 'usesrc groups' where the destination address may belong to
13780 	 * another interface to allow multipathing to happen.
13781 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13782 	 * where the local address may not be unique. In this case we were
13783 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13784 	 * actually returned. The new lookup, which is more specific, should
13785 	 * only find the IRE_LOCAL associated with the ingress ill if one
13786 	 * exists.
13787 	 */
13788 
13789 	if (ire->ire_ipversion == IPV4_VERSION) {
13790 		if (ipst->ips_ip_strict_dst_multihoming)
13791 			strict_check = B_TRUE;
13792 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13793 		    ill->ill_ipif, ALL_ZONES, NULL,
13794 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13795 	} else {
13796 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13797 		if (ipst->ips_ipv6_strict_dst_multihoming)
13798 			strict_check = B_TRUE;
13799 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13800 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13801 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13802 	}
13803 	/*
13804 	 * If the same ire that was returned in ip_input() is found then this
13805 	 * is an indication that interface groups are in use. The packet
13806 	 * arrived on a different ill in the group than the one associated with
13807 	 * the destination address.  If a different ire was found then the same
13808 	 * IP address must be hosted on multiple ills. This is possible with
13809 	 * unnumbered point2point interfaces. We switch to use this new ire in
13810 	 * order to have accurate interface statistics.
13811 	 */
13812 	if (new_ire != NULL) {
13813 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13814 			ire_refrele(ire);
13815 			ire = new_ire;
13816 		} else {
13817 			ire_refrele(new_ire);
13818 		}
13819 		return (ire);
13820 	} else if ((ire->ire_rfq == NULL) &&
13821 	    (ire->ire_ipversion == IPV4_VERSION)) {
13822 		/*
13823 		 * The best match could have been the original ire which
13824 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13825 		 * the strict multihoming checks are irrelevant as we consider
13826 		 * local addresses hosted on lo0 to be interface agnostic. We
13827 		 * only expect a null ire_rfq on IREs which are associated with
13828 		 * lo0 hence we can return now.
13829 		 */
13830 		return (ire);
13831 	}
13832 
13833 	/*
13834 	 * Chase pointers once and store locally.
13835 	 */
13836 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13837 	    (ill_t *)(ire->ire_rfq->q_ptr);
13838 	ifindex = ill->ill_usesrc_ifindex;
13839 
13840 	/*
13841 	 * Check if it's a legal address on the 'usesrc' interface.
13842 	 */
13843 	if ((ifindex != 0) && (ire_ill != NULL) &&
13844 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13845 		return (ire);
13846 	}
13847 
13848 	/*
13849 	 * If the ip*_strict_dst_multihoming switch is on then we can
13850 	 * only accept this packet if the interface is marked as routing.
13851 	 */
13852 	if (!(strict_check))
13853 		return (ire);
13854 
13855 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13856 	    ILLF_ROUTER) != 0) {
13857 		return (ire);
13858 	}
13859 
13860 	ire_refrele(ire);
13861 	return (NULL);
13862 }
13863 
13864 ire_t *
13865 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13866 {
13867 	ipha_t	*ipha;
13868 	ipaddr_t ip_dst, ip_src;
13869 	ire_t	*src_ire = NULL;
13870 	ill_t	*stq_ill;
13871 	uint_t	hlen;
13872 	uint_t	pkt_len;
13873 	uint32_t sum;
13874 	queue_t	*dev_q;
13875 	boolean_t check_multirt = B_FALSE;
13876 	ip_stack_t *ipst = ill->ill_ipst;
13877 
13878 	ipha = (ipha_t *)mp->b_rptr;
13879 
13880 	/*
13881 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13882 	 * The loopback address check for both src and dst has already
13883 	 * been checked in ip_input
13884 	 */
13885 	ip_dst = ntohl(dst);
13886 	ip_src = ntohl(ipha->ipha_src);
13887 
13888 	if (ip_dst == INADDR_ANY || IN_BADCLASS(ip_dst) ||
13889 	    IN_CLASSD(ip_src)) {
13890 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13891 		goto drop;
13892 	}
13893 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13894 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13895 
13896 	if (src_ire != NULL) {
13897 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13898 		goto drop;
13899 	}
13900 
13901 
13902 	/* No ire cache of nexthop. So first create one  */
13903 	if (ire == NULL) {
13904 		ire = ire_forward(dst, &check_multirt, NULL, NULL, NULL, ipst);
13905 		/*
13906 		 * We only come to ip_fast_forward if ip_cgtp_filter is
13907 		 * is not set. So upon return from ire_forward
13908 		 * check_multirt should remain as false.
13909 		 */
13910 		ASSERT(!check_multirt);
13911 		if (ire == NULL) {
13912 			/* An attempt was made to forward the packet */
13913 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13914 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13915 			mp->b_prev = mp->b_next = 0;
13916 			/* send icmp unreachable */
13917 			/* Sent by forwarding path, and router is global zone */
13918 			if (ip_source_routed(ipha, ipst)) {
13919 				icmp_unreachable(ill->ill_wq, mp,
13920 				    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID,
13921 				    ipst);
13922 			} else {
13923 				icmp_unreachable(ill->ill_wq, mp,
13924 				    ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13925 				    ipst);
13926 			}
13927 			return (ire);
13928 		}
13929 	}
13930 
13931 	/*
13932 	 * Forwarding fastpath exception case:
13933 	 * If either of the follwoing case is true, we take
13934 	 * the slowpath
13935 	 *	o forwarding is not enabled
13936 	 *	o incoming and outgoing interface are the same, or the same
13937 	 *	  IPMP group
13938 	 *	o corresponding ire is in incomplete state
13939 	 *	o packet needs fragmentation
13940 	 *
13941 	 * The codeflow from here on is thus:
13942 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13943 	 */
13944 	pkt_len = ntohs(ipha->ipha_length);
13945 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13946 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13947 	    !(ill->ill_flags & ILLF_ROUTER) ||
13948 	    (ill == stq_ill) ||
13949 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
13950 	    (ire->ire_nce == NULL) ||
13951 	    (ire->ire_nce->nce_state != ND_REACHABLE) ||
13952 	    (pkt_len > ire->ire_max_frag) ||
13953 	    ipha->ipha_ttl <= 1) {
13954 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13955 		    ipha, ill, B_FALSE);
13956 		return (ire);
13957 	}
13958 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13959 
13960 	DTRACE_PROBE4(ip4__forwarding__start,
13961 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13962 
13963 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
13964 	    ipst->ips_ipv4firewall_forwarding,
13965 	    ill, stq_ill, ipha, mp, mp, ipst);
13966 
13967 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13968 
13969 	if (mp == NULL)
13970 		goto drop;
13971 
13972 	mp->b_datap->db_struioun.cksum.flags = 0;
13973 	/* Adjust the checksum to reflect the ttl decrement. */
13974 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13975 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
13976 	ipha->ipha_ttl--;
13977 
13978 	dev_q = ire->ire_stq->q_next;
13979 	if ((dev_q->q_next != NULL ||
13980 	    dev_q->q_first != NULL) && !canput(dev_q)) {
13981 		goto indiscard;
13982 	}
13983 
13984 	hlen = ire->ire_nce->nce_fp_mp != NULL ?
13985 	    MBLKL(ire->ire_nce->nce_fp_mp) : 0;
13986 
13987 	if (hlen != 0 || ire->ire_nce->nce_res_mp != NULL) {
13988 		mblk_t *mpip = mp;
13989 
13990 		mp = ip_wput_attach_llhdr(mpip, ire, 0, 0);
13991 		if (mp != NULL) {
13992 			DTRACE_PROBE4(ip4__physical__out__start,
13993 			    ill_t *, NULL, ill_t *, stq_ill,
13994 			    ipha_t *, ipha, mblk_t *, mp);
13995 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
13996 			    ipst->ips_ipv4firewall_physical_out,
13997 			    NULL, stq_ill, ipha, mp, mpip, ipst);
13998 			DTRACE_PROBE1(ip4__physical__out__end, mblk_t *,
13999 			    mp);
14000 			if (mp == NULL)
14001 				goto drop;
14002 
14003 			UPDATE_IB_PKT_COUNT(ire);
14004 			ire->ire_last_used_time = lbolt;
14005 			BUMP_MIB(stq_ill->ill_ip_mib,
14006 			    ipIfStatsHCOutForwDatagrams);
14007 			BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14008 			UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets,
14009 			    pkt_len);
14010 			putnext(ire->ire_stq, mp);
14011 			return (ire);
14012 		}
14013 	}
14014 
14015 indiscard:
14016 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14017 drop:
14018 	if (mp != NULL)
14019 		freemsg(mp);
14020 	if (src_ire != NULL)
14021 		ire_refrele(src_ire);
14022 	return (ire);
14023 
14024 }
14025 
14026 /*
14027  * This function is called in the forwarding slowpath, when
14028  * either the ire lacks the link-layer address, or the packet needs
14029  * further processing(eg. fragmentation), before transmission.
14030  */
14031 
14032 static void
14033 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14034     ill_t *ill, boolean_t ll_multicast)
14035 {
14036 	ill_group_t	*ill_group;
14037 	ill_group_t	*ire_group;
14038 	queue_t		*dev_q;
14039 	ire_t		*src_ire;
14040 	ip_stack_t	*ipst = ill->ill_ipst;
14041 
14042 	ASSERT(ire->ire_stq != NULL);
14043 
14044 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14045 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14046 
14047 	if (ll_multicast != 0) {
14048 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14049 		goto drop_pkt;
14050 	}
14051 
14052 	/*
14053 	 * check if ipha_src is a broadcast address. Note that this
14054 	 * check is redundant when we get here from ip_fast_forward()
14055 	 * which has already done this check. However, since we can
14056 	 * also get here from ip_rput_process_broadcast() or, for
14057 	 * for the slow path through ip_fast_forward(), we perform
14058 	 * the check again for code-reusability
14059 	 */
14060 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14061 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14062 	if (src_ire != NULL || ntohl(ipha->ipha_dst) == INADDR_ANY ||
14063 	    IN_BADCLASS(ntohl(ipha->ipha_dst))) {
14064 		if (src_ire != NULL)
14065 			ire_refrele(src_ire);
14066 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14067 		ip2dbg(("ip_rput_process_forward: Received packet with"
14068 		    " bad src/dst address on %s\n", ill->ill_name));
14069 		goto drop_pkt;
14070 	}
14071 
14072 	ill_group = ill->ill_group;
14073 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
14074 	/*
14075 	 * Check if we want to forward this one at this time.
14076 	 * We allow source routed packets on a host provided that
14077 	 * they go out the same interface or same interface group
14078 	 * as they came in on.
14079 	 *
14080 	 * XXX To be quicker, we may wish to not chase pointers to
14081 	 * get the ILLF_ROUTER flag and instead store the
14082 	 * forwarding policy in the ire.  An unfortunate
14083 	 * side-effect of that would be requiring an ire flush
14084 	 * whenever the ILLF_ROUTER flag changes.
14085 	 */
14086 	if (((ill->ill_flags &
14087 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
14088 	    ILLF_ROUTER) == 0) &&
14089 	    !(ip_source_routed(ipha, ipst) && (ire->ire_rfq == q ||
14090 	    (ill_group != NULL && ill_group == ire_group)))) {
14091 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14092 		if (ip_source_routed(ipha, ipst)) {
14093 			q = WR(q);
14094 			/*
14095 			 * Clear the indication that this may have
14096 			 * hardware checksum as we are not using it.
14097 			 */
14098 			DB_CKSUMFLAGS(mp) = 0;
14099 			/* Sent by forwarding path, and router is global zone */
14100 			icmp_unreachable(q, mp,
14101 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14102 			return;
14103 		}
14104 		goto drop_pkt;
14105 	}
14106 
14107 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14108 
14109 	/* Packet is being forwarded. Turning off hwcksum flag. */
14110 	DB_CKSUMFLAGS(mp) = 0;
14111 	if (ipst->ips_ip_g_send_redirects) {
14112 		/*
14113 		 * Check whether the incoming interface and outgoing
14114 		 * interface is part of the same group. If so,
14115 		 * send redirects.
14116 		 *
14117 		 * Check the source address to see if it originated
14118 		 * on the same logical subnet it is going back out on.
14119 		 * If so, we should be able to send it a redirect.
14120 		 * Avoid sending a redirect if the destination
14121 		 * is directly connected (i.e., ipha_dst is the same
14122 		 * as ire_gateway_addr or the ire_addr of the
14123 		 * nexthop IRE_CACHE ), or if the packet was source
14124 		 * routed out this interface.
14125 		 */
14126 		ipaddr_t src, nhop;
14127 		mblk_t	*mp1;
14128 		ire_t	*nhop_ire = NULL;
14129 
14130 		/*
14131 		 * Check whether ire_rfq and q are from the same ill
14132 		 * or if they are not same, they at least belong
14133 		 * to the same group. If so, send redirects.
14134 		 */
14135 		if ((ire->ire_rfq == q ||
14136 		    (ill_group != NULL && ill_group == ire_group)) &&
14137 		    !ip_source_routed(ipha, ipst)) {
14138 
14139 			nhop = (ire->ire_gateway_addr != 0 ?
14140 			    ire->ire_gateway_addr : ire->ire_addr);
14141 
14142 			if (ipha->ipha_dst == nhop) {
14143 				/*
14144 				 * We avoid sending a redirect if the
14145 				 * destination is directly connected
14146 				 * because it is possible that multiple
14147 				 * IP subnets may have been configured on
14148 				 * the link, and the source may not
14149 				 * be on the same subnet as ip destination,
14150 				 * even though they are on the same
14151 				 * physical link.
14152 				 */
14153 				goto sendit;
14154 			}
14155 
14156 			src = ipha->ipha_src;
14157 
14158 			/*
14159 			 * We look up the interface ire for the nexthop,
14160 			 * to see if ipha_src is in the same subnet
14161 			 * as the nexthop.
14162 			 *
14163 			 * Note that, if, in the future, IRE_CACHE entries
14164 			 * are obsoleted,  this lookup will not be needed,
14165 			 * as the ire passed to this function will be the
14166 			 * same as the nhop_ire computed below.
14167 			 */
14168 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14169 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14170 			    0, NULL, MATCH_IRE_TYPE, ipst);
14171 
14172 			if (nhop_ire != NULL) {
14173 				if ((src & nhop_ire->ire_mask) ==
14174 				    (nhop & nhop_ire->ire_mask)) {
14175 					/*
14176 					 * The source is directly connected.
14177 					 * Just copy the ip header (which is
14178 					 * in the first mblk)
14179 					 */
14180 					mp1 = copyb(mp);
14181 					if (mp1 != NULL) {
14182 						icmp_send_redirect(WR(q), mp1,
14183 						    nhop, ipst);
14184 					}
14185 				}
14186 				ire_refrele(nhop_ire);
14187 			}
14188 		}
14189 	}
14190 sendit:
14191 	dev_q = ire->ire_stq->q_next;
14192 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
14193 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14194 		freemsg(mp);
14195 		return;
14196 	}
14197 
14198 	ip_rput_forward(ire, ipha, mp, ill);
14199 	return;
14200 
14201 drop_pkt:
14202 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14203 	freemsg(mp);
14204 }
14205 
14206 ire_t *
14207 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14208     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14209 {
14210 	queue_t		*q;
14211 	uint16_t	hcksumflags;
14212 	ip_stack_t	*ipst = ill->ill_ipst;
14213 
14214 	q = *qp;
14215 
14216 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14217 
14218 	/*
14219 	 * Clear the indication that this may have hardware
14220 	 * checksum as we are not using it for forwarding.
14221 	 */
14222 	hcksumflags = DB_CKSUMFLAGS(mp);
14223 	DB_CKSUMFLAGS(mp) = 0;
14224 
14225 	/*
14226 	 * Directed broadcast forwarding: if the packet came in over a
14227 	 * different interface then it is routed out over we can forward it.
14228 	 */
14229 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14230 		ire_refrele(ire);
14231 		freemsg(mp);
14232 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14233 		return (NULL);
14234 	}
14235 	/*
14236 	 * For multicast we have set dst to be INADDR_BROADCAST
14237 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
14238 	 * only for broadcast packets.
14239 	 */
14240 	if (!CLASSD(ipha->ipha_dst)) {
14241 		ire_t *new_ire;
14242 		ipif_t *ipif;
14243 		/*
14244 		 * For ill groups, as the switch duplicates broadcasts
14245 		 * across all the ports, we need to filter out and
14246 		 * send up only one copy. There is one copy for every
14247 		 * broadcast address on each ill. Thus, we look for a
14248 		 * specific IRE on this ill and look at IRE_MARK_NORECV
14249 		 * later to see whether this ill is eligible to receive
14250 		 * them or not. ill_nominate_bcast_rcv() nominates only
14251 		 * one set of IREs for receiving.
14252 		 */
14253 
14254 		ipif = ipif_get_next_ipif(NULL, ill);
14255 		if (ipif == NULL) {
14256 			ire_refrele(ire);
14257 			freemsg(mp);
14258 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14259 			return (NULL);
14260 		}
14261 		new_ire = ire_ctable_lookup(dst, 0, 0,
14262 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14263 		ipif_refrele(ipif);
14264 
14265 		if (new_ire != NULL) {
14266 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
14267 				ire_refrele(ire);
14268 				ire_refrele(new_ire);
14269 				freemsg(mp);
14270 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14271 				return (NULL);
14272 			}
14273 			/*
14274 			 * In the special case of multirouted broadcast
14275 			 * packets, we unconditionally need to "gateway"
14276 			 * them to the appropriate interface here.
14277 			 * In the normal case, this cannot happen, because
14278 			 * there is no broadcast IRE tagged with the
14279 			 * RTF_MULTIRT flag.
14280 			 */
14281 			if (new_ire->ire_flags & RTF_MULTIRT) {
14282 				ire_refrele(new_ire);
14283 				if (ire->ire_rfq != NULL) {
14284 					q = ire->ire_rfq;
14285 					*qp = q;
14286 				}
14287 			} else {
14288 				ire_refrele(ire);
14289 				ire = new_ire;
14290 			}
14291 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14292 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14293 				/*
14294 				 * Free the message if
14295 				 * ip_g_forward_directed_bcast is turned
14296 				 * off for non-local broadcast.
14297 				 */
14298 				ire_refrele(ire);
14299 				freemsg(mp);
14300 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14301 				return (NULL);
14302 			}
14303 		} else {
14304 			/*
14305 			 * This CGTP packet successfully passed the
14306 			 * CGTP filter, but the related CGTP
14307 			 * broadcast IRE has not been found,
14308 			 * meaning that the redundant ipif is
14309 			 * probably down. However, if we discarded
14310 			 * this packet, its duplicate would be
14311 			 * filtered out by the CGTP filter so none
14312 			 * of them would get through. So we keep
14313 			 * going with this one.
14314 			 */
14315 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14316 			if (ire->ire_rfq != NULL) {
14317 				q = ire->ire_rfq;
14318 				*qp = q;
14319 			}
14320 		}
14321 	}
14322 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14323 		/*
14324 		 * Verify that there are not more then one
14325 		 * IRE_BROADCAST with this broadcast address which
14326 		 * has ire_stq set.
14327 		 * TODO: simplify, loop over all IRE's
14328 		 */
14329 		ire_t	*ire1;
14330 		int	num_stq = 0;
14331 		mblk_t	*mp1;
14332 
14333 		/* Find the first one with ire_stq set */
14334 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14335 		for (ire1 = ire; ire1 &&
14336 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14337 		    ire1 = ire1->ire_next)
14338 			;
14339 		if (ire1) {
14340 			ire_refrele(ire);
14341 			ire = ire1;
14342 			IRE_REFHOLD(ire);
14343 		}
14344 
14345 		/* Check if there are additional ones with stq set */
14346 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14347 			if (ire->ire_addr != ire1->ire_addr)
14348 				break;
14349 			if (ire1->ire_stq) {
14350 				num_stq++;
14351 				break;
14352 			}
14353 		}
14354 		rw_exit(&ire->ire_bucket->irb_lock);
14355 		if (num_stq == 1 && ire->ire_stq != NULL) {
14356 			ip1dbg(("ip_rput_process_broadcast: directed "
14357 			    "broadcast to 0x%x\n",
14358 			    ntohl(ire->ire_addr)));
14359 			mp1 = copymsg(mp);
14360 			if (mp1) {
14361 				switch (ipha->ipha_protocol) {
14362 				case IPPROTO_UDP:
14363 					ip_udp_input(q, mp1, ipha, ire, ill);
14364 					break;
14365 				default:
14366 					ip_proto_input(q, mp1, ipha, ire, ill,
14367 					    B_FALSE);
14368 					break;
14369 				}
14370 			}
14371 			/*
14372 			 * Adjust ttl to 2 (1+1 - the forward engine
14373 			 * will decrement it by one.
14374 			 */
14375 			if (ip_csum_hdr(ipha)) {
14376 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14377 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14378 				freemsg(mp);
14379 				ire_refrele(ire);
14380 				return (NULL);
14381 			}
14382 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14383 			ipha->ipha_hdr_checksum = 0;
14384 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14385 			ip_rput_process_forward(q, mp, ire, ipha,
14386 			    ill, ll_multicast);
14387 			ire_refrele(ire);
14388 			return (NULL);
14389 		}
14390 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14391 		    ntohl(ire->ire_addr)));
14392 	}
14393 
14394 
14395 	/* Restore any hardware checksum flags */
14396 	DB_CKSUMFLAGS(mp) = hcksumflags;
14397 	return (ire);
14398 }
14399 
14400 /* ARGSUSED */
14401 static boolean_t
14402 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14403     int *ll_multicast, ipaddr_t *dstp)
14404 {
14405 	ip_stack_t	*ipst = ill->ill_ipst;
14406 
14407 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14408 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14409 	    ntohs(ipha->ipha_length));
14410 
14411 	/*
14412 	 * Forward packets only if we have joined the allmulti
14413 	 * group on this interface.
14414 	 */
14415 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14416 		int retval;
14417 
14418 		/*
14419 		 * Clear the indication that this may have hardware
14420 		 * checksum as we are not using it.
14421 		 */
14422 		DB_CKSUMFLAGS(mp) = 0;
14423 		retval = ip_mforward(ill, ipha, mp);
14424 		/* ip_mforward updates mib variables if needed */
14425 		/* clear b_prev - used by ip_mroute_decap */
14426 		mp->b_prev = NULL;
14427 
14428 		switch (retval) {
14429 		case 0:
14430 			/*
14431 			 * pkt is okay and arrived on phyint.
14432 			 *
14433 			 * If we are running as a multicast router
14434 			 * we need to see all IGMP and/or PIM packets.
14435 			 */
14436 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14437 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14438 				goto done;
14439 			}
14440 			break;
14441 		case -1:
14442 			/* pkt is mal-formed, toss it */
14443 			goto drop_pkt;
14444 		case 1:
14445 			/* pkt is okay and arrived on a tunnel */
14446 			/*
14447 			 * If we are running a multicast router
14448 			 *  we need to see all igmp packets.
14449 			 */
14450 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14451 				*dstp = INADDR_BROADCAST;
14452 				*ll_multicast = 1;
14453 				return (B_FALSE);
14454 			}
14455 
14456 			goto drop_pkt;
14457 		}
14458 	}
14459 
14460 	ILM_WALKER_HOLD(ill);
14461 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14462 		/*
14463 		 * This might just be caused by the fact that
14464 		 * multiple IP Multicast addresses map to the same
14465 		 * link layer multicast - no need to increment counter!
14466 		 */
14467 		ILM_WALKER_RELE(ill);
14468 		freemsg(mp);
14469 		return (B_TRUE);
14470 	}
14471 	ILM_WALKER_RELE(ill);
14472 done:
14473 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14474 	/*
14475 	 * This assumes the we deliver to all streams for multicast
14476 	 * and broadcast packets.
14477 	 */
14478 	*dstp = INADDR_BROADCAST;
14479 	*ll_multicast = 1;
14480 	return (B_FALSE);
14481 drop_pkt:
14482 	ip2dbg(("ip_rput: drop pkt\n"));
14483 	freemsg(mp);
14484 	return (B_TRUE);
14485 }
14486 
14487 static boolean_t
14488 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14489     int *ll_multicast, mblk_t **mpp)
14490 {
14491 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14492 	boolean_t must_copy = B_FALSE;
14493 	struct iocblk   *iocp;
14494 	ipha_t		*ipha;
14495 	ip_stack_t	*ipst = ill->ill_ipst;
14496 
14497 #define	rptr    ((uchar_t *)ipha)
14498 
14499 	first_mp = *first_mpp;
14500 	mp = *mpp;
14501 
14502 	ASSERT(first_mp == mp);
14503 
14504 	/*
14505 	 * if db_ref > 1 then copymsg and free original. Packet may be
14506 	 * changed and do not want other entity who has a reference to this
14507 	 * message to trip over the changes. This is a blind change because
14508 	 * trying to catch all places that might change packet is too
14509 	 * difficult (since it may be a module above this one)
14510 	 *
14511 	 * This corresponds to the non-fast path case. We walk down the full
14512 	 * chain in this case, and check the db_ref count of all the dblks,
14513 	 * and do a copymsg if required. It is possible that the db_ref counts
14514 	 * of the data blocks in the mblk chain can be different.
14515 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14516 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14517 	 * 'snoop' is running.
14518 	 */
14519 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14520 		if (mp1->b_datap->db_ref > 1) {
14521 			must_copy = B_TRUE;
14522 			break;
14523 		}
14524 	}
14525 
14526 	if (must_copy) {
14527 		mp1 = copymsg(mp);
14528 		if (mp1 == NULL) {
14529 			for (mp1 = mp; mp1 != NULL;
14530 			    mp1 = mp1->b_cont) {
14531 				mp1->b_next = NULL;
14532 				mp1->b_prev = NULL;
14533 			}
14534 			freemsg(mp);
14535 			if (ill != NULL) {
14536 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14537 			} else {
14538 				BUMP_MIB(&ipst->ips_ip_mib,
14539 				    ipIfStatsInDiscards);
14540 			}
14541 			return (B_TRUE);
14542 		}
14543 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14544 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14545 			/* Copy b_prev - used by ip_mroute_decap */
14546 			to_mp->b_prev = from_mp->b_prev;
14547 			from_mp->b_prev = NULL;
14548 		}
14549 		*first_mpp = first_mp = mp1;
14550 		freemsg(mp);
14551 		mp = mp1;
14552 		*mpp = mp1;
14553 	}
14554 
14555 	ipha = (ipha_t *)mp->b_rptr;
14556 
14557 	/*
14558 	 * previous code has a case for M_DATA.
14559 	 * We want to check how that happens.
14560 	 */
14561 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14562 	switch (first_mp->b_datap->db_type) {
14563 	case M_PROTO:
14564 	case M_PCPROTO:
14565 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14566 		    DL_UNITDATA_IND) {
14567 			/* Go handle anything other than data elsewhere. */
14568 			ip_rput_dlpi(q, mp);
14569 			return (B_TRUE);
14570 		}
14571 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
14572 		/* Ditch the DLPI header. */
14573 		mp1 = mp->b_cont;
14574 		ASSERT(first_mp == mp);
14575 		*first_mpp = mp1;
14576 		freeb(mp);
14577 		*mpp = mp1;
14578 		return (B_FALSE);
14579 	case M_IOCACK:
14580 		ip1dbg(("got iocack "));
14581 		iocp = (struct iocblk *)mp->b_rptr;
14582 		switch (iocp->ioc_cmd) {
14583 		case DL_IOC_HDR_INFO:
14584 			ill = (ill_t *)q->q_ptr;
14585 			ill_fastpath_ack(ill, mp);
14586 			return (B_TRUE);
14587 		case SIOCSTUNPARAM:
14588 		case OSIOCSTUNPARAM:
14589 			/* Go through qwriter_ip */
14590 			break;
14591 		case SIOCGTUNPARAM:
14592 		case OSIOCGTUNPARAM:
14593 			ip_rput_other(NULL, q, mp, NULL);
14594 			return (B_TRUE);
14595 		default:
14596 			putnext(q, mp);
14597 			return (B_TRUE);
14598 		}
14599 		/* FALLTHRU */
14600 	case M_ERROR:
14601 	case M_HANGUP:
14602 		/*
14603 		 * Since this is on the ill stream we unconditionally
14604 		 * bump up the refcount
14605 		 */
14606 		ill_refhold(ill);
14607 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14608 		return (B_TRUE);
14609 	case M_CTL:
14610 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14611 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14612 		    IPHADA_M_CTL)) {
14613 			/*
14614 			 * It's an IPsec accelerated packet.
14615 			 * Make sure that the ill from which we received the
14616 			 * packet has enabled IPsec hardware acceleration.
14617 			 */
14618 			if (!(ill->ill_capabilities &
14619 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14620 				/* IPsec kstats: bean counter */
14621 				freemsg(mp);
14622 				return (B_TRUE);
14623 			}
14624 
14625 			/*
14626 			 * Make mp point to the mblk following the M_CTL,
14627 			 * then process according to type of mp.
14628 			 * After this processing, first_mp will point to
14629 			 * the data-attributes and mp to the pkt following
14630 			 * the M_CTL.
14631 			 */
14632 			mp = first_mp->b_cont;
14633 			if (mp == NULL) {
14634 				freemsg(first_mp);
14635 				return (B_TRUE);
14636 			}
14637 			/*
14638 			 * A Hardware Accelerated packet can only be M_DATA
14639 			 * ESP or AH packet.
14640 			 */
14641 			if (mp->b_datap->db_type != M_DATA) {
14642 				/* non-M_DATA IPsec accelerated packet */
14643 				IPSECHW_DEBUG(IPSECHW_PKT,
14644 				    ("non-M_DATA IPsec accelerated pkt\n"));
14645 				freemsg(first_mp);
14646 				return (B_TRUE);
14647 			}
14648 			ipha = (ipha_t *)mp->b_rptr;
14649 			if (ipha->ipha_protocol != IPPROTO_AH &&
14650 			    ipha->ipha_protocol != IPPROTO_ESP) {
14651 				IPSECHW_DEBUG(IPSECHW_PKT,
14652 				    ("non-M_DATA IPsec accelerated pkt\n"));
14653 				freemsg(first_mp);
14654 				return (B_TRUE);
14655 			}
14656 			*mpp = mp;
14657 			return (B_FALSE);
14658 		}
14659 		putnext(q, mp);
14660 		return (B_TRUE);
14661 	case M_IOCNAK:
14662 		ip1dbg(("got iocnak "));
14663 		iocp = (struct iocblk *)mp->b_rptr;
14664 		switch (iocp->ioc_cmd) {
14665 		case SIOCSTUNPARAM:
14666 		case OSIOCSTUNPARAM:
14667 			/*
14668 			 * Since this is on the ill stream we unconditionally
14669 			 * bump up the refcount
14670 			 */
14671 			ill_refhold(ill);
14672 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14673 			return (B_TRUE);
14674 		case DL_IOC_HDR_INFO:
14675 		case SIOCGTUNPARAM:
14676 		case OSIOCGTUNPARAM:
14677 			ip_rput_other(NULL, q, mp, NULL);
14678 			return (B_TRUE);
14679 		default:
14680 			break;
14681 		}
14682 		/* FALLTHRU */
14683 	default:
14684 		putnext(q, mp);
14685 		return (B_TRUE);
14686 	}
14687 }
14688 
14689 /* Read side put procedure.  Packets coming from the wire arrive here. */
14690 void
14691 ip_rput(queue_t *q, mblk_t *mp)
14692 {
14693 	ill_t	*ill;
14694 	union DL_primitives *dl;
14695 
14696 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14697 
14698 	ill = (ill_t *)q->q_ptr;
14699 
14700 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14701 		/*
14702 		 * If things are opening or closing, only accept high-priority
14703 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14704 		 * created; on close, things hanging off the ill may have been
14705 		 * freed already.)
14706 		 */
14707 		dl = (union DL_primitives *)mp->b_rptr;
14708 		if (DB_TYPE(mp) != M_PCPROTO ||
14709 		    dl->dl_primitive == DL_UNITDATA_IND) {
14710 			/*
14711 			 * SIOC[GS]TUNPARAM ioctls can come here.
14712 			 */
14713 			inet_freemsg(mp);
14714 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14715 			    "ip_rput_end: q %p (%S)", q, "uninit");
14716 			return;
14717 		}
14718 	}
14719 
14720 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14721 	    "ip_rput_end: q %p (%S)", q, "end");
14722 
14723 	ip_input(ill, NULL, mp, NULL);
14724 }
14725 
14726 static mblk_t *
14727 ip_fix_dbref(ill_t *ill, mblk_t *mp)
14728 {
14729 	mblk_t *mp1;
14730 	boolean_t adjusted = B_FALSE;
14731 	ip_stack_t *ipst = ill->ill_ipst;
14732 
14733 	IP_STAT(ipst, ip_db_ref);
14734 	/*
14735 	 * The IP_RECVSLLA option depends on having the
14736 	 * link layer header. First check that:
14737 	 * a> the underlying device is of type ether,
14738 	 * since this option is currently supported only
14739 	 * over ethernet.
14740 	 * b> there is enough room to copy over the link
14741 	 * layer header.
14742 	 *
14743 	 * Once the checks are done, adjust rptr so that
14744 	 * the link layer header will be copied via
14745 	 * copymsg. Note that, IFT_ETHER may be returned
14746 	 * by some non-ethernet drivers but in this case
14747 	 * the second check will fail.
14748 	 */
14749 	if (ill->ill_type == IFT_ETHER &&
14750 	    (mp->b_rptr - mp->b_datap->db_base) >=
14751 	    sizeof (struct ether_header)) {
14752 		mp->b_rptr -= sizeof (struct ether_header);
14753 		adjusted = B_TRUE;
14754 	}
14755 	mp1 = copymsg(mp);
14756 
14757 	if (mp1 == NULL) {
14758 		mp->b_next = NULL;
14759 		/* clear b_prev - used by ip_mroute_decap */
14760 		mp->b_prev = NULL;
14761 		freemsg(mp);
14762 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14763 		return (NULL);
14764 	}
14765 
14766 	if (adjusted) {
14767 		/*
14768 		 * Copy is done. Restore the pointer in
14769 		 * the _new_ mblk
14770 		 */
14771 		mp1->b_rptr += sizeof (struct ether_header);
14772 	}
14773 
14774 	/* Copy b_prev - used by ip_mroute_decap */
14775 	mp1->b_prev = mp->b_prev;
14776 	mp->b_prev = NULL;
14777 
14778 	/* preserve the hardware checksum flags and data, if present */
14779 	if (DB_CKSUMFLAGS(mp) != 0) {
14780 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
14781 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
14782 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
14783 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
14784 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
14785 	}
14786 
14787 	freemsg(mp);
14788 	return (mp1);
14789 }
14790 
14791 /*
14792  * Direct read side procedure capable of dealing with chains. GLDv3 based
14793  * drivers call this function directly with mblk chains while STREAMS
14794  * read side procedure ip_rput() calls this for single packet with ip_ring
14795  * set to NULL to process one packet at a time.
14796  *
14797  * The ill will always be valid if this function is called directly from
14798  * the driver.
14799  *
14800  * If ip_input() is called from GLDv3:
14801  *
14802  *   - This must be a non-VLAN IP stream.
14803  *   - 'mp' is either an untagged or a special priority-tagged packet.
14804  *   - Any VLAN tag that was in the MAC header has been stripped.
14805  *
14806  * If the IP header in packet is not 32-bit aligned, every message in the
14807  * chain will be aligned before further operations. This is required on SPARC
14808  * platform.
14809  */
14810 /* ARGSUSED */
14811 void
14812 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14813     struct mac_header_info_s *mhip)
14814 {
14815 	ipaddr_t		dst = NULL;
14816 	ipaddr_t		prev_dst;
14817 	ire_t			*ire = NULL;
14818 	ipha_t			*ipha;
14819 	uint_t			pkt_len;
14820 	ssize_t			len;
14821 	uint_t			opt_len;
14822 	int			ll_multicast;
14823 	int			cgtp_flt_pkt;
14824 	queue_t			*q = ill->ill_rq;
14825 	squeue_t		*curr_sqp = NULL;
14826 	mblk_t 			*head = NULL;
14827 	mblk_t			*tail = NULL;
14828 	mblk_t			*first_mp;
14829 	mblk_t 			*mp;
14830 	mblk_t			*dmp;
14831 	int			cnt = 0;
14832 	ip_stack_t		*ipst = ill->ill_ipst;
14833 
14834 	ASSERT(mp_chain != NULL);
14835 	ASSERT(ill != NULL);
14836 
14837 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14838 
14839 #define	rptr	((uchar_t *)ipha)
14840 
14841 	while (mp_chain != NULL) {
14842 		first_mp = mp = mp_chain;
14843 		mp_chain = mp_chain->b_next;
14844 		mp->b_next = NULL;
14845 		ll_multicast = 0;
14846 
14847 		/*
14848 		 * We do ire caching from one iteration to
14849 		 * another. In the event the packet chain contains
14850 		 * all packets from the same dst, this caching saves
14851 		 * an ire_cache_lookup for each of the succeeding
14852 		 * packets in a packet chain.
14853 		 */
14854 		prev_dst = dst;
14855 
14856 		/*
14857 		 * if db_ref > 1 then copymsg and free original. Packet
14858 		 * may be changed and we do not want the other entity
14859 		 * who has a reference to this message to trip over the
14860 		 * changes. This is a blind change because trying to
14861 		 * catch all places that might change the packet is too
14862 		 * difficult.
14863 		 *
14864 		 * This corresponds to the fast path case, where we have
14865 		 * a chain of M_DATA mblks.  We check the db_ref count
14866 		 * of only the 1st data block in the mblk chain. There
14867 		 * doesn't seem to be a reason why a device driver would
14868 		 * send up data with varying db_ref counts in the mblk
14869 		 * chain. In any case the Fast path is a private
14870 		 * interface, and our drivers don't do such a thing.
14871 		 * Given the above assumption, there is no need to walk
14872 		 * down the entire mblk chain (which could have a
14873 		 * potential performance problem)
14874 		 */
14875 
14876 		if (DB_REF(mp) > 1) {
14877 			if ((mp = ip_fix_dbref(ill, mp)) == NULL)
14878 				continue;
14879 		}
14880 
14881 		/*
14882 		 * Check and align the IP header.
14883 		 */
14884 		first_mp = mp;
14885 		if (DB_TYPE(mp) == M_DATA) {
14886 			dmp = mp;
14887 		} else if (DB_TYPE(mp) == M_PROTO &&
14888 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14889 			dmp = mp->b_cont;
14890 		} else {
14891 			dmp = NULL;
14892 		}
14893 		if (dmp != NULL) {
14894 			/*
14895 			 * IP header ptr not aligned?
14896 			 * OR IP header not complete in first mblk
14897 			 */
14898 			if (!OK_32PTR(dmp->b_rptr) ||
14899 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
14900 				if (!ip_check_and_align_header(q, dmp, ipst))
14901 					continue;
14902 			}
14903 		}
14904 
14905 		/*
14906 		 * ip_input fast path
14907 		 */
14908 
14909 		/* mblk type is not M_DATA */
14910 		if (DB_TYPE(mp) != M_DATA) {
14911 			if (ip_rput_process_notdata(q, &first_mp, ill,
14912 			    &ll_multicast, &mp))
14913 				continue;
14914 		}
14915 
14916 		/* Make sure its an M_DATA and that its aligned */
14917 		ASSERT(DB_TYPE(mp) == M_DATA);
14918 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
14919 
14920 		ipha = (ipha_t *)mp->b_rptr;
14921 		len = mp->b_wptr - rptr;
14922 		pkt_len = ntohs(ipha->ipha_length);
14923 
14924 		/*
14925 		 * We must count all incoming packets, even if they end
14926 		 * up being dropped later on.
14927 		 */
14928 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
14929 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
14930 
14931 		/* multiple mblk or too short */
14932 		len -= pkt_len;
14933 		if (len != 0) {
14934 			/*
14935 			 * Make sure we have data length consistent
14936 			 * with the IP header.
14937 			 */
14938 			if (mp->b_cont == NULL) {
14939 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14940 					BUMP_MIB(ill->ill_ip_mib,
14941 					    ipIfStatsInHdrErrors);
14942 					ip2dbg(("ip_input: drop pkt\n"));
14943 					freemsg(mp);
14944 					continue;
14945 				}
14946 				mp->b_wptr = rptr + pkt_len;
14947 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
14948 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14949 					BUMP_MIB(ill->ill_ip_mib,
14950 					    ipIfStatsInHdrErrors);
14951 					ip2dbg(("ip_input: drop pkt\n"));
14952 					freemsg(mp);
14953 					continue;
14954 				}
14955 				(void) adjmsg(mp, -len);
14956 				IP_STAT(ipst, ip_multimblk3);
14957 			}
14958 		}
14959 
14960 		/* Obtain the dst of the current packet */
14961 		dst = ipha->ipha_dst;
14962 
14963 		if (IP_LOOPBACK_ADDR(dst) ||
14964 		    IP_LOOPBACK_ADDR(ipha->ipha_src)) {
14965 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
14966 			cmn_err(CE_CONT, "dst %X src %X\n",
14967 			    dst, ipha->ipha_src);
14968 			freemsg(mp);
14969 			continue;
14970 		}
14971 
14972 		/*
14973 		 * The event for packets being received from a 'physical'
14974 		 * interface is placed after validation of the source and/or
14975 		 * destination address as being local so that packets can be
14976 		 * redirected to loopback addresses using ipnat.
14977 		 */
14978 		DTRACE_PROBE4(ip4__physical__in__start,
14979 		    ill_t *, ill, ill_t *, NULL,
14980 		    ipha_t *, ipha, mblk_t *, first_mp);
14981 
14982 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
14983 		    ipst->ips_ipv4firewall_physical_in,
14984 		    ill, NULL, ipha, first_mp, mp, ipst);
14985 
14986 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
14987 
14988 		if (first_mp == NULL) {
14989 			continue;
14990 		}
14991 		dst = ipha->ipha_dst;
14992 
14993 		/*
14994 		 * Attach any necessary label information to
14995 		 * this packet
14996 		 */
14997 		if (is_system_labeled() &&
14998 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
14999 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15000 			freemsg(mp);
15001 			continue;
15002 		}
15003 
15004 		/*
15005 		 * Reuse the cached ire only if the ipha_dst of the previous
15006 		 * packet is the same as the current packet AND it is not
15007 		 * INADDR_ANY.
15008 		 */
15009 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15010 		    (ire != NULL)) {
15011 			ire_refrele(ire);
15012 			ire = NULL;
15013 		}
15014 		opt_len = ipha->ipha_version_and_hdr_length -
15015 		    IP_SIMPLE_HDR_VERSION;
15016 
15017 		/*
15018 		 * Check to see if we can take the fastpath.
15019 		 * That is possible if the following conditions are met
15020 		 *	o Tsol disabled
15021 		 *	o CGTP disabled
15022 		 *	o ipp_action_count is 0
15023 		 *	o no options in the packet
15024 		 *	o not a RSVP packet
15025 		 * 	o not a multicast packet
15026 		 *	o ill not in IP_DHCPINIT_IF mode
15027 		 */
15028 		if (!is_system_labeled() &&
15029 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
15030 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15031 		    !ll_multicast && !CLASSD(dst) && ill->ill_dhcpinit == 0) {
15032 			if (ire == NULL)
15033 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL,
15034 				    ipst);
15035 
15036 			/* incoming packet is for forwarding */
15037 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
15038 				ire = ip_fast_forward(ire, dst, ill, mp);
15039 				continue;
15040 			}
15041 			/* incoming packet is for local consumption */
15042 			if (ire->ire_type & IRE_LOCAL)
15043 				goto local;
15044 		}
15045 
15046 		/*
15047 		 * Disable ire caching for anything more complex
15048 		 * than the simple fast path case we checked for above.
15049 		 */
15050 		if (ire != NULL) {
15051 			ire_refrele(ire);
15052 			ire = NULL;
15053 		}
15054 
15055 		/*
15056 		 * Brutal hack for DHCPv4 unicast: RFC2131 allows a DHCP
15057 		 * server to unicast DHCP packets to a DHCP client using the
15058 		 * IP address it is offering to the client.  This can be
15059 		 * disabled through the "broadcast bit", but not all DHCP
15060 		 * servers honor that bit.  Therefore, to interoperate with as
15061 		 * many DHCP servers as possible, the DHCP client allows the
15062 		 * server to unicast, but we treat those packets as broadcast
15063 		 * here.  Note that we don't rewrite the packet itself since
15064 		 * (a) that would mess up the checksums and (b) the DHCP
15065 		 * client conn is bound to INADDR_ANY so ip_fanout_udp() will
15066 		 * hand it the packet regardless.
15067 		 */
15068 		if (ill->ill_dhcpinit != 0 &&
15069 		    IS_SIMPLE_IPH(ipha) && ipha->ipha_protocol == IPPROTO_UDP &&
15070 		    MBLKL(mp) > sizeof (ipha_t) + sizeof (udpha_t)) {
15071 			udpha_t *udpha = (udpha_t *)&ipha[1];
15072 
15073 			if (ntohs(udpha->uha_dst_port) == IPPORT_BOOTPC) {
15074 				DTRACE_PROBE2(ip4__dhcpinit__pkt, ill_t *, ill,
15075 				    mblk_t *, mp);
15076 				dst = INADDR_BROADCAST;
15077 			}
15078 		}
15079 
15080 		/* Full-blown slow path */
15081 		if (opt_len != 0) {
15082 			if (len != 0)
15083 				IP_STAT(ipst, ip_multimblk4);
15084 			else
15085 				IP_STAT(ipst, ip_ipoptions);
15086 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15087 			    &dst, ipst))
15088 				continue;
15089 		}
15090 
15091 		/*
15092 		 * Invoke the CGTP (multirouting) filtering module to process
15093 		 * the incoming packet. Packets identified as duplicates
15094 		 * must be discarded. Filtering is active only if the
15095 		 * the ip_cgtp_filter ndd variable is non-zero.
15096 		 */
15097 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15098 		if (ipst->ips_ip_cgtp_filter &&
15099 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15100 			netstackid_t stackid;
15101 
15102 			stackid = ipst->ips_netstack->netstack_stackid;
15103 			cgtp_flt_pkt =
15104 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15105 			    ill->ill_phyint->phyint_ifindex, mp);
15106 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15107 				freemsg(first_mp);
15108 				continue;
15109 			}
15110 		}
15111 
15112 		/*
15113 		 * If rsvpd is running, let RSVP daemon handle its processing
15114 		 * and forwarding of RSVP multicast/unicast packets.
15115 		 * If rsvpd is not running but mrouted is running, RSVP
15116 		 * multicast packets are forwarded as multicast traffic
15117 		 * and RSVP unicast packets are forwarded by unicast router.
15118 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15119 		 * packets are not forwarded, but the unicast packets are
15120 		 * forwarded like unicast traffic.
15121 		 */
15122 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15123 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15124 		    NULL) {
15125 			/* RSVP packet and rsvpd running. Treat as ours */
15126 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15127 			/*
15128 			 * This assumes that we deliver to all streams for
15129 			 * multicast and broadcast packets.
15130 			 * We have to force ll_multicast to 1 to handle the
15131 			 * M_DATA messages passed in from ip_mroute_decap.
15132 			 */
15133 			dst = INADDR_BROADCAST;
15134 			ll_multicast = 1;
15135 		} else if (CLASSD(dst)) {
15136 			/* packet is multicast */
15137 			mp->b_next = NULL;
15138 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15139 			    &ll_multicast, &dst))
15140 				continue;
15141 		}
15142 
15143 		if (ire == NULL) {
15144 			ire = ire_cache_lookup(dst, ALL_ZONES,
15145 			    MBLK_GETLABEL(mp), ipst);
15146 		}
15147 
15148 		if (ire == NULL) {
15149 			/*
15150 			 * No IRE for this destination, so it can't be for us.
15151 			 * Unless we are forwarding, drop the packet.
15152 			 * We have to let source routed packets through
15153 			 * since we don't yet know if they are 'ping -l'
15154 			 * packets i.e. if they will go out over the
15155 			 * same interface as they came in on.
15156 			 */
15157 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15158 			if (ire == NULL)
15159 				continue;
15160 		}
15161 
15162 		/*
15163 		 * Broadcast IRE may indicate either broadcast or
15164 		 * multicast packet
15165 		 */
15166 		if (ire->ire_type == IRE_BROADCAST) {
15167 			/*
15168 			 * Skip broadcast checks if packet is UDP multicast;
15169 			 * we'd rather not enter ip_rput_process_broadcast()
15170 			 * unless the packet is broadcast for real, since
15171 			 * that routine is a no-op for multicast.
15172 			 */
15173 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15174 			    !CLASSD(ipha->ipha_dst)) {
15175 				ire = ip_rput_process_broadcast(&q, mp,
15176 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15177 				    ll_multicast);
15178 				if (ire == NULL)
15179 					continue;
15180 			}
15181 		} else if (ire->ire_stq != NULL) {
15182 			/* fowarding? */
15183 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15184 			    ll_multicast);
15185 			/* ip_rput_process_forward consumed the packet */
15186 			continue;
15187 		}
15188 
15189 local:
15190 		/*
15191 		 * If the queue in the ire is different to the ingress queue
15192 		 * then we need to check to see if we can accept the packet.
15193 		 * Note that for multicast packets and broadcast packets sent
15194 		 * to a broadcast address which is shared between multiple
15195 		 * interfaces we should not do this since we just got a random
15196 		 * broadcast ire.
15197 		 */
15198 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15199 			if ((ire = ip_check_multihome(&ipha->ipha_dst, ire,
15200 			    ill)) == NULL) {
15201 				/* Drop packet */
15202 				BUMP_MIB(ill->ill_ip_mib,
15203 				    ipIfStatsForwProhibits);
15204 				freemsg(mp);
15205 				continue;
15206 			}
15207 			if (ire->ire_rfq != NULL)
15208 				q = ire->ire_rfq;
15209 		}
15210 
15211 		switch (ipha->ipha_protocol) {
15212 		case IPPROTO_TCP:
15213 			ASSERT(first_mp == mp);
15214 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15215 			    mp, 0, q, ip_ring)) != NULL) {
15216 				if (curr_sqp == NULL) {
15217 					curr_sqp = GET_SQUEUE(mp);
15218 					ASSERT(cnt == 0);
15219 					cnt++;
15220 					head = tail = mp;
15221 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15222 					ASSERT(tail != NULL);
15223 					cnt++;
15224 					tail->b_next = mp;
15225 					tail = mp;
15226 				} else {
15227 					/*
15228 					 * A different squeue. Send the
15229 					 * chain for the previous squeue on
15230 					 * its way. This shouldn't happen
15231 					 * often unless interrupt binding
15232 					 * changes.
15233 					 */
15234 					IP_STAT(ipst, ip_input_multi_squeue);
15235 					squeue_enter_chain(curr_sqp, head,
15236 					    tail, cnt, SQTAG_IP_INPUT);
15237 					curr_sqp = GET_SQUEUE(mp);
15238 					head = mp;
15239 					tail = mp;
15240 					cnt = 1;
15241 				}
15242 			}
15243 			continue;
15244 		case IPPROTO_UDP:
15245 			ASSERT(first_mp == mp);
15246 			ip_udp_input(q, mp, ipha, ire, ill);
15247 			continue;
15248 		case IPPROTO_SCTP:
15249 			ASSERT(first_mp == mp);
15250 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15251 			    q, dst);
15252 			/* ire has been released by ip_sctp_input */
15253 			ire = NULL;
15254 			continue;
15255 		default:
15256 			ip_proto_input(q, first_mp, ipha, ire, ill, B_FALSE);
15257 			continue;
15258 		}
15259 	}
15260 
15261 	if (ire != NULL)
15262 		ire_refrele(ire);
15263 
15264 	if (head != NULL)
15265 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
15266 
15267 	/*
15268 	 * This code is there just to make netperf/ttcp look good.
15269 	 *
15270 	 * Its possible that after being in polling mode (and having cleared
15271 	 * the backlog), squeues have turned the interrupt frequency higher
15272 	 * to improve latency at the expense of more CPU utilization (less
15273 	 * packets per interrupts or more number of interrupts). Workloads
15274 	 * like ttcp/netperf do manage to tickle polling once in a while
15275 	 * but for the remaining time, stay in higher interrupt mode since
15276 	 * their packet arrival rate is pretty uniform and this shows up
15277 	 * as higher CPU utilization. Since people care about CPU utilization
15278 	 * while running netperf/ttcp, turn the interrupt frequency back to
15279 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
15280 	 */
15281 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
15282 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
15283 			ip_ring->rr_poll_state &= ~ILL_POLLING;
15284 			ip_ring->rr_blank(ip_ring->rr_handle,
15285 			    ip_ring->rr_normal_blank_time,
15286 			    ip_ring->rr_normal_pkt_cnt);
15287 		}
15288 		}
15289 
15290 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15291 	    "ip_input_end: q %p (%S)", q, "end");
15292 #undef  rptr
15293 }
15294 
15295 static void
15296 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15297     t_uscalar_t err)
15298 {
15299 	if (dl_err == DL_SYSERR) {
15300 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15301 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15302 		    ill->ill_name, dlpi_prim_str(prim), err);
15303 		return;
15304 	}
15305 
15306 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15307 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
15308 	    dlpi_err_str(dl_err));
15309 }
15310 
15311 /*
15312  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15313  * than DL_UNITDATA_IND messages. If we need to process this message
15314  * exclusively, we call qwriter_ip, in which case we also need to call
15315  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15316  */
15317 void
15318 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15319 {
15320 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15321 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15322 	ill_t		*ill = (ill_t *)q->q_ptr;
15323 	boolean_t	pending;
15324 
15325 	ip1dbg(("ip_rput_dlpi"));
15326 	if (dloa->dl_primitive == DL_ERROR_ACK) {
15327 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
15328 		    "%s (0x%x), unix %u\n", ill->ill_name,
15329 		    dlpi_prim_str(dlea->dl_error_primitive),
15330 		    dlea->dl_error_primitive,
15331 		    dlpi_err_str(dlea->dl_errno),
15332 		    dlea->dl_errno,
15333 		    dlea->dl_unix_errno));
15334 	}
15335 
15336 	/*
15337 	 * If we received an ACK but didn't send a request for it, then it
15338 	 * can't be part of any pending operation; discard up-front.
15339 	 */
15340 	switch (dloa->dl_primitive) {
15341 	case DL_NOTIFY_IND:
15342 		pending = B_TRUE;
15343 		break;
15344 	case DL_ERROR_ACK:
15345 		pending = ill_dlpi_pending(ill, dlea->dl_error_primitive);
15346 		break;
15347 	case DL_OK_ACK:
15348 		pending = ill_dlpi_pending(ill, dloa->dl_correct_primitive);
15349 		break;
15350 	case DL_INFO_ACK:
15351 		pending = ill_dlpi_pending(ill, DL_INFO_REQ);
15352 		break;
15353 	case DL_BIND_ACK:
15354 		pending = ill_dlpi_pending(ill, DL_BIND_REQ);
15355 		break;
15356 	case DL_PHYS_ADDR_ACK:
15357 		pending = ill_dlpi_pending(ill, DL_PHYS_ADDR_REQ);
15358 		break;
15359 	case DL_NOTIFY_ACK:
15360 		pending = ill_dlpi_pending(ill, DL_NOTIFY_REQ);
15361 		break;
15362 	case DL_CONTROL_ACK:
15363 		pending = ill_dlpi_pending(ill, DL_CONTROL_REQ);
15364 		break;
15365 	case DL_CAPABILITY_ACK:
15366 		pending = ill_dlpi_pending(ill, DL_CAPABILITY_REQ);
15367 		break;
15368 	default:
15369 		/* Not a DLPI message we support or were expecting */
15370 		freemsg(mp);
15371 		return;
15372 	}
15373 
15374 	if (!pending) {
15375 		freemsg(mp);
15376 		return;
15377 	}
15378 
15379 	switch (dloa->dl_primitive) {
15380 	case DL_ERROR_ACK:
15381 		if (dlea->dl_error_primitive == DL_UNBIND_REQ) {
15382 			mutex_enter(&ill->ill_lock);
15383 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15384 			cv_signal(&ill->ill_cv);
15385 			mutex_exit(&ill->ill_lock);
15386 		}
15387 		break;
15388 
15389 	case DL_OK_ACK:
15390 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
15391 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
15392 		switch (dloa->dl_correct_primitive) {
15393 		case DL_UNBIND_REQ:
15394 			mutex_enter(&ill->ill_lock);
15395 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15396 			cv_signal(&ill->ill_cv);
15397 			mutex_exit(&ill->ill_lock);
15398 			break;
15399 
15400 		case DL_ENABMULTI_REQ:
15401 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15402 				ill->ill_dlpi_multicast_state = IDS_OK;
15403 			break;
15404 		}
15405 		break;
15406 	default:
15407 		break;
15408 	}
15409 
15410 	/*
15411 	 * We know the message is one we're waiting for (or DL_NOTIFY_IND),
15412 	 * and we need to become writer to continue to process it. If it's not
15413 	 * a DL_NOTIFY_IND, we assume we're in the middle of an exclusive
15414 	 * operation and pass CUR_OP.  If this isn't true, we'll end up doing
15415 	 * some work as part of the current exclusive operation that actually
15416 	 * is not part of it -- which is wrong, but better than the
15417 	 * alternative of deadlock (if NEW_OP is always used).  Someday, we
15418 	 * should track which DLPI requests have ACKs that we wait on
15419 	 * synchronously so we can know whether to use CUR_OP or NEW_OP.
15420 	 *
15421 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15422 	 * Since this is on the ill stream we unconditionally bump up the
15423 	 * refcount without doing ILL_CAN_LOOKUP().
15424 	 */
15425 	ill_refhold(ill);
15426 	if (dloa->dl_primitive == DL_NOTIFY_IND)
15427 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15428 	else
15429 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15430 }
15431 
15432 /*
15433  * Handling of DLPI messages that require exclusive access to the ipsq.
15434  *
15435  * Need to do ill_pending_mp_release on ioctl completion, which could
15436  * happen here. (along with mi_copy_done)
15437  */
15438 /* ARGSUSED */
15439 static void
15440 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15441 {
15442 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15443 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15444 	int		err = 0;
15445 	ill_t		*ill;
15446 	ipif_t		*ipif = NULL;
15447 	mblk_t		*mp1 = NULL;
15448 	conn_t		*connp = NULL;
15449 	t_uscalar_t	paddrreq;
15450 	mblk_t		*mp_hw;
15451 	boolean_t	success;
15452 	boolean_t	ioctl_aborted = B_FALSE;
15453 	boolean_t	log = B_TRUE;
15454 	hook_nic_event_t	*info;
15455 	ip_stack_t		*ipst;
15456 
15457 	ip1dbg(("ip_rput_dlpi_writer .."));
15458 	ill = (ill_t *)q->q_ptr;
15459 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15460 
15461 	ASSERT(IAM_WRITER_ILL(ill));
15462 
15463 	ipst = ill->ill_ipst;
15464 
15465 	/*
15466 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15467 	 * both are null or non-null. However we can assert that only
15468 	 * after grabbing the ipsq_lock. So we don't make any assertion
15469 	 * here and in other places in the code.
15470 	 */
15471 	ipif = ipsq->ipsq_pending_ipif;
15472 	/*
15473 	 * The current ioctl could have been aborted by the user and a new
15474 	 * ioctl to bring up another ill could have started. We could still
15475 	 * get a response from the driver later.
15476 	 */
15477 	if (ipif != NULL && ipif->ipif_ill != ill)
15478 		ioctl_aborted = B_TRUE;
15479 
15480 	switch (dloa->dl_primitive) {
15481 	case DL_ERROR_ACK:
15482 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15483 		    dlpi_prim_str(dlea->dl_error_primitive)));
15484 
15485 		switch (dlea->dl_error_primitive) {
15486 		case DL_PROMISCON_REQ:
15487 		case DL_PROMISCOFF_REQ:
15488 		case DL_DISABMULTI_REQ:
15489 		case DL_UNBIND_REQ:
15490 		case DL_ATTACH_REQ:
15491 		case DL_INFO_REQ:
15492 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15493 			break;
15494 		case DL_NOTIFY_REQ:
15495 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15496 			log = B_FALSE;
15497 			break;
15498 		case DL_PHYS_ADDR_REQ:
15499 			/*
15500 			 * For IPv6 only, there are two additional
15501 			 * phys_addr_req's sent to the driver to get the
15502 			 * IPv6 token and lla. This allows IP to acquire
15503 			 * the hardware address format for a given interface
15504 			 * without having built in knowledge of the hardware
15505 			 * address. ill_phys_addr_pend keeps track of the last
15506 			 * DL_PAR sent so we know which response we are
15507 			 * dealing with. ill_dlpi_done will update
15508 			 * ill_phys_addr_pend when it sends the next req.
15509 			 * We don't complete the IOCTL until all three DL_PARs
15510 			 * have been attempted, so set *_len to 0 and break.
15511 			 */
15512 			paddrreq = ill->ill_phys_addr_pend;
15513 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15514 			if (paddrreq == DL_IPV6_TOKEN) {
15515 				ill->ill_token_length = 0;
15516 				log = B_FALSE;
15517 				break;
15518 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15519 				ill->ill_nd_lla_len = 0;
15520 				log = B_FALSE;
15521 				break;
15522 			}
15523 			/*
15524 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15525 			 * We presumably have an IOCTL hanging out waiting
15526 			 * for completion. Find it and complete the IOCTL
15527 			 * with the error noted.
15528 			 * However, ill_dl_phys was called on an ill queue
15529 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15530 			 * set. But the ioctl is known to be pending on ill_wq.
15531 			 */
15532 			if (!ill->ill_ifname_pending)
15533 				break;
15534 			ill->ill_ifname_pending = 0;
15535 			if (!ioctl_aborted)
15536 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15537 			if (mp1 != NULL) {
15538 				/*
15539 				 * This operation (SIOCSLIFNAME) must have
15540 				 * happened on the ill. Assert there is no conn
15541 				 */
15542 				ASSERT(connp == NULL);
15543 				q = ill->ill_wq;
15544 			}
15545 			break;
15546 		case DL_BIND_REQ:
15547 			ill_dlpi_done(ill, DL_BIND_REQ);
15548 			if (ill->ill_ifname_pending)
15549 				break;
15550 			/*
15551 			 * Something went wrong with the bind.  We presumably
15552 			 * have an IOCTL hanging out waiting for completion.
15553 			 * Find it, take down the interface that was coming
15554 			 * up, and complete the IOCTL with the error noted.
15555 			 */
15556 			if (!ioctl_aborted)
15557 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15558 			if (mp1 != NULL) {
15559 				/*
15560 				 * This operation (SIOCSLIFFLAGS) must have
15561 				 * happened from a conn.
15562 				 */
15563 				ASSERT(connp != NULL);
15564 				q = CONNP_TO_WQ(connp);
15565 				if (ill->ill_move_in_progress) {
15566 					ILL_CLEAR_MOVE(ill);
15567 				}
15568 				(void) ipif_down(ipif, NULL, NULL);
15569 				/* error is set below the switch */
15570 			}
15571 			break;
15572 		case DL_ENABMULTI_REQ:
15573 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15574 
15575 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15576 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15577 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15578 				ipif_t *ipif;
15579 
15580 				printf("ip: joining multicasts failed (%d)"
15581 				    " on %s - will use link layer "
15582 				    "broadcasts for multicast\n",
15583 				    dlea->dl_errno, ill->ill_name);
15584 
15585 				/*
15586 				 * Set up the multicast mapping alone.
15587 				 * writer, so ok to access ill->ill_ipif
15588 				 * without any lock.
15589 				 */
15590 				ipif = ill->ill_ipif;
15591 				mutex_enter(&ill->ill_phyint->phyint_lock);
15592 				ill->ill_phyint->phyint_flags |=
15593 				    PHYI_MULTI_BCAST;
15594 				mutex_exit(&ill->ill_phyint->phyint_lock);
15595 
15596 				if (!ill->ill_isv6) {
15597 					(void) ipif_arp_setup_multicast(ipif,
15598 					    NULL);
15599 				} else {
15600 					(void) ipif_ndp_setup_multicast(ipif,
15601 					    NULL);
15602 				}
15603 			}
15604 			freemsg(mp);	/* Don't want to pass this up */
15605 			return;
15606 
15607 		case DL_CAPABILITY_REQ:
15608 		case DL_CONTROL_REQ:
15609 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15610 			ill->ill_dlpi_capab_state = IDS_FAILED;
15611 			freemsg(mp);
15612 			return;
15613 		}
15614 		/*
15615 		 * Note the error for IOCTL completion (mp1 is set when
15616 		 * ready to complete ioctl). If ill_ifname_pending_err is
15617 		 * set, an error occured during plumbing (ill_ifname_pending),
15618 		 * so we want to report that error.
15619 		 *
15620 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15621 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15622 		 * expected to get errack'd if the driver doesn't support
15623 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15624 		 * if these error conditions are encountered.
15625 		 */
15626 		if (mp1 != NULL) {
15627 			if (ill->ill_ifname_pending_err != 0)  {
15628 				err = ill->ill_ifname_pending_err;
15629 				ill->ill_ifname_pending_err = 0;
15630 			} else {
15631 				err = dlea->dl_unix_errno ?
15632 				    dlea->dl_unix_errno : ENXIO;
15633 			}
15634 		/*
15635 		 * If we're plumbing an interface and an error hasn't already
15636 		 * been saved, set ill_ifname_pending_err to the error passed
15637 		 * up. Ignore the error if log is B_FALSE (see comment above).
15638 		 */
15639 		} else if (log && ill->ill_ifname_pending &&
15640 		    ill->ill_ifname_pending_err == 0) {
15641 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15642 			    dlea->dl_unix_errno : ENXIO;
15643 		}
15644 
15645 		if (log)
15646 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15647 			    dlea->dl_errno, dlea->dl_unix_errno);
15648 		break;
15649 	case DL_CAPABILITY_ACK:
15650 		/* Call a routine to handle this one. */
15651 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15652 		ill_capability_ack(ill, mp);
15653 
15654 		/*
15655 		 * If the ack is due to renegotiation, we will need to send
15656 		 * a new CAPABILITY_REQ to start the renegotiation.
15657 		 */
15658 		if (ill->ill_capab_reneg) {
15659 			ill->ill_capab_reneg = B_FALSE;
15660 			ill_capability_probe(ill);
15661 		}
15662 		break;
15663 	case DL_CONTROL_ACK:
15664 		/* We treat all of these as "fire and forget" */
15665 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15666 		break;
15667 	case DL_INFO_ACK:
15668 		/* Call a routine to handle this one. */
15669 		ill_dlpi_done(ill, DL_INFO_REQ);
15670 		ip_ll_subnet_defaults(ill, mp);
15671 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15672 		return;
15673 	case DL_BIND_ACK:
15674 		/*
15675 		 * We should have an IOCTL waiting on this unless
15676 		 * sent by ill_dl_phys, in which case just return
15677 		 */
15678 		ill_dlpi_done(ill, DL_BIND_REQ);
15679 		if (ill->ill_ifname_pending)
15680 			break;
15681 
15682 		if (!ioctl_aborted)
15683 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15684 		if (mp1 == NULL)
15685 			break;
15686 		/*
15687 		 * Because mp1 was added by ill_dl_up(), and it always
15688 		 * passes a valid connp, connp must be valid here.
15689 		 */
15690 		ASSERT(connp != NULL);
15691 		q = CONNP_TO_WQ(connp);
15692 
15693 		/*
15694 		 * We are exclusive. So nothing can change even after
15695 		 * we get the pending mp. If need be we can put it back
15696 		 * and restart, as in calling ipif_arp_up()  below.
15697 		 */
15698 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15699 
15700 		mutex_enter(&ill->ill_lock);
15701 
15702 		ill->ill_dl_up = 1;
15703 
15704 		if ((info = ill->ill_nic_event_info) != NULL) {
15705 			ip2dbg(("ip_rput_dlpi_writer: unexpected nic event %d "
15706 			    "attached for %s\n", info->hne_event,
15707 			    ill->ill_name));
15708 			if (info->hne_data != NULL)
15709 				kmem_free(info->hne_data, info->hne_datalen);
15710 			kmem_free(info, sizeof (hook_nic_event_t));
15711 		}
15712 
15713 		info = kmem_alloc(sizeof (hook_nic_event_t), KM_NOSLEEP);
15714 		if (info != NULL) {
15715 			info->hne_nic = ill->ill_phyint->phyint_hook_ifindex;
15716 			info->hne_lif = 0;
15717 			info->hne_event = NE_UP;
15718 			info->hne_data = NULL;
15719 			info->hne_datalen = 0;
15720 			info->hne_family = ill->ill_isv6 ?
15721 			    ipst->ips_ipv6_net_data : ipst->ips_ipv4_net_data;
15722 		} else
15723 			ip2dbg(("ip_rput_dlpi_writer: could not attach UP nic "
15724 			    "event information for %s (ENOMEM)\n",
15725 			    ill->ill_name));
15726 
15727 		ill->ill_nic_event_info = info;
15728 
15729 		mutex_exit(&ill->ill_lock);
15730 
15731 		/*
15732 		 * Now bring up the resolver; when that is complete, we'll
15733 		 * create IREs.  Note that we intentionally mirror what
15734 		 * ipif_up() would have done, because we got here by way of
15735 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15736 		 */
15737 		if (ill->ill_isv6) {
15738 			/*
15739 			 * v6 interfaces.
15740 			 * Unlike ARP which has to do another bind
15741 			 * and attach, once we get here we are
15742 			 * done with NDP. Except in the case of
15743 			 * ILLF_XRESOLV, in which case we send an
15744 			 * AR_INTERFACE_UP to the external resolver.
15745 			 * If all goes well, the ioctl will complete
15746 			 * in ip_rput(). If there's an error, we
15747 			 * complete it here.
15748 			 */
15749 			if ((err = ipif_ndp_up(ipif)) == 0) {
15750 				if (ill->ill_flags & ILLF_XRESOLV) {
15751 					mutex_enter(&connp->conn_lock);
15752 					mutex_enter(&ill->ill_lock);
15753 					success = ipsq_pending_mp_add(
15754 					    connp, ipif, q, mp1, 0);
15755 					mutex_exit(&ill->ill_lock);
15756 					mutex_exit(&connp->conn_lock);
15757 					if (success) {
15758 						err = ipif_resolver_up(ipif,
15759 						    Res_act_initial);
15760 						if (err == EINPROGRESS) {
15761 							freemsg(mp);
15762 							return;
15763 						}
15764 						ASSERT(err != 0);
15765 						mp1 = ipsq_pending_mp_get(ipsq,
15766 						    &connp);
15767 						ASSERT(mp1 != NULL);
15768 					} else {
15769 						/* conn has started closing */
15770 						err = EINTR;
15771 					}
15772 				} else { /* Non XRESOLV interface */
15773 					(void) ipif_resolver_up(ipif,
15774 					    Res_act_initial);
15775 					err = ipif_up_done_v6(ipif);
15776 				}
15777 			}
15778 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
15779 			/*
15780 			 * ARP and other v4 external resolvers.
15781 			 * Leave the pending mblk intact so that
15782 			 * the ioctl completes in ip_rput().
15783 			 */
15784 			mutex_enter(&connp->conn_lock);
15785 			mutex_enter(&ill->ill_lock);
15786 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
15787 			mutex_exit(&ill->ill_lock);
15788 			mutex_exit(&connp->conn_lock);
15789 			if (success) {
15790 				err = ipif_resolver_up(ipif, Res_act_initial);
15791 				if (err == EINPROGRESS) {
15792 					freemsg(mp);
15793 					return;
15794 				}
15795 				ASSERT(err != 0);
15796 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15797 			} else {
15798 				/* The conn has started closing */
15799 				err = EINTR;
15800 			}
15801 		} else {
15802 			/*
15803 			 * This one is complete. Reply to pending ioctl.
15804 			 */
15805 			(void) ipif_resolver_up(ipif, Res_act_initial);
15806 			err = ipif_up_done(ipif);
15807 		}
15808 
15809 		if ((err == 0) && (ill->ill_up_ipifs)) {
15810 			err = ill_up_ipifs(ill, q, mp1);
15811 			if (err == EINPROGRESS) {
15812 				freemsg(mp);
15813 				return;
15814 			}
15815 		}
15816 
15817 		if (ill->ill_up_ipifs) {
15818 			ill_group_cleanup(ill);
15819 		}
15820 
15821 		break;
15822 	case DL_NOTIFY_IND: {
15823 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
15824 		ire_t *ire;
15825 		boolean_t need_ire_walk_v4 = B_FALSE;
15826 		boolean_t need_ire_walk_v6 = B_FALSE;
15827 
15828 		switch (notify->dl_notification) {
15829 		case DL_NOTE_PHYS_ADDR:
15830 			err = ill_set_phys_addr(ill, mp);
15831 			break;
15832 
15833 		case DL_NOTE_FASTPATH_FLUSH:
15834 			ill_fastpath_flush(ill);
15835 			break;
15836 
15837 		case DL_NOTE_SDU_SIZE:
15838 			/*
15839 			 * Change the MTU size of the interface, of all
15840 			 * attached ipif's, and of all relevant ire's.  The
15841 			 * new value's a uint32_t at notify->dl_data.
15842 			 * Mtu change Vs. new ire creation - protocol below.
15843 			 *
15844 			 * a Mark the ipif as IPIF_CHANGING.
15845 			 * b Set the new mtu in the ipif.
15846 			 * c Change the ire_max_frag on all affected ires
15847 			 * d Unmark the IPIF_CHANGING
15848 			 *
15849 			 * To see how the protocol works, assume an interface
15850 			 * route is also being added simultaneously by
15851 			 * ip_rt_add and let 'ipif' be the ipif referenced by
15852 			 * the ire. If the ire is created before step a,
15853 			 * it will be cleaned up by step c. If the ire is
15854 			 * created after step d, it will see the new value of
15855 			 * ipif_mtu. Any attempt to create the ire between
15856 			 * steps a to d will fail because of the IPIF_CHANGING
15857 			 * flag. Note that ire_create() is passed a pointer to
15858 			 * the ipif_mtu, and not the value. During ire_add
15859 			 * under the bucket lock, the ire_max_frag of the
15860 			 * new ire being created is set from the ipif/ire from
15861 			 * which it is being derived.
15862 			 */
15863 			mutex_enter(&ill->ill_lock);
15864 			ill->ill_max_frag = (uint_t)notify->dl_data;
15865 
15866 			/*
15867 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
15868 			 * leave it alone
15869 			 */
15870 			if (ill->ill_mtu_userspecified) {
15871 				mutex_exit(&ill->ill_lock);
15872 				break;
15873 			}
15874 			ill->ill_max_mtu = ill->ill_max_frag;
15875 			if (ill->ill_isv6) {
15876 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
15877 					ill->ill_max_mtu = IPV6_MIN_MTU;
15878 			} else {
15879 				if (ill->ill_max_mtu < IP_MIN_MTU)
15880 					ill->ill_max_mtu = IP_MIN_MTU;
15881 			}
15882 			for (ipif = ill->ill_ipif; ipif != NULL;
15883 			    ipif = ipif->ipif_next) {
15884 				/*
15885 				 * Don't override the mtu if the user
15886 				 * has explicitly set it.
15887 				 */
15888 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
15889 					continue;
15890 				ipif->ipif_mtu = (uint_t)notify->dl_data;
15891 				if (ipif->ipif_isv6)
15892 					ire = ipif_to_ire_v6(ipif);
15893 				else
15894 					ire = ipif_to_ire(ipif);
15895 				if (ire != NULL) {
15896 					ire->ire_max_frag = ipif->ipif_mtu;
15897 					ire_refrele(ire);
15898 				}
15899 				if (ipif->ipif_flags & IPIF_UP) {
15900 					if (ill->ill_isv6)
15901 						need_ire_walk_v6 = B_TRUE;
15902 					else
15903 						need_ire_walk_v4 = B_TRUE;
15904 				}
15905 			}
15906 			mutex_exit(&ill->ill_lock);
15907 			if (need_ire_walk_v4)
15908 				ire_walk_v4(ill_mtu_change, (char *)ill,
15909 				    ALL_ZONES, ipst);
15910 			if (need_ire_walk_v6)
15911 				ire_walk_v6(ill_mtu_change, (char *)ill,
15912 				    ALL_ZONES, ipst);
15913 			break;
15914 		case DL_NOTE_LINK_UP:
15915 		case DL_NOTE_LINK_DOWN: {
15916 			/*
15917 			 * We are writer. ill / phyint / ipsq assocs stable.
15918 			 * The RUNNING flag reflects the state of the link.
15919 			 */
15920 			phyint_t *phyint = ill->ill_phyint;
15921 			uint64_t new_phyint_flags;
15922 			boolean_t changed = B_FALSE;
15923 			boolean_t went_up;
15924 
15925 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
15926 			mutex_enter(&phyint->phyint_lock);
15927 			new_phyint_flags = went_up ?
15928 			    phyint->phyint_flags | PHYI_RUNNING :
15929 			    phyint->phyint_flags & ~PHYI_RUNNING;
15930 			if (new_phyint_flags != phyint->phyint_flags) {
15931 				phyint->phyint_flags = new_phyint_flags;
15932 				changed = B_TRUE;
15933 			}
15934 			mutex_exit(&phyint->phyint_lock);
15935 			/*
15936 			 * ill_restart_dad handles the DAD restart and routing
15937 			 * socket notification logic.
15938 			 */
15939 			if (changed) {
15940 				ill_restart_dad(phyint->phyint_illv4, went_up);
15941 				ill_restart_dad(phyint->phyint_illv6, went_up);
15942 			}
15943 			break;
15944 		}
15945 		case DL_NOTE_PROMISC_ON_PHYS:
15946 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15947 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
15948 			mutex_enter(&ill->ill_lock);
15949 			ill->ill_promisc_on_phys = B_TRUE;
15950 			mutex_exit(&ill->ill_lock);
15951 			break;
15952 		case DL_NOTE_PROMISC_OFF_PHYS:
15953 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15954 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
15955 			mutex_enter(&ill->ill_lock);
15956 			ill->ill_promisc_on_phys = B_FALSE;
15957 			mutex_exit(&ill->ill_lock);
15958 			break;
15959 		case DL_NOTE_CAPAB_RENEG:
15960 			/*
15961 			 * Something changed on the driver side.
15962 			 * It wants us to renegotiate the capabilities
15963 			 * on this ill. One possible cause is the aggregation
15964 			 * interface under us where a port got added or
15965 			 * went away.
15966 			 *
15967 			 * If the capability negotiation is already done
15968 			 * or is in progress, reset the capabilities and
15969 			 * mark the ill's ill_capab_reneg to be B_TRUE,
15970 			 * so that when the ack comes back, we can start
15971 			 * the renegotiation process.
15972 			 *
15973 			 * Note that if ill_capab_reneg is already B_TRUE
15974 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
15975 			 * the capability resetting request has been sent
15976 			 * and the renegotiation has not been started yet;
15977 			 * nothing needs to be done in this case.
15978 			 */
15979 			if (ill->ill_dlpi_capab_state != IDS_UNKNOWN) {
15980 				ill_capability_reset(ill);
15981 				ill->ill_capab_reneg = B_TRUE;
15982 			}
15983 			break;
15984 		default:
15985 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
15986 			    "type 0x%x for DL_NOTIFY_IND\n",
15987 			    notify->dl_notification));
15988 			break;
15989 		}
15990 
15991 		/*
15992 		 * As this is an asynchronous operation, we
15993 		 * should not call ill_dlpi_done
15994 		 */
15995 		break;
15996 	}
15997 	case DL_NOTIFY_ACK: {
15998 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
15999 
16000 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16001 			ill->ill_note_link = 1;
16002 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16003 		break;
16004 	}
16005 	case DL_PHYS_ADDR_ACK: {
16006 		/*
16007 		 * As part of plumbing the interface via SIOCSLIFNAME,
16008 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16009 		 * whose answers we receive here.  As each answer is received,
16010 		 * we call ill_dlpi_done() to dispatch the next request as
16011 		 * we're processing the current one.  Once all answers have
16012 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16013 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16014 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16015 		 * available, but we know the ioctl is pending on ill_wq.)
16016 		 */
16017 		uint_t paddrlen, paddroff;
16018 
16019 		paddrreq = ill->ill_phys_addr_pend;
16020 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16021 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16022 
16023 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16024 		if (paddrreq == DL_IPV6_TOKEN) {
16025 			/*
16026 			 * bcopy to low-order bits of ill_token
16027 			 *
16028 			 * XXX Temporary hack - currently, all known tokens
16029 			 * are 64 bits, so I'll cheat for the moment.
16030 			 */
16031 			bcopy(mp->b_rptr + paddroff,
16032 			    &ill->ill_token.s6_addr32[2], paddrlen);
16033 			ill->ill_token_length = paddrlen;
16034 			break;
16035 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16036 			ASSERT(ill->ill_nd_lla_mp == NULL);
16037 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16038 			mp = NULL;
16039 			break;
16040 		}
16041 
16042 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16043 		ASSERT(ill->ill_phys_addr_mp == NULL);
16044 		if (!ill->ill_ifname_pending)
16045 			break;
16046 		ill->ill_ifname_pending = 0;
16047 		if (!ioctl_aborted)
16048 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16049 		if (mp1 != NULL) {
16050 			ASSERT(connp == NULL);
16051 			q = ill->ill_wq;
16052 		}
16053 		/*
16054 		 * If any error acks received during the plumbing sequence,
16055 		 * ill_ifname_pending_err will be set. Break out and send up
16056 		 * the error to the pending ioctl.
16057 		 */
16058 		if (ill->ill_ifname_pending_err != 0) {
16059 			err = ill->ill_ifname_pending_err;
16060 			ill->ill_ifname_pending_err = 0;
16061 			break;
16062 		}
16063 
16064 		ill->ill_phys_addr_mp = mp;
16065 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16066 		mp = NULL;
16067 
16068 		/*
16069 		 * If paddrlen is zero, the DLPI provider doesn't support
16070 		 * physical addresses.  The other two tests were historical
16071 		 * workarounds for bugs in our former PPP implementation, but
16072 		 * now other things have grown dependencies on them -- e.g.,
16073 		 * the tun module specifies a dl_addr_length of zero in its
16074 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16075 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16076 		 * but only after careful testing ensures that all dependent
16077 		 * broken DLPI providers have been fixed.
16078 		 */
16079 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16080 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16081 			ill->ill_phys_addr = NULL;
16082 		} else if (paddrlen != ill->ill_phys_addr_length) {
16083 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16084 			    paddrlen, ill->ill_phys_addr_length));
16085 			err = EINVAL;
16086 			break;
16087 		}
16088 
16089 		if (ill->ill_nd_lla_mp == NULL) {
16090 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16091 				err = ENOMEM;
16092 				break;
16093 			}
16094 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16095 		}
16096 
16097 		/*
16098 		 * Set the interface token.  If the zeroth interface address
16099 		 * is unspecified, then set it to the link local address.
16100 		 */
16101 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16102 			(void) ill_setdefaulttoken(ill);
16103 
16104 		ASSERT(ill->ill_ipif->ipif_id == 0);
16105 		if (ipif != NULL &&
16106 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16107 			(void) ipif_setlinklocal(ipif);
16108 		}
16109 		break;
16110 	}
16111 	case DL_OK_ACK:
16112 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16113 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
16114 		    dloa->dl_correct_primitive));
16115 		switch (dloa->dl_correct_primitive) {
16116 		case DL_PROMISCON_REQ:
16117 		case DL_PROMISCOFF_REQ:
16118 		case DL_ENABMULTI_REQ:
16119 		case DL_DISABMULTI_REQ:
16120 		case DL_UNBIND_REQ:
16121 		case DL_ATTACH_REQ:
16122 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16123 			break;
16124 		}
16125 		break;
16126 	default:
16127 		break;
16128 	}
16129 
16130 	freemsg(mp);
16131 	if (mp1 != NULL) {
16132 		/*
16133 		 * The operation must complete without EINPROGRESS
16134 		 * since ipsq_pending_mp_get() has removed the mblk
16135 		 * from ipsq_pending_mp.  Otherwise, the operation
16136 		 * will be stuck forever in the ipsq.
16137 		 */
16138 		ASSERT(err != EINPROGRESS);
16139 
16140 		switch (ipsq->ipsq_current_ioctl) {
16141 		case 0:
16142 			ipsq_current_finish(ipsq);
16143 			break;
16144 
16145 		case SIOCLIFADDIF:
16146 		case SIOCSLIFNAME:
16147 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16148 			break;
16149 
16150 		default:
16151 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16152 			break;
16153 		}
16154 	}
16155 }
16156 
16157 /*
16158  * ip_rput_other is called by ip_rput to handle messages modifying the global
16159  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16160  */
16161 /* ARGSUSED */
16162 void
16163 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16164 {
16165 	ill_t		*ill;
16166 	struct iocblk	*iocp;
16167 	mblk_t		*mp1;
16168 	conn_t		*connp = NULL;
16169 
16170 	ip1dbg(("ip_rput_other "));
16171 	ill = (ill_t *)q->q_ptr;
16172 	/*
16173 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16174 	 * in which case ipsq is NULL.
16175 	 */
16176 	if (ipsq != NULL) {
16177 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16178 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16179 	}
16180 
16181 	switch (mp->b_datap->db_type) {
16182 	case M_ERROR:
16183 	case M_HANGUP:
16184 		/*
16185 		 * The device has a problem.  We force the ILL down.  It can
16186 		 * be brought up again manually using SIOCSIFFLAGS (via
16187 		 * ifconfig or equivalent).
16188 		 */
16189 		ASSERT(ipsq != NULL);
16190 		if (mp->b_rptr < mp->b_wptr)
16191 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16192 		if (ill->ill_error == 0)
16193 			ill->ill_error = ENXIO;
16194 		if (!ill_down_start(q, mp))
16195 			return;
16196 		ipif_all_down_tail(ipsq, q, mp, NULL);
16197 		break;
16198 	case M_IOCACK:
16199 		iocp = (struct iocblk *)mp->b_rptr;
16200 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16201 		switch (iocp->ioc_cmd) {
16202 		case SIOCSTUNPARAM:
16203 		case OSIOCSTUNPARAM:
16204 			ASSERT(ipsq != NULL);
16205 			/*
16206 			 * Finish socket ioctl passed through to tun.
16207 			 * We should have an IOCTL waiting on this.
16208 			 */
16209 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16210 			if (ill->ill_isv6) {
16211 				struct iftun_req *ta;
16212 
16213 				/*
16214 				 * if a source or destination is
16215 				 * being set, try and set the link
16216 				 * local address for the tunnel
16217 				 */
16218 				ta = (struct iftun_req *)mp->b_cont->
16219 				    b_cont->b_rptr;
16220 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16221 					ipif_set_tun_llink(ill, ta);
16222 				}
16223 
16224 			}
16225 			if (mp1 != NULL) {
16226 				/*
16227 				 * Now copy back the b_next/b_prev used by
16228 				 * mi code for the mi_copy* functions.
16229 				 * See ip_sioctl_tunparam() for the reason.
16230 				 * Also protect against missing b_cont.
16231 				 */
16232 				if (mp->b_cont != NULL) {
16233 					mp->b_cont->b_next =
16234 					    mp1->b_cont->b_next;
16235 					mp->b_cont->b_prev =
16236 					    mp1->b_cont->b_prev;
16237 				}
16238 				inet_freemsg(mp1);
16239 				ASSERT(connp != NULL);
16240 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16241 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16242 			} else {
16243 				ASSERT(connp == NULL);
16244 				putnext(q, mp);
16245 			}
16246 			break;
16247 		case SIOCGTUNPARAM:
16248 		case OSIOCGTUNPARAM:
16249 			/*
16250 			 * This is really M_IOCDATA from the tunnel driver.
16251 			 * convert back and complete the ioctl.
16252 			 * We should have an IOCTL waiting on this.
16253 			 */
16254 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16255 			if (mp1) {
16256 				/*
16257 				 * Now copy back the b_next/b_prev used by
16258 				 * mi code for the mi_copy* functions.
16259 				 * See ip_sioctl_tunparam() for the reason.
16260 				 * Also protect against missing b_cont.
16261 				 */
16262 				if (mp->b_cont != NULL) {
16263 					mp->b_cont->b_next =
16264 					    mp1->b_cont->b_next;
16265 					mp->b_cont->b_prev =
16266 					    mp1->b_cont->b_prev;
16267 				}
16268 				inet_freemsg(mp1);
16269 				if (iocp->ioc_error == 0)
16270 					mp->b_datap->db_type = M_IOCDATA;
16271 				ASSERT(connp != NULL);
16272 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16273 				    iocp->ioc_error, COPYOUT, NULL);
16274 			} else {
16275 				ASSERT(connp == NULL);
16276 				putnext(q, mp);
16277 			}
16278 			break;
16279 		default:
16280 			break;
16281 		}
16282 		break;
16283 	case M_IOCNAK:
16284 		iocp = (struct iocblk *)mp->b_rptr;
16285 
16286 		switch (iocp->ioc_cmd) {
16287 		int mode;
16288 
16289 		case DL_IOC_HDR_INFO:
16290 			/*
16291 			 * If this was the first attempt turn of the
16292 			 * fastpath probing.
16293 			 */
16294 			mutex_enter(&ill->ill_lock);
16295 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16296 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16297 				mutex_exit(&ill->ill_lock);
16298 				ill_fastpath_nack(ill);
16299 				ip1dbg(("ip_rput: DLPI fastpath off on "
16300 				    "interface %s\n",
16301 				    ill->ill_name));
16302 			} else {
16303 				mutex_exit(&ill->ill_lock);
16304 			}
16305 			freemsg(mp);
16306 			break;
16307 		case SIOCSTUNPARAM:
16308 		case OSIOCSTUNPARAM:
16309 			ASSERT(ipsq != NULL);
16310 			/*
16311 			 * Finish socket ioctl passed through to tun
16312 			 * We should have an IOCTL waiting on this.
16313 			 */
16314 			/* FALLTHRU */
16315 		case SIOCGTUNPARAM:
16316 		case OSIOCGTUNPARAM:
16317 			/*
16318 			 * This is really M_IOCDATA from the tunnel driver.
16319 			 * convert back and complete the ioctl.
16320 			 * We should have an IOCTL waiting on this.
16321 			 */
16322 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16323 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16324 				mp1 = ill_pending_mp_get(ill, &connp,
16325 				    iocp->ioc_id);
16326 				mode = COPYOUT;
16327 				ipsq = NULL;
16328 			} else {
16329 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16330 				mode = NO_COPYOUT;
16331 			}
16332 			if (mp1 != NULL) {
16333 				/*
16334 				 * Now copy back the b_next/b_prev used by
16335 				 * mi code for the mi_copy* functions.
16336 				 * See ip_sioctl_tunparam() for the reason.
16337 				 * Also protect against missing b_cont.
16338 				 */
16339 				if (mp->b_cont != NULL) {
16340 					mp->b_cont->b_next =
16341 					    mp1->b_cont->b_next;
16342 					mp->b_cont->b_prev =
16343 					    mp1->b_cont->b_prev;
16344 				}
16345 				inet_freemsg(mp1);
16346 				if (iocp->ioc_error == 0)
16347 					iocp->ioc_error = EINVAL;
16348 				ASSERT(connp != NULL);
16349 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16350 				    iocp->ioc_error, mode, ipsq);
16351 			} else {
16352 				ASSERT(connp == NULL);
16353 				putnext(q, mp);
16354 			}
16355 			break;
16356 		default:
16357 			break;
16358 		}
16359 	default:
16360 		break;
16361 	}
16362 }
16363 
16364 /*
16365  * NOTE : This function does not ire_refrele the ire argument passed in.
16366  *
16367  * IPQoS notes
16368  * IP policy is invoked twice for a forwarded packet, once on the read side
16369  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16370  * enabled. An additional parameter, in_ill, has been added for this purpose.
16371  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16372  * because ip_mroute drops this information.
16373  *
16374  */
16375 void
16376 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16377 {
16378 	uint32_t	old_pkt_len;
16379 	uint32_t	pkt_len;
16380 	queue_t	*q;
16381 	uint32_t	sum;
16382 #define	rptr	((uchar_t *)ipha)
16383 	uint32_t	max_frag;
16384 	uint32_t	ill_index;
16385 	ill_t		*out_ill;
16386 	mib2_ipIfStatsEntry_t *mibptr;
16387 	ip_stack_t	*ipst = ((ill_t *)(ire->ire_stq->q_ptr))->ill_ipst;
16388 
16389 	/* Get the ill_index of the incoming ILL */
16390 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16391 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16392 
16393 	/* Initiate Read side IPPF processing */
16394 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16395 		ip_process(IPP_FWD_IN, &mp, ill_index);
16396 		if (mp == NULL) {
16397 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16398 			    "during IPPF processing\n"));
16399 			return;
16400 		}
16401 	}
16402 
16403 	/* Adjust the checksum to reflect the ttl decrement. */
16404 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16405 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16406 
16407 	if (ipha->ipha_ttl-- <= 1) {
16408 		if (ip_csum_hdr(ipha)) {
16409 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16410 			goto drop_pkt;
16411 		}
16412 		/*
16413 		 * Note: ire_stq this will be NULL for multicast
16414 		 * datagrams using the long path through arp (the IRE
16415 		 * is not an IRE_CACHE). This should not cause
16416 		 * problems since we don't generate ICMP errors for
16417 		 * multicast packets.
16418 		 */
16419 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16420 		q = ire->ire_stq;
16421 		if (q != NULL) {
16422 			/* Sent by forwarding path, and router is global zone */
16423 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16424 			    GLOBAL_ZONEID, ipst);
16425 		} else
16426 			freemsg(mp);
16427 		return;
16428 	}
16429 
16430 	/*
16431 	 * Don't forward if the interface is down
16432 	 */
16433 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16434 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16435 		ip2dbg(("ip_rput_forward:interface is down\n"));
16436 		goto drop_pkt;
16437 	}
16438 
16439 	/* Get the ill_index of the outgoing ILL */
16440 	out_ill = ire_to_ill(ire);
16441 	ill_index = out_ill->ill_phyint->phyint_ifindex;
16442 
16443 	DTRACE_PROBE4(ip4__forwarding__start,
16444 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16445 
16446 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16447 	    ipst->ips_ipv4firewall_forwarding,
16448 	    in_ill, out_ill, ipha, mp, mp, ipst);
16449 
16450 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16451 
16452 	if (mp == NULL)
16453 		return;
16454 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16455 
16456 	if (is_system_labeled()) {
16457 		mblk_t *mp1;
16458 
16459 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16460 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16461 			goto drop_pkt;
16462 		}
16463 		/* Size may have changed */
16464 		mp = mp1;
16465 		ipha = (ipha_t *)mp->b_rptr;
16466 		pkt_len = ntohs(ipha->ipha_length);
16467 	}
16468 
16469 	/* Check if there are options to update */
16470 	if (!IS_SIMPLE_IPH(ipha)) {
16471 		if (ip_csum_hdr(ipha)) {
16472 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16473 			goto drop_pkt;
16474 		}
16475 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16476 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16477 			return;
16478 		}
16479 
16480 		ipha->ipha_hdr_checksum = 0;
16481 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16482 	}
16483 	max_frag = ire->ire_max_frag;
16484 	if (pkt_len > max_frag) {
16485 		/*
16486 		 * It needs fragging on its way out.  We haven't
16487 		 * verified the header checksum yet.  Since we
16488 		 * are going to put a surely good checksum in the
16489 		 * outgoing header, we have to make sure that it
16490 		 * was good coming in.
16491 		 */
16492 		if (ip_csum_hdr(ipha)) {
16493 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16494 			goto drop_pkt;
16495 		}
16496 		/* Initiate Write side IPPF processing */
16497 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16498 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16499 			if (mp == NULL) {
16500 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16501 				    " during IPPF processing\n"));
16502 				return;
16503 			}
16504 		}
16505 		/*
16506 		 * Handle labeled packet resizing.
16507 		 *
16508 		 * If we have added a label, inform ip_wput_frag() of its
16509 		 * effect on the MTU for ICMP messages.
16510 		 */
16511 		if (pkt_len > old_pkt_len) {
16512 			uint32_t secopt_size;
16513 
16514 			secopt_size = pkt_len - old_pkt_len;
16515 			if (secopt_size < max_frag)
16516 				max_frag -= secopt_size;
16517 		}
16518 
16519 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
16520 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16521 		return;
16522 	}
16523 
16524 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16525 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16526 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16527 	    ipst->ips_ipv4firewall_physical_out,
16528 	    NULL, out_ill, ipha, mp, mp, ipst);
16529 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16530 	if (mp == NULL)
16531 		return;
16532 
16533 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16534 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16535 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16536 	/* ip_xmit_v4 always consumes the packet */
16537 	return;
16538 
16539 drop_pkt:;
16540 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16541 	freemsg(mp);
16542 #undef	rptr
16543 }
16544 
16545 void
16546 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16547 {
16548 	ire_t	*ire;
16549 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16550 
16551 	ASSERT(!ipif->ipif_isv6);
16552 	/*
16553 	 * Find an IRE which matches the destination and the outgoing
16554 	 * queue in the cache table. All we need is an IRE_CACHE which
16555 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16556 	 * then it is enough to have some IRE_CACHE in the group.
16557 	 */
16558 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16559 		dst = ipif->ipif_pp_dst_addr;
16560 
16561 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16562 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR, ipst);
16563 	if (ire == NULL) {
16564 		/*
16565 		 * Mark this packet to make it be delivered to
16566 		 * ip_rput_forward after the new ire has been
16567 		 * created.
16568 		 */
16569 		mp->b_prev = NULL;
16570 		mp->b_next = mp;
16571 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16572 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16573 	} else {
16574 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16575 		IRE_REFRELE(ire);
16576 	}
16577 }
16578 
16579 /* Update any source route, record route or timestamp options */
16580 static int
16581 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16582 {
16583 	ipoptp_t	opts;
16584 	uchar_t		*opt;
16585 	uint8_t		optval;
16586 	uint8_t		optlen;
16587 	ipaddr_t	dst;
16588 	uint32_t	ts;
16589 	ire_t		*dst_ire = NULL;
16590 	ire_t		*tmp_ire = NULL;
16591 	timestruc_t	now;
16592 
16593 	ip2dbg(("ip_rput_forward_options\n"));
16594 	dst = ipha->ipha_dst;
16595 	for (optval = ipoptp_first(&opts, ipha);
16596 	    optval != IPOPT_EOL;
16597 	    optval = ipoptp_next(&opts)) {
16598 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16599 		opt = opts.ipoptp_cur;
16600 		optlen = opts.ipoptp_len;
16601 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16602 		    optval, opts.ipoptp_len));
16603 		switch (optval) {
16604 			uint32_t off;
16605 		case IPOPT_SSRR:
16606 		case IPOPT_LSRR:
16607 			/* Check if adminstratively disabled */
16608 			if (!ipst->ips_ip_forward_src_routed) {
16609 				if (ire->ire_stq != NULL) {
16610 					/*
16611 					 * Sent by forwarding path, and router
16612 					 * is global zone
16613 					 */
16614 					icmp_unreachable(ire->ire_stq, mp,
16615 					    ICMP_SOURCE_ROUTE_FAILED,
16616 					    GLOBAL_ZONEID, ipst);
16617 				} else {
16618 					ip0dbg(("ip_rput_forward_options: "
16619 					    "unable to send unreach\n"));
16620 					freemsg(mp);
16621 				}
16622 				return (-1);
16623 			}
16624 
16625 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16626 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16627 			if (dst_ire == NULL) {
16628 				/*
16629 				 * Must be partial since ip_rput_options
16630 				 * checked for strict.
16631 				 */
16632 				break;
16633 			}
16634 			off = opt[IPOPT_OFFSET];
16635 			off--;
16636 		redo_srr:
16637 			if (optlen < IP_ADDR_LEN ||
16638 			    off > optlen - IP_ADDR_LEN) {
16639 				/* End of source route */
16640 				ip1dbg((
16641 				    "ip_rput_forward_options: end of SR\n"));
16642 				ire_refrele(dst_ire);
16643 				break;
16644 			}
16645 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16646 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16647 			    IP_ADDR_LEN);
16648 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16649 			    ntohl(dst)));
16650 
16651 			/*
16652 			 * Check if our address is present more than
16653 			 * once as consecutive hops in source route.
16654 			 */
16655 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16656 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16657 			if (tmp_ire != NULL) {
16658 				ire_refrele(tmp_ire);
16659 				off += IP_ADDR_LEN;
16660 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16661 				goto redo_srr;
16662 			}
16663 			ipha->ipha_dst = dst;
16664 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16665 			ire_refrele(dst_ire);
16666 			break;
16667 		case IPOPT_RR:
16668 			off = opt[IPOPT_OFFSET];
16669 			off--;
16670 			if (optlen < IP_ADDR_LEN ||
16671 			    off > optlen - IP_ADDR_LEN) {
16672 				/* No more room - ignore */
16673 				ip1dbg((
16674 				    "ip_rput_forward_options: end of RR\n"));
16675 				break;
16676 			}
16677 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16678 			    IP_ADDR_LEN);
16679 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16680 			break;
16681 		case IPOPT_TS:
16682 			/* Insert timestamp if there is room */
16683 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16684 			case IPOPT_TS_TSONLY:
16685 				off = IPOPT_TS_TIMELEN;
16686 				break;
16687 			case IPOPT_TS_PRESPEC:
16688 			case IPOPT_TS_PRESPEC_RFC791:
16689 				/* Verify that the address matched */
16690 				off = opt[IPOPT_OFFSET] - 1;
16691 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16692 				dst_ire = ire_ctable_lookup(dst, 0,
16693 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16694 				    MATCH_IRE_TYPE, ipst);
16695 				if (dst_ire == NULL) {
16696 					/* Not for us */
16697 					break;
16698 				}
16699 				ire_refrele(dst_ire);
16700 				/* FALLTHRU */
16701 			case IPOPT_TS_TSANDADDR:
16702 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16703 				break;
16704 			default:
16705 				/*
16706 				 * ip_*put_options should have already
16707 				 * dropped this packet.
16708 				 */
16709 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16710 				    "unknown IT - bug in ip_rput_options?\n");
16711 				return (0);	/* Keep "lint" happy */
16712 			}
16713 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16714 				/* Increase overflow counter */
16715 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16716 				opt[IPOPT_POS_OV_FLG] =
16717 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16718 				    (off << 4));
16719 				break;
16720 			}
16721 			off = opt[IPOPT_OFFSET] - 1;
16722 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16723 			case IPOPT_TS_PRESPEC:
16724 			case IPOPT_TS_PRESPEC_RFC791:
16725 			case IPOPT_TS_TSANDADDR:
16726 				bcopy(&ire->ire_src_addr,
16727 				    (char *)opt + off, IP_ADDR_LEN);
16728 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16729 				/* FALLTHRU */
16730 			case IPOPT_TS_TSONLY:
16731 				off = opt[IPOPT_OFFSET] - 1;
16732 				/* Compute # of milliseconds since midnight */
16733 				gethrestime(&now);
16734 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16735 				    now.tv_nsec / (NANOSEC / MILLISEC);
16736 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16737 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16738 				break;
16739 			}
16740 			break;
16741 		}
16742 	}
16743 	return (0);
16744 }
16745 
16746 /*
16747  * This is called after processing at least one of AH/ESP headers.
16748  *
16749  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16750  * the actual, physical interface on which the packet was received,
16751  * but, when ip_strict_dst_multihoming is set to 1, could be the
16752  * interface which had the ipha_dst configured when the packet went
16753  * through ip_rput. The ill_index corresponding to the recv_ill
16754  * is saved in ipsec_in_rill_index
16755  *
16756  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
16757  * cannot assume "ire" points to valid data for any IPv6 cases.
16758  */
16759 void
16760 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16761 {
16762 	mblk_t *mp;
16763 	ipaddr_t dst;
16764 	in6_addr_t *v6dstp;
16765 	ipha_t *ipha;
16766 	ip6_t *ip6h;
16767 	ipsec_in_t *ii;
16768 	boolean_t ill_need_rele = B_FALSE;
16769 	boolean_t rill_need_rele = B_FALSE;
16770 	boolean_t ire_need_rele = B_FALSE;
16771 	netstack_t	*ns;
16772 	ip_stack_t	*ipst;
16773 
16774 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16775 	ASSERT(ii->ipsec_in_ill_index != 0);
16776 	ns = ii->ipsec_in_ns;
16777 	ASSERT(ii->ipsec_in_ns != NULL);
16778 	ipst = ns->netstack_ip;
16779 
16780 	mp = ipsec_mp->b_cont;
16781 	ASSERT(mp != NULL);
16782 
16783 
16784 	if (ill == NULL) {
16785 		ASSERT(recv_ill == NULL);
16786 		/*
16787 		 * We need to get the original queue on which ip_rput_local
16788 		 * or ip_rput_data_v6 was called.
16789 		 */
16790 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16791 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
16792 		ill_need_rele = B_TRUE;
16793 
16794 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16795 			recv_ill = ill_lookup_on_ifindex(
16796 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16797 			    NULL, NULL, NULL, NULL, ipst);
16798 			rill_need_rele = B_TRUE;
16799 		} else {
16800 			recv_ill = ill;
16801 		}
16802 
16803 		if ((ill == NULL) || (recv_ill == NULL)) {
16804 			ip0dbg(("ip_fanout_proto_again: interface "
16805 			    "disappeared\n"));
16806 			if (ill != NULL)
16807 				ill_refrele(ill);
16808 			if (recv_ill != NULL)
16809 				ill_refrele(recv_ill);
16810 			freemsg(ipsec_mp);
16811 			return;
16812 		}
16813 	}
16814 
16815 	ASSERT(ill != NULL && recv_ill != NULL);
16816 
16817 	if (mp->b_datap->db_type == M_CTL) {
16818 		/*
16819 		 * AH/ESP is returning the ICMP message after
16820 		 * removing their headers. Fanout again till
16821 		 * it gets to the right protocol.
16822 		 */
16823 		if (ii->ipsec_in_v4) {
16824 			icmph_t *icmph;
16825 			int iph_hdr_length;
16826 			int hdr_length;
16827 
16828 			ipha = (ipha_t *)mp->b_rptr;
16829 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
16830 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
16831 			ipha = (ipha_t *)&icmph[1];
16832 			hdr_length = IPH_HDR_LENGTH(ipha);
16833 			/*
16834 			 * icmp_inbound_error_fanout may need to do pullupmsg.
16835 			 * Reset the type to M_DATA.
16836 			 */
16837 			mp->b_datap->db_type = M_DATA;
16838 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
16839 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
16840 			    B_FALSE, ill, ii->ipsec_in_zoneid);
16841 		} else {
16842 			icmp6_t *icmp6;
16843 			int hdr_length;
16844 
16845 			ip6h = (ip6_t *)mp->b_rptr;
16846 			/* Don't call hdr_length_v6() unless you have to. */
16847 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
16848 				hdr_length = ip_hdr_length_v6(mp, ip6h);
16849 			else
16850 				hdr_length = IPV6_HDR_LEN;
16851 
16852 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
16853 			/*
16854 			 * icmp_inbound_error_fanout_v6 may need to do
16855 			 * pullupmsg.  Reset the type to M_DATA.
16856 			 */
16857 			mp->b_datap->db_type = M_DATA;
16858 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
16859 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
16860 		}
16861 		if (ill_need_rele)
16862 			ill_refrele(ill);
16863 		if (rill_need_rele)
16864 			ill_refrele(recv_ill);
16865 		return;
16866 	}
16867 
16868 	if (ii->ipsec_in_v4) {
16869 		ipha = (ipha_t *)mp->b_rptr;
16870 		dst = ipha->ipha_dst;
16871 		if (CLASSD(dst)) {
16872 			/*
16873 			 * Multicast has to be delivered to all streams.
16874 			 */
16875 			dst = INADDR_BROADCAST;
16876 		}
16877 
16878 		if (ire == NULL) {
16879 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
16880 			    MBLK_GETLABEL(mp), ipst);
16881 			if (ire == NULL) {
16882 				if (ill_need_rele)
16883 					ill_refrele(ill);
16884 				if (rill_need_rele)
16885 					ill_refrele(recv_ill);
16886 				ip1dbg(("ip_fanout_proto_again: "
16887 				    "IRE not found"));
16888 				freemsg(ipsec_mp);
16889 				return;
16890 			}
16891 			ire_need_rele = B_TRUE;
16892 		}
16893 
16894 		switch (ipha->ipha_protocol) {
16895 			case IPPROTO_UDP:
16896 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
16897 				    recv_ill);
16898 				if (ire_need_rele)
16899 					ire_refrele(ire);
16900 				break;
16901 			case IPPROTO_TCP:
16902 				if (!ire_need_rele)
16903 					IRE_REFHOLD(ire);
16904 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
16905 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
16906 				IRE_REFRELE(ire);
16907 				if (mp != NULL)
16908 					squeue_enter_chain(GET_SQUEUE(mp), mp,
16909 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
16910 				break;
16911 			case IPPROTO_SCTP:
16912 				if (!ire_need_rele)
16913 					IRE_REFHOLD(ire);
16914 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
16915 				    ipsec_mp, 0, ill->ill_rq, dst);
16916 				break;
16917 			default:
16918 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
16919 				    recv_ill, B_FALSE);
16920 				if (ire_need_rele)
16921 					ire_refrele(ire);
16922 				break;
16923 		}
16924 	} else {
16925 		uint32_t rput_flags = 0;
16926 
16927 		ip6h = (ip6_t *)mp->b_rptr;
16928 		v6dstp = &ip6h->ip6_dst;
16929 		/*
16930 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
16931 		 * address.
16932 		 *
16933 		 * Currently, we don't store that state in the IPSEC_IN
16934 		 * message, and we may need to.
16935 		 */
16936 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
16937 		    IP6_IN_LLMCAST : 0);
16938 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
16939 		    NULL, NULL);
16940 	}
16941 	if (ill_need_rele)
16942 		ill_refrele(ill);
16943 	if (rill_need_rele)
16944 		ill_refrele(recv_ill);
16945 }
16946 
16947 /*
16948  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
16949  * returns 'true' if there are still fragments left on the queue, in
16950  * which case we restart the timer.
16951  */
16952 void
16953 ill_frag_timer(void *arg)
16954 {
16955 	ill_t	*ill = (ill_t *)arg;
16956 	boolean_t frag_pending;
16957 	ip_stack_t	*ipst = ill->ill_ipst;
16958 
16959 	mutex_enter(&ill->ill_lock);
16960 	ASSERT(!ill->ill_fragtimer_executing);
16961 	if (ill->ill_state_flags & ILL_CONDEMNED) {
16962 		ill->ill_frag_timer_id = 0;
16963 		mutex_exit(&ill->ill_lock);
16964 		return;
16965 	}
16966 	ill->ill_fragtimer_executing = 1;
16967 	mutex_exit(&ill->ill_lock);
16968 
16969 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
16970 
16971 	/*
16972 	 * Restart the timer, if we have fragments pending or if someone
16973 	 * wanted us to be scheduled again.
16974 	 */
16975 	mutex_enter(&ill->ill_lock);
16976 	ill->ill_fragtimer_executing = 0;
16977 	ill->ill_frag_timer_id = 0;
16978 	if (frag_pending || ill->ill_fragtimer_needrestart)
16979 		ill_frag_timer_start(ill);
16980 	mutex_exit(&ill->ill_lock);
16981 }
16982 
16983 void
16984 ill_frag_timer_start(ill_t *ill)
16985 {
16986 	ip_stack_t	*ipst = ill->ill_ipst;
16987 
16988 	ASSERT(MUTEX_HELD(&ill->ill_lock));
16989 
16990 	/* If the ill is closing or opening don't proceed */
16991 	if (ill->ill_state_flags & ILL_CONDEMNED)
16992 		return;
16993 
16994 	if (ill->ill_fragtimer_executing) {
16995 		/*
16996 		 * ill_frag_timer is currently executing. Just record the
16997 		 * the fact that we want the timer to be restarted.
16998 		 * ill_frag_timer will post a timeout before it returns,
16999 		 * ensuring it will be called again.
17000 		 */
17001 		ill->ill_fragtimer_needrestart = 1;
17002 		return;
17003 	}
17004 
17005 	if (ill->ill_frag_timer_id == 0) {
17006 		/*
17007 		 * The timer is neither running nor is the timeout handler
17008 		 * executing. Post a timeout so that ill_frag_timer will be
17009 		 * called
17010 		 */
17011 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17012 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
17013 		ill->ill_fragtimer_needrestart = 0;
17014 	}
17015 }
17016 
17017 /*
17018  * This routine is needed for loopback when forwarding multicasts.
17019  *
17020  * IPQoS Notes:
17021  * IPPF processing is done in fanout routines.
17022  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17023  * processing for IPsec packets is done when it comes back in clear.
17024  * NOTE : The callers of this function need to do the ire_refrele for the
17025  *	  ire that is being passed in.
17026  */
17027 void
17028 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17029     ill_t *recv_ill, boolean_t esp_in_udp_packet)
17030 {
17031 	ill_t	*ill = (ill_t *)q->q_ptr;
17032 	uint32_t	sum;
17033 	uint32_t	u1;
17034 	uint32_t	u2;
17035 	int		hdr_length;
17036 	boolean_t	mctl_present;
17037 	mblk_t		*first_mp = mp;
17038 	mblk_t		*hada_mp = NULL;
17039 	ipha_t		*inner_ipha;
17040 	ip_stack_t	*ipst;
17041 
17042 	ASSERT(recv_ill != NULL);
17043 	ipst = recv_ill->ill_ipst;
17044 
17045 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17046 	    "ip_rput_locl_start: q %p", q);
17047 
17048 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17049 	ASSERT(ill != NULL);
17050 
17051 
17052 #define	rptr	((uchar_t *)ipha)
17053 #define	iphs	((uint16_t *)ipha)
17054 
17055 	/*
17056 	 * no UDP or TCP packet should come here anymore.
17057 	 */
17058 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
17059 	    ipha->ipha_protocol != IPPROTO_UDP);
17060 
17061 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17062 	if (mctl_present &&
17063 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17064 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17065 
17066 		/*
17067 		 * It's an IPsec accelerated packet.
17068 		 * Keep a pointer to the data attributes around until
17069 		 * we allocate the ipsec_info_t.
17070 		 */
17071 		IPSECHW_DEBUG(IPSECHW_PKT,
17072 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17073 		hada_mp = first_mp;
17074 		hada_mp->b_cont = NULL;
17075 		/*
17076 		 * Since it is accelerated, it comes directly from
17077 		 * the ill and the data attributes is followed by
17078 		 * the packet data.
17079 		 */
17080 		ASSERT(mp->b_datap->db_type != M_CTL);
17081 		first_mp = mp;
17082 		mctl_present = B_FALSE;
17083 	}
17084 
17085 	/*
17086 	 * IF M_CTL is not present, then ipsec_in_is_secure
17087 	 * should return B_TRUE. There is a case where loopback
17088 	 * packets has an M_CTL in the front with all the
17089 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17090 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17091 	 * packets never comes here, it is safe to ASSERT the
17092 	 * following.
17093 	 */
17094 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17095 
17096 	/*
17097 	 * Also, we should never have an mctl_present if this is an
17098 	 * ESP-in-UDP packet.
17099 	 */
17100 	ASSERT(!mctl_present || !esp_in_udp_packet);
17101 
17102 
17103 	/* u1 is # words of IP options */
17104 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17105 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17106 
17107 	if (u1 || (!esp_in_udp_packet && !mctl_present)) {
17108 		if (u1) {
17109 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17110 				if (hada_mp != NULL)
17111 					freemsg(hada_mp);
17112 				return;
17113 			}
17114 		} else {
17115 			/* Check the IP header checksum.  */
17116 #define	uph	((uint16_t *)ipha)
17117 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17118 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17119 #undef  uph
17120 			/* finish doing IP checksum */
17121 			sum = (sum & 0xFFFF) + (sum >> 16);
17122 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17123 			if (sum && sum != 0xFFFF) {
17124 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17125 				goto drop_pkt;
17126 			}
17127 		}
17128 	}
17129 
17130 	/*
17131 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17132 	 * might be called more than once for secure packets, count only
17133 	 * the first time.
17134 	 */
17135 	if (!mctl_present) {
17136 		UPDATE_IB_PKT_COUNT(ire);
17137 		ire->ire_last_used_time = lbolt;
17138 	}
17139 
17140 	/* Check for fragmentation offset. */
17141 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17142 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17143 	if (u1) {
17144 		/*
17145 		 * We re-assemble fragments before we do the AH/ESP
17146 		 * processing. Thus, M_CTL should not be present
17147 		 * while we are re-assembling.
17148 		 */
17149 		ASSERT(!mctl_present);
17150 		ASSERT(first_mp == mp);
17151 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
17152 			return;
17153 		}
17154 		/*
17155 		 * Make sure that first_mp points back to mp as
17156 		 * the mp we came in with could have changed in
17157 		 * ip_rput_fragment().
17158 		 */
17159 		ipha = (ipha_t *)mp->b_rptr;
17160 		first_mp = mp;
17161 	}
17162 
17163 	/*
17164 	 * Clear hardware checksumming flag as it is currently only
17165 	 * used by TCP and UDP.
17166 	 */
17167 	DB_CKSUMFLAGS(mp) = 0;
17168 
17169 	/* Now we have a complete datagram, destined for this machine. */
17170 	u1 = IPH_HDR_LENGTH(ipha);
17171 	switch (ipha->ipha_protocol) {
17172 	case IPPROTO_ICMP: {
17173 		ire_t		*ire_zone;
17174 		ilm_t		*ilm;
17175 		mblk_t		*mp1;
17176 		zoneid_t	last_zoneid;
17177 
17178 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17179 			ASSERT(ire->ire_type == IRE_BROADCAST);
17180 			/*
17181 			 * In the multicast case, applications may have joined
17182 			 * the group from different zones, so we need to deliver
17183 			 * the packet to each of them. Loop through the
17184 			 * multicast memberships structures (ilm) on the receive
17185 			 * ill and send a copy of the packet up each matching
17186 			 * one. However, we don't do this for multicasts sent on
17187 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17188 			 * they must stay in the sender's zone.
17189 			 *
17190 			 * ilm_add_v6() ensures that ilms in the same zone are
17191 			 * contiguous in the ill_ilm list. We use this property
17192 			 * to avoid sending duplicates needed when two
17193 			 * applications in the same zone join the same group on
17194 			 * different logical interfaces: we ignore the ilm if
17195 			 * its zoneid is the same as the last matching one.
17196 			 * In addition, the sending of the packet for
17197 			 * ire_zoneid is delayed until all of the other ilms
17198 			 * have been exhausted.
17199 			 */
17200 			last_zoneid = -1;
17201 			ILM_WALKER_HOLD(recv_ill);
17202 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17203 			    ilm = ilm->ilm_next) {
17204 				if ((ilm->ilm_flags & ILM_DELETED) ||
17205 				    ipha->ipha_dst != ilm->ilm_addr ||
17206 				    ilm->ilm_zoneid == last_zoneid ||
17207 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17208 				    ilm->ilm_zoneid == ALL_ZONES ||
17209 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17210 					continue;
17211 				mp1 = ip_copymsg(first_mp);
17212 				if (mp1 == NULL)
17213 					continue;
17214 				icmp_inbound(q, mp1, B_TRUE, ill,
17215 				    0, sum, mctl_present, B_TRUE,
17216 				    recv_ill, ilm->ilm_zoneid);
17217 				last_zoneid = ilm->ilm_zoneid;
17218 			}
17219 			ILM_WALKER_RELE(recv_ill);
17220 		} else if (ire->ire_type == IRE_BROADCAST) {
17221 			/*
17222 			 * In the broadcast case, there may be many zones
17223 			 * which need a copy of the packet delivered to them.
17224 			 * There is one IRE_BROADCAST per broadcast address
17225 			 * and per zone; we walk those using a helper function.
17226 			 * In addition, the sending of the packet for ire is
17227 			 * delayed until all of the other ires have been
17228 			 * processed.
17229 			 */
17230 			IRB_REFHOLD(ire->ire_bucket);
17231 			ire_zone = NULL;
17232 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17233 			    ire)) != NULL) {
17234 				mp1 = ip_copymsg(first_mp);
17235 				if (mp1 == NULL)
17236 					continue;
17237 
17238 				UPDATE_IB_PKT_COUNT(ire_zone);
17239 				ire_zone->ire_last_used_time = lbolt;
17240 				icmp_inbound(q, mp1, B_TRUE, ill,
17241 				    0, sum, mctl_present, B_TRUE,
17242 				    recv_ill, ire_zone->ire_zoneid);
17243 			}
17244 			IRB_REFRELE(ire->ire_bucket);
17245 		}
17246 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17247 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17248 		    ire->ire_zoneid);
17249 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17250 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17251 		return;
17252 	}
17253 	case IPPROTO_IGMP:
17254 		/*
17255 		 * If we are not willing to accept IGMP packets in clear,
17256 		 * then check with global policy.
17257 		 */
17258 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17259 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17260 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17261 			if (first_mp == NULL)
17262 				return;
17263 		}
17264 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17265 			freemsg(first_mp);
17266 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17267 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17268 			return;
17269 		}
17270 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17271 			/* Bad packet - discarded by igmp_input */
17272 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17273 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17274 			if (mctl_present)
17275 				freeb(first_mp);
17276 			return;
17277 		}
17278 		/*
17279 		 * igmp_input() may have returned the pulled up message.
17280 		 * So first_mp and ipha need to be reinitialized.
17281 		 */
17282 		ipha = (ipha_t *)mp->b_rptr;
17283 		if (mctl_present)
17284 			first_mp->b_cont = mp;
17285 		else
17286 			first_mp = mp;
17287 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17288 		    connf_head != NULL) {
17289 			/* No user-level listener for IGMP packets */
17290 			goto drop_pkt;
17291 		}
17292 		/* deliver to local raw users */
17293 		break;
17294 	case IPPROTO_PIM:
17295 		/*
17296 		 * If we are not willing to accept PIM packets in clear,
17297 		 * then check with global policy.
17298 		 */
17299 		if (ipst->ips_pim_accept_clear_messages == 0) {
17300 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17301 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17302 			if (first_mp == NULL)
17303 				return;
17304 		}
17305 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17306 			freemsg(first_mp);
17307 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17308 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17309 			return;
17310 		}
17311 		if (pim_input(q, mp, ill) != 0) {
17312 			/* Bad packet - discarded by pim_input */
17313 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17314 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17315 			if (mctl_present)
17316 				freeb(first_mp);
17317 			return;
17318 		}
17319 
17320 		/*
17321 		 * pim_input() may have pulled up the message so ipha needs to
17322 		 * be reinitialized.
17323 		 */
17324 		ipha = (ipha_t *)mp->b_rptr;
17325 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17326 		    connf_head != NULL) {
17327 			/* No user-level listener for PIM packets */
17328 			goto drop_pkt;
17329 		}
17330 		/* deliver to local raw users */
17331 		break;
17332 	case IPPROTO_ENCAP:
17333 		/*
17334 		 * Handle self-encapsulated packets (IP-in-IP where
17335 		 * the inner addresses == the outer addresses).
17336 		 */
17337 		hdr_length = IPH_HDR_LENGTH(ipha);
17338 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17339 		    mp->b_wptr) {
17340 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17341 			    sizeof (ipha_t) - mp->b_rptr)) {
17342 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17343 				freemsg(first_mp);
17344 				return;
17345 			}
17346 			ipha = (ipha_t *)mp->b_rptr;
17347 		}
17348 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17349 		/*
17350 		 * Check the sanity of the inner IP header.
17351 		 */
17352 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17353 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17354 			freemsg(first_mp);
17355 			return;
17356 		}
17357 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17358 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17359 			freemsg(first_mp);
17360 			return;
17361 		}
17362 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17363 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17364 			ipsec_in_t *ii;
17365 
17366 			/*
17367 			 * Self-encapsulated tunnel packet. Remove
17368 			 * the outer IP header and fanout again.
17369 			 * We also need to make sure that the inner
17370 			 * header is pulled up until options.
17371 			 */
17372 			mp->b_rptr = (uchar_t *)inner_ipha;
17373 			ipha = inner_ipha;
17374 			hdr_length = IPH_HDR_LENGTH(ipha);
17375 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17376 				if (!pullupmsg(mp, (uchar_t *)ipha +
17377 				    + hdr_length - mp->b_rptr)) {
17378 					freemsg(first_mp);
17379 					return;
17380 				}
17381 				ipha = (ipha_t *)mp->b_rptr;
17382 			}
17383 			if (!mctl_present) {
17384 				ASSERT(first_mp == mp);
17385 				/*
17386 				 * This means that somebody is sending
17387 				 * Self-encapsualted packets without AH/ESP.
17388 				 * If AH/ESP was present, we would have already
17389 				 * allocated the first_mp.
17390 				 */
17391 				first_mp = ipsec_in_alloc(B_TRUE,
17392 				    ipst->ips_netstack);
17393 				if (first_mp == NULL) {
17394 					ip1dbg(("ip_proto_input: IPSEC_IN "
17395 					    "allocation failure.\n"));
17396 					BUMP_MIB(ill->ill_ip_mib,
17397 					    ipIfStatsInDiscards);
17398 					freemsg(mp);
17399 					return;
17400 				}
17401 				first_mp->b_cont = mp;
17402 			}
17403 			/*
17404 			 * We generally store the ill_index if we need to
17405 			 * do IPsec processing as we lose the ill queue when
17406 			 * we come back. But in this case, we never should
17407 			 * have to store the ill_index here as it should have
17408 			 * been stored previously when we processed the
17409 			 * AH/ESP header in this routine or for non-ipsec
17410 			 * cases, we still have the queue. But for some bad
17411 			 * packets from the wire, we can get to IPsec after
17412 			 * this and we better store the index for that case.
17413 			 */
17414 			ill = (ill_t *)q->q_ptr;
17415 			ii = (ipsec_in_t *)first_mp->b_rptr;
17416 			ii->ipsec_in_ill_index =
17417 			    ill->ill_phyint->phyint_ifindex;
17418 			ii->ipsec_in_rill_index =
17419 			    recv_ill->ill_phyint->phyint_ifindex;
17420 			if (ii->ipsec_in_decaps) {
17421 				/*
17422 				 * This packet is self-encapsulated multiple
17423 				 * times. We don't want to recurse infinitely.
17424 				 * To keep it simple, drop the packet.
17425 				 */
17426 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17427 				freemsg(first_mp);
17428 				return;
17429 			}
17430 			ii->ipsec_in_decaps = B_TRUE;
17431 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17432 			    ire);
17433 			return;
17434 		}
17435 		break;
17436 	case IPPROTO_AH:
17437 	case IPPROTO_ESP: {
17438 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17439 
17440 		/*
17441 		 * Fast path for AH/ESP. If this is the first time
17442 		 * we are sending a datagram to AH/ESP, allocate
17443 		 * a IPSEC_IN message and prepend it. Otherwise,
17444 		 * just fanout.
17445 		 */
17446 
17447 		int ipsec_rc;
17448 		ipsec_in_t *ii;
17449 		netstack_t *ns = ipst->ips_netstack;
17450 
17451 		IP_STAT(ipst, ipsec_proto_ahesp);
17452 		if (!mctl_present) {
17453 			ASSERT(first_mp == mp);
17454 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17455 			if (first_mp == NULL) {
17456 				ip1dbg(("ip_proto_input: IPSEC_IN "
17457 				    "allocation failure.\n"));
17458 				freemsg(hada_mp); /* okay ifnull */
17459 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17460 				freemsg(mp);
17461 				return;
17462 			}
17463 			/*
17464 			 * Store the ill_index so that when we come back
17465 			 * from IPsec we ride on the same queue.
17466 			 */
17467 			ill = (ill_t *)q->q_ptr;
17468 			ii = (ipsec_in_t *)first_mp->b_rptr;
17469 			ii->ipsec_in_ill_index =
17470 			    ill->ill_phyint->phyint_ifindex;
17471 			ii->ipsec_in_rill_index =
17472 			    recv_ill->ill_phyint->phyint_ifindex;
17473 			first_mp->b_cont = mp;
17474 			/*
17475 			 * Cache hardware acceleration info.
17476 			 */
17477 			if (hada_mp != NULL) {
17478 				IPSECHW_DEBUG(IPSECHW_PKT,
17479 				    ("ip_rput_local: caching data attr.\n"));
17480 				ii->ipsec_in_accelerated = B_TRUE;
17481 				ii->ipsec_in_da = hada_mp;
17482 				hada_mp = NULL;
17483 			}
17484 		} else {
17485 			ii = (ipsec_in_t *)first_mp->b_rptr;
17486 		}
17487 
17488 		if (!ipsec_loaded(ipss)) {
17489 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17490 			    ire->ire_zoneid, ipst);
17491 			return;
17492 		}
17493 
17494 		ns = ipst->ips_netstack;
17495 		/* select inbound SA and have IPsec process the pkt */
17496 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17497 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17498 			boolean_t esp_in_udp_sa;
17499 			if (esph == NULL)
17500 				return;
17501 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17502 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17503 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
17504 			    IPSA_F_NATT) != 0);
17505 			/*
17506 			 * The following is a fancy, but quick, way of saying:
17507 			 * ESP-in-UDP SA and Raw ESP packet --> drop
17508 			 *    OR
17509 			 * ESP SA and ESP-in-UDP packet --> drop
17510 			 */
17511 			if (esp_in_udp_sa != esp_in_udp_packet) {
17512 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17513 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
17514 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
17515 				    &ns->netstack_ipsec->ipsec_dropper);
17516 				return;
17517 			}
17518 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17519 			    first_mp, esph);
17520 		} else {
17521 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17522 			if (ah == NULL)
17523 				return;
17524 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17525 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17526 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17527 			    first_mp, ah);
17528 		}
17529 
17530 		switch (ipsec_rc) {
17531 		case IPSEC_STATUS_SUCCESS:
17532 			break;
17533 		case IPSEC_STATUS_FAILED:
17534 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17535 			/* FALLTHRU */
17536 		case IPSEC_STATUS_PENDING:
17537 			return;
17538 		}
17539 		/* we're done with IPsec processing, send it up */
17540 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17541 		return;
17542 	}
17543 	default:
17544 		break;
17545 	}
17546 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17547 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17548 		    ire->ire_zoneid));
17549 		goto drop_pkt;
17550 	}
17551 	/*
17552 	 * Handle protocols with which IP is less intimate.  There
17553 	 * can be more than one stream bound to a particular
17554 	 * protocol.  When this is the case, each one gets a copy
17555 	 * of any incoming packets.
17556 	 */
17557 	ip_fanout_proto(q, first_mp, ill, ipha,
17558 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17559 	    B_TRUE, recv_ill, ire->ire_zoneid);
17560 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17561 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17562 	return;
17563 
17564 drop_pkt:
17565 	freemsg(first_mp);
17566 	if (hada_mp != NULL)
17567 		freeb(hada_mp);
17568 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17569 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17570 #undef	rptr
17571 #undef  iphs
17572 
17573 }
17574 
17575 /*
17576  * Update any source route, record route or timestamp options.
17577  * Check that we are at end of strict source route.
17578  * The options have already been checked for sanity in ip_rput_options().
17579  */
17580 static boolean_t
17581 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17582     ip_stack_t *ipst)
17583 {
17584 	ipoptp_t	opts;
17585 	uchar_t		*opt;
17586 	uint8_t		optval;
17587 	uint8_t		optlen;
17588 	ipaddr_t	dst;
17589 	uint32_t	ts;
17590 	ire_t		*dst_ire;
17591 	timestruc_t	now;
17592 	zoneid_t	zoneid;
17593 	ill_t		*ill;
17594 
17595 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17596 
17597 	ip2dbg(("ip_rput_local_options\n"));
17598 
17599 	for (optval = ipoptp_first(&opts, ipha);
17600 	    optval != IPOPT_EOL;
17601 	    optval = ipoptp_next(&opts)) {
17602 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17603 		opt = opts.ipoptp_cur;
17604 		optlen = opts.ipoptp_len;
17605 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17606 		    optval, optlen));
17607 		switch (optval) {
17608 			uint32_t off;
17609 		case IPOPT_SSRR:
17610 		case IPOPT_LSRR:
17611 			off = opt[IPOPT_OFFSET];
17612 			off--;
17613 			if (optlen < IP_ADDR_LEN ||
17614 			    off > optlen - IP_ADDR_LEN) {
17615 				/* End of source route */
17616 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17617 				break;
17618 			}
17619 			/*
17620 			 * This will only happen if two consecutive entries
17621 			 * in the source route contains our address or if
17622 			 * it is a packet with a loose source route which
17623 			 * reaches us before consuming the whole source route
17624 			 */
17625 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17626 			if (optval == IPOPT_SSRR) {
17627 				goto bad_src_route;
17628 			}
17629 			/*
17630 			 * Hack: instead of dropping the packet truncate the
17631 			 * source route to what has been used by filling the
17632 			 * rest with IPOPT_NOP.
17633 			 */
17634 			opt[IPOPT_OLEN] = (uint8_t)off;
17635 			while (off < optlen) {
17636 				opt[off++] = IPOPT_NOP;
17637 			}
17638 			break;
17639 		case IPOPT_RR:
17640 			off = opt[IPOPT_OFFSET];
17641 			off--;
17642 			if (optlen < IP_ADDR_LEN ||
17643 			    off > optlen - IP_ADDR_LEN) {
17644 				/* No more room - ignore */
17645 				ip1dbg((
17646 				    "ip_rput_local_options: end of RR\n"));
17647 				break;
17648 			}
17649 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17650 			    IP_ADDR_LEN);
17651 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17652 			break;
17653 		case IPOPT_TS:
17654 			/* Insert timestamp if there is romm */
17655 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17656 			case IPOPT_TS_TSONLY:
17657 				off = IPOPT_TS_TIMELEN;
17658 				break;
17659 			case IPOPT_TS_PRESPEC:
17660 			case IPOPT_TS_PRESPEC_RFC791:
17661 				/* Verify that the address matched */
17662 				off = opt[IPOPT_OFFSET] - 1;
17663 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17664 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17665 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
17666 				    ipst);
17667 				if (dst_ire == NULL) {
17668 					/* Not for us */
17669 					break;
17670 				}
17671 				ire_refrele(dst_ire);
17672 				/* FALLTHRU */
17673 			case IPOPT_TS_TSANDADDR:
17674 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17675 				break;
17676 			default:
17677 				/*
17678 				 * ip_*put_options should have already
17679 				 * dropped this packet.
17680 				 */
17681 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17682 				    "unknown IT - bug in ip_rput_options?\n");
17683 				return (B_TRUE);	/* Keep "lint" happy */
17684 			}
17685 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17686 				/* Increase overflow counter */
17687 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17688 				opt[IPOPT_POS_OV_FLG] =
17689 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17690 				    (off << 4));
17691 				break;
17692 			}
17693 			off = opt[IPOPT_OFFSET] - 1;
17694 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17695 			case IPOPT_TS_PRESPEC:
17696 			case IPOPT_TS_PRESPEC_RFC791:
17697 			case IPOPT_TS_TSANDADDR:
17698 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17699 				    IP_ADDR_LEN);
17700 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17701 				/* FALLTHRU */
17702 			case IPOPT_TS_TSONLY:
17703 				off = opt[IPOPT_OFFSET] - 1;
17704 				/* Compute # of milliseconds since midnight */
17705 				gethrestime(&now);
17706 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17707 				    now.tv_nsec / (NANOSEC / MILLISEC);
17708 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17709 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17710 				break;
17711 			}
17712 			break;
17713 		}
17714 	}
17715 	return (B_TRUE);
17716 
17717 bad_src_route:
17718 	q = WR(q);
17719 	if (q->q_next != NULL)
17720 		ill = q->q_ptr;
17721 	else
17722 		ill = NULL;
17723 
17724 	/* make sure we clear any indication of a hardware checksum */
17725 	DB_CKSUMFLAGS(mp) = 0;
17726 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
17727 	if (zoneid == ALL_ZONES)
17728 		freemsg(mp);
17729 	else
17730 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17731 	return (B_FALSE);
17732 
17733 }
17734 
17735 /*
17736  * Process IP options in an inbound packet.  If an option affects the
17737  * effective destination address, return the next hop address via dstp.
17738  * Returns -1 if something fails in which case an ICMP error has been sent
17739  * and mp freed.
17740  */
17741 static int
17742 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
17743     ip_stack_t *ipst)
17744 {
17745 	ipoptp_t	opts;
17746 	uchar_t		*opt;
17747 	uint8_t		optval;
17748 	uint8_t		optlen;
17749 	ipaddr_t	dst;
17750 	intptr_t	code = 0;
17751 	ire_t		*ire = NULL;
17752 	zoneid_t	zoneid;
17753 	ill_t		*ill;
17754 
17755 	ip2dbg(("ip_rput_options\n"));
17756 	dst = ipha->ipha_dst;
17757 	for (optval = ipoptp_first(&opts, ipha);
17758 	    optval != IPOPT_EOL;
17759 	    optval = ipoptp_next(&opts)) {
17760 		opt = opts.ipoptp_cur;
17761 		optlen = opts.ipoptp_len;
17762 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17763 		    optval, optlen));
17764 		/*
17765 		 * Note: we need to verify the checksum before we
17766 		 * modify anything thus this routine only extracts the next
17767 		 * hop dst from any source route.
17768 		 */
17769 		switch (optval) {
17770 			uint32_t off;
17771 		case IPOPT_SSRR:
17772 		case IPOPT_LSRR:
17773 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17774 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17775 			if (ire == NULL) {
17776 				if (optval == IPOPT_SSRR) {
17777 					ip1dbg(("ip_rput_options: not next"
17778 					    " strict source route 0x%x\n",
17779 					    ntohl(dst)));
17780 					code = (char *)&ipha->ipha_dst -
17781 					    (char *)ipha;
17782 					goto param_prob; /* RouterReq's */
17783 				}
17784 				ip2dbg(("ip_rput_options: "
17785 				    "not next source route 0x%x\n",
17786 				    ntohl(dst)));
17787 				break;
17788 			}
17789 			ire_refrele(ire);
17790 
17791 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17792 				ip1dbg((
17793 				    "ip_rput_options: bad option offset\n"));
17794 				code = (char *)&opt[IPOPT_OLEN] -
17795 				    (char *)ipha;
17796 				goto param_prob;
17797 			}
17798 			off = opt[IPOPT_OFFSET];
17799 			off--;
17800 		redo_srr:
17801 			if (optlen < IP_ADDR_LEN ||
17802 			    off > optlen - IP_ADDR_LEN) {
17803 				/* End of source route */
17804 				ip1dbg(("ip_rput_options: end of SR\n"));
17805 				break;
17806 			}
17807 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17808 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
17809 			    ntohl(dst)));
17810 
17811 			/*
17812 			 * Check if our address is present more than
17813 			 * once as consecutive hops in source route.
17814 			 * XXX verify per-interface ip_forwarding
17815 			 * for source route?
17816 			 */
17817 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17818 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17819 
17820 			if (ire != NULL) {
17821 				ire_refrele(ire);
17822 				off += IP_ADDR_LEN;
17823 				goto redo_srr;
17824 			}
17825 
17826 			if (dst == htonl(INADDR_LOOPBACK)) {
17827 				ip1dbg(("ip_rput_options: loopback addr in "
17828 				    "source route!\n"));
17829 				goto bad_src_route;
17830 			}
17831 			/*
17832 			 * For strict: verify that dst is directly
17833 			 * reachable.
17834 			 */
17835 			if (optval == IPOPT_SSRR) {
17836 				ire = ire_ftable_lookup(dst, 0, 0,
17837 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
17838 				    MBLK_GETLABEL(mp),
17839 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
17840 				if (ire == NULL) {
17841 					ip1dbg(("ip_rput_options: SSRR not "
17842 					    "directly reachable: 0x%x\n",
17843 					    ntohl(dst)));
17844 					goto bad_src_route;
17845 				}
17846 				ire_refrele(ire);
17847 			}
17848 			/*
17849 			 * Defer update of the offset and the record route
17850 			 * until the packet is forwarded.
17851 			 */
17852 			break;
17853 		case IPOPT_RR:
17854 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17855 				ip1dbg((
17856 				    "ip_rput_options: bad option offset\n"));
17857 				code = (char *)&opt[IPOPT_OLEN] -
17858 				    (char *)ipha;
17859 				goto param_prob;
17860 			}
17861 			break;
17862 		case IPOPT_TS:
17863 			/*
17864 			 * Verify that length >= 5 and that there is either
17865 			 * room for another timestamp or that the overflow
17866 			 * counter is not maxed out.
17867 			 */
17868 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
17869 			if (optlen < IPOPT_MINLEN_IT) {
17870 				goto param_prob;
17871 			}
17872 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17873 				ip1dbg((
17874 				    "ip_rput_options: bad option offset\n"));
17875 				code = (char *)&opt[IPOPT_OFFSET] -
17876 				    (char *)ipha;
17877 				goto param_prob;
17878 			}
17879 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17880 			case IPOPT_TS_TSONLY:
17881 				off = IPOPT_TS_TIMELEN;
17882 				break;
17883 			case IPOPT_TS_TSANDADDR:
17884 			case IPOPT_TS_PRESPEC:
17885 			case IPOPT_TS_PRESPEC_RFC791:
17886 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17887 				break;
17888 			default:
17889 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
17890 				    (char *)ipha;
17891 				goto param_prob;
17892 			}
17893 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
17894 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
17895 				/*
17896 				 * No room and the overflow counter is 15
17897 				 * already.
17898 				 */
17899 				goto param_prob;
17900 			}
17901 			break;
17902 		}
17903 	}
17904 
17905 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
17906 		*dstp = dst;
17907 		return (0);
17908 	}
17909 
17910 	ip1dbg(("ip_rput_options: error processing IP options."));
17911 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
17912 
17913 param_prob:
17914 	q = WR(q);
17915 	if (q->q_next != NULL)
17916 		ill = q->q_ptr;
17917 	else
17918 		ill = NULL;
17919 
17920 	/* make sure we clear any indication of a hardware checksum */
17921 	DB_CKSUMFLAGS(mp) = 0;
17922 	/* Don't know whether this is for non-global or global/forwarding */
17923 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
17924 	if (zoneid == ALL_ZONES)
17925 		freemsg(mp);
17926 	else
17927 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
17928 	return (-1);
17929 
17930 bad_src_route:
17931 	q = WR(q);
17932 	if (q->q_next != NULL)
17933 		ill = q->q_ptr;
17934 	else
17935 		ill = NULL;
17936 
17937 	/* make sure we clear any indication of a hardware checksum */
17938 	DB_CKSUMFLAGS(mp) = 0;
17939 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
17940 	if (zoneid == ALL_ZONES)
17941 		freemsg(mp);
17942 	else
17943 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17944 	return (-1);
17945 }
17946 
17947 /*
17948  * IP & ICMP info in >=14 msg's ...
17949  *  - ip fixed part (mib2_ip_t)
17950  *  - icmp fixed part (mib2_icmp_t)
17951  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
17952  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
17953  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
17954  *  - ipRouteAttributeTable (ip 102)	labeled routes
17955  *  - ip multicast membership (ip_member_t)
17956  *  - ip multicast source filtering (ip_grpsrc_t)
17957  *  - igmp fixed part (struct igmpstat)
17958  *  - multicast routing stats (struct mrtstat)
17959  *  - multicast routing vifs (array of struct vifctl)
17960  *  - multicast routing routes (array of struct mfcctl)
17961  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
17962  *					One per ill plus one generic
17963  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
17964  *					One per ill plus one generic
17965  *  - ipv6RouteEntry			all IPv6 IREs
17966  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
17967  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
17968  *  - ipv6AddrEntry			all IPv6 ipifs
17969  *  - ipv6 multicast membership (ipv6_member_t)
17970  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
17971  *
17972  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
17973  *
17974  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
17975  * already filled in by the caller.
17976  * Return value of 0 indicates that no messages were sent and caller
17977  * should free mpctl.
17978  */
17979 int
17980 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
17981 {
17982 	ip_stack_t *ipst;
17983 	sctp_stack_t *sctps;
17984 
17985 	if (q->q_next != NULL) {
17986 		ipst = ILLQ_TO_IPST(q);
17987 	} else {
17988 		ipst = CONNQ_TO_IPST(q);
17989 	}
17990 	ASSERT(ipst != NULL);
17991 	sctps = ipst->ips_netstack->netstack_sctp;
17992 
17993 	if (mpctl == NULL || mpctl->b_cont == NULL) {
17994 		return (0);
17995 	}
17996 
17997 	/*
17998 	 * For the purposes of the (broken) packet shell use
17999 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
18000 	 * to make TCP and UDP appear first in the list of mib items.
18001 	 * TBD: We could expand this and use it in netstat so that
18002 	 * the kernel doesn't have to produce large tables (connections,
18003 	 * routes, etc) when netstat only wants the statistics or a particular
18004 	 * table.
18005 	 */
18006 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
18007 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
18008 			return (1);
18009 		}
18010 	}
18011 
18012 	if (level != MIB2_TCP) {
18013 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
18014 			return (1);
18015 		}
18016 	}
18017 
18018 	if (level != MIB2_UDP) {
18019 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
18020 			return (1);
18021 		}
18022 	}
18023 
18024 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18025 	    ipst)) == NULL) {
18026 		return (1);
18027 	}
18028 
18029 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18030 		return (1);
18031 	}
18032 
18033 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18034 		return (1);
18035 	}
18036 
18037 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18038 		return (1);
18039 	}
18040 
18041 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18042 		return (1);
18043 	}
18044 
18045 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18046 		return (1);
18047 	}
18048 
18049 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18050 		return (1);
18051 	}
18052 
18053 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18054 		return (1);
18055 	}
18056 
18057 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18058 		return (1);
18059 	}
18060 
18061 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18062 		return (1);
18063 	}
18064 
18065 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18066 		return (1);
18067 	}
18068 
18069 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18070 		return (1);
18071 	}
18072 
18073 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18074 		return (1);
18075 	}
18076 
18077 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18078 		return (1);
18079 	}
18080 
18081 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, ipst)) == NULL) {
18082 		return (1);
18083 	}
18084 
18085 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, ipst);
18086 	if (mpctl == NULL) {
18087 		return (1);
18088 	}
18089 
18090 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18091 		return (1);
18092 	}
18093 	freemsg(mpctl);
18094 	return (1);
18095 }
18096 
18097 
18098 /* Get global (legacy) IPv4 statistics */
18099 static mblk_t *
18100 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18101     ip_stack_t *ipst)
18102 {
18103 	mib2_ip_t		old_ip_mib;
18104 	struct opthdr		*optp;
18105 	mblk_t			*mp2ctl;
18106 
18107 	/*
18108 	 * make a copy of the original message
18109 	 */
18110 	mp2ctl = copymsg(mpctl);
18111 
18112 	/* fixed length IP structure... */
18113 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18114 	optp->level = MIB2_IP;
18115 	optp->name = 0;
18116 	SET_MIB(old_ip_mib.ipForwarding,
18117 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18118 	SET_MIB(old_ip_mib.ipDefaultTTL,
18119 	    (uint32_t)ipst->ips_ip_def_ttl);
18120 	SET_MIB(old_ip_mib.ipReasmTimeout,
18121 	    ipst->ips_ip_g_frag_timeout);
18122 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18123 	    sizeof (mib2_ipAddrEntry_t));
18124 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18125 	    sizeof (mib2_ipRouteEntry_t));
18126 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18127 	    sizeof (mib2_ipNetToMediaEntry_t));
18128 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18129 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18130 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18131 	    sizeof (mib2_ipAttributeEntry_t));
18132 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18133 
18134 	/*
18135 	 * Grab the statistics from the new IP MIB
18136 	 */
18137 	SET_MIB(old_ip_mib.ipInReceives,
18138 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18139 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18140 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18141 	SET_MIB(old_ip_mib.ipForwDatagrams,
18142 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18143 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18144 	    ipmib->ipIfStatsInUnknownProtos);
18145 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18146 	SET_MIB(old_ip_mib.ipInDelivers,
18147 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18148 	SET_MIB(old_ip_mib.ipOutRequests,
18149 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18150 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18151 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18152 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18153 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18154 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18155 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18156 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18157 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18158 
18159 	/* ipRoutingDiscards is not being used */
18160 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18161 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18162 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18163 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18164 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18165 	    ipmib->ipIfStatsReasmDuplicates);
18166 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18167 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18168 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18169 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18170 	SET_MIB(old_ip_mib.rawipInOverflows,
18171 	    ipmib->rawipIfStatsInOverflows);
18172 
18173 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18174 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18175 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18176 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18177 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18178 	    ipmib->ipIfStatsOutSwitchIPVersion);
18179 
18180 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18181 	    (int)sizeof (old_ip_mib))) {
18182 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18183 		    (uint_t)sizeof (old_ip_mib)));
18184 	}
18185 
18186 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18187 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18188 	    (int)optp->level, (int)optp->name, (int)optp->len));
18189 	qreply(q, mpctl);
18190 	return (mp2ctl);
18191 }
18192 
18193 /* Per interface IPv4 statistics */
18194 static mblk_t *
18195 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18196 {
18197 	struct opthdr		*optp;
18198 	mblk_t			*mp2ctl;
18199 	ill_t			*ill;
18200 	ill_walk_context_t	ctx;
18201 	mblk_t			*mp_tail = NULL;
18202 	mib2_ipIfStatsEntry_t	global_ip_mib;
18203 
18204 	/*
18205 	 * Make a copy of the original message
18206 	 */
18207 	mp2ctl = copymsg(mpctl);
18208 
18209 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18210 	optp->level = MIB2_IP;
18211 	optp->name = MIB2_IP_TRAFFIC_STATS;
18212 	/* Include "unknown interface" ip_mib */
18213 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18214 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18215 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18216 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18217 	    (ipst->ips_ip_g_forward ? 1 : 2));
18218 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18219 	    (uint32_t)ipst->ips_ip_def_ttl);
18220 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18221 	    sizeof (mib2_ipIfStatsEntry_t));
18222 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18223 	    sizeof (mib2_ipAddrEntry_t));
18224 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18225 	    sizeof (mib2_ipRouteEntry_t));
18226 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18227 	    sizeof (mib2_ipNetToMediaEntry_t));
18228 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18229 	    sizeof (ip_member_t));
18230 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18231 	    sizeof (ip_grpsrc_t));
18232 
18233 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18234 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18235 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18236 		    "failed to allocate %u bytes\n",
18237 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18238 	}
18239 
18240 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18241 
18242 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18243 	ill = ILL_START_WALK_V4(&ctx, ipst);
18244 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18245 		ill->ill_ip_mib->ipIfStatsIfIndex =
18246 		    ill->ill_phyint->phyint_ifindex;
18247 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18248 		    (ipst->ips_ip_g_forward ? 1 : 2));
18249 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18250 		    (uint32_t)ipst->ips_ip_def_ttl);
18251 
18252 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18253 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18254 		    (char *)ill->ill_ip_mib,
18255 		    (int)sizeof (*ill->ill_ip_mib))) {
18256 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18257 			    "failed to allocate %u bytes\n",
18258 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18259 		}
18260 	}
18261 	rw_exit(&ipst->ips_ill_g_lock);
18262 
18263 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18264 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18265 	    "level %d, name %d, len %d\n",
18266 	    (int)optp->level, (int)optp->name, (int)optp->len));
18267 	qreply(q, mpctl);
18268 
18269 	if (mp2ctl == NULL)
18270 		return (NULL);
18271 
18272 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18273 }
18274 
18275 /* Global IPv4 ICMP statistics */
18276 static mblk_t *
18277 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18278 {
18279 	struct opthdr		*optp;
18280 	mblk_t			*mp2ctl;
18281 
18282 	/*
18283 	 * Make a copy of the original message
18284 	 */
18285 	mp2ctl = copymsg(mpctl);
18286 
18287 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18288 	optp->level = MIB2_ICMP;
18289 	optp->name = 0;
18290 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18291 	    (int)sizeof (ipst->ips_icmp_mib))) {
18292 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18293 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18294 	}
18295 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18296 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18297 	    (int)optp->level, (int)optp->name, (int)optp->len));
18298 	qreply(q, mpctl);
18299 	return (mp2ctl);
18300 }
18301 
18302 /* Global IPv4 IGMP statistics */
18303 static mblk_t *
18304 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18305 {
18306 	struct opthdr		*optp;
18307 	mblk_t			*mp2ctl;
18308 
18309 	/*
18310 	 * make a copy of the original message
18311 	 */
18312 	mp2ctl = copymsg(mpctl);
18313 
18314 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18315 	optp->level = EXPER_IGMP;
18316 	optp->name = 0;
18317 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18318 	    (int)sizeof (ipst->ips_igmpstat))) {
18319 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18320 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18321 	}
18322 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18323 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18324 	    (int)optp->level, (int)optp->name, (int)optp->len));
18325 	qreply(q, mpctl);
18326 	return (mp2ctl);
18327 }
18328 
18329 /* Global IPv4 Multicast Routing statistics */
18330 static mblk_t *
18331 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18332 {
18333 	struct opthdr		*optp;
18334 	mblk_t			*mp2ctl;
18335 
18336 	/*
18337 	 * make a copy of the original message
18338 	 */
18339 	mp2ctl = copymsg(mpctl);
18340 
18341 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18342 	optp->level = EXPER_DVMRP;
18343 	optp->name = 0;
18344 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18345 		ip0dbg(("ip_mroute_stats: failed\n"));
18346 	}
18347 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18348 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18349 	    (int)optp->level, (int)optp->name, (int)optp->len));
18350 	qreply(q, mpctl);
18351 	return (mp2ctl);
18352 }
18353 
18354 /* IPv4 address information */
18355 static mblk_t *
18356 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18357 {
18358 	struct opthdr		*optp;
18359 	mblk_t			*mp2ctl;
18360 	mblk_t			*mp_tail = NULL;
18361 	ill_t			*ill;
18362 	ipif_t			*ipif;
18363 	uint_t			bitval;
18364 	mib2_ipAddrEntry_t	mae;
18365 	zoneid_t		zoneid;
18366 	ill_walk_context_t ctx;
18367 
18368 	/*
18369 	 * make a copy of the original message
18370 	 */
18371 	mp2ctl = copymsg(mpctl);
18372 
18373 	/* ipAddrEntryTable */
18374 
18375 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18376 	optp->level = MIB2_IP;
18377 	optp->name = MIB2_IP_ADDR;
18378 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18379 
18380 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18381 	ill = ILL_START_WALK_V4(&ctx, ipst);
18382 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18383 		for (ipif = ill->ill_ipif; ipif != NULL;
18384 		    ipif = ipif->ipif_next) {
18385 			if (ipif->ipif_zoneid != zoneid &&
18386 			    ipif->ipif_zoneid != ALL_ZONES)
18387 				continue;
18388 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18389 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18390 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18391 
18392 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18393 			    OCTET_LENGTH);
18394 			mae.ipAdEntIfIndex.o_length =
18395 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18396 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18397 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18398 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18399 			mae.ipAdEntInfo.ae_subnet_len =
18400 			    ip_mask_to_plen(ipif->ipif_net_mask);
18401 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18402 			for (bitval = 1;
18403 			    bitval &&
18404 			    !(bitval & ipif->ipif_brd_addr);
18405 			    bitval <<= 1)
18406 				noop;
18407 			mae.ipAdEntBcastAddr = bitval;
18408 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18409 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18410 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18411 			mae.ipAdEntInfo.ae_broadcast_addr =
18412 			    ipif->ipif_brd_addr;
18413 			mae.ipAdEntInfo.ae_pp_dst_addr =
18414 			    ipif->ipif_pp_dst_addr;
18415 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18416 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18417 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18418 
18419 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18420 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18421 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18422 				    "allocate %u bytes\n",
18423 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18424 			}
18425 		}
18426 	}
18427 	rw_exit(&ipst->ips_ill_g_lock);
18428 
18429 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18430 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18431 	    (int)optp->level, (int)optp->name, (int)optp->len));
18432 	qreply(q, mpctl);
18433 	return (mp2ctl);
18434 }
18435 
18436 /* IPv6 address information */
18437 static mblk_t *
18438 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18439 {
18440 	struct opthdr		*optp;
18441 	mblk_t			*mp2ctl;
18442 	mblk_t			*mp_tail = NULL;
18443 	ill_t			*ill;
18444 	ipif_t			*ipif;
18445 	mib2_ipv6AddrEntry_t	mae6;
18446 	zoneid_t		zoneid;
18447 	ill_walk_context_t	ctx;
18448 
18449 	/*
18450 	 * make a copy of the original message
18451 	 */
18452 	mp2ctl = copymsg(mpctl);
18453 
18454 	/* ipv6AddrEntryTable */
18455 
18456 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18457 	optp->level = MIB2_IP6;
18458 	optp->name = MIB2_IP6_ADDR;
18459 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18460 
18461 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18462 	ill = ILL_START_WALK_V6(&ctx, ipst);
18463 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18464 		for (ipif = ill->ill_ipif; ipif != NULL;
18465 		    ipif = ipif->ipif_next) {
18466 			if (ipif->ipif_zoneid != zoneid &&
18467 			    ipif->ipif_zoneid != ALL_ZONES)
18468 				continue;
18469 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18470 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18471 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18472 
18473 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18474 			    OCTET_LENGTH);
18475 			mae6.ipv6AddrIfIndex.o_length =
18476 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18477 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18478 			mae6.ipv6AddrPfxLength =
18479 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18480 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18481 			mae6.ipv6AddrInfo.ae_subnet_len =
18482 			    mae6.ipv6AddrPfxLength;
18483 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18484 
18485 			/* Type: stateless(1), stateful(2), unknown(3) */
18486 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18487 				mae6.ipv6AddrType = 1;
18488 			else
18489 				mae6.ipv6AddrType = 2;
18490 			/* Anycast: true(1), false(2) */
18491 			if (ipif->ipif_flags & IPIF_ANYCAST)
18492 				mae6.ipv6AddrAnycastFlag = 1;
18493 			else
18494 				mae6.ipv6AddrAnycastFlag = 2;
18495 
18496 			/*
18497 			 * Address status: preferred(1), deprecated(2),
18498 			 * invalid(3), inaccessible(4), unknown(5)
18499 			 */
18500 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18501 				mae6.ipv6AddrStatus = 3;
18502 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18503 				mae6.ipv6AddrStatus = 2;
18504 			else
18505 				mae6.ipv6AddrStatus = 1;
18506 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18507 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18508 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18509 			    ipif->ipif_v6pp_dst_addr;
18510 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18511 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18512 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18513 			mae6.ipv6AddrIdentifier = ill->ill_token;
18514 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18515 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18516 			mae6.ipv6AddrRetransmitTime =
18517 			    ill->ill_reachable_retrans_time;
18518 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18519 			    (char *)&mae6,
18520 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18521 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18522 				    "allocate %u bytes\n",
18523 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18524 			}
18525 		}
18526 	}
18527 	rw_exit(&ipst->ips_ill_g_lock);
18528 
18529 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18530 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: 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 /* IPv4 multicast group membership. */
18537 static mblk_t *
18538 ip_snmp_get_mib2_ip_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 	ipif_t			*ipif;
18544 	ilm_t			*ilm;
18545 	ip_member_t		ipm;
18546 	mblk_t			*mp_tail = NULL;
18547 	ill_walk_context_t	ctx;
18548 	zoneid_t		zoneid;
18549 
18550 	/*
18551 	 * make a copy of the original message
18552 	 */
18553 	mp2ctl = copymsg(mpctl);
18554 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18555 
18556 	/* ipGroupMember table */
18557 	optp = (struct opthdr *)&mpctl->b_rptr[
18558 	    sizeof (struct T_optmgmt_ack)];
18559 	optp->level = MIB2_IP;
18560 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18561 
18562 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18563 	ill = ILL_START_WALK_V4(&ctx, ipst);
18564 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18565 		ILM_WALKER_HOLD(ill);
18566 		for (ipif = ill->ill_ipif; ipif != NULL;
18567 		    ipif = ipif->ipif_next) {
18568 			if (ipif->ipif_zoneid != zoneid &&
18569 			    ipif->ipif_zoneid != ALL_ZONES)
18570 				continue;	/* not this zone */
18571 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
18572 			    OCTET_LENGTH);
18573 			ipm.ipGroupMemberIfIndex.o_length =
18574 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18575 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18576 				ASSERT(ilm->ilm_ipif != NULL);
18577 				ASSERT(ilm->ilm_ill == NULL);
18578 				if (ilm->ilm_ipif != ipif)
18579 					continue;
18580 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18581 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18582 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18583 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18584 				    (char *)&ipm, (int)sizeof (ipm))) {
18585 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18586 					    "failed to allocate %u bytes\n",
18587 					    (uint_t)sizeof (ipm)));
18588 				}
18589 			}
18590 		}
18591 		ILM_WALKER_RELE(ill);
18592 	}
18593 	rw_exit(&ipst->ips_ill_g_lock);
18594 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18595 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18596 	    (int)optp->level, (int)optp->name, (int)optp->len));
18597 	qreply(q, mpctl);
18598 	return (mp2ctl);
18599 }
18600 
18601 /* IPv6 multicast group membership. */
18602 static mblk_t *
18603 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18604 {
18605 	struct opthdr		*optp;
18606 	mblk_t			*mp2ctl;
18607 	ill_t			*ill;
18608 	ilm_t			*ilm;
18609 	ipv6_member_t		ipm6;
18610 	mblk_t			*mp_tail = NULL;
18611 	ill_walk_context_t	ctx;
18612 	zoneid_t		zoneid;
18613 
18614 	/*
18615 	 * make a copy of the original message
18616 	 */
18617 	mp2ctl = copymsg(mpctl);
18618 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18619 
18620 	/* ip6GroupMember table */
18621 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18622 	optp->level = MIB2_IP6;
18623 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18624 
18625 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18626 	ill = ILL_START_WALK_V6(&ctx, ipst);
18627 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18628 		ILM_WALKER_HOLD(ill);
18629 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18630 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18631 			ASSERT(ilm->ilm_ipif == NULL);
18632 			ASSERT(ilm->ilm_ill != NULL);
18633 			if (ilm->ilm_zoneid != zoneid)
18634 				continue;	/* not this zone */
18635 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18636 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18637 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18638 			if (!snmp_append_data2(mpctl->b_cont,
18639 			    &mp_tail,
18640 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18641 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18642 				    "failed to allocate %u bytes\n",
18643 				    (uint_t)sizeof (ipm6)));
18644 			}
18645 		}
18646 		ILM_WALKER_RELE(ill);
18647 	}
18648 	rw_exit(&ipst->ips_ill_g_lock);
18649 
18650 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18651 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18652 	    (int)optp->level, (int)optp->name, (int)optp->len));
18653 	qreply(q, mpctl);
18654 	return (mp2ctl);
18655 }
18656 
18657 /* IP multicast filtered sources */
18658 static mblk_t *
18659 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18660 {
18661 	struct opthdr		*optp;
18662 	mblk_t			*mp2ctl;
18663 	ill_t			*ill;
18664 	ipif_t			*ipif;
18665 	ilm_t			*ilm;
18666 	ip_grpsrc_t		ips;
18667 	mblk_t			*mp_tail = NULL;
18668 	ill_walk_context_t	ctx;
18669 	zoneid_t		zoneid;
18670 	int			i;
18671 	slist_t			*sl;
18672 
18673 	/*
18674 	 * make a copy of the original message
18675 	 */
18676 	mp2ctl = copymsg(mpctl);
18677 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18678 
18679 	/* ipGroupSource table */
18680 	optp = (struct opthdr *)&mpctl->b_rptr[
18681 	    sizeof (struct T_optmgmt_ack)];
18682 	optp->level = MIB2_IP;
18683 	optp->name = EXPER_IP_GROUP_SOURCES;
18684 
18685 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18686 	ill = ILL_START_WALK_V4(&ctx, ipst);
18687 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18688 		ILM_WALKER_HOLD(ill);
18689 		for (ipif = ill->ill_ipif; ipif != NULL;
18690 		    ipif = ipif->ipif_next) {
18691 			if (ipif->ipif_zoneid != zoneid)
18692 				continue;	/* not this zone */
18693 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
18694 			    OCTET_LENGTH);
18695 			ips.ipGroupSourceIfIndex.o_length =
18696 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
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_ipif != ipif || SLIST_IS_EMPTY(sl))
18702 					continue;
18703 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18704 				for (i = 0; i < sl->sl_numsrc; i++) {
18705 					if (!IN6_IS_ADDR_V4MAPPED(
18706 					    &sl->sl_addr[i]))
18707 						continue;
18708 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18709 					    ips.ipGroupSourceAddress);
18710 					if (snmp_append_data2(mpctl->b_cont,
18711 					    &mp_tail, (char *)&ips,
18712 					    (int)sizeof (ips)) == 0) {
18713 						ip1dbg(("ip_snmp_get_mib2_"
18714 						    "ip_group_src: failed to "
18715 						    "allocate %u bytes\n",
18716 						    (uint_t)sizeof (ips)));
18717 					}
18718 				}
18719 			}
18720 		}
18721 		ILM_WALKER_RELE(ill);
18722 	}
18723 	rw_exit(&ipst->ips_ill_g_lock);
18724 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18725 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18726 	    (int)optp->level, (int)optp->name, (int)optp->len));
18727 	qreply(q, mpctl);
18728 	return (mp2ctl);
18729 }
18730 
18731 /* IPv6 multicast filtered sources. */
18732 static mblk_t *
18733 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18734 {
18735 	struct opthdr		*optp;
18736 	mblk_t			*mp2ctl;
18737 	ill_t			*ill;
18738 	ilm_t			*ilm;
18739 	ipv6_grpsrc_t		ips6;
18740 	mblk_t			*mp_tail = NULL;
18741 	ill_walk_context_t	ctx;
18742 	zoneid_t		zoneid;
18743 	int			i;
18744 	slist_t			*sl;
18745 
18746 	/*
18747 	 * make a copy of the original message
18748 	 */
18749 	mp2ctl = copymsg(mpctl);
18750 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18751 
18752 	/* ip6GroupMember table */
18753 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18754 	optp->level = MIB2_IP6;
18755 	optp->name = EXPER_IP6_GROUP_SOURCES;
18756 
18757 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18758 	ill = ILL_START_WALK_V6(&ctx, ipst);
18759 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18760 		ILM_WALKER_HOLD(ill);
18761 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18762 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18763 			ASSERT(ilm->ilm_ipif == NULL);
18764 			ASSERT(ilm->ilm_ill != NULL);
18765 			sl = ilm->ilm_filter;
18766 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18767 				continue;
18768 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18769 			for (i = 0; i < sl->sl_numsrc; i++) {
18770 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18771 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18772 				    (char *)&ips6, (int)sizeof (ips6))) {
18773 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18774 					    "group_src: failed to allocate "
18775 					    "%u bytes\n",
18776 					    (uint_t)sizeof (ips6)));
18777 				}
18778 			}
18779 		}
18780 		ILM_WALKER_RELE(ill);
18781 	}
18782 	rw_exit(&ipst->ips_ill_g_lock);
18783 
18784 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18785 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18786 	    (int)optp->level, (int)optp->name, (int)optp->len));
18787 	qreply(q, mpctl);
18788 	return (mp2ctl);
18789 }
18790 
18791 /* Multicast routing virtual interface table. */
18792 static mblk_t *
18793 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18794 {
18795 	struct opthdr		*optp;
18796 	mblk_t			*mp2ctl;
18797 
18798 	/*
18799 	 * make a copy of the original message
18800 	 */
18801 	mp2ctl = copymsg(mpctl);
18802 
18803 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18804 	optp->level = EXPER_DVMRP;
18805 	optp->name = EXPER_DVMRP_VIF;
18806 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
18807 		ip0dbg(("ip_mroute_vif: failed\n"));
18808 	}
18809 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18810 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
18811 	    (int)optp->level, (int)optp->name, (int)optp->len));
18812 	qreply(q, mpctl);
18813 	return (mp2ctl);
18814 }
18815 
18816 /* Multicast routing table. */
18817 static mblk_t *
18818 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18819 {
18820 	struct opthdr		*optp;
18821 	mblk_t			*mp2ctl;
18822 
18823 	/*
18824 	 * make a copy of the original message
18825 	 */
18826 	mp2ctl = copymsg(mpctl);
18827 
18828 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18829 	optp->level = EXPER_DVMRP;
18830 	optp->name = EXPER_DVMRP_MRT;
18831 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
18832 		ip0dbg(("ip_mroute_mrt: failed\n"));
18833 	}
18834 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18835 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
18836 	    (int)optp->level, (int)optp->name, (int)optp->len));
18837 	qreply(q, mpctl);
18838 	return (mp2ctl);
18839 }
18840 
18841 /*
18842  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
18843  * in one IRE walk.
18844  */
18845 static mblk_t *
18846 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18847 {
18848 	struct opthdr	*optp;
18849 	mblk_t		*mp2ctl;	/* Returned */
18850 	mblk_t		*mp3ctl;	/* nettomedia */
18851 	mblk_t		*mp4ctl;	/* routeattrs */
18852 	iproutedata_t	ird;
18853 	zoneid_t	zoneid;
18854 
18855 	/*
18856 	 * make copies of the original message
18857 	 *	- mp2ctl is returned unchanged to the caller for his use
18858 	 *	- mpctl is sent upstream as ipRouteEntryTable
18859 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
18860 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
18861 	 */
18862 	mp2ctl = copymsg(mpctl);
18863 	mp3ctl = copymsg(mpctl);
18864 	mp4ctl = copymsg(mpctl);
18865 	if (mp3ctl == NULL || mp4ctl == NULL) {
18866 		freemsg(mp4ctl);
18867 		freemsg(mp3ctl);
18868 		freemsg(mp2ctl);
18869 		freemsg(mpctl);
18870 		return (NULL);
18871 	}
18872 
18873 	bzero(&ird, sizeof (ird));
18874 
18875 	ird.ird_route.lp_head = mpctl->b_cont;
18876 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18877 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18878 
18879 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18880 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
18881 
18882 	/* ipRouteEntryTable in mpctl */
18883 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18884 	optp->level = MIB2_IP;
18885 	optp->name = MIB2_IP_ROUTE;
18886 	optp->len = msgdsize(ird.ird_route.lp_head);
18887 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18888 	    (int)optp->level, (int)optp->name, (int)optp->len));
18889 	qreply(q, mpctl);
18890 
18891 	/* ipNetToMediaEntryTable in mp3ctl */
18892 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18893 	optp->level = MIB2_IP;
18894 	optp->name = MIB2_IP_MEDIA;
18895 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18896 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18897 	    (int)optp->level, (int)optp->name, (int)optp->len));
18898 	qreply(q, mp3ctl);
18899 
18900 	/* ipRouteAttributeTable in mp4ctl */
18901 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18902 	optp->level = MIB2_IP;
18903 	optp->name = EXPER_IP_RTATTR;
18904 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18905 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18906 	    (int)optp->level, (int)optp->name, (int)optp->len));
18907 	if (optp->len == 0)
18908 		freemsg(mp4ctl);
18909 	else
18910 		qreply(q, mp4ctl);
18911 
18912 	return (mp2ctl);
18913 }
18914 
18915 /*
18916  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
18917  * ipv6NetToMediaEntryTable in an NDP walk.
18918  */
18919 static mblk_t *
18920 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18921 {
18922 	struct opthdr	*optp;
18923 	mblk_t		*mp2ctl;	/* Returned */
18924 	mblk_t		*mp3ctl;	/* nettomedia */
18925 	mblk_t		*mp4ctl;	/* routeattrs */
18926 	iproutedata_t	ird;
18927 	zoneid_t	zoneid;
18928 
18929 	/*
18930 	 * make copies of the original message
18931 	 *	- mp2ctl is returned unchanged to the caller for his use
18932 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
18933 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
18934 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
18935 	 */
18936 	mp2ctl = copymsg(mpctl);
18937 	mp3ctl = copymsg(mpctl);
18938 	mp4ctl = copymsg(mpctl);
18939 	if (mp3ctl == NULL || mp4ctl == NULL) {
18940 		freemsg(mp4ctl);
18941 		freemsg(mp3ctl);
18942 		freemsg(mp2ctl);
18943 		freemsg(mpctl);
18944 		return (NULL);
18945 	}
18946 
18947 	bzero(&ird, sizeof (ird));
18948 
18949 	ird.ird_route.lp_head = mpctl->b_cont;
18950 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18951 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18952 
18953 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18954 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
18955 
18956 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18957 	optp->level = MIB2_IP6;
18958 	optp->name = MIB2_IP6_ROUTE;
18959 	optp->len = msgdsize(ird.ird_route.lp_head);
18960 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18961 	    (int)optp->level, (int)optp->name, (int)optp->len));
18962 	qreply(q, mpctl);
18963 
18964 	/* ipv6NetToMediaEntryTable in mp3ctl */
18965 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
18966 
18967 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18968 	optp->level = MIB2_IP6;
18969 	optp->name = MIB2_IP6_MEDIA;
18970 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18971 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18972 	    (int)optp->level, (int)optp->name, (int)optp->len));
18973 	qreply(q, mp3ctl);
18974 
18975 	/* ipv6RouteAttributeTable in mp4ctl */
18976 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18977 	optp->level = MIB2_IP6;
18978 	optp->name = EXPER_IP_RTATTR;
18979 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18980 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18981 	    (int)optp->level, (int)optp->name, (int)optp->len));
18982 	if (optp->len == 0)
18983 		freemsg(mp4ctl);
18984 	else
18985 		qreply(q, mp4ctl);
18986 
18987 	return (mp2ctl);
18988 }
18989 
18990 /*
18991  * IPv6 mib: One per ill
18992  */
18993 static mblk_t *
18994 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18995 {
18996 	struct opthdr		*optp;
18997 	mblk_t			*mp2ctl;
18998 	ill_t			*ill;
18999 	ill_walk_context_t	ctx;
19000 	mblk_t			*mp_tail = NULL;
19001 
19002 	/*
19003 	 * Make a copy of the original message
19004 	 */
19005 	mp2ctl = copymsg(mpctl);
19006 
19007 	/* fixed length IPv6 structure ... */
19008 
19009 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19010 	optp->level = MIB2_IP6;
19011 	optp->name = 0;
19012 	/* Include "unknown interface" ip6_mib */
19013 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19014 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19015 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19016 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19017 	    ipst->ips_ipv6_forward ? 1 : 2);
19018 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19019 	    ipst->ips_ipv6_def_hops);
19020 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19021 	    sizeof (mib2_ipIfStatsEntry_t));
19022 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19023 	    sizeof (mib2_ipv6AddrEntry_t));
19024 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19025 	    sizeof (mib2_ipv6RouteEntry_t));
19026 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19027 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19028 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19029 	    sizeof (ipv6_member_t));
19030 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19031 	    sizeof (ipv6_grpsrc_t));
19032 
19033 	/*
19034 	 * Synchronize 64- and 32-bit counters
19035 	 */
19036 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19037 	    ipIfStatsHCInReceives);
19038 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19039 	    ipIfStatsHCInDelivers);
19040 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19041 	    ipIfStatsHCOutRequests);
19042 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19043 	    ipIfStatsHCOutForwDatagrams);
19044 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19045 	    ipIfStatsHCOutMcastPkts);
19046 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19047 	    ipIfStatsHCInMcastPkts);
19048 
19049 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19050 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19051 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19052 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19053 	}
19054 
19055 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19056 	ill = ILL_START_WALK_V6(&ctx, ipst);
19057 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19058 		ill->ill_ip_mib->ipIfStatsIfIndex =
19059 		    ill->ill_phyint->phyint_ifindex;
19060 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19061 		    ipst->ips_ipv6_forward ? 1 : 2);
19062 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19063 		    ill->ill_max_hops);
19064 
19065 		/*
19066 		 * Synchronize 64- and 32-bit counters
19067 		 */
19068 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19069 		    ipIfStatsHCInReceives);
19070 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19071 		    ipIfStatsHCInDelivers);
19072 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19073 		    ipIfStatsHCOutRequests);
19074 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19075 		    ipIfStatsHCOutForwDatagrams);
19076 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19077 		    ipIfStatsHCOutMcastPkts);
19078 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19079 		    ipIfStatsHCInMcastPkts);
19080 
19081 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19082 		    (char *)ill->ill_ip_mib,
19083 		    (int)sizeof (*ill->ill_ip_mib))) {
19084 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19085 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19086 		}
19087 	}
19088 	rw_exit(&ipst->ips_ill_g_lock);
19089 
19090 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19091 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19092 	    (int)optp->level, (int)optp->name, (int)optp->len));
19093 	qreply(q, mpctl);
19094 	return (mp2ctl);
19095 }
19096 
19097 /*
19098  * ICMPv6 mib: One per ill
19099  */
19100 static mblk_t *
19101 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19102 {
19103 	struct opthdr		*optp;
19104 	mblk_t			*mp2ctl;
19105 	ill_t			*ill;
19106 	ill_walk_context_t	ctx;
19107 	mblk_t			*mp_tail = NULL;
19108 	/*
19109 	 * Make a copy of the original message
19110 	 */
19111 	mp2ctl = copymsg(mpctl);
19112 
19113 	/* fixed length ICMPv6 structure ... */
19114 
19115 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19116 	optp->level = MIB2_ICMP6;
19117 	optp->name = 0;
19118 	/* Include "unknown interface" icmp6_mib */
19119 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19120 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19121 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19122 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19123 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19124 	    (char *)&ipst->ips_icmp6_mib,
19125 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19126 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19127 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19128 	}
19129 
19130 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19131 	ill = ILL_START_WALK_V6(&ctx, ipst);
19132 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19133 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19134 		    ill->ill_phyint->phyint_ifindex;
19135 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19136 		    (char *)ill->ill_icmp6_mib,
19137 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19138 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19139 			    "%u bytes\n",
19140 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19141 		}
19142 	}
19143 	rw_exit(&ipst->ips_ill_g_lock);
19144 
19145 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19146 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19147 	    (int)optp->level, (int)optp->name, (int)optp->len));
19148 	qreply(q, mpctl);
19149 	return (mp2ctl);
19150 }
19151 
19152 /*
19153  * ire_walk routine to create both ipRouteEntryTable and
19154  * ipRouteAttributeTable in one IRE walk
19155  */
19156 static void
19157 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19158 {
19159 	ill_t				*ill;
19160 	ipif_t				*ipif;
19161 	mib2_ipRouteEntry_t		*re;
19162 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19163 	ipaddr_t			gw_addr;
19164 	tsol_ire_gw_secattr_t		*attrp;
19165 	tsol_gc_t			*gc = NULL;
19166 	tsol_gcgrp_t			*gcgrp = NULL;
19167 	uint_t				sacnt = 0;
19168 	int				i;
19169 
19170 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19171 
19172 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19173 		return;
19174 
19175 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19176 		mutex_enter(&attrp->igsa_lock);
19177 		if ((gc = attrp->igsa_gc) != NULL) {
19178 			gcgrp = gc->gc_grp;
19179 			ASSERT(gcgrp != NULL);
19180 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19181 			sacnt = 1;
19182 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19183 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19184 			gc = gcgrp->gcgrp_head;
19185 			sacnt = gcgrp->gcgrp_count;
19186 		}
19187 		mutex_exit(&attrp->igsa_lock);
19188 
19189 		/* do nothing if there's no gc to report */
19190 		if (gc == NULL) {
19191 			ASSERT(sacnt == 0);
19192 			if (gcgrp != NULL) {
19193 				/* we might as well drop the lock now */
19194 				rw_exit(&gcgrp->gcgrp_rwlock);
19195 				gcgrp = NULL;
19196 			}
19197 			attrp = NULL;
19198 		}
19199 
19200 		ASSERT(gc == NULL || (gcgrp != NULL &&
19201 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19202 	}
19203 	ASSERT(sacnt == 0 || gc != NULL);
19204 
19205 	if (sacnt != 0 &&
19206 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19207 		kmem_free(re, sizeof (*re));
19208 		rw_exit(&gcgrp->gcgrp_rwlock);
19209 		return;
19210 	}
19211 
19212 	/*
19213 	 * Return all IRE types for route table... let caller pick and choose
19214 	 */
19215 	re->ipRouteDest = ire->ire_addr;
19216 	ipif = ire->ire_ipif;
19217 	re->ipRouteIfIndex.o_length = 0;
19218 	if (ire->ire_type == IRE_CACHE) {
19219 		ill = (ill_t *)ire->ire_stq->q_ptr;
19220 		re->ipRouteIfIndex.o_length =
19221 		    ill->ill_name_length == 0 ? 0 :
19222 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19223 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19224 		    re->ipRouteIfIndex.o_length);
19225 	} else if (ipif != NULL) {
19226 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19227 		re->ipRouteIfIndex.o_length =
19228 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19229 	}
19230 	re->ipRouteMetric1 = -1;
19231 	re->ipRouteMetric2 = -1;
19232 	re->ipRouteMetric3 = -1;
19233 	re->ipRouteMetric4 = -1;
19234 
19235 	gw_addr = ire->ire_gateway_addr;
19236 
19237 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19238 		re->ipRouteNextHop = ire->ire_src_addr;
19239 	else
19240 		re->ipRouteNextHop = gw_addr;
19241 	/* indirect(4), direct(3), or invalid(2) */
19242 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19243 		re->ipRouteType = 2;
19244 	else
19245 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19246 	re->ipRouteProto = -1;
19247 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19248 	re->ipRouteMask = ire->ire_mask;
19249 	re->ipRouteMetric5 = -1;
19250 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19251 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19252 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19253 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19254 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19255 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19256 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19257 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19258 
19259 	if (ire->ire_flags & RTF_DYNAMIC) {
19260 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19261 	} else {
19262 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19263 	}
19264 
19265 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19266 	    (char *)re, (int)sizeof (*re))) {
19267 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19268 		    (uint_t)sizeof (*re)));
19269 	}
19270 
19271 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19272 		iaeptr->iae_routeidx = ird->ird_idx;
19273 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19274 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19275 	}
19276 
19277 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19278 	    (char *)iae, sacnt * sizeof (*iae))) {
19279 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19280 		    (unsigned)(sacnt * sizeof (*iae))));
19281 	}
19282 
19283 	/* bump route index for next pass */
19284 	ird->ird_idx++;
19285 
19286 	kmem_free(re, sizeof (*re));
19287 	if (sacnt != 0)
19288 		kmem_free(iae, sacnt * sizeof (*iae));
19289 
19290 	if (gcgrp != NULL)
19291 		rw_exit(&gcgrp->gcgrp_rwlock);
19292 }
19293 
19294 /*
19295  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19296  */
19297 static void
19298 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19299 {
19300 	ill_t				*ill;
19301 	ipif_t				*ipif;
19302 	mib2_ipv6RouteEntry_t		*re;
19303 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19304 	in6_addr_t			gw_addr_v6;
19305 	tsol_ire_gw_secattr_t		*attrp;
19306 	tsol_gc_t			*gc = NULL;
19307 	tsol_gcgrp_t			*gcgrp = NULL;
19308 	uint_t				sacnt = 0;
19309 	int				i;
19310 
19311 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19312 
19313 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19314 		return;
19315 
19316 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19317 		mutex_enter(&attrp->igsa_lock);
19318 		if ((gc = attrp->igsa_gc) != NULL) {
19319 			gcgrp = gc->gc_grp;
19320 			ASSERT(gcgrp != NULL);
19321 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19322 			sacnt = 1;
19323 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19324 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19325 			gc = gcgrp->gcgrp_head;
19326 			sacnt = gcgrp->gcgrp_count;
19327 		}
19328 		mutex_exit(&attrp->igsa_lock);
19329 
19330 		/* do nothing if there's no gc to report */
19331 		if (gc == NULL) {
19332 			ASSERT(sacnt == 0);
19333 			if (gcgrp != NULL) {
19334 				/* we might as well drop the lock now */
19335 				rw_exit(&gcgrp->gcgrp_rwlock);
19336 				gcgrp = NULL;
19337 			}
19338 			attrp = NULL;
19339 		}
19340 
19341 		ASSERT(gc == NULL || (gcgrp != NULL &&
19342 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19343 	}
19344 	ASSERT(sacnt == 0 || gc != NULL);
19345 
19346 	if (sacnt != 0 &&
19347 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19348 		kmem_free(re, sizeof (*re));
19349 		rw_exit(&gcgrp->gcgrp_rwlock);
19350 		return;
19351 	}
19352 
19353 	/*
19354 	 * Return all IRE types for route table... let caller pick and choose
19355 	 */
19356 	re->ipv6RouteDest = ire->ire_addr_v6;
19357 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19358 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19359 	re->ipv6RouteIfIndex.o_length = 0;
19360 	ipif = ire->ire_ipif;
19361 	if (ire->ire_type == IRE_CACHE) {
19362 		ill = (ill_t *)ire->ire_stq->q_ptr;
19363 		re->ipv6RouteIfIndex.o_length =
19364 		    ill->ill_name_length == 0 ? 0 :
19365 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19366 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19367 		    re->ipv6RouteIfIndex.o_length);
19368 	} else if (ipif != NULL) {
19369 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19370 		re->ipv6RouteIfIndex.o_length =
19371 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19372 	}
19373 
19374 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19375 
19376 	mutex_enter(&ire->ire_lock);
19377 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19378 	mutex_exit(&ire->ire_lock);
19379 
19380 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19381 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19382 	else
19383 		re->ipv6RouteNextHop = gw_addr_v6;
19384 
19385 	/* remote(4), local(3), or discard(2) */
19386 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19387 		re->ipv6RouteType = 2;
19388 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19389 		re->ipv6RouteType = 3;
19390 	else
19391 		re->ipv6RouteType = 4;
19392 
19393 	re->ipv6RouteProtocol	= -1;
19394 	re->ipv6RoutePolicy	= 0;
19395 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19396 	re->ipv6RouteNextHopRDI	= 0;
19397 	re->ipv6RouteWeight	= 0;
19398 	re->ipv6RouteMetric	= 0;
19399 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19400 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19401 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19402 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19403 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19404 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19405 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19406 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19407 
19408 	if (ire->ire_flags & RTF_DYNAMIC) {
19409 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19410 	} else {
19411 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19412 	}
19413 
19414 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19415 	    (char *)re, (int)sizeof (*re))) {
19416 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19417 		    (uint_t)sizeof (*re)));
19418 	}
19419 
19420 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19421 		iaeptr->iae_routeidx = ird->ird_idx;
19422 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19423 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19424 	}
19425 
19426 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19427 	    (char *)iae, sacnt * sizeof (*iae))) {
19428 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19429 		    (unsigned)(sacnt * sizeof (*iae))));
19430 	}
19431 
19432 	/* bump route index for next pass */
19433 	ird->ird_idx++;
19434 
19435 	kmem_free(re, sizeof (*re));
19436 	if (sacnt != 0)
19437 		kmem_free(iae, sacnt * sizeof (*iae));
19438 
19439 	if (gcgrp != NULL)
19440 		rw_exit(&gcgrp->gcgrp_rwlock);
19441 }
19442 
19443 /*
19444  * ndp_walk routine to create ipv6NetToMediaEntryTable
19445  */
19446 static int
19447 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19448 {
19449 	ill_t				*ill;
19450 	mib2_ipv6NetToMediaEntry_t	ntme;
19451 	dl_unitdata_req_t		*dl;
19452 
19453 	ill = nce->nce_ill;
19454 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19455 		return (0);
19456 
19457 	/*
19458 	 * Neighbor cache entry attached to IRE with on-link
19459 	 * destination.
19460 	 */
19461 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19462 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19463 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19464 	    (nce->nce_res_mp != NULL)) {
19465 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19466 		ntme.ipv6NetToMediaPhysAddress.o_length =
19467 		    dl->dl_dest_addr_length;
19468 	} else {
19469 		ntme.ipv6NetToMediaPhysAddress.o_length =
19470 		    ill->ill_phys_addr_length;
19471 	}
19472 	if (nce->nce_res_mp != NULL) {
19473 		bcopy((char *)nce->nce_res_mp->b_rptr +
19474 		    NCE_LL_ADDR_OFFSET(ill),
19475 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19476 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19477 	} else {
19478 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19479 		    ill->ill_phys_addr_length);
19480 	}
19481 	/*
19482 	 * Note: Returns ND_* states. Should be:
19483 	 * reachable(1), stale(2), delay(3), probe(4),
19484 	 * invalid(5), unknown(6)
19485 	 */
19486 	ntme.ipv6NetToMediaState = nce->nce_state;
19487 	ntme.ipv6NetToMediaLastUpdated = 0;
19488 
19489 	/* other(1), dynamic(2), static(3), local(4) */
19490 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19491 		ntme.ipv6NetToMediaType = 4;
19492 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19493 		ntme.ipv6NetToMediaType = 1;
19494 	} else {
19495 		ntme.ipv6NetToMediaType = 2;
19496 	}
19497 
19498 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19499 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19500 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19501 		    (uint_t)sizeof (ntme)));
19502 	}
19503 	return (0);
19504 }
19505 
19506 /*
19507  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19508  */
19509 /* ARGSUSED */
19510 int
19511 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19512 {
19513 	switch (level) {
19514 	case MIB2_IP:
19515 	case MIB2_ICMP:
19516 		switch (name) {
19517 		default:
19518 			break;
19519 		}
19520 		return (1);
19521 	default:
19522 		return (1);
19523 	}
19524 }
19525 
19526 /*
19527  * When there exists both a 64- and 32-bit counter of a particular type
19528  * (i.e., InReceives), only the 64-bit counters are added.
19529  */
19530 void
19531 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19532 {
19533 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19534 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19535 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19536 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19537 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19538 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19539 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19540 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19541 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19542 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19543 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19544 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19545 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19546 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19547 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19548 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19549 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19550 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19551 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19552 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19553 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19554 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19555 	    o2->ipIfStatsInWrongIPVersion);
19556 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19557 	    o2->ipIfStatsInWrongIPVersion);
19558 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19559 	    o2->ipIfStatsOutSwitchIPVersion);
19560 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19561 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19562 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19563 	    o2->ipIfStatsHCInForwDatagrams);
19564 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19565 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19566 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19567 	    o2->ipIfStatsHCOutForwDatagrams);
19568 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19569 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19570 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19571 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19572 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19573 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19574 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19575 	    o2->ipIfStatsHCOutMcastOctets);
19576 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19577 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19578 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19579 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19580 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19581 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19582 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19583 }
19584 
19585 void
19586 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19587 {
19588 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19589 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19590 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19591 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19592 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19593 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19594 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19595 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19596 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19597 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19598 	    o2->ipv6IfIcmpInRouterSolicits);
19599 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19600 	    o2->ipv6IfIcmpInRouterAdvertisements);
19601 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19602 	    o2->ipv6IfIcmpInNeighborSolicits);
19603 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19604 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19605 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19606 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19607 	    o2->ipv6IfIcmpInGroupMembQueries);
19608 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19609 	    o2->ipv6IfIcmpInGroupMembResponses);
19610 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19611 	    o2->ipv6IfIcmpInGroupMembReductions);
19612 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19613 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19614 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19615 	    o2->ipv6IfIcmpOutDestUnreachs);
19616 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19617 	    o2->ipv6IfIcmpOutAdminProhibs);
19618 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19619 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19620 	    o2->ipv6IfIcmpOutParmProblems);
19621 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19622 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19623 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19624 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19625 	    o2->ipv6IfIcmpOutRouterSolicits);
19626 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19627 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19628 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19629 	    o2->ipv6IfIcmpOutNeighborSolicits);
19630 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19631 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19632 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19633 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19634 	    o2->ipv6IfIcmpOutGroupMembQueries);
19635 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19636 	    o2->ipv6IfIcmpOutGroupMembResponses);
19637 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19638 	    o2->ipv6IfIcmpOutGroupMembReductions);
19639 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19640 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19641 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19642 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19643 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19644 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19645 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19646 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19647 	    o2->ipv6IfIcmpInGroupMembTotal);
19648 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19649 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19650 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19651 	    o2->ipv6IfIcmpInGroupMembBadReports);
19652 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19653 	    o2->ipv6IfIcmpInGroupMembOurReports);
19654 }
19655 
19656 /*
19657  * Called before the options are updated to check if this packet will
19658  * be source routed from here.
19659  * This routine assumes that the options are well formed i.e. that they
19660  * have already been checked.
19661  */
19662 static boolean_t
19663 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
19664 {
19665 	ipoptp_t	opts;
19666 	uchar_t		*opt;
19667 	uint8_t		optval;
19668 	uint8_t		optlen;
19669 	ipaddr_t	dst;
19670 	ire_t		*ire;
19671 
19672 	if (IS_SIMPLE_IPH(ipha)) {
19673 		ip2dbg(("not source routed\n"));
19674 		return (B_FALSE);
19675 	}
19676 	dst = ipha->ipha_dst;
19677 	for (optval = ipoptp_first(&opts, ipha);
19678 	    optval != IPOPT_EOL;
19679 	    optval = ipoptp_next(&opts)) {
19680 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19681 		opt = opts.ipoptp_cur;
19682 		optlen = opts.ipoptp_len;
19683 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19684 		    optval, optlen));
19685 		switch (optval) {
19686 			uint32_t off;
19687 		case IPOPT_SSRR:
19688 		case IPOPT_LSRR:
19689 			/*
19690 			 * If dst is one of our addresses and there are some
19691 			 * entries left in the source route return (true).
19692 			 */
19693 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19694 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
19695 			if (ire == NULL) {
19696 				ip2dbg(("ip_source_routed: not next"
19697 				    " source route 0x%x\n",
19698 				    ntohl(dst)));
19699 				return (B_FALSE);
19700 			}
19701 			ire_refrele(ire);
19702 			off = opt[IPOPT_OFFSET];
19703 			off--;
19704 			if (optlen < IP_ADDR_LEN ||
19705 			    off > optlen - IP_ADDR_LEN) {
19706 				/* End of source route */
19707 				ip1dbg(("ip_source_routed: end of SR\n"));
19708 				return (B_FALSE);
19709 			}
19710 			return (B_TRUE);
19711 		}
19712 	}
19713 	ip2dbg(("not source routed\n"));
19714 	return (B_FALSE);
19715 }
19716 
19717 /*
19718  * Check if the packet contains any source route.
19719  */
19720 static boolean_t
19721 ip_source_route_included(ipha_t *ipha)
19722 {
19723 	ipoptp_t	opts;
19724 	uint8_t		optval;
19725 
19726 	if (IS_SIMPLE_IPH(ipha))
19727 		return (B_FALSE);
19728 	for (optval = ipoptp_first(&opts, ipha);
19729 	    optval != IPOPT_EOL;
19730 	    optval = ipoptp_next(&opts)) {
19731 		switch (optval) {
19732 		case IPOPT_SSRR:
19733 		case IPOPT_LSRR:
19734 			return (B_TRUE);
19735 		}
19736 	}
19737 	return (B_FALSE);
19738 }
19739 
19740 /*
19741  * Called when the IRE expiration timer fires.
19742  */
19743 void
19744 ip_trash_timer_expire(void *args)
19745 {
19746 	int			flush_flag = 0;
19747 	ire_expire_arg_t	iea;
19748 	ip_stack_t		*ipst = (ip_stack_t *)args;
19749 
19750 	iea.iea_ipst = ipst;	/* No netstack_hold */
19751 
19752 	/*
19753 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19754 	 * This lock makes sure that a new invocation of this function
19755 	 * that occurs due to an almost immediate timer firing will not
19756 	 * progress beyond this point until the current invocation is done
19757 	 */
19758 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19759 	ipst->ips_ip_ire_expire_id = 0;
19760 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19761 
19762 	/* Periodic timer */
19763 	if (ipst->ips_ip_ire_arp_time_elapsed >=
19764 	    ipst->ips_ip_ire_arp_interval) {
19765 		/*
19766 		 * Remove all IRE_CACHE entries since they might
19767 		 * contain arp information.
19768 		 */
19769 		flush_flag |= FLUSH_ARP_TIME;
19770 		ipst->ips_ip_ire_arp_time_elapsed = 0;
19771 		IP_STAT(ipst, ip_ire_arp_timer_expired);
19772 	}
19773 	if (ipst->ips_ip_ire_rd_time_elapsed >=
19774 	    ipst->ips_ip_ire_redir_interval) {
19775 		/* Remove all redirects */
19776 		flush_flag |= FLUSH_REDIRECT_TIME;
19777 		ipst->ips_ip_ire_rd_time_elapsed = 0;
19778 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
19779 	}
19780 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
19781 	    ipst->ips_ip_ire_pathmtu_interval) {
19782 		/* Increase path mtu */
19783 		flush_flag |= FLUSH_MTU_TIME;
19784 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
19785 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
19786 	}
19787 
19788 	/*
19789 	 * Optimize for the case when there are no redirects in the
19790 	 * ftable, that is, no need to walk the ftable in that case.
19791 	 */
19792 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
19793 		iea.iea_flush_flag = flush_flag;
19794 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
19795 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
19796 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
19797 		    NULL, ALL_ZONES, ipst);
19798 	}
19799 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
19800 	    ipst->ips_ip_redirect_cnt > 0) {
19801 		iea.iea_flush_flag = flush_flag;
19802 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
19803 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
19804 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
19805 	}
19806 	if (flush_flag & FLUSH_MTU_TIME) {
19807 		/*
19808 		 * Walk all IPv6 IRE's and update them
19809 		 * Note that ARP and redirect timers are not
19810 		 * needed since NUD handles stale entries.
19811 		 */
19812 		flush_flag = FLUSH_MTU_TIME;
19813 		iea.iea_flush_flag = flush_flag;
19814 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
19815 		    ALL_ZONES, ipst);
19816 	}
19817 
19818 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
19819 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
19820 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
19821 
19822 	/*
19823 	 * Hold the lock to serialize timeout calls and prevent
19824 	 * stale values in ip_ire_expire_id. Otherwise it is possible
19825 	 * for the timer to fire and a new invocation of this function
19826 	 * to start before the return value of timeout has been stored
19827 	 * in ip_ire_expire_id by the current invocation.
19828 	 */
19829 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19830 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
19831 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
19832 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19833 }
19834 
19835 /*
19836  * Called by the memory allocator subsystem directly, when the system
19837  * is running low on memory.
19838  */
19839 /* ARGSUSED */
19840 void
19841 ip_trash_ire_reclaim(void *args)
19842 {
19843 	netstack_handle_t nh;
19844 	netstack_t *ns;
19845 
19846 	netstack_next_init(&nh);
19847 	while ((ns = netstack_next(&nh)) != NULL) {
19848 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
19849 		netstack_rele(ns);
19850 	}
19851 	netstack_next_fini(&nh);
19852 }
19853 
19854 static void
19855 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
19856 {
19857 	ire_cache_count_t icc;
19858 	ire_cache_reclaim_t icr;
19859 	ncc_cache_count_t ncc;
19860 	nce_cache_reclaim_t ncr;
19861 	uint_t delete_cnt;
19862 	/*
19863 	 * Memory reclaim call back.
19864 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
19865 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
19866 	 * entries, determine what fraction to free for
19867 	 * each category of IRE_CACHE entries giving absolute priority
19868 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
19869 	 * entry will be freed unless all offlink entries are freed).
19870 	 */
19871 	icc.icc_total = 0;
19872 	icc.icc_unused = 0;
19873 	icc.icc_offlink = 0;
19874 	icc.icc_pmtu = 0;
19875 	icc.icc_onlink = 0;
19876 	ire_walk(ire_cache_count, (char *)&icc, ipst);
19877 
19878 	/*
19879 	 * Free NCEs for IPv6 like the onlink ires.
19880 	 */
19881 	ncc.ncc_total = 0;
19882 	ncc.ncc_host = 0;
19883 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
19884 
19885 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
19886 	    icc.icc_pmtu + icc.icc_onlink);
19887 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
19888 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
19889 	if (delete_cnt == 0)
19890 		return;
19891 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
19892 	/* Always delete all unused offlink entries */
19893 	icr.icr_ipst = ipst;
19894 	icr.icr_unused = 1;
19895 	if (delete_cnt <= icc.icc_unused) {
19896 		/*
19897 		 * Only need to free unused entries.  In other words,
19898 		 * there are enough unused entries to free to meet our
19899 		 * target number of freed ire cache entries.
19900 		 */
19901 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
19902 		ncr.ncr_host = 0;
19903 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
19904 		/*
19905 		 * Only need to free unused entries, plus a fraction of offlink
19906 		 * entries.  It follows from the first if statement that
19907 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
19908 		 */
19909 		delete_cnt -= icc.icc_unused;
19910 		/* Round up # deleted by truncating fraction */
19911 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
19912 		icr.icr_pmtu = icr.icr_onlink = 0;
19913 		ncr.ncr_host = 0;
19914 	} else if (delete_cnt <=
19915 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
19916 		/*
19917 		 * Free all unused and offlink entries, plus a fraction of
19918 		 * pmtu entries.  It follows from the previous if statement
19919 		 * that icc_pmtu is non-zero, and that
19920 		 * delete_cnt != icc_unused + icc_offlink.
19921 		 */
19922 		icr.icr_offlink = 1;
19923 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
19924 		/* Round up # deleted by truncating fraction */
19925 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
19926 		icr.icr_onlink = 0;
19927 		ncr.ncr_host = 0;
19928 	} else {
19929 		/*
19930 		 * Free all unused, offlink, and pmtu entries, plus a fraction
19931 		 * of onlink entries.  If we're here, then we know that
19932 		 * icc_onlink is non-zero, and that
19933 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
19934 		 */
19935 		icr.icr_offlink = icr.icr_pmtu = 1;
19936 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
19937 		    icc.icc_pmtu;
19938 		/* Round up # deleted by truncating fraction */
19939 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
19940 		/* Using the same delete fraction as for onlink IREs */
19941 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
19942 	}
19943 #ifdef DEBUG
19944 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
19945 	    "fractions %d/%d/%d/%d\n",
19946 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
19947 	    icc.icc_unused, icc.icc_offlink,
19948 	    icc.icc_pmtu, icc.icc_onlink,
19949 	    icr.icr_unused, icr.icr_offlink,
19950 	    icr.icr_pmtu, icr.icr_onlink));
19951 #endif
19952 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
19953 	if (ncr.ncr_host != 0)
19954 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
19955 		    (uchar_t *)&ncr, ipst);
19956 #ifdef DEBUG
19957 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
19958 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
19959 	ire_walk(ire_cache_count, (char *)&icc, ipst);
19960 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
19961 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
19962 	    icc.icc_pmtu, icc.icc_onlink));
19963 #endif
19964 }
19965 
19966 /*
19967  * ip_unbind is called when a copy of an unbind request is received from the
19968  * upper level protocol.  We remove this conn from any fanout hash list it is
19969  * on, and zero out the bind information.  No reply is expected up above.
19970  */
19971 mblk_t *
19972 ip_unbind(queue_t *q, mblk_t *mp)
19973 {
19974 	conn_t	*connp = Q_TO_CONN(q);
19975 
19976 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
19977 
19978 	if (is_system_labeled() && connp->conn_anon_port) {
19979 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
19980 		    connp->conn_mlp_type, connp->conn_ulp,
19981 		    ntohs(connp->conn_lport), B_FALSE);
19982 		connp->conn_anon_port = 0;
19983 	}
19984 	connp->conn_mlp_type = mlptSingle;
19985 
19986 	ipcl_hash_remove(connp);
19987 
19988 	ASSERT(mp->b_cont == NULL);
19989 	/*
19990 	 * Convert mp into a T_OK_ACK
19991 	 */
19992 	mp = mi_tpi_ok_ack_alloc(mp);
19993 
19994 	/*
19995 	 * should not happen in practice... T_OK_ACK is smaller than the
19996 	 * original message.
19997 	 */
19998 	if (mp == NULL)
19999 		return (NULL);
20000 
20001 	return (mp);
20002 }
20003 
20004 /*
20005  * Write side put procedure.  Outbound data, IOCTLs, responses from
20006  * resolvers, etc, come down through here.
20007  *
20008  * arg2 is always a queue_t *.
20009  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20010  * the zoneid.
20011  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20012  */
20013 void
20014 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20015 {
20016 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20017 }
20018 
20019 void
20020 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20021     ip_opt_info_t *infop)
20022 {
20023 	conn_t		*connp = NULL;
20024 	queue_t		*q = (queue_t *)arg2;
20025 	ipha_t		*ipha;
20026 #define	rptr	((uchar_t *)ipha)
20027 	ire_t		*ire = NULL;
20028 	ire_t		*sctp_ire = NULL;
20029 	uint32_t	v_hlen_tos_len;
20030 	ipaddr_t	dst;
20031 	mblk_t		*first_mp = NULL;
20032 	boolean_t	mctl_present;
20033 	ipsec_out_t	*io;
20034 	int		match_flags;
20035 	ill_t		*attach_ill = NULL;
20036 					/* Bind to IPIF_NOFAILOVER ill etc. */
20037 	ill_t		*xmit_ill = NULL;	/* IP_PKTINFO etc. */
20038 	ipif_t		*dst_ipif;
20039 	boolean_t	multirt_need_resolve = B_FALSE;
20040 	mblk_t		*copy_mp = NULL;
20041 	int		err;
20042 	zoneid_t	zoneid;
20043 	int	adjust;
20044 	uint16_t iplen;
20045 	boolean_t	need_decref = B_FALSE;
20046 	boolean_t	ignore_dontroute = B_FALSE;
20047 	boolean_t	ignore_nexthop = B_FALSE;
20048 	boolean_t	ip_nexthop = B_FALSE;
20049 	ipaddr_t	nexthop_addr;
20050 	ip_stack_t	*ipst;
20051 
20052 #ifdef	_BIG_ENDIAN
20053 #define	V_HLEN	(v_hlen_tos_len >> 24)
20054 #else
20055 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20056 #endif
20057 
20058 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20059 	    "ip_wput_start: q %p", q);
20060 
20061 	/*
20062 	 * ip_wput fast path
20063 	 */
20064 
20065 	/* is packet from ARP ? */
20066 	if (q->q_next != NULL) {
20067 		zoneid = (zoneid_t)(uintptr_t)arg;
20068 		goto qnext;
20069 	}
20070 
20071 	connp = (conn_t *)arg;
20072 	ASSERT(connp != NULL);
20073 	zoneid = connp->conn_zoneid;
20074 	ipst = connp->conn_netstack->netstack_ip;
20075 
20076 	/* is queue flow controlled? */
20077 	if ((q->q_first != NULL || connp->conn_draining) &&
20078 	    (caller == IP_WPUT)) {
20079 		ASSERT(!need_decref);
20080 		(void) putq(q, mp);
20081 		return;
20082 	}
20083 
20084 	/* Multidata transmit? */
20085 	if (DB_TYPE(mp) == M_MULTIDATA) {
20086 		/*
20087 		 * We should never get here, since all Multidata messages
20088 		 * originating from tcp should have been directed over to
20089 		 * tcp_multisend() in the first place.
20090 		 */
20091 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20092 		freemsg(mp);
20093 		return;
20094 	} else if (DB_TYPE(mp) != M_DATA)
20095 		goto notdata;
20096 
20097 	if (mp->b_flag & MSGHASREF) {
20098 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20099 		mp->b_flag &= ~MSGHASREF;
20100 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20101 		need_decref = B_TRUE;
20102 	}
20103 	ipha = (ipha_t *)mp->b_rptr;
20104 
20105 	/* is IP header non-aligned or mblk smaller than basic IP header */
20106 #ifndef SAFETY_BEFORE_SPEED
20107 	if (!OK_32PTR(rptr) ||
20108 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20109 		goto hdrtoosmall;
20110 #endif
20111 
20112 	ASSERT(OK_32PTR(ipha));
20113 
20114 	/*
20115 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20116 	 * wrong version, we'll catch it again in ip_output_v6.
20117 	 *
20118 	 * Note that this is *only* locally-generated output here, and never
20119 	 * forwarded data, and that we need to deal only with transports that
20120 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20121 	 * label.)
20122 	 */
20123 	if (is_system_labeled() &&
20124 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20125 	    !connp->conn_ulp_labeled) {
20126 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
20127 		    connp->conn_mac_exempt, ipst);
20128 		ipha = (ipha_t *)mp->b_rptr;
20129 		if (err != 0) {
20130 			first_mp = mp;
20131 			if (err == EINVAL)
20132 				goto icmp_parameter_problem;
20133 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20134 			goto discard_pkt;
20135 		}
20136 		iplen = ntohs(ipha->ipha_length) + adjust;
20137 		ipha->ipha_length = htons(iplen);
20138 	}
20139 
20140 	ASSERT(infop != NULL);
20141 
20142 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20143 		/*
20144 		 * IP_PKTINFO ancillary option is present.
20145 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20146 		 * allows using address of any zone as the source address.
20147 		 */
20148 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20149 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20150 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20151 		if (ire == NULL)
20152 			goto drop_pkt;
20153 		ire_refrele(ire);
20154 		ire = NULL;
20155 	}
20156 
20157 	/*
20158 	 * IP_DONTFAILOVER_IF and IP_BOUND_IF have precedence over ill index
20159 	 * passed in IP_PKTINFO.
20160 	 */
20161 	if (infop->ip_opt_ill_index != 0 &&
20162 	    connp->conn_outgoing_ill == NULL &&
20163 	    connp->conn_nofailover_ill == NULL) {
20164 
20165 		xmit_ill = ill_lookup_on_ifindex(
20166 		    infop->ip_opt_ill_index, B_FALSE, NULL, NULL, NULL, NULL,
20167 		    ipst);
20168 
20169 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20170 			goto drop_pkt;
20171 		/*
20172 		 * check that there is an ipif belonging
20173 		 * to our zone. IPCL_ZONEID is not used because
20174 		 * IP_ALLZONES option is valid only when the ill is
20175 		 * accessible from all zones i.e has a valid ipif in
20176 		 * all zones.
20177 		 */
20178 		if (!ipif_lookup_zoneid_group(xmit_ill, zoneid, 0, NULL)) {
20179 			goto drop_pkt;
20180 		}
20181 	}
20182 
20183 	/*
20184 	 * If there is a policy, try to attach an ipsec_out in
20185 	 * the front. At the end, first_mp either points to a
20186 	 * M_DATA message or IPSEC_OUT message linked to a
20187 	 * M_DATA message. We have to do it now as we might
20188 	 * lose the "conn" if we go through ip_newroute.
20189 	 */
20190 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20191 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20192 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20193 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20194 			if (need_decref)
20195 				CONN_DEC_REF(connp);
20196 			return;
20197 		} else {
20198 			ASSERT(mp->b_datap->db_type == M_CTL);
20199 			first_mp = mp;
20200 			mp = mp->b_cont;
20201 			mctl_present = B_TRUE;
20202 		}
20203 	} else {
20204 		first_mp = mp;
20205 		mctl_present = B_FALSE;
20206 	}
20207 
20208 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20209 
20210 	/* is wrong version or IP options present */
20211 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20212 		goto version_hdrlen_check;
20213 	dst = ipha->ipha_dst;
20214 
20215 	if (connp->conn_nofailover_ill != NULL) {
20216 		attach_ill = conn_get_held_ill(connp,
20217 		    &connp->conn_nofailover_ill, &err);
20218 		if (err == ILL_LOOKUP_FAILED) {
20219 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20220 			if (need_decref)
20221 				CONN_DEC_REF(connp);
20222 			freemsg(first_mp);
20223 			return;
20224 		}
20225 	}
20226 
20227 	/* If IP_BOUND_IF has been set, use that ill. */
20228 	if (connp->conn_outgoing_ill != NULL) {
20229 		xmit_ill = conn_get_held_ill(connp,
20230 		    &connp->conn_outgoing_ill, &err);
20231 		if (err == ILL_LOOKUP_FAILED)
20232 			goto drop_pkt;
20233 
20234 		goto send_from_ill;
20235 	}
20236 
20237 	/* is packet multicast? */
20238 	if (CLASSD(dst))
20239 		goto multicast;
20240 
20241 	/*
20242 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20243 	 * takes precedence over conn_dontroute and conn_nexthop_set
20244 	 */
20245 	if (xmit_ill != NULL)
20246 		goto send_from_ill;
20247 
20248 	if (connp->conn_dontroute || connp->conn_nexthop_set) {
20249 		/*
20250 		 * If the destination is a broadcast, local, or loopback
20251 		 * address, SO_DONTROUTE and IP_NEXTHOP go through the
20252 		 * standard path.
20253 		 */
20254 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20255 		if ((ire == NULL) || (ire->ire_type &
20256 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK)) == 0) {
20257 			if (ire != NULL) {
20258 				ire_refrele(ire);
20259 				/* No more access to ire */
20260 				ire = NULL;
20261 			}
20262 			/*
20263 			 * bypass routing checks and go directly to interface.
20264 			 */
20265 			if (connp->conn_dontroute)
20266 				goto dontroute;
20267 
20268 			ASSERT(connp->conn_nexthop_set);
20269 			ip_nexthop = B_TRUE;
20270 			nexthop_addr = connp->conn_nexthop_v4;
20271 			goto send_from_ill;
20272 		}
20273 
20274 		/* Must be a broadcast, a loopback or a local ire */
20275 		ire_refrele(ire);
20276 		/* No more access to ire */
20277 		ire = NULL;
20278 	}
20279 
20280 	if (attach_ill != NULL)
20281 		goto send_from_ill;
20282 
20283 	/*
20284 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20285 	 * this for the tcp global queue and listen end point
20286 	 * as it does not really have a real destination to
20287 	 * talk to.  This is also true for SCTP.
20288 	 */
20289 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20290 	    !connp->conn_fully_bound) {
20291 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20292 		if (ire == NULL)
20293 			goto noirefound;
20294 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20295 		    "ip_wput_end: q %p (%S)", q, "end");
20296 
20297 		/*
20298 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20299 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20300 		 */
20301 		if (ire->ire_flags & RTF_MULTIRT) {
20302 
20303 			/*
20304 			 * Force the TTL of multirouted packets if required.
20305 			 * The TTL of such packets is bounded by the
20306 			 * ip_multirt_ttl ndd variable.
20307 			 */
20308 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20309 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20310 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20311 				    "(was %d), dst 0x%08x\n",
20312 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20313 				    ntohl(ire->ire_addr)));
20314 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20315 			}
20316 			/*
20317 			 * We look at this point if there are pending
20318 			 * unresolved routes. ire_multirt_resolvable()
20319 			 * checks in O(n) that all IRE_OFFSUBNET ire
20320 			 * entries for the packet's destination and
20321 			 * flagged RTF_MULTIRT are currently resolved.
20322 			 * If some remain unresolved, we make a copy
20323 			 * of the current message. It will be used
20324 			 * to initiate additional route resolutions.
20325 			 */
20326 			multirt_need_resolve =
20327 			    ire_multirt_need_resolve(ire->ire_addr,
20328 			    MBLK_GETLABEL(first_mp), ipst);
20329 			ip2dbg(("ip_wput[TCP]: ire %p, "
20330 			    "multirt_need_resolve %d, first_mp %p\n",
20331 			    (void *)ire, multirt_need_resolve,
20332 			    (void *)first_mp));
20333 			if (multirt_need_resolve) {
20334 				copy_mp = copymsg(first_mp);
20335 				if (copy_mp != NULL) {
20336 					MULTIRT_DEBUG_TAG(copy_mp);
20337 				}
20338 			}
20339 		}
20340 
20341 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20342 
20343 		/*
20344 		 * Try to resolve another multiroute if
20345 		 * ire_multirt_need_resolve() deemed it necessary.
20346 		 */
20347 		if (copy_mp != NULL)
20348 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20349 		if (need_decref)
20350 			CONN_DEC_REF(connp);
20351 		return;
20352 	}
20353 
20354 	/*
20355 	 * Access to conn_ire_cache. (protected by conn_lock)
20356 	 *
20357 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20358 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20359 	 * send a packet or two with the IRE_CACHE that is going away.
20360 	 * Access to the ire requires an ire refhold on the ire prior to
20361 	 * its use since an interface unplumb thread may delete the cached
20362 	 * ire and release the refhold at any time.
20363 	 *
20364 	 * Caching an ire in the conn_ire_cache
20365 	 *
20366 	 * o Caching an ire pointer in the conn requires a strict check for
20367 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20368 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20369 	 * in the conn is done after making sure under the bucket lock that the
20370 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20371 	 * caching an ire after the unplumb thread has cleaned up the conn.
20372 	 * If the conn does not send a packet subsequently the unplumb thread
20373 	 * will be hanging waiting for the ire count to drop to zero.
20374 	 *
20375 	 * o We also need to atomically test for a null conn_ire_cache and
20376 	 * set the conn_ire_cache under the the protection of the conn_lock
20377 	 * to avoid races among concurrent threads trying to simultaneously
20378 	 * cache an ire in the conn_ire_cache.
20379 	 */
20380 	mutex_enter(&connp->conn_lock);
20381 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20382 
20383 	if (ire != NULL && ire->ire_addr == dst &&
20384 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20385 
20386 		IRE_REFHOLD(ire);
20387 		mutex_exit(&connp->conn_lock);
20388 
20389 	} else {
20390 		boolean_t cached = B_FALSE;
20391 		connp->conn_ire_cache = NULL;
20392 		mutex_exit(&connp->conn_lock);
20393 		/* Release the old ire */
20394 		if (ire != NULL && sctp_ire == NULL)
20395 			IRE_REFRELE_NOTR(ire);
20396 
20397 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20398 		if (ire == NULL)
20399 			goto noirefound;
20400 		IRE_REFHOLD_NOTR(ire);
20401 
20402 		mutex_enter(&connp->conn_lock);
20403 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20404 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20405 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20406 				if (connp->conn_ulp == IPPROTO_TCP)
20407 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20408 				connp->conn_ire_cache = ire;
20409 				cached = B_TRUE;
20410 			}
20411 			rw_exit(&ire->ire_bucket->irb_lock);
20412 		}
20413 		mutex_exit(&connp->conn_lock);
20414 
20415 		/*
20416 		 * We can continue to use the ire but since it was
20417 		 * not cached, we should drop the extra reference.
20418 		 */
20419 		if (!cached)
20420 			IRE_REFRELE_NOTR(ire);
20421 	}
20422 
20423 
20424 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20425 	    "ip_wput_end: q %p (%S)", q, "end");
20426 
20427 	/*
20428 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20429 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20430 	 */
20431 	if (ire->ire_flags & RTF_MULTIRT) {
20432 
20433 		/*
20434 		 * Force the TTL of multirouted packets if required.
20435 		 * The TTL of such packets is bounded by the
20436 		 * ip_multirt_ttl ndd variable.
20437 		 */
20438 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20439 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20440 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20441 			    "(was %d), dst 0x%08x\n",
20442 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20443 			    ntohl(ire->ire_addr)));
20444 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20445 		}
20446 
20447 		/*
20448 		 * At this point, we check to see if there are any pending
20449 		 * unresolved routes. ire_multirt_resolvable()
20450 		 * checks in O(n) that all IRE_OFFSUBNET ire
20451 		 * entries for the packet's destination and
20452 		 * flagged RTF_MULTIRT are currently resolved.
20453 		 * If some remain unresolved, we make a copy
20454 		 * of the current message. It will be used
20455 		 * to initiate additional route resolutions.
20456 		 */
20457 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20458 		    MBLK_GETLABEL(first_mp), ipst);
20459 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20460 		    "multirt_need_resolve %d, first_mp %p\n",
20461 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20462 		if (multirt_need_resolve) {
20463 			copy_mp = copymsg(first_mp);
20464 			if (copy_mp != NULL) {
20465 				MULTIRT_DEBUG_TAG(copy_mp);
20466 			}
20467 		}
20468 	}
20469 
20470 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20471 
20472 	/*
20473 	 * Try to resolve another multiroute if
20474 	 * ire_multirt_resolvable() deemed it necessary
20475 	 */
20476 	if (copy_mp != NULL)
20477 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20478 	if (need_decref)
20479 		CONN_DEC_REF(connp);
20480 	return;
20481 
20482 qnext:
20483 	/*
20484 	 * Upper Level Protocols pass down complete IP datagrams
20485 	 * as M_DATA messages.	Everything else is a sideshow.
20486 	 *
20487 	 * 1) We could be re-entering ip_wput because of ip_neworute
20488 	 *    in which case we could have a IPSEC_OUT message. We
20489 	 *    need to pass through ip_wput like other datagrams and
20490 	 *    hence cannot branch to ip_wput_nondata.
20491 	 *
20492 	 * 2) ARP, AH, ESP, and other clients who are on the module
20493 	 *    instance of IP stream, give us something to deal with.
20494 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20495 	 *
20496 	 * 3) ICMP replies also could come here.
20497 	 */
20498 	ipst = ILLQ_TO_IPST(q);
20499 
20500 	if (DB_TYPE(mp) != M_DATA) {
20501 notdata:
20502 		if (DB_TYPE(mp) == M_CTL) {
20503 			/*
20504 			 * M_CTL messages are used by ARP, AH and ESP to
20505 			 * communicate with IP. We deal with IPSEC_IN and
20506 			 * IPSEC_OUT here. ip_wput_nondata handles other
20507 			 * cases.
20508 			 */
20509 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20510 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20511 				first_mp = mp->b_cont;
20512 				first_mp->b_flag &= ~MSGHASREF;
20513 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20514 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20515 				CONN_DEC_REF(connp);
20516 				connp = NULL;
20517 			}
20518 			if (ii->ipsec_info_type == IPSEC_IN) {
20519 				/*
20520 				 * Either this message goes back to
20521 				 * IPsec for further processing or to
20522 				 * ULP after policy checks.
20523 				 */
20524 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20525 				return;
20526 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20527 				io = (ipsec_out_t *)ii;
20528 				if (io->ipsec_out_proc_begin) {
20529 					/*
20530 					 * IPsec processing has already started.
20531 					 * Complete it.
20532 					 * IPQoS notes: We don't care what is
20533 					 * in ipsec_out_ill_index since this
20534 					 * won't be processed for IPQoS policies
20535 					 * in ipsec_out_process.
20536 					 */
20537 					ipsec_out_process(q, mp, NULL,
20538 					    io->ipsec_out_ill_index);
20539 					return;
20540 				} else {
20541 					connp = (q->q_next != NULL) ?
20542 					    NULL : Q_TO_CONN(q);
20543 					first_mp = mp;
20544 					mp = mp->b_cont;
20545 					mctl_present = B_TRUE;
20546 				}
20547 				zoneid = io->ipsec_out_zoneid;
20548 				ASSERT(zoneid != ALL_ZONES);
20549 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20550 				/*
20551 				 * It's an IPsec control message requesting
20552 				 * an SADB update to be sent to the IPsec
20553 				 * hardware acceleration capable ills.
20554 				 */
20555 				ipsec_ctl_t *ipsec_ctl =
20556 				    (ipsec_ctl_t *)mp->b_rptr;
20557 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20558 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20559 				mblk_t *cmp = mp->b_cont;
20560 
20561 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20562 				ASSERT(cmp != NULL);
20563 
20564 				freeb(mp);
20565 				ill_ipsec_capab_send_all(satype, cmp, sa,
20566 				    ipst->ips_netstack);
20567 				return;
20568 			} else {
20569 				/*
20570 				 * This must be ARP or special TSOL signaling.
20571 				 */
20572 				ip_wput_nondata(NULL, q, mp, NULL);
20573 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20574 				    "ip_wput_end: q %p (%S)", q, "nondata");
20575 				return;
20576 			}
20577 		} else {
20578 			/*
20579 			 * This must be non-(ARP/AH/ESP) messages.
20580 			 */
20581 			ASSERT(!need_decref);
20582 			ip_wput_nondata(NULL, q, mp, NULL);
20583 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20584 			    "ip_wput_end: q %p (%S)", q, "nondata");
20585 			return;
20586 		}
20587 	} else {
20588 		first_mp = mp;
20589 		mctl_present = B_FALSE;
20590 	}
20591 
20592 	ASSERT(first_mp != NULL);
20593 	/*
20594 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20595 	 * to make sure that this packet goes out on the same interface it
20596 	 * came in. We handle that here.
20597 	 */
20598 	if (mctl_present) {
20599 		uint_t ifindex;
20600 
20601 		io = (ipsec_out_t *)first_mp->b_rptr;
20602 		if (io->ipsec_out_attach_if || io->ipsec_out_ip_nexthop) {
20603 			/*
20604 			 * We may have lost the conn context if we are
20605 			 * coming here from ip_newroute(). Copy the
20606 			 * nexthop information.
20607 			 */
20608 			if (io->ipsec_out_ip_nexthop) {
20609 				ip_nexthop = B_TRUE;
20610 				nexthop_addr = io->ipsec_out_nexthop_addr;
20611 
20612 				ipha = (ipha_t *)mp->b_rptr;
20613 				dst = ipha->ipha_dst;
20614 				goto send_from_ill;
20615 			} else {
20616 				ASSERT(io->ipsec_out_ill_index != 0);
20617 				ifindex = io->ipsec_out_ill_index;
20618 				attach_ill = ill_lookup_on_ifindex(ifindex,
20619 				    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20620 				if (attach_ill == NULL) {
20621 					ASSERT(xmit_ill == NULL);
20622 					ip1dbg(("ip_output: bad ifindex for "
20623 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20624 					    ifindex));
20625 					freemsg(first_mp);
20626 					BUMP_MIB(&ipst->ips_ip_mib,
20627 					    ipIfStatsOutDiscards);
20628 					ASSERT(!need_decref);
20629 					return;
20630 				}
20631 			}
20632 		}
20633 	}
20634 
20635 	ASSERT(xmit_ill == NULL);
20636 
20637 	/* We have a complete IP datagram heading outbound. */
20638 	ipha = (ipha_t *)mp->b_rptr;
20639 
20640 #ifndef SPEED_BEFORE_SAFETY
20641 	/*
20642 	 * Make sure we have a full-word aligned message and that at least
20643 	 * a simple IP header is accessible in the first message.  If not,
20644 	 * try a pullup.
20645 	 */
20646 	if (!OK_32PTR(rptr) ||
20647 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
20648 hdrtoosmall:
20649 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20650 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20651 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20652 			if (first_mp == NULL)
20653 				first_mp = mp;
20654 			goto discard_pkt;
20655 		}
20656 
20657 		/* This function assumes that mp points to an IPv4 packet. */
20658 		if (is_system_labeled() && q->q_next == NULL &&
20659 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20660 		    !connp->conn_ulp_labeled) {
20661 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20662 			    &adjust, connp->conn_mac_exempt, ipst);
20663 			ipha = (ipha_t *)mp->b_rptr;
20664 			if (first_mp != NULL)
20665 				first_mp->b_cont = mp;
20666 			if (err != 0) {
20667 				if (first_mp == NULL)
20668 					first_mp = mp;
20669 				if (err == EINVAL)
20670 					goto icmp_parameter_problem;
20671 				ip2dbg(("ip_wput: label check failed (%d)\n",
20672 				    err));
20673 				goto discard_pkt;
20674 			}
20675 			iplen = ntohs(ipha->ipha_length) + adjust;
20676 			ipha->ipha_length = htons(iplen);
20677 		}
20678 
20679 		ipha = (ipha_t *)mp->b_rptr;
20680 		if (first_mp == NULL) {
20681 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20682 			/*
20683 			 * If we got here because of "goto hdrtoosmall"
20684 			 * We need to attach a IPSEC_OUT.
20685 			 */
20686 			if (connp->conn_out_enforce_policy) {
20687 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
20688 				    NULL, ipha->ipha_protocol,
20689 				    ipst->ips_netstack)) == NULL)) {
20690 					BUMP_MIB(&ipst->ips_ip_mib,
20691 					    ipIfStatsOutDiscards);
20692 					if (need_decref)
20693 						CONN_DEC_REF(connp);
20694 					return;
20695 				} else {
20696 					ASSERT(mp->b_datap->db_type == M_CTL);
20697 					first_mp = mp;
20698 					mp = mp->b_cont;
20699 					mctl_present = B_TRUE;
20700 				}
20701 			} else {
20702 				first_mp = mp;
20703 				mctl_present = B_FALSE;
20704 			}
20705 		}
20706 	}
20707 #endif
20708 
20709 	/* Most of the code below is written for speed, not readability */
20710 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20711 
20712 	/*
20713 	 * If ip_newroute() fails, we're going to need a full
20714 	 * header for the icmp wraparound.
20715 	 */
20716 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20717 		uint_t	v_hlen;
20718 version_hdrlen_check:
20719 		ASSERT(first_mp != NULL);
20720 		v_hlen = V_HLEN;
20721 		/*
20722 		 * siphon off IPv6 packets coming down from transport
20723 		 * layer modules here.
20724 		 * Note: high-order bit carries NUD reachability confirmation
20725 		 */
20726 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20727 			/*
20728 			 * FIXME: assume that callers of ip_output* call
20729 			 * the right version?
20730 			 */
20731 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
20732 			ASSERT(xmit_ill == NULL);
20733 			if (attach_ill != NULL)
20734 				ill_refrele(attach_ill);
20735 			if (need_decref)
20736 				mp->b_flag |= MSGHASREF;
20737 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20738 			return;
20739 		}
20740 
20741 		if ((v_hlen >> 4) != IP_VERSION) {
20742 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20743 			    "ip_wput_end: q %p (%S)", q, "badvers");
20744 			goto discard_pkt;
20745 		}
20746 		/*
20747 		 * Is the header length at least 20 bytes?
20748 		 *
20749 		 * Are there enough bytes accessible in the header?  If
20750 		 * not, try a pullup.
20751 		 */
20752 		v_hlen &= 0xF;
20753 		v_hlen <<= 2;
20754 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20755 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20756 			    "ip_wput_end: q %p (%S)", q, "badlen");
20757 			goto discard_pkt;
20758 		}
20759 		if (v_hlen > (mp->b_wptr - rptr)) {
20760 			if (!pullupmsg(mp, v_hlen)) {
20761 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20762 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20763 				goto discard_pkt;
20764 			}
20765 			ipha = (ipha_t *)mp->b_rptr;
20766 		}
20767 		/*
20768 		 * Move first entry from any source route into ipha_dst and
20769 		 * verify the options
20770 		 */
20771 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
20772 		    zoneid, ipst)) {
20773 			ASSERT(xmit_ill == NULL);
20774 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20775 			if (attach_ill != NULL)
20776 				ill_refrele(attach_ill);
20777 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20778 			    "ip_wput_end: q %p (%S)", q, "badopts");
20779 			if (need_decref)
20780 				CONN_DEC_REF(connp);
20781 			return;
20782 		}
20783 	}
20784 	dst = ipha->ipha_dst;
20785 
20786 	/*
20787 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20788 	 * we have to run the packet through ip_newroute which will take
20789 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
20790 	 * a resolver, or assigning a default gateway, etc.
20791 	 */
20792 	if (CLASSD(dst)) {
20793 		ipif_t	*ipif;
20794 		uint32_t setsrc = 0;
20795 
20796 multicast:
20797 		ASSERT(first_mp != NULL);
20798 		ip2dbg(("ip_wput: CLASSD\n"));
20799 		if (connp == NULL) {
20800 			/*
20801 			 * Use the first good ipif on the ill.
20802 			 * XXX Should this ever happen? (Appears
20803 			 * to show up with just ppp and no ethernet due
20804 			 * to in.rdisc.)
20805 			 * However, ire_send should be able to
20806 			 * call ip_wput_ire directly.
20807 			 *
20808 			 * XXX Also, this can happen for ICMP and other packets
20809 			 * with multicast source addresses.  Perhaps we should
20810 			 * fix things so that we drop the packet in question,
20811 			 * but for now, just run with it.
20812 			 */
20813 			ill_t *ill = (ill_t *)q->q_ptr;
20814 
20815 			/*
20816 			 * Don't honor attach_if for this case. If ill
20817 			 * is part of the group, ipif could belong to
20818 			 * any ill and we cannot maintain attach_ill
20819 			 * and ipif_ill same anymore and the assert
20820 			 * below would fail.
20821 			 */
20822 			if (mctl_present && io->ipsec_out_attach_if) {
20823 				io->ipsec_out_ill_index = 0;
20824 				io->ipsec_out_attach_if = B_FALSE;
20825 				ASSERT(attach_ill != NULL);
20826 				ill_refrele(attach_ill);
20827 				attach_ill = NULL;
20828 			}
20829 
20830 			ASSERT(attach_ill == NULL);
20831 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
20832 			if (ipif == NULL) {
20833 				if (need_decref)
20834 					CONN_DEC_REF(connp);
20835 				freemsg(first_mp);
20836 				return;
20837 			}
20838 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
20839 			    ntohl(dst), ill->ill_name));
20840 		} else {
20841 			/*
20842 			 * The order of precedence is IP_BOUND_IF, IP_PKTINFO
20843 			 * and IP_MULTICAST_IF.  The block comment above this
20844 			 * function explains the locking mechanism used here.
20845 			 */
20846 			if (xmit_ill == NULL) {
20847 				xmit_ill = conn_get_held_ill(connp,
20848 				    &connp->conn_outgoing_ill, &err);
20849 				if (err == ILL_LOOKUP_FAILED) {
20850 					ip1dbg(("ip_wput: No ill for "
20851 					    "IP_BOUND_IF\n"));
20852 					BUMP_MIB(&ipst->ips_ip_mib,
20853 					    ipIfStatsOutNoRoutes);
20854 					goto drop_pkt;
20855 				}
20856 			}
20857 
20858 			if (xmit_ill == NULL) {
20859 				ipif = conn_get_held_ipif(connp,
20860 				    &connp->conn_multicast_ipif, &err);
20861 				if (err == IPIF_LOOKUP_FAILED) {
20862 					ip1dbg(("ip_wput: No ipif for "
20863 					    "multicast\n"));
20864 					BUMP_MIB(&ipst->ips_ip_mib,
20865 					    ipIfStatsOutNoRoutes);
20866 					goto drop_pkt;
20867 				}
20868 			}
20869 			if (xmit_ill != NULL) {
20870 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20871 				if (ipif == NULL) {
20872 					ip1dbg(("ip_wput: No ipif for "
20873 					    "xmit_ill\n"));
20874 					BUMP_MIB(&ipst->ips_ip_mib,
20875 					    ipIfStatsOutNoRoutes);
20876 					goto drop_pkt;
20877 				}
20878 			} else if (ipif == NULL || ipif->ipif_isv6) {
20879 				/*
20880 				 * We must do this ipif determination here
20881 				 * else we could pass through ip_newroute
20882 				 * and come back here without the conn context.
20883 				 *
20884 				 * Note: we do late binding i.e. we bind to
20885 				 * the interface when the first packet is sent.
20886 				 * For performance reasons we do not rebind on
20887 				 * each packet but keep the binding until the
20888 				 * next IP_MULTICAST_IF option.
20889 				 *
20890 				 * conn_multicast_{ipif,ill} are shared between
20891 				 * IPv4 and IPv6 and AF_INET6 sockets can
20892 				 * send both IPv4 and IPv6 packets. Hence
20893 				 * we have to check that "isv6" matches above.
20894 				 */
20895 				if (ipif != NULL)
20896 					ipif_refrele(ipif);
20897 				ipif = ipif_lookup_group(dst, zoneid, ipst);
20898 				if (ipif == NULL) {
20899 					ip1dbg(("ip_wput: No ipif for "
20900 					    "multicast\n"));
20901 					BUMP_MIB(&ipst->ips_ip_mib,
20902 					    ipIfStatsOutNoRoutes);
20903 					goto drop_pkt;
20904 				}
20905 				err = conn_set_held_ipif(connp,
20906 				    &connp->conn_multicast_ipif, ipif);
20907 				if (err == IPIF_LOOKUP_FAILED) {
20908 					ipif_refrele(ipif);
20909 					ip1dbg(("ip_wput: No ipif for "
20910 					    "multicast\n"));
20911 					BUMP_MIB(&ipst->ips_ip_mib,
20912 					    ipIfStatsOutNoRoutes);
20913 					goto drop_pkt;
20914 				}
20915 			}
20916 		}
20917 		ASSERT(!ipif->ipif_isv6);
20918 		/*
20919 		 * As we may lose the conn by the time we reach ip_wput_ire,
20920 		 * we copy conn_multicast_loop and conn_dontroute on to an
20921 		 * ipsec_out. In case if this datagram goes out secure,
20922 		 * we need the ill_index also. Copy that also into the
20923 		 * ipsec_out.
20924 		 */
20925 		if (mctl_present) {
20926 			io = (ipsec_out_t *)first_mp->b_rptr;
20927 			ASSERT(first_mp->b_datap->db_type == M_CTL);
20928 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
20929 		} else {
20930 			ASSERT(mp == first_mp);
20931 			if ((first_mp = allocb(sizeof (ipsec_info_t),
20932 			    BPRI_HI)) == NULL) {
20933 				ipif_refrele(ipif);
20934 				first_mp = mp;
20935 				goto discard_pkt;
20936 			}
20937 			first_mp->b_datap->db_type = M_CTL;
20938 			first_mp->b_wptr += sizeof (ipsec_info_t);
20939 			/* ipsec_out_secure is B_FALSE now */
20940 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
20941 			io = (ipsec_out_t *)first_mp->b_rptr;
20942 			io->ipsec_out_type = IPSEC_OUT;
20943 			io->ipsec_out_len = sizeof (ipsec_out_t);
20944 			io->ipsec_out_use_global_policy = B_TRUE;
20945 			io->ipsec_out_ns = ipst->ips_netstack;
20946 			first_mp->b_cont = mp;
20947 			mctl_present = B_TRUE;
20948 		}
20949 		if (attach_ill != NULL) {
20950 			ASSERT(attach_ill == ipif->ipif_ill);
20951 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
20952 
20953 			/*
20954 			 * Check if we need an ire that will not be
20955 			 * looked up by anybody else i.e. HIDDEN.
20956 			 */
20957 			if (ill_is_probeonly(attach_ill)) {
20958 				match_flags |= MATCH_IRE_MARK_HIDDEN;
20959 			}
20960 			io->ipsec_out_ill_index =
20961 			    attach_ill->ill_phyint->phyint_ifindex;
20962 			io->ipsec_out_attach_if = B_TRUE;
20963 		} else {
20964 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
20965 			io->ipsec_out_ill_index =
20966 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
20967 		}
20968 		if (connp != NULL) {
20969 			io->ipsec_out_multicast_loop =
20970 			    connp->conn_multicast_loop;
20971 			io->ipsec_out_dontroute = connp->conn_dontroute;
20972 			io->ipsec_out_zoneid = connp->conn_zoneid;
20973 		}
20974 		/*
20975 		 * If the application uses IP_MULTICAST_IF with
20976 		 * different logical addresses of the same ILL, we
20977 		 * need to make sure that the soruce address of
20978 		 * the packet matches the logical IP address used
20979 		 * in the option. We do it by initializing ipha_src
20980 		 * here. This should keep IPsec also happy as
20981 		 * when we return from IPsec processing, we don't
20982 		 * have to worry about getting the right address on
20983 		 * the packet. Thus it is sufficient to look for
20984 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
20985 		 * MATCH_IRE_IPIF.
20986 		 *
20987 		 * NOTE : We need to do it for non-secure case also as
20988 		 * this might go out secure if there is a global policy
20989 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
20990 		 * address, the source should be initialized already and
20991 		 * hence we won't be initializing here.
20992 		 *
20993 		 * As we do not have the ire yet, it is possible that
20994 		 * we set the source address here and then later discover
20995 		 * that the ire implies the source address to be assigned
20996 		 * through the RTF_SETSRC flag.
20997 		 * In that case, the setsrc variable will remind us
20998 		 * that overwritting the source address by the one
20999 		 * of the RTF_SETSRC-flagged ire is allowed.
21000 		 */
21001 		if (ipha->ipha_src == INADDR_ANY &&
21002 		    (connp == NULL || !connp->conn_unspec_src)) {
21003 			ipha->ipha_src = ipif->ipif_src_addr;
21004 			setsrc = RTF_SETSRC;
21005 		}
21006 		/*
21007 		 * Find an IRE which matches the destination and the outgoing
21008 		 * queue (i.e. the outgoing interface.)
21009 		 * For loopback use a unicast IP address for
21010 		 * the ire lookup.
21011 		 */
21012 		if (IS_LOOPBACK(ipif->ipif_ill))
21013 			dst = ipif->ipif_lcl_addr;
21014 
21015 		/*
21016 		 * If xmit_ill is set, we branch out to ip_newroute_ipif.
21017 		 * We don't need to lookup ire in ctable as the packet
21018 		 * needs to be sent to the destination through the specified
21019 		 * ill irrespective of ires in the cache table.
21020 		 */
21021 		ire = NULL;
21022 		if (xmit_ill == NULL) {
21023 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21024 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21025 		}
21026 
21027 		/*
21028 		 * refrele attach_ill as its not needed anymore.
21029 		 */
21030 		if (attach_ill != NULL) {
21031 			ill_refrele(attach_ill);
21032 			attach_ill = NULL;
21033 		}
21034 
21035 		if (ire == NULL) {
21036 			/*
21037 			 * Multicast loopback and multicast forwarding is
21038 			 * done in ip_wput_ire.
21039 			 *
21040 			 * Mark this packet to make it be delivered to
21041 			 * ip_wput_ire after the new ire has been
21042 			 * created.
21043 			 *
21044 			 * The call to ip_newroute_ipif takes into account
21045 			 * the setsrc reminder. In any case, we take care
21046 			 * of the RTF_MULTIRT flag.
21047 			 */
21048 			mp->b_prev = mp->b_next = NULL;
21049 			if (xmit_ill == NULL ||
21050 			    xmit_ill->ill_ipif_up_count > 0) {
21051 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21052 				    setsrc | RTF_MULTIRT, zoneid, infop);
21053 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21054 				    "ip_wput_end: q %p (%S)", q, "noire");
21055 			} else {
21056 				freemsg(first_mp);
21057 			}
21058 			ipif_refrele(ipif);
21059 			if (xmit_ill != NULL)
21060 				ill_refrele(xmit_ill);
21061 			if (need_decref)
21062 				CONN_DEC_REF(connp);
21063 			return;
21064 		}
21065 
21066 		ipif_refrele(ipif);
21067 		ipif = NULL;
21068 		ASSERT(xmit_ill == NULL);
21069 
21070 		/*
21071 		 * Honor the RTF_SETSRC flag for multicast packets,
21072 		 * if allowed by the setsrc reminder.
21073 		 */
21074 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21075 			ipha->ipha_src = ire->ire_src_addr;
21076 		}
21077 
21078 		/*
21079 		 * Unconditionally force the TTL to 1 for
21080 		 * multirouted multicast packets:
21081 		 * multirouted multicast should not cross
21082 		 * multicast routers.
21083 		 */
21084 		if (ire->ire_flags & RTF_MULTIRT) {
21085 			if (ipha->ipha_ttl > 1) {
21086 				ip2dbg(("ip_wput: forcing multicast "
21087 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21088 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21089 				ipha->ipha_ttl = 1;
21090 			}
21091 		}
21092 	} else {
21093 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
21094 		if ((ire != NULL) && (ire->ire_type &
21095 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21096 			ignore_dontroute = B_TRUE;
21097 			ignore_nexthop = B_TRUE;
21098 		}
21099 		if (ire != NULL) {
21100 			ire_refrele(ire);
21101 			ire = NULL;
21102 		}
21103 		/*
21104 		 * Guard against coming in from arp in which case conn is NULL.
21105 		 * Also guard against non M_DATA with dontroute set but
21106 		 * destined to local, loopback or broadcast addresses.
21107 		 */
21108 		if (connp != NULL && connp->conn_dontroute &&
21109 		    !ignore_dontroute) {
21110 dontroute:
21111 			/*
21112 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21113 			 * routing protocols from seeing false direct
21114 			 * connectivity.
21115 			 */
21116 			ipha->ipha_ttl = 1;
21117 
21118 			/* If suitable ipif not found, drop packet */
21119 			dst_ipif = ipif_lookup_onlink_addr(dst, zoneid, ipst);
21120 			if (dst_ipif == NULL) {
21121 noroute:
21122 				ip1dbg(("ip_wput: no route for dst using"
21123 				    " SO_DONTROUTE\n"));
21124 				BUMP_MIB(&ipst->ips_ip_mib,
21125 				    ipIfStatsOutNoRoutes);
21126 				mp->b_prev = mp->b_next = NULL;
21127 				if (first_mp == NULL)
21128 					first_mp = mp;
21129 				goto drop_pkt;
21130 			} else {
21131 				/*
21132 				 * If suitable ipif has been found, set
21133 				 * xmit_ill to the corresponding
21134 				 * ipif_ill because we'll be using the
21135 				 * send_from_ill logic below.
21136 				 */
21137 				ASSERT(xmit_ill == NULL);
21138 				xmit_ill = dst_ipif->ipif_ill;
21139 				mutex_enter(&xmit_ill->ill_lock);
21140 				if (!ILL_CAN_LOOKUP(xmit_ill)) {
21141 					mutex_exit(&xmit_ill->ill_lock);
21142 					xmit_ill = NULL;
21143 					ipif_refrele(dst_ipif);
21144 					goto noroute;
21145 				}
21146 				ill_refhold_locked(xmit_ill);
21147 				mutex_exit(&xmit_ill->ill_lock);
21148 				ipif_refrele(dst_ipif);
21149 			}
21150 		}
21151 		/*
21152 		 * If we are bound to IPIF_NOFAILOVER address, look for
21153 		 * an IRE_CACHE matching the ill.
21154 		 */
21155 send_from_ill:
21156 		if (attach_ill != NULL) {
21157 			ipif_t	*attach_ipif;
21158 
21159 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21160 
21161 			/*
21162 			 * Check if we need an ire that will not be
21163 			 * looked up by anybody else i.e. HIDDEN.
21164 			 */
21165 			if (ill_is_probeonly(attach_ill)) {
21166 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21167 			}
21168 
21169 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
21170 			if (attach_ipif == NULL) {
21171 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
21172 				goto discard_pkt;
21173 			}
21174 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
21175 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21176 			ipif_refrele(attach_ipif);
21177 		} else if (xmit_ill != NULL) {
21178 			ipif_t *ipif;
21179 
21180 			/*
21181 			 * Mark this packet as originated locally
21182 			 */
21183 			mp->b_prev = mp->b_next = NULL;
21184 
21185 			/*
21186 			 * Could be SO_DONTROUTE case also.
21187 			 * Verify that at least one ipif is up on the ill.
21188 			 */
21189 			if (xmit_ill->ill_ipif_up_count == 0) {
21190 				ip1dbg(("ip_output: xmit_ill %s is down\n",
21191 				    xmit_ill->ill_name));
21192 				goto drop_pkt;
21193 			}
21194 
21195 			ipif = ipif_get_next_ipif(NULL, xmit_ill);
21196 			if (ipif == NULL) {
21197 				ip1dbg(("ip_output: xmit_ill %s NULL ipif\n",
21198 				    xmit_ill->ill_name));
21199 				goto drop_pkt;
21200 			}
21201 
21202 			/*
21203 			 * Look for a ire that is part of the group,
21204 			 * if found use it else call ip_newroute_ipif.
21205 			 * IPCL_ZONEID is not used for matching because
21206 			 * IP_ALLZONES option is valid only when the
21207 			 * ill is accessible from all zones i.e has a
21208 			 * valid ipif in all zones.
21209 			 */
21210 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21211 			ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21212 			    MBLK_GETLABEL(mp), match_flags, ipst);
21213 			/*
21214 			 * If an ire exists use it or else create
21215 			 * an ire but don't add it to the cache.
21216 			 * Adding an ire may cause issues with
21217 			 * asymmetric routing.
21218 			 * In case of multiroute always act as if
21219 			 * ire does not exist.
21220 			 */
21221 			if (ire == NULL || ire->ire_flags & RTF_MULTIRT) {
21222 				if (ire != NULL)
21223 					ire_refrele(ire);
21224 				ip_newroute_ipif(q, first_mp, ipif,
21225 				    dst, connp, 0, zoneid, infop);
21226 				ipif_refrele(ipif);
21227 				ip1dbg(("ip_output: xmit_ill via %s\n",
21228 				    xmit_ill->ill_name));
21229 				ill_refrele(xmit_ill);
21230 				if (need_decref)
21231 					CONN_DEC_REF(connp);
21232 				return;
21233 			}
21234 			ipif_refrele(ipif);
21235 		} else if (ip_nexthop || (connp != NULL &&
21236 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21237 			if (!ip_nexthop) {
21238 				ip_nexthop = B_TRUE;
21239 				nexthop_addr = connp->conn_nexthop_v4;
21240 			}
21241 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21242 			    MATCH_IRE_GW;
21243 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21244 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21245 		} else {
21246 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp),
21247 			    ipst);
21248 		}
21249 		if (!ire) {
21250 			/*
21251 			 * Make sure we don't load spread if this
21252 			 * is IPIF_NOFAILOVER case.
21253 			 */
21254 			if ((attach_ill != NULL) ||
21255 			    (ip_nexthop && !ignore_nexthop)) {
21256 				if (mctl_present) {
21257 					io = (ipsec_out_t *)first_mp->b_rptr;
21258 					ASSERT(first_mp->b_datap->db_type ==
21259 					    M_CTL);
21260 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21261 				} else {
21262 					ASSERT(mp == first_mp);
21263 					first_mp = allocb(
21264 					    sizeof (ipsec_info_t), BPRI_HI);
21265 					if (first_mp == NULL) {
21266 						first_mp = mp;
21267 						goto discard_pkt;
21268 					}
21269 					first_mp->b_datap->db_type = M_CTL;
21270 					first_mp->b_wptr +=
21271 					    sizeof (ipsec_info_t);
21272 					/* ipsec_out_secure is B_FALSE now */
21273 					bzero(first_mp->b_rptr,
21274 					    sizeof (ipsec_info_t));
21275 					io = (ipsec_out_t *)first_mp->b_rptr;
21276 					io->ipsec_out_type = IPSEC_OUT;
21277 					io->ipsec_out_len =
21278 					    sizeof (ipsec_out_t);
21279 					io->ipsec_out_use_global_policy =
21280 					    B_TRUE;
21281 					io->ipsec_out_ns = ipst->ips_netstack;
21282 					first_mp->b_cont = mp;
21283 					mctl_present = B_TRUE;
21284 				}
21285 				if (attach_ill != NULL) {
21286 					io->ipsec_out_ill_index = attach_ill->
21287 					    ill_phyint->phyint_ifindex;
21288 					io->ipsec_out_attach_if = B_TRUE;
21289 				} else {
21290 					io->ipsec_out_ip_nexthop = ip_nexthop;
21291 					io->ipsec_out_nexthop_addr =
21292 					    nexthop_addr;
21293 				}
21294 			}
21295 noirefound:
21296 			/*
21297 			 * Mark this packet as having originated on
21298 			 * this machine.  This will be noted in
21299 			 * ire_add_then_send, which needs to know
21300 			 * whether to run it back through ip_wput or
21301 			 * ip_rput following successful resolution.
21302 			 */
21303 			mp->b_prev = NULL;
21304 			mp->b_next = NULL;
21305 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21306 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21307 			    "ip_wput_end: q %p (%S)", q, "newroute");
21308 			if (attach_ill != NULL)
21309 				ill_refrele(attach_ill);
21310 			if (xmit_ill != NULL)
21311 				ill_refrele(xmit_ill);
21312 			if (need_decref)
21313 				CONN_DEC_REF(connp);
21314 			return;
21315 		}
21316 	}
21317 
21318 	/* We now know where we are going with it. */
21319 
21320 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21321 	    "ip_wput_end: q %p (%S)", q, "end");
21322 
21323 	/*
21324 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21325 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21326 	 */
21327 	if (ire->ire_flags & RTF_MULTIRT) {
21328 		/*
21329 		 * Force the TTL of multirouted packets if required.
21330 		 * The TTL of such packets is bounded by the
21331 		 * ip_multirt_ttl ndd variable.
21332 		 */
21333 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21334 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21335 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21336 			    "(was %d), dst 0x%08x\n",
21337 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21338 			    ntohl(ire->ire_addr)));
21339 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21340 		}
21341 		/*
21342 		 * At this point, we check to see if there are any pending
21343 		 * unresolved routes. ire_multirt_resolvable()
21344 		 * checks in O(n) that all IRE_OFFSUBNET ire
21345 		 * entries for the packet's destination and
21346 		 * flagged RTF_MULTIRT are currently resolved.
21347 		 * If some remain unresolved, we make a copy
21348 		 * of the current message. It will be used
21349 		 * to initiate additional route resolutions.
21350 		 */
21351 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21352 		    MBLK_GETLABEL(first_mp), ipst);
21353 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21354 		    "multirt_need_resolve %d, first_mp %p\n",
21355 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21356 		if (multirt_need_resolve) {
21357 			copy_mp = copymsg(first_mp);
21358 			if (copy_mp != NULL) {
21359 				MULTIRT_DEBUG_TAG(copy_mp);
21360 			}
21361 		}
21362 	}
21363 
21364 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21365 	/*
21366 	 * Try to resolve another multiroute if
21367 	 * ire_multirt_resolvable() deemed it necessary.
21368 	 * At this point, we need to distinguish
21369 	 * multicasts from other packets. For multicasts,
21370 	 * we call ip_newroute_ipif() and request that both
21371 	 * multirouting and setsrc flags are checked.
21372 	 */
21373 	if (copy_mp != NULL) {
21374 		if (CLASSD(dst)) {
21375 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21376 			if (ipif) {
21377 				ASSERT(infop->ip_opt_ill_index == 0);
21378 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21379 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21380 				ipif_refrele(ipif);
21381 			} else {
21382 				MULTIRT_DEBUG_UNTAG(copy_mp);
21383 				freemsg(copy_mp);
21384 				copy_mp = NULL;
21385 			}
21386 		} else {
21387 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21388 		}
21389 	}
21390 	if (attach_ill != NULL)
21391 		ill_refrele(attach_ill);
21392 	if (xmit_ill != NULL)
21393 		ill_refrele(xmit_ill);
21394 	if (need_decref)
21395 		CONN_DEC_REF(connp);
21396 	return;
21397 
21398 icmp_parameter_problem:
21399 	/* could not have originated externally */
21400 	ASSERT(mp->b_prev == NULL);
21401 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21402 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21403 		/* it's the IP header length that's in trouble */
21404 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21405 		first_mp = NULL;
21406 	}
21407 
21408 discard_pkt:
21409 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21410 drop_pkt:
21411 	ip1dbg(("ip_wput: dropped packet\n"));
21412 	if (ire != NULL)
21413 		ire_refrele(ire);
21414 	if (need_decref)
21415 		CONN_DEC_REF(connp);
21416 	freemsg(first_mp);
21417 	if (attach_ill != NULL)
21418 		ill_refrele(attach_ill);
21419 	if (xmit_ill != NULL)
21420 		ill_refrele(xmit_ill);
21421 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21422 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21423 }
21424 
21425 /*
21426  * If this is a conn_t queue, then we pass in the conn. This includes the
21427  * zoneid.
21428  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21429  * in which case we use the global zoneid since those are all part of
21430  * the global zone.
21431  */
21432 void
21433 ip_wput(queue_t *q, mblk_t *mp)
21434 {
21435 	if (CONN_Q(q))
21436 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21437 	else
21438 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21439 }
21440 
21441 /*
21442  *
21443  * The following rules must be observed when accessing any ipif or ill
21444  * that has been cached in the conn. Typically conn_nofailover_ill,
21445  * conn_outgoing_ill, conn_multicast_ipif and conn_multicast_ill.
21446  *
21447  * Access: The ipif or ill pointed to from the conn can be accessed under
21448  * the protection of the conn_lock or after it has been refheld under the
21449  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21450  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21451  * The reason for this is that a concurrent unplumb could actually be
21452  * cleaning up these cached pointers by walking the conns and might have
21453  * finished cleaning up the conn in question. The macros check that an
21454  * unplumb has not yet started on the ipif or ill.
21455  *
21456  * Caching: An ipif or ill pointer may be cached in the conn only after
21457  * making sure that an unplumb has not started. So the caching is done
21458  * while holding both the conn_lock and the ill_lock and after using the
21459  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21460  * flag before starting the cleanup of conns.
21461  *
21462  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21463  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21464  * or a reference to the ipif or a reference to an ire that references the
21465  * ipif. An ipif does not change its ill except for failover/failback. Since
21466  * failover/failback happens only after bringing down the ipif and making sure
21467  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
21468  * the above holds.
21469  */
21470 ipif_t *
21471 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21472 {
21473 	ipif_t	*ipif;
21474 	ill_t	*ill;
21475 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21476 
21477 	*err = 0;
21478 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21479 	mutex_enter(&connp->conn_lock);
21480 	ipif = *ipifp;
21481 	if (ipif != NULL) {
21482 		ill = ipif->ipif_ill;
21483 		mutex_enter(&ill->ill_lock);
21484 		if (IPIF_CAN_LOOKUP(ipif)) {
21485 			ipif_refhold_locked(ipif);
21486 			mutex_exit(&ill->ill_lock);
21487 			mutex_exit(&connp->conn_lock);
21488 			rw_exit(&ipst->ips_ill_g_lock);
21489 			return (ipif);
21490 		} else {
21491 			*err = IPIF_LOOKUP_FAILED;
21492 		}
21493 		mutex_exit(&ill->ill_lock);
21494 	}
21495 	mutex_exit(&connp->conn_lock);
21496 	rw_exit(&ipst->ips_ill_g_lock);
21497 	return (NULL);
21498 }
21499 
21500 ill_t *
21501 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21502 {
21503 	ill_t	*ill;
21504 
21505 	*err = 0;
21506 	mutex_enter(&connp->conn_lock);
21507 	ill = *illp;
21508 	if (ill != NULL) {
21509 		mutex_enter(&ill->ill_lock);
21510 		if (ILL_CAN_LOOKUP(ill)) {
21511 			ill_refhold_locked(ill);
21512 			mutex_exit(&ill->ill_lock);
21513 			mutex_exit(&connp->conn_lock);
21514 			return (ill);
21515 		} else {
21516 			*err = ILL_LOOKUP_FAILED;
21517 		}
21518 		mutex_exit(&ill->ill_lock);
21519 	}
21520 	mutex_exit(&connp->conn_lock);
21521 	return (NULL);
21522 }
21523 
21524 static int
21525 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21526 {
21527 	ill_t	*ill;
21528 
21529 	ill = ipif->ipif_ill;
21530 	mutex_enter(&connp->conn_lock);
21531 	mutex_enter(&ill->ill_lock);
21532 	if (IPIF_CAN_LOOKUP(ipif)) {
21533 		*ipifp = ipif;
21534 		mutex_exit(&ill->ill_lock);
21535 		mutex_exit(&connp->conn_lock);
21536 		return (0);
21537 	}
21538 	mutex_exit(&ill->ill_lock);
21539 	mutex_exit(&connp->conn_lock);
21540 	return (IPIF_LOOKUP_FAILED);
21541 }
21542 
21543 /*
21544  * This is called if the outbound datagram needs fragmentation.
21545  *
21546  * NOTE : This function does not ire_refrele the ire argument passed in.
21547  */
21548 static void
21549 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21550     ip_stack_t *ipst)
21551 {
21552 	ipha_t		*ipha;
21553 	mblk_t		*mp;
21554 	uint32_t	v_hlen_tos_len;
21555 	uint32_t	max_frag;
21556 	uint32_t	frag_flag;
21557 	boolean_t	dont_use;
21558 
21559 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21560 		mp = ipsec_mp->b_cont;
21561 	} else {
21562 		mp = ipsec_mp;
21563 	}
21564 
21565 	ipha = (ipha_t *)mp->b_rptr;
21566 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21567 
21568 #ifdef	_BIG_ENDIAN
21569 #define	V_HLEN	(v_hlen_tos_len >> 24)
21570 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21571 #else
21572 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21573 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21574 #endif
21575 
21576 #ifndef SPEED_BEFORE_SAFETY
21577 	/*
21578 	 * Check that ipha_length is consistent with
21579 	 * the mblk length
21580 	 */
21581 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21582 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21583 		    LENGTH, msgdsize(mp)));
21584 		freemsg(ipsec_mp);
21585 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21586 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21587 		    "packet length mismatch");
21588 		return;
21589 	}
21590 #endif
21591 	/*
21592 	 * Don't use frag_flag if pre-built packet or source
21593 	 * routed or if multicast (since multicast packets do not solicit
21594 	 * ICMP "packet too big" messages). Get the values of
21595 	 * max_frag and frag_flag atomically by acquiring the
21596 	 * ire_lock.
21597 	 */
21598 	mutex_enter(&ire->ire_lock);
21599 	max_frag = ire->ire_max_frag;
21600 	frag_flag = ire->ire_frag_flag;
21601 	mutex_exit(&ire->ire_lock);
21602 
21603 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21604 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21605 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21606 
21607 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21608 	    (dont_use ? 0 : frag_flag), zoneid, ipst);
21609 }
21610 
21611 /*
21612  * Used for deciding the MSS size for the upper layer. Thus
21613  * we need to check the outbound policy values in the conn.
21614  */
21615 int
21616 conn_ipsec_length(conn_t *connp)
21617 {
21618 	ipsec_latch_t *ipl;
21619 
21620 	ipl = connp->conn_latch;
21621 	if (ipl == NULL)
21622 		return (0);
21623 
21624 	if (ipl->ipl_out_policy == NULL)
21625 		return (0);
21626 
21627 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21628 }
21629 
21630 /*
21631  * Returns an estimate of the IPsec headers size. This is used if
21632  * we don't want to call into IPsec to get the exact size.
21633  */
21634 int
21635 ipsec_out_extra_length(mblk_t *ipsec_mp)
21636 {
21637 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21638 	ipsec_action_t *a;
21639 
21640 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21641 	if (!io->ipsec_out_secure)
21642 		return (0);
21643 
21644 	a = io->ipsec_out_act;
21645 
21646 	if (a == NULL) {
21647 		ASSERT(io->ipsec_out_policy != NULL);
21648 		a = io->ipsec_out_policy->ipsp_act;
21649 	}
21650 	ASSERT(a != NULL);
21651 
21652 	return (a->ipa_ovhd);
21653 }
21654 
21655 /*
21656  * Returns an estimate of the IPsec headers size. This is used if
21657  * we don't want to call into IPsec to get the exact size.
21658  */
21659 int
21660 ipsec_in_extra_length(mblk_t *ipsec_mp)
21661 {
21662 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21663 	ipsec_action_t *a;
21664 
21665 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21666 
21667 	a = ii->ipsec_in_action;
21668 	return (a == NULL ? 0 : a->ipa_ovhd);
21669 }
21670 
21671 /*
21672  * If there are any source route options, return the true final
21673  * destination. Otherwise, return the destination.
21674  */
21675 ipaddr_t
21676 ip_get_dst(ipha_t *ipha)
21677 {
21678 	ipoptp_t	opts;
21679 	uchar_t		*opt;
21680 	uint8_t		optval;
21681 	uint8_t		optlen;
21682 	ipaddr_t	dst;
21683 	uint32_t off;
21684 
21685 	dst = ipha->ipha_dst;
21686 
21687 	if (IS_SIMPLE_IPH(ipha))
21688 		return (dst);
21689 
21690 	for (optval = ipoptp_first(&opts, ipha);
21691 	    optval != IPOPT_EOL;
21692 	    optval = ipoptp_next(&opts)) {
21693 		opt = opts.ipoptp_cur;
21694 		optlen = opts.ipoptp_len;
21695 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21696 		switch (optval) {
21697 		case IPOPT_SSRR:
21698 		case IPOPT_LSRR:
21699 			off = opt[IPOPT_OFFSET];
21700 			/*
21701 			 * If one of the conditions is true, it means
21702 			 * end of options and dst already has the right
21703 			 * value.
21704 			 */
21705 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21706 				off = optlen - IP_ADDR_LEN;
21707 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21708 			}
21709 			return (dst);
21710 		default:
21711 			break;
21712 		}
21713 	}
21714 
21715 	return (dst);
21716 }
21717 
21718 mblk_t *
21719 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21720     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21721 {
21722 	ipsec_out_t	*io;
21723 	mblk_t		*first_mp;
21724 	boolean_t policy_present;
21725 	ip_stack_t	*ipst;
21726 	ipsec_stack_t	*ipss;
21727 
21728 	ASSERT(ire != NULL);
21729 	ipst = ire->ire_ipst;
21730 	ipss = ipst->ips_netstack->netstack_ipsec;
21731 
21732 	first_mp = mp;
21733 	if (mp->b_datap->db_type == M_CTL) {
21734 		io = (ipsec_out_t *)first_mp->b_rptr;
21735 		/*
21736 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21737 		 *
21738 		 * 1) There is per-socket policy (including cached global
21739 		 *    policy) or a policy on the IP-in-IP tunnel.
21740 		 * 2) There is no per-socket policy, but it is
21741 		 *    a multicast packet that needs to go out
21742 		 *    on a specific interface. This is the case
21743 		 *    where (ip_wput and ip_wput_multicast) attaches
21744 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21745 		 *
21746 		 * In case (2) we check with global policy to
21747 		 * see if there is a match and set the ill_index
21748 		 * appropriately so that we can lookup the ire
21749 		 * properly in ip_wput_ipsec_out.
21750 		 */
21751 
21752 		/*
21753 		 * ipsec_out_use_global_policy is set to B_FALSE
21754 		 * in ipsec_in_to_out(). Refer to that function for
21755 		 * details.
21756 		 */
21757 		if ((io->ipsec_out_latch == NULL) &&
21758 		    (io->ipsec_out_use_global_policy)) {
21759 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21760 			    ire, connp, unspec_src, zoneid));
21761 		}
21762 		if (!io->ipsec_out_secure) {
21763 			/*
21764 			 * If this is not a secure packet, drop
21765 			 * the IPSEC_OUT mp and treat it as a clear
21766 			 * packet. This happens when we are sending
21767 			 * a ICMP reply back to a clear packet. See
21768 			 * ipsec_in_to_out() for details.
21769 			 */
21770 			mp = first_mp->b_cont;
21771 			freeb(first_mp);
21772 		}
21773 		return (mp);
21774 	}
21775 	/*
21776 	 * See whether we need to attach a global policy here. We
21777 	 * don't depend on the conn (as it could be null) for deciding
21778 	 * what policy this datagram should go through because it
21779 	 * should have happened in ip_wput if there was some
21780 	 * policy. This normally happens for connections which are not
21781 	 * fully bound preventing us from caching policies in
21782 	 * ip_bind. Packets coming from the TCP listener/global queue
21783 	 * - which are non-hard_bound - could also be affected by
21784 	 * applying policy here.
21785 	 *
21786 	 * If this packet is coming from tcp global queue or listener,
21787 	 * we will be applying policy here.  This may not be *right*
21788 	 * if these packets are coming from the detached connection as
21789 	 * it could have gone in clear before. This happens only if a
21790 	 * TCP connection started when there is no policy and somebody
21791 	 * added policy before it became detached. Thus packets of the
21792 	 * detached connection could go out secure and the other end
21793 	 * would drop it because it will be expecting in clear. The
21794 	 * converse is not true i.e if somebody starts a TCP
21795 	 * connection and deletes the policy, all the packets will
21796 	 * still go out with the policy that existed before deleting
21797 	 * because ip_unbind sends up policy information which is used
21798 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21799 	 * TCP to attach a dummy IPSEC_OUT and set
21800 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21801 	 * affect performance for normal cases, we are not doing it.
21802 	 * Thus, set policy before starting any TCP connections.
21803 	 *
21804 	 * NOTE - We might apply policy even for a hard bound connection
21805 	 * - for which we cached policy in ip_bind - if somebody added
21806 	 * global policy after we inherited the policy in ip_bind.
21807 	 * This means that the packets that were going out in clear
21808 	 * previously would start going secure and hence get dropped
21809 	 * on the other side. To fix this, TCP attaches a dummy
21810 	 * ipsec_out and make sure that we don't apply global policy.
21811 	 */
21812 	if (ipha != NULL)
21813 		policy_present = ipss->ipsec_outbound_v4_policy_present;
21814 	else
21815 		policy_present = ipss->ipsec_outbound_v6_policy_present;
21816 	if (!policy_present)
21817 		return (mp);
21818 
21819 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21820 	    zoneid));
21821 }
21822 
21823 ire_t *
21824 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
21825 {
21826 	ipaddr_t addr;
21827 	ire_t *save_ire;
21828 	irb_t *irb;
21829 	ill_group_t *illgrp;
21830 	int	err;
21831 
21832 	save_ire = ire;
21833 	addr = ire->ire_addr;
21834 
21835 	ASSERT(ire->ire_type == IRE_BROADCAST);
21836 
21837 	illgrp = connp->conn_outgoing_ill->ill_group;
21838 	if (illgrp == NULL) {
21839 		*conn_outgoing_ill = conn_get_held_ill(connp,
21840 		    &connp->conn_outgoing_ill, &err);
21841 		if (err == ILL_LOOKUP_FAILED) {
21842 			ire_refrele(save_ire);
21843 			return (NULL);
21844 		}
21845 		return (save_ire);
21846 	}
21847 	/*
21848 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
21849 	 * If it is part of the group, we need to send on the ire
21850 	 * that has been cleared of IRE_MARK_NORECV and that belongs
21851 	 * to this group. This is okay as IP_BOUND_IF really means
21852 	 * any ill in the group. We depend on the fact that the
21853 	 * first ire in the group is always cleared of IRE_MARK_NORECV
21854 	 * if such an ire exists. This is possible only if you have
21855 	 * at least one ill in the group that has not failed.
21856 	 *
21857 	 * First get to the ire that matches the address and group.
21858 	 *
21859 	 * We don't look for an ire with a matching zoneid because a given zone
21860 	 * won't always have broadcast ires on all ills in the group.
21861 	 */
21862 	irb = ire->ire_bucket;
21863 	rw_enter(&irb->irb_lock, RW_READER);
21864 	if (ire->ire_marks & IRE_MARK_NORECV) {
21865 		/*
21866 		 * If the current zone only has an ire broadcast for this
21867 		 * address marked NORECV, the ire we want is ahead in the
21868 		 * bucket, so we look it up deliberately ignoring the zoneid.
21869 		 */
21870 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
21871 			if (ire->ire_addr != addr)
21872 				continue;
21873 			/* skip over deleted ires */
21874 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
21875 				continue;
21876 		}
21877 	}
21878 	while (ire != NULL) {
21879 		/*
21880 		 * If a new interface is coming up, we could end up
21881 		 * seeing the loopback ire and the non-loopback ire
21882 		 * may not have been added yet. So check for ire_stq
21883 		 */
21884 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
21885 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
21886 			break;
21887 		}
21888 		ire = ire->ire_next;
21889 	}
21890 	if (ire != NULL && ire->ire_addr == addr &&
21891 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
21892 		IRE_REFHOLD(ire);
21893 		rw_exit(&irb->irb_lock);
21894 		ire_refrele(save_ire);
21895 		*conn_outgoing_ill = ire_to_ill(ire);
21896 		/*
21897 		 * Refhold the ill to make the conn_outgoing_ill
21898 		 * independent of the ire. ip_wput_ire goes in a loop
21899 		 * and may refrele the ire. Since we have an ire at this
21900 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
21901 		 */
21902 		ill_refhold(*conn_outgoing_ill);
21903 		return (ire);
21904 	}
21905 	rw_exit(&irb->irb_lock);
21906 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
21907 	/*
21908 	 * If we can't find a suitable ire, return the original ire.
21909 	 */
21910 	return (save_ire);
21911 }
21912 
21913 /*
21914  * This function does the ire_refrele of the ire passed in as the
21915  * argument. As this function looks up more ires i.e broadcast ires,
21916  * it needs to REFRELE them. Currently, for simplicity we don't
21917  * differentiate the one passed in and looked up here. We always
21918  * REFRELE.
21919  * IPQoS Notes:
21920  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
21921  * IPsec packets are done in ipsec_out_process.
21922  *
21923  */
21924 void
21925 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
21926     zoneid_t zoneid)
21927 {
21928 	ipha_t		*ipha;
21929 #define	rptr	((uchar_t *)ipha)
21930 	queue_t		*stq;
21931 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
21932 	uint32_t	v_hlen_tos_len;
21933 	uint32_t	ttl_protocol;
21934 	ipaddr_t	src;
21935 	ipaddr_t	dst;
21936 	uint32_t	cksum;
21937 	ipaddr_t	orig_src;
21938 	ire_t		*ire1;
21939 	mblk_t		*next_mp;
21940 	uint_t		hlen;
21941 	uint16_t	*up;
21942 	uint32_t	max_frag = ire->ire_max_frag;
21943 	ill_t		*ill = ire_to_ill(ire);
21944 	int		clusterwide;
21945 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
21946 	int		ipsec_len;
21947 	mblk_t		*first_mp;
21948 	ipsec_out_t	*io;
21949 	boolean_t	conn_dontroute;		/* conn value for multicast */
21950 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
21951 	boolean_t	multicast_forward;	/* Should we forward ? */
21952 	boolean_t	unspec_src;
21953 	ill_t		*conn_outgoing_ill = NULL;
21954 	ill_t		*ire_ill;
21955 	ill_t		*ire1_ill;
21956 	ill_t		*out_ill;
21957 	uint32_t 	ill_index = 0;
21958 	boolean_t	multirt_send = B_FALSE;
21959 	int		err;
21960 	ipxmit_state_t	pktxmit_state;
21961 	ip_stack_t	*ipst = ire->ire_ipst;
21962 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
21963 
21964 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
21965 	    "ip_wput_ire_start: q %p", q);
21966 
21967 	multicast_forward = B_FALSE;
21968 	unspec_src = (connp != NULL && connp->conn_unspec_src);
21969 
21970 	if (ire->ire_flags & RTF_MULTIRT) {
21971 		/*
21972 		 * Multirouting case. The bucket where ire is stored
21973 		 * probably holds other RTF_MULTIRT flagged ire
21974 		 * to the destination. In this call to ip_wput_ire,
21975 		 * we attempt to send the packet through all
21976 		 * those ires. Thus, we first ensure that ire is the
21977 		 * first RTF_MULTIRT ire in the bucket,
21978 		 * before walking the ire list.
21979 		 */
21980 		ire_t *first_ire;
21981 		irb_t *irb = ire->ire_bucket;
21982 		ASSERT(irb != NULL);
21983 
21984 		/* Make sure we do not omit any multiroute ire. */
21985 		IRB_REFHOLD(irb);
21986 		for (first_ire = irb->irb_ire;
21987 		    first_ire != NULL;
21988 		    first_ire = first_ire->ire_next) {
21989 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
21990 			    (first_ire->ire_addr == ire->ire_addr) &&
21991 			    !(first_ire->ire_marks &
21992 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
21993 				break;
21994 			}
21995 		}
21996 
21997 		if ((first_ire != NULL) && (first_ire != ire)) {
21998 			IRE_REFHOLD(first_ire);
21999 			ire_refrele(ire);
22000 			ire = first_ire;
22001 			ill = ire_to_ill(ire);
22002 		}
22003 		IRB_REFRELE(irb);
22004 	}
22005 
22006 	/*
22007 	 * conn_outgoing_ill variable is used only in the broadcast loop.
22008 	 * for performance we don't grab the mutexs in the fastpath
22009 	 */
22010 	if ((connp != NULL) &&
22011 	    (ire->ire_type == IRE_BROADCAST) &&
22012 	    ((connp->conn_nofailover_ill != NULL) ||
22013 	    (connp->conn_outgoing_ill != NULL))) {
22014 		/*
22015 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
22016 		 * option. So, see if this endpoint is bound to a
22017 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
22018 		 * that if the interface is failed, we will still send
22019 		 * the packet on the same ill which is what we want.
22020 		 */
22021 		conn_outgoing_ill = conn_get_held_ill(connp,
22022 		    &connp->conn_nofailover_ill, &err);
22023 		if (err == ILL_LOOKUP_FAILED) {
22024 			ire_refrele(ire);
22025 			freemsg(mp);
22026 			return;
22027 		}
22028 		if (conn_outgoing_ill == NULL) {
22029 			/*
22030 			 * Choose a good ill in the group to send the
22031 			 * packets on.
22032 			 */
22033 			ire = conn_set_outgoing_ill(connp, ire,
22034 			    &conn_outgoing_ill);
22035 			if (ire == NULL) {
22036 				freemsg(mp);
22037 				return;
22038 			}
22039 		}
22040 	}
22041 
22042 	if (mp->b_datap->db_type != M_CTL) {
22043 		ipha = (ipha_t *)mp->b_rptr;
22044 	} else {
22045 		io = (ipsec_out_t *)mp->b_rptr;
22046 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22047 		ASSERT(zoneid == io->ipsec_out_zoneid);
22048 		ASSERT(zoneid != ALL_ZONES);
22049 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22050 		dst = ipha->ipha_dst;
22051 		/*
22052 		 * For the multicast case, ipsec_out carries conn_dontroute and
22053 		 * conn_multicast_loop as conn may not be available here. We
22054 		 * need this for multicast loopback and forwarding which is done
22055 		 * later in the code.
22056 		 */
22057 		if (CLASSD(dst)) {
22058 			conn_dontroute = io->ipsec_out_dontroute;
22059 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22060 			/*
22061 			 * If conn_dontroute is not set or conn_multicast_loop
22062 			 * is set, we need to do forwarding/loopback. For
22063 			 * datagrams from ip_wput_multicast, conn_dontroute is
22064 			 * set to B_TRUE and conn_multicast_loop is set to
22065 			 * B_FALSE so that we neither do forwarding nor
22066 			 * loopback.
22067 			 */
22068 			if (!conn_dontroute || conn_multicast_loop)
22069 				multicast_forward = B_TRUE;
22070 		}
22071 	}
22072 
22073 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22074 	    ire->ire_zoneid != ALL_ZONES) {
22075 		/*
22076 		 * When a zone sends a packet to another zone, we try to deliver
22077 		 * the packet under the same conditions as if the destination
22078 		 * was a real node on the network. To do so, we look for a
22079 		 * matching route in the forwarding table.
22080 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22081 		 * ip_newroute() does.
22082 		 * Note that IRE_LOCAL are special, since they are used
22083 		 * when the zoneid doesn't match in some cases. This means that
22084 		 * we need to handle ipha_src differently since ire_src_addr
22085 		 * belongs to the receiving zone instead of the sending zone.
22086 		 * When ip_restrict_interzone_loopback is set, then
22087 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22088 		 * for loopback between zones when the logical "Ethernet" would
22089 		 * have looped them back.
22090 		 */
22091 		ire_t *src_ire;
22092 
22093 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22094 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22095 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22096 		if (src_ire != NULL &&
22097 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22098 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22099 		    ire_local_same_ill_group(ire, src_ire))) {
22100 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22101 				ipha->ipha_src = src_ire->ire_src_addr;
22102 			ire_refrele(src_ire);
22103 		} else {
22104 			ire_refrele(ire);
22105 			if (conn_outgoing_ill != NULL)
22106 				ill_refrele(conn_outgoing_ill);
22107 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22108 			if (src_ire != NULL) {
22109 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22110 					ire_refrele(src_ire);
22111 					freemsg(mp);
22112 					return;
22113 				}
22114 				ire_refrele(src_ire);
22115 			}
22116 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22117 				/* Failed */
22118 				freemsg(mp);
22119 				return;
22120 			}
22121 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22122 			    ipst);
22123 			return;
22124 		}
22125 	}
22126 
22127 	if (mp->b_datap->db_type == M_CTL ||
22128 	    ipss->ipsec_outbound_v4_policy_present) {
22129 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22130 		    unspec_src, zoneid);
22131 		if (mp == NULL) {
22132 			ire_refrele(ire);
22133 			if (conn_outgoing_ill != NULL)
22134 				ill_refrele(conn_outgoing_ill);
22135 			return;
22136 		}
22137 	}
22138 
22139 	first_mp = mp;
22140 	ipsec_len = 0;
22141 
22142 	if (first_mp->b_datap->db_type == M_CTL) {
22143 		io = (ipsec_out_t *)first_mp->b_rptr;
22144 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22145 		mp = first_mp->b_cont;
22146 		ipsec_len = ipsec_out_extra_length(first_mp);
22147 		ASSERT(ipsec_len >= 0);
22148 		/* We already picked up the zoneid from the M_CTL above */
22149 		ASSERT(zoneid == io->ipsec_out_zoneid);
22150 		ASSERT(zoneid != ALL_ZONES);
22151 
22152 		/*
22153 		 * Drop M_CTL here if IPsec processing is not needed.
22154 		 * (Non-IPsec use of M_CTL extracted any information it
22155 		 * needed above).
22156 		 */
22157 		if (ipsec_len == 0) {
22158 			freeb(first_mp);
22159 			first_mp = mp;
22160 		}
22161 	}
22162 
22163 	/*
22164 	 * Fast path for ip_wput_ire
22165 	 */
22166 
22167 	ipha = (ipha_t *)mp->b_rptr;
22168 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22169 	dst = ipha->ipha_dst;
22170 
22171 	/*
22172 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22173 	 * if the socket is a SOCK_RAW type. The transport checksum should
22174 	 * be provided in the pre-built packet, so we don't need to compute it.
22175 	 * Also, other application set flags, like DF, should not be altered.
22176 	 * Other transport MUST pass down zero.
22177 	 */
22178 	ip_hdr_included = ipha->ipha_ident;
22179 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22180 
22181 	if (CLASSD(dst)) {
22182 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22183 		    ntohl(dst),
22184 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22185 		    ntohl(ire->ire_addr)));
22186 	}
22187 
22188 /* Macros to extract header fields from data already in registers */
22189 #ifdef	_BIG_ENDIAN
22190 #define	V_HLEN	(v_hlen_tos_len >> 24)
22191 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22192 #define	PROTO	(ttl_protocol & 0xFF)
22193 #else
22194 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22195 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22196 #define	PROTO	(ttl_protocol >> 8)
22197 #endif
22198 
22199 
22200 	orig_src = src = ipha->ipha_src;
22201 	/* (The loop back to "another" is explained down below.) */
22202 another:;
22203 	/*
22204 	 * Assign an ident value for this packet.  We assign idents on
22205 	 * a per destination basis out of the IRE.  There could be
22206 	 * other threads targeting the same destination, so we have to
22207 	 * arrange for a atomic increment.  Note that we use a 32-bit
22208 	 * atomic add because it has better performance than its
22209 	 * 16-bit sibling.
22210 	 *
22211 	 * If running in cluster mode and if the source address
22212 	 * belongs to a replicated service then vector through
22213 	 * cl_inet_ipident vector to allocate ip identifier
22214 	 * NOTE: This is a contract private interface with the
22215 	 * clustering group.
22216 	 */
22217 	clusterwide = 0;
22218 	if (cl_inet_ipident) {
22219 		ASSERT(cl_inet_isclusterwide);
22220 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
22221 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
22222 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
22223 			    AF_INET, (uint8_t *)(uintptr_t)src,
22224 			    (uint8_t *)(uintptr_t)dst);
22225 			clusterwide = 1;
22226 		}
22227 	}
22228 	if (!clusterwide) {
22229 		ipha->ipha_ident =
22230 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22231 	}
22232 
22233 #ifndef _BIG_ENDIAN
22234 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22235 #endif
22236 
22237 	/*
22238 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22239 	 * This is needed to obey conn_unspec_src when packets go through
22240 	 * ip_newroute + arp.
22241 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22242 	 */
22243 	if (src == INADDR_ANY && !unspec_src) {
22244 		/*
22245 		 * Assign the appropriate source address from the IRE if none
22246 		 * was specified.
22247 		 */
22248 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22249 
22250 		/*
22251 		 * With IP multipathing, broadcast packets are sent on the ire
22252 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
22253 		 * the group. However, this ire might not be in the same zone so
22254 		 * we can't always use its source address. We look for a
22255 		 * broadcast ire in the same group and in the right zone.
22256 		 */
22257 		if (ire->ire_type == IRE_BROADCAST &&
22258 		    ire->ire_zoneid != zoneid) {
22259 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
22260 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
22261 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
22262 			if (src_ire != NULL) {
22263 				src = src_ire->ire_src_addr;
22264 				ire_refrele(src_ire);
22265 			} else {
22266 				ire_refrele(ire);
22267 				if (conn_outgoing_ill != NULL)
22268 					ill_refrele(conn_outgoing_ill);
22269 				freemsg(first_mp);
22270 				if (ill != NULL) {
22271 					BUMP_MIB(ill->ill_ip_mib,
22272 					    ipIfStatsOutDiscards);
22273 				} else {
22274 					BUMP_MIB(&ipst->ips_ip_mib,
22275 					    ipIfStatsOutDiscards);
22276 				}
22277 				return;
22278 			}
22279 		} else {
22280 			src = ire->ire_src_addr;
22281 		}
22282 
22283 		if (connp == NULL) {
22284 			ip1dbg(("ip_wput_ire: no connp and no src "
22285 			    "address for dst 0x%x, using src 0x%x\n",
22286 			    ntohl(dst),
22287 			    ntohl(src)));
22288 		}
22289 		ipha->ipha_src = src;
22290 	}
22291 	stq = ire->ire_stq;
22292 
22293 	/*
22294 	 * We only allow ire chains for broadcasts since there will
22295 	 * be multiple IRE_CACHE entries for the same multicast
22296 	 * address (one per ipif).
22297 	 */
22298 	next_mp = NULL;
22299 
22300 	/* broadcast packet */
22301 	if (ire->ire_type == IRE_BROADCAST)
22302 		goto broadcast;
22303 
22304 	/* loopback ? */
22305 	if (stq == NULL)
22306 		goto nullstq;
22307 
22308 	/* The ill_index for outbound ILL */
22309 	ill_index = Q_TO_INDEX(stq);
22310 
22311 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22312 	ttl_protocol = ((uint16_t *)ipha)[4];
22313 
22314 	/* pseudo checksum (do it in parts for IP header checksum) */
22315 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22316 
22317 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22318 		queue_t *dev_q = stq->q_next;
22319 
22320 		/* flow controlled */
22321 		if ((dev_q->q_next || dev_q->q_first) &&
22322 		    !canput(dev_q))
22323 			goto blocked;
22324 		if ((PROTO == IPPROTO_UDP) &&
22325 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22326 			hlen = (V_HLEN & 0xF) << 2;
22327 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22328 			if (*up != 0) {
22329 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22330 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22331 				/* Software checksum? */
22332 				if (DB_CKSUMFLAGS(mp) == 0) {
22333 					IP_STAT(ipst, ip_out_sw_cksum);
22334 					IP_STAT_UPDATE(ipst,
22335 					    ip_udp_out_sw_cksum_bytes,
22336 					    LENGTH - hlen);
22337 				}
22338 			}
22339 		}
22340 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22341 		hlen = (V_HLEN & 0xF) << 2;
22342 		if (PROTO == IPPROTO_TCP) {
22343 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22344 			/*
22345 			 * The packet header is processed once and for all, even
22346 			 * in the multirouting case. We disable hardware
22347 			 * checksum if the packet is multirouted, as it will be
22348 			 * replicated via several interfaces, and not all of
22349 			 * them may have this capability.
22350 			 */
22351 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22352 			    LENGTH, max_frag, ipsec_len, cksum);
22353 			/* Software checksum? */
22354 			if (DB_CKSUMFLAGS(mp) == 0) {
22355 				IP_STAT(ipst, ip_out_sw_cksum);
22356 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22357 				    LENGTH - hlen);
22358 			}
22359 		} else {
22360 			sctp_hdr_t	*sctph;
22361 
22362 			ASSERT(PROTO == IPPROTO_SCTP);
22363 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22364 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22365 			/*
22366 			 * Zero out the checksum field to ensure proper
22367 			 * checksum calculation.
22368 			 */
22369 			sctph->sh_chksum = 0;
22370 #ifdef	DEBUG
22371 			if (!skip_sctp_cksum)
22372 #endif
22373 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22374 		}
22375 	}
22376 
22377 	/*
22378 	 * If this is a multicast packet and originated from ip_wput
22379 	 * we need to do loopback and forwarding checks. If it comes
22380 	 * from ip_wput_multicast, we SHOULD not do this.
22381 	 */
22382 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22383 
22384 	/* checksum */
22385 	cksum += ttl_protocol;
22386 
22387 	/* fragment the packet */
22388 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22389 		goto fragmentit;
22390 	/*
22391 	 * Don't use frag_flag if packet is pre-built or source
22392 	 * routed or if multicast (since multicast packets do
22393 	 * not solicit ICMP "packet too big" messages).
22394 	 */
22395 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22396 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22397 	    !ip_source_route_included(ipha)) &&
22398 	    !CLASSD(ipha->ipha_dst))
22399 		ipha->ipha_fragment_offset_and_flags |=
22400 		    htons(ire->ire_frag_flag);
22401 
22402 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22403 		/* calculate IP header checksum */
22404 		cksum += ipha->ipha_ident;
22405 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22406 		cksum += ipha->ipha_fragment_offset_and_flags;
22407 
22408 		/* IP options present */
22409 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22410 		if (hlen)
22411 			goto checksumoptions;
22412 
22413 		/* calculate hdr checksum */
22414 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22415 		cksum = ~(cksum + (cksum >> 16));
22416 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22417 	}
22418 	if (ipsec_len != 0) {
22419 		/*
22420 		 * We will do the rest of the processing after
22421 		 * we come back from IPsec in ip_wput_ipsec_out().
22422 		 */
22423 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22424 
22425 		io = (ipsec_out_t *)first_mp->b_rptr;
22426 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
22427 		    ill_phyint->phyint_ifindex;
22428 
22429 		ipsec_out_process(q, first_mp, ire, ill_index);
22430 		ire_refrele(ire);
22431 		if (conn_outgoing_ill != NULL)
22432 			ill_refrele(conn_outgoing_ill);
22433 		return;
22434 	}
22435 
22436 	/*
22437 	 * In most cases, the emission loop below is entered only
22438 	 * once. Only in the case where the ire holds the
22439 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22440 	 * flagged ires in the bucket, and send the packet
22441 	 * through all crossed RTF_MULTIRT routes.
22442 	 */
22443 	if (ire->ire_flags & RTF_MULTIRT) {
22444 		multirt_send = B_TRUE;
22445 	}
22446 	do {
22447 		if (multirt_send) {
22448 			irb_t *irb;
22449 			/*
22450 			 * We are in a multiple send case, need to get
22451 			 * the next ire and make a duplicate of the packet.
22452 			 * ire1 holds here the next ire to process in the
22453 			 * bucket. If multirouting is expected,
22454 			 * any non-RTF_MULTIRT ire that has the
22455 			 * right destination address is ignored.
22456 			 */
22457 			irb = ire->ire_bucket;
22458 			ASSERT(irb != NULL);
22459 
22460 			IRB_REFHOLD(irb);
22461 			for (ire1 = ire->ire_next;
22462 			    ire1 != NULL;
22463 			    ire1 = ire1->ire_next) {
22464 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22465 					continue;
22466 				if (ire1->ire_addr != ire->ire_addr)
22467 					continue;
22468 				if (ire1->ire_marks &
22469 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22470 					continue;
22471 
22472 				/* Got one */
22473 				IRE_REFHOLD(ire1);
22474 				break;
22475 			}
22476 			IRB_REFRELE(irb);
22477 
22478 			if (ire1 != NULL) {
22479 				next_mp = copyb(mp);
22480 				if ((next_mp == NULL) ||
22481 				    ((mp->b_cont != NULL) &&
22482 				    ((next_mp->b_cont =
22483 				    dupmsg(mp->b_cont)) == NULL))) {
22484 					freemsg(next_mp);
22485 					next_mp = NULL;
22486 					ire_refrele(ire1);
22487 					ire1 = NULL;
22488 				}
22489 			}
22490 
22491 			/* Last multiroute ire; don't loop anymore. */
22492 			if (ire1 == NULL) {
22493 				multirt_send = B_FALSE;
22494 			}
22495 		}
22496 
22497 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22498 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22499 		    mblk_t *, mp);
22500 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22501 		    ipst->ips_ipv4firewall_physical_out,
22502 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, ipst);
22503 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22504 		if (mp == NULL)
22505 			goto release_ire_and_ill;
22506 
22507 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22508 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22509 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
22510 		if ((pktxmit_state == SEND_FAILED) ||
22511 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22512 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22513 			    "- packet dropped\n"));
22514 release_ire_and_ill:
22515 			ire_refrele(ire);
22516 			if (next_mp != NULL) {
22517 				freemsg(next_mp);
22518 				ire_refrele(ire1);
22519 			}
22520 			if (conn_outgoing_ill != NULL)
22521 				ill_refrele(conn_outgoing_ill);
22522 			return;
22523 		}
22524 
22525 		if (CLASSD(dst)) {
22526 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22527 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22528 			    LENGTH);
22529 		}
22530 
22531 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22532 		    "ip_wput_ire_end: q %p (%S)",
22533 		    q, "last copy out");
22534 		IRE_REFRELE(ire);
22535 
22536 		if (multirt_send) {
22537 			ASSERT(ire1);
22538 			/*
22539 			 * Proceed with the next RTF_MULTIRT ire,
22540 			 * Also set up the send-to queue accordingly.
22541 			 */
22542 			ire = ire1;
22543 			ire1 = NULL;
22544 			stq = ire->ire_stq;
22545 			mp = next_mp;
22546 			next_mp = NULL;
22547 			ipha = (ipha_t *)mp->b_rptr;
22548 			ill_index = Q_TO_INDEX(stq);
22549 			ill = (ill_t *)stq->q_ptr;
22550 		}
22551 	} while (multirt_send);
22552 	if (conn_outgoing_ill != NULL)
22553 		ill_refrele(conn_outgoing_ill);
22554 	return;
22555 
22556 	/*
22557 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22558 	 */
22559 broadcast:
22560 	{
22561 		/*
22562 		 * Avoid broadcast storms by setting the ttl to 1
22563 		 * for broadcasts. This parameter can be set
22564 		 * via ndd, so make sure that for the SO_DONTROUTE
22565 		 * case that ipha_ttl is always set to 1.
22566 		 * In the event that we are replying to incoming
22567 		 * ICMP packets, conn could be NULL.
22568 		 */
22569 		if ((connp != NULL) && connp->conn_dontroute)
22570 			ipha->ipha_ttl = 1;
22571 		else
22572 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22573 
22574 		/*
22575 		 * Note that we are not doing a IRB_REFHOLD here.
22576 		 * Actually we don't care if the list changes i.e
22577 		 * if somebody deletes an IRE from the list while
22578 		 * we drop the lock, the next time we come around
22579 		 * ire_next will be NULL and hence we won't send
22580 		 * out multiple copies which is fine.
22581 		 */
22582 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22583 		ire1 = ire->ire_next;
22584 		if (conn_outgoing_ill != NULL) {
22585 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22586 				ASSERT(ire1 == ire->ire_next);
22587 				if (ire1 != NULL && ire1->ire_addr == dst) {
22588 					ire_refrele(ire);
22589 					ire = ire1;
22590 					IRE_REFHOLD(ire);
22591 					ire1 = ire->ire_next;
22592 					continue;
22593 				}
22594 				rw_exit(&ire->ire_bucket->irb_lock);
22595 				/* Did not find a matching ill */
22596 				ip1dbg(("ip_wput_ire: broadcast with no "
22597 				    "matching IP_BOUND_IF ill %s dst %x\n",
22598 				    conn_outgoing_ill->ill_name, dst));
22599 				freemsg(first_mp);
22600 				if (ire != NULL)
22601 					ire_refrele(ire);
22602 				ill_refrele(conn_outgoing_ill);
22603 				return;
22604 			}
22605 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22606 			/*
22607 			 * If the next IRE has the same address and is not one
22608 			 * of the two copies that we need to send, try to see
22609 			 * whether this copy should be sent at all. This
22610 			 * assumes that we insert loopbacks first and then
22611 			 * non-loopbacks. This is acheived by inserting the
22612 			 * loopback always before non-loopback.
22613 			 * This is used to send a single copy of a broadcast
22614 			 * packet out all physical interfaces that have an
22615 			 * matching IRE_BROADCAST while also looping
22616 			 * back one copy (to ip_wput_local) for each
22617 			 * matching physical interface. However, we avoid
22618 			 * sending packets out different logical that match by
22619 			 * having ipif_up/ipif_down supress duplicate
22620 			 * IRE_BROADCASTS.
22621 			 *
22622 			 * This feature is currently used to get broadcasts
22623 			 * sent to multiple interfaces, when the broadcast
22624 			 * address being used applies to multiple interfaces.
22625 			 * For example, a whole net broadcast will be
22626 			 * replicated on every connected subnet of
22627 			 * the target net.
22628 			 *
22629 			 * Each zone has its own set of IRE_BROADCASTs, so that
22630 			 * we're able to distribute inbound packets to multiple
22631 			 * zones who share a broadcast address. We avoid looping
22632 			 * back outbound packets in different zones but on the
22633 			 * same ill, as the application would see duplicates.
22634 			 *
22635 			 * If the interfaces are part of the same group,
22636 			 * we would want to send only one copy out for
22637 			 * whole group.
22638 			 *
22639 			 * This logic assumes that ire_add_v4() groups the
22640 			 * IRE_BROADCAST entries so that those with the same
22641 			 * ire_addr and ill_group are kept together.
22642 			 */
22643 			ire_ill = ire->ire_ipif->ipif_ill;
22644 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22645 				if (ire_ill->ill_group != NULL &&
22646 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22647 					/*
22648 					 * If the current zone only has an ire
22649 					 * broadcast for this address marked
22650 					 * NORECV, the ire we want is ahead in
22651 					 * the bucket, so we look it up
22652 					 * deliberately ignoring the zoneid.
22653 					 */
22654 					for (ire1 = ire->ire_bucket->irb_ire;
22655 					    ire1 != NULL;
22656 					    ire1 = ire1->ire_next) {
22657 						ire1_ill =
22658 						    ire1->ire_ipif->ipif_ill;
22659 						if (ire1->ire_addr != dst)
22660 							continue;
22661 						/* skip over the current ire */
22662 						if (ire1 == ire)
22663 							continue;
22664 						/* skip over deleted ires */
22665 						if (ire1->ire_marks &
22666 						    IRE_MARK_CONDEMNED)
22667 							continue;
22668 						/*
22669 						 * non-loopback ire in our
22670 						 * group: use it for the next
22671 						 * pass in the loop
22672 						 */
22673 						if (ire1->ire_stq != NULL &&
22674 						    ire1_ill->ill_group ==
22675 						    ire_ill->ill_group)
22676 							break;
22677 					}
22678 				}
22679 			} else {
22680 				while (ire1 != NULL && ire1->ire_addr == dst) {
22681 					ire1_ill = ire1->ire_ipif->ipif_ill;
22682 					/*
22683 					 * We can have two broadcast ires on the
22684 					 * same ill in different zones; here
22685 					 * we'll send a copy of the packet on
22686 					 * each ill and the fanout code will
22687 					 * call conn_wantpacket() to check that
22688 					 * the zone has the broadcast address
22689 					 * configured on the ill. If the two
22690 					 * ires are in the same group we only
22691 					 * send one copy up.
22692 					 */
22693 					if (ire1_ill != ire_ill &&
22694 					    (ire1_ill->ill_group == NULL ||
22695 					    ire_ill->ill_group == NULL ||
22696 					    ire1_ill->ill_group !=
22697 					    ire_ill->ill_group)) {
22698 						break;
22699 					}
22700 					ire1 = ire1->ire_next;
22701 				}
22702 			}
22703 		}
22704 		ASSERT(multirt_send == B_FALSE);
22705 		if (ire1 != NULL && ire1->ire_addr == dst) {
22706 			if ((ire->ire_flags & RTF_MULTIRT) &&
22707 			    (ire1->ire_flags & RTF_MULTIRT)) {
22708 				/*
22709 				 * We are in the multirouting case.
22710 				 * The message must be sent at least
22711 				 * on both ires. These ires have been
22712 				 * inserted AFTER the standard ones
22713 				 * in ip_rt_add(). There are thus no
22714 				 * other ire entries for the destination
22715 				 * address in the rest of the bucket
22716 				 * that do not have the RTF_MULTIRT
22717 				 * flag. We don't process a copy
22718 				 * of the message here. This will be
22719 				 * done in the final sending loop.
22720 				 */
22721 				multirt_send = B_TRUE;
22722 			} else {
22723 				next_mp = ip_copymsg(first_mp);
22724 				if (next_mp != NULL)
22725 					IRE_REFHOLD(ire1);
22726 			}
22727 		}
22728 		rw_exit(&ire->ire_bucket->irb_lock);
22729 	}
22730 
22731 	if (stq) {
22732 		/*
22733 		 * A non-NULL send-to queue means this packet is going
22734 		 * out of this machine.
22735 		 */
22736 		out_ill = (ill_t *)stq->q_ptr;
22737 
22738 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22739 		ttl_protocol = ((uint16_t *)ipha)[4];
22740 		/*
22741 		 * We accumulate the pseudo header checksum in cksum.
22742 		 * This is pretty hairy code, so watch close.  One
22743 		 * thing to keep in mind is that UDP and TCP have
22744 		 * stored their respective datagram lengths in their
22745 		 * checksum fields.  This lines things up real nice.
22746 		 */
22747 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22748 		    (src >> 16) + (src & 0xFFFF);
22749 		/*
22750 		 * We assume the udp checksum field contains the
22751 		 * length, so to compute the pseudo header checksum,
22752 		 * all we need is the protocol number and src/dst.
22753 		 */
22754 		/* Provide the checksums for UDP and TCP. */
22755 		if ((PROTO == IPPROTO_TCP) &&
22756 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22757 			/* hlen gets the number of uchar_ts in the IP header */
22758 			hlen = (V_HLEN & 0xF) << 2;
22759 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22760 			IP_STAT(ipst, ip_out_sw_cksum);
22761 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22762 			    LENGTH - hlen);
22763 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22764 		} else if (PROTO == IPPROTO_SCTP &&
22765 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22766 			sctp_hdr_t	*sctph;
22767 
22768 			hlen = (V_HLEN & 0xF) << 2;
22769 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22770 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22771 			sctph->sh_chksum = 0;
22772 #ifdef	DEBUG
22773 			if (!skip_sctp_cksum)
22774 #endif
22775 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22776 		} else {
22777 			queue_t *dev_q = stq->q_next;
22778 
22779 			if ((dev_q->q_next || dev_q->q_first) &&
22780 			    !canput(dev_q)) {
22781 blocked:
22782 				ipha->ipha_ident = ip_hdr_included;
22783 				/*
22784 				 * If we don't have a conn to apply
22785 				 * backpressure, free the message.
22786 				 * In the ire_send path, we don't know
22787 				 * the position to requeue the packet. Rather
22788 				 * than reorder packets, we just drop this
22789 				 * packet.
22790 				 */
22791 				if (ipst->ips_ip_output_queue &&
22792 				    connp != NULL &&
22793 				    caller != IRE_SEND) {
22794 					if (caller == IP_WSRV) {
22795 						connp->conn_did_putbq = 1;
22796 						(void) putbq(connp->conn_wq,
22797 						    first_mp);
22798 						conn_drain_insert(connp);
22799 						/*
22800 						 * This is the service thread,
22801 						 * and the queue is already
22802 						 * noenabled. The check for
22803 						 * canput and the putbq is not
22804 						 * atomic. So we need to check
22805 						 * again.
22806 						 */
22807 						if (canput(stq->q_next))
22808 							connp->conn_did_putbq
22809 							    = 0;
22810 						IP_STAT(ipst, ip_conn_flputbq);
22811 					} else {
22812 						/*
22813 						 * We are not the service proc.
22814 						 * ip_wsrv will be scheduled or
22815 						 * is already running.
22816 						 */
22817 						(void) putq(connp->conn_wq,
22818 						    first_mp);
22819 					}
22820 				} else {
22821 					out_ill = (ill_t *)stq->q_ptr;
22822 					BUMP_MIB(out_ill->ill_ip_mib,
22823 					    ipIfStatsOutDiscards);
22824 					freemsg(first_mp);
22825 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22826 					    "ip_wput_ire_end: q %p (%S)",
22827 					    q, "discard");
22828 				}
22829 				ire_refrele(ire);
22830 				if (next_mp) {
22831 					ire_refrele(ire1);
22832 					freemsg(next_mp);
22833 				}
22834 				if (conn_outgoing_ill != NULL)
22835 					ill_refrele(conn_outgoing_ill);
22836 				return;
22837 			}
22838 			if ((PROTO == IPPROTO_UDP) &&
22839 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22840 				/*
22841 				 * hlen gets the number of uchar_ts in the
22842 				 * IP header
22843 				 */
22844 				hlen = (V_HLEN & 0xF) << 2;
22845 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22846 				max_frag = ire->ire_max_frag;
22847 				if (*up != 0) {
22848 					IP_CKSUM_XMIT(out_ill, ire, mp, ipha,
22849 					    up, PROTO, hlen, LENGTH, max_frag,
22850 					    ipsec_len, cksum);
22851 					/* Software checksum? */
22852 					if (DB_CKSUMFLAGS(mp) == 0) {
22853 						IP_STAT(ipst, ip_out_sw_cksum);
22854 						IP_STAT_UPDATE(ipst,
22855 						    ip_udp_out_sw_cksum_bytes,
22856 						    LENGTH - hlen);
22857 					}
22858 				}
22859 			}
22860 		}
22861 		/*
22862 		 * Need to do this even when fragmenting. The local
22863 		 * loopback can be done without computing checksums
22864 		 * but forwarding out other interface must be done
22865 		 * after the IP checksum (and ULP checksums) have been
22866 		 * computed.
22867 		 *
22868 		 * NOTE : multicast_forward is set only if this packet
22869 		 * originated from ip_wput. For packets originating from
22870 		 * ip_wput_multicast, it is not set.
22871 		 */
22872 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
22873 multi_loopback:
22874 			ip2dbg(("ip_wput: multicast, loop %d\n",
22875 			    conn_multicast_loop));
22876 
22877 			/*  Forget header checksum offload */
22878 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
22879 
22880 			/*
22881 			 * Local loopback of multicasts?  Check the
22882 			 * ill.
22883 			 *
22884 			 * Note that the loopback function will not come
22885 			 * in through ip_rput - it will only do the
22886 			 * client fanout thus we need to do an mforward
22887 			 * as well.  The is different from the BSD
22888 			 * logic.
22889 			 */
22890 			if (ill != NULL) {
22891 				ilm_t	*ilm;
22892 
22893 				ILM_WALKER_HOLD(ill);
22894 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
22895 				    ALL_ZONES);
22896 				ILM_WALKER_RELE(ill);
22897 				if (ilm != NULL) {
22898 					/*
22899 					 * Pass along the virtual output q.
22900 					 * ip_wput_local() will distribute the
22901 					 * packet to all the matching zones,
22902 					 * except the sending zone when
22903 					 * IP_MULTICAST_LOOP is false.
22904 					 */
22905 					ip_multicast_loopback(q, ill, first_mp,
22906 					    conn_multicast_loop ? 0 :
22907 					    IP_FF_NO_MCAST_LOOP, zoneid);
22908 				}
22909 			}
22910 			if (ipha->ipha_ttl == 0) {
22911 				/*
22912 				 * 0 => only to this host i.e. we are
22913 				 * done. We are also done if this was the
22914 				 * loopback interface since it is sufficient
22915 				 * to loopback one copy of a multicast packet.
22916 				 */
22917 				freemsg(first_mp);
22918 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22919 				    "ip_wput_ire_end: q %p (%S)",
22920 				    q, "loopback");
22921 				ire_refrele(ire);
22922 				if (conn_outgoing_ill != NULL)
22923 					ill_refrele(conn_outgoing_ill);
22924 				return;
22925 			}
22926 			/*
22927 			 * ILLF_MULTICAST is checked in ip_newroute
22928 			 * i.e. we don't need to check it here since
22929 			 * all IRE_CACHEs come from ip_newroute.
22930 			 * For multicast traffic, SO_DONTROUTE is interpreted
22931 			 * to mean only send the packet out the interface
22932 			 * (optionally specified with IP_MULTICAST_IF)
22933 			 * and do not forward it out additional interfaces.
22934 			 * RSVP and the rsvp daemon is an example of a
22935 			 * protocol and user level process that
22936 			 * handles it's own routing. Hence, it uses the
22937 			 * SO_DONTROUTE option to accomplish this.
22938 			 */
22939 
22940 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
22941 			    ill != NULL) {
22942 				/* Unconditionally redo the checksum */
22943 				ipha->ipha_hdr_checksum = 0;
22944 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22945 
22946 				/*
22947 				 * If this needs to go out secure, we need
22948 				 * to wait till we finish the IPsec
22949 				 * processing.
22950 				 */
22951 				if (ipsec_len == 0 &&
22952 				    ip_mforward(ill, ipha, mp)) {
22953 					freemsg(first_mp);
22954 					ip1dbg(("ip_wput: mforward failed\n"));
22955 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22956 					    "ip_wput_ire_end: q %p (%S)",
22957 					    q, "mforward failed");
22958 					ire_refrele(ire);
22959 					if (conn_outgoing_ill != NULL)
22960 						ill_refrele(conn_outgoing_ill);
22961 					return;
22962 				}
22963 			}
22964 		}
22965 		max_frag = ire->ire_max_frag;
22966 		cksum += ttl_protocol;
22967 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
22968 			/* No fragmentation required for this one. */
22969 			/*
22970 			 * Don't use frag_flag if packet is pre-built or source
22971 			 * routed or if multicast (since multicast packets do
22972 			 * not solicit ICMP "packet too big" messages).
22973 			 */
22974 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22975 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22976 			    !ip_source_route_included(ipha)) &&
22977 			    !CLASSD(ipha->ipha_dst))
22978 				ipha->ipha_fragment_offset_and_flags |=
22979 				    htons(ire->ire_frag_flag);
22980 
22981 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22982 				/* Complete the IP header checksum. */
22983 				cksum += ipha->ipha_ident;
22984 				cksum += (v_hlen_tos_len >> 16)+
22985 				    (v_hlen_tos_len & 0xFFFF);
22986 				cksum += ipha->ipha_fragment_offset_and_flags;
22987 				hlen = (V_HLEN & 0xF) -
22988 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22989 				if (hlen) {
22990 checksumoptions:
22991 					/*
22992 					 * Account for the IP Options in the IP
22993 					 * header checksum.
22994 					 */
22995 					up = (uint16_t *)(rptr+
22996 					    IP_SIMPLE_HDR_LENGTH);
22997 					do {
22998 						cksum += up[0];
22999 						cksum += up[1];
23000 						up += 2;
23001 					} while (--hlen);
23002 				}
23003 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23004 				cksum = ~(cksum + (cksum >> 16));
23005 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23006 			}
23007 			if (ipsec_len != 0) {
23008 				ipsec_out_process(q, first_mp, ire, ill_index);
23009 				if (!next_mp) {
23010 					ire_refrele(ire);
23011 					if (conn_outgoing_ill != NULL)
23012 						ill_refrele(conn_outgoing_ill);
23013 					return;
23014 				}
23015 				goto next;
23016 			}
23017 
23018 			/*
23019 			 * multirt_send has already been handled
23020 			 * for broadcast, but not yet for multicast
23021 			 * or IP options.
23022 			 */
23023 			if (next_mp == NULL) {
23024 				if (ire->ire_flags & RTF_MULTIRT) {
23025 					multirt_send = B_TRUE;
23026 				}
23027 			}
23028 
23029 			/*
23030 			 * In most cases, the emission loop below is
23031 			 * entered only once. Only in the case where
23032 			 * the ire holds the RTF_MULTIRT flag, do we loop
23033 			 * to process all RTF_MULTIRT ires in the bucket,
23034 			 * and send the packet through all crossed
23035 			 * RTF_MULTIRT routes.
23036 			 */
23037 			do {
23038 				if (multirt_send) {
23039 					irb_t *irb;
23040 
23041 					irb = ire->ire_bucket;
23042 					ASSERT(irb != NULL);
23043 					/*
23044 					 * We are in a multiple send case,
23045 					 * need to get the next IRE and make
23046 					 * a duplicate of the packet.
23047 					 */
23048 					IRB_REFHOLD(irb);
23049 					for (ire1 = ire->ire_next;
23050 					    ire1 != NULL;
23051 					    ire1 = ire1->ire_next) {
23052 						if (!(ire1->ire_flags &
23053 						    RTF_MULTIRT)) {
23054 							continue;
23055 						}
23056 						if (ire1->ire_addr !=
23057 						    ire->ire_addr) {
23058 							continue;
23059 						}
23060 						if (ire1->ire_marks &
23061 						    (IRE_MARK_CONDEMNED|
23062 						    IRE_MARK_HIDDEN)) {
23063 							continue;
23064 						}
23065 
23066 						/* Got one */
23067 						IRE_REFHOLD(ire1);
23068 						break;
23069 					}
23070 					IRB_REFRELE(irb);
23071 
23072 					if (ire1 != NULL) {
23073 						next_mp = copyb(mp);
23074 						if ((next_mp == NULL) ||
23075 						    ((mp->b_cont != NULL) &&
23076 						    ((next_mp->b_cont =
23077 						    dupmsg(mp->b_cont))
23078 						    == NULL))) {
23079 							freemsg(next_mp);
23080 							next_mp = NULL;
23081 							ire_refrele(ire1);
23082 							ire1 = NULL;
23083 						}
23084 					}
23085 
23086 					/*
23087 					 * Last multiroute ire; don't loop
23088 					 * anymore. The emission is over
23089 					 * and next_mp is NULL.
23090 					 */
23091 					if (ire1 == NULL) {
23092 						multirt_send = B_FALSE;
23093 					}
23094 				}
23095 
23096 				out_ill = ire_to_ill(ire);
23097 				DTRACE_PROBE4(ip4__physical__out__start,
23098 				    ill_t *, NULL,
23099 				    ill_t *, out_ill,
23100 				    ipha_t *, ipha, mblk_t *, mp);
23101 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23102 				    ipst->ips_ipv4firewall_physical_out,
23103 				    NULL, out_ill, ipha, mp, mp, ipst);
23104 				DTRACE_PROBE1(ip4__physical__out__end,
23105 				    mblk_t *, mp);
23106 				if (mp == NULL)
23107 					goto release_ire_and_ill_2;
23108 
23109 				ASSERT(ipsec_len == 0);
23110 				mp->b_prev =
23111 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23112 				DTRACE_PROBE2(ip__xmit__2,
23113 				    mblk_t *, mp, ire_t *, ire);
23114 				pktxmit_state = ip_xmit_v4(mp, ire,
23115 				    NULL, B_TRUE);
23116 				if ((pktxmit_state == SEND_FAILED) ||
23117 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23118 release_ire_and_ill_2:
23119 					if (next_mp) {
23120 						freemsg(next_mp);
23121 						ire_refrele(ire1);
23122 					}
23123 					ire_refrele(ire);
23124 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23125 					    "ip_wput_ire_end: q %p (%S)",
23126 					    q, "discard MDATA");
23127 					if (conn_outgoing_ill != NULL)
23128 						ill_refrele(conn_outgoing_ill);
23129 					return;
23130 				}
23131 
23132 				if (CLASSD(dst)) {
23133 					BUMP_MIB(out_ill->ill_ip_mib,
23134 					    ipIfStatsHCOutMcastPkts);
23135 					UPDATE_MIB(out_ill->ill_ip_mib,
23136 					    ipIfStatsHCOutMcastOctets,
23137 					    LENGTH);
23138 				} else if (ire->ire_type == IRE_BROADCAST) {
23139 					BUMP_MIB(out_ill->ill_ip_mib,
23140 					    ipIfStatsHCOutBcastPkts);
23141 				}
23142 
23143 				if (multirt_send) {
23144 					/*
23145 					 * We are in a multiple send case,
23146 					 * need to re-enter the sending loop
23147 					 * using the next ire.
23148 					 */
23149 					ire_refrele(ire);
23150 					ire = ire1;
23151 					stq = ire->ire_stq;
23152 					mp = next_mp;
23153 					next_mp = NULL;
23154 					ipha = (ipha_t *)mp->b_rptr;
23155 					ill_index = Q_TO_INDEX(stq);
23156 				}
23157 			} while (multirt_send);
23158 
23159 			if (!next_mp) {
23160 				/*
23161 				 * Last copy going out (the ultra-common
23162 				 * case).  Note that we intentionally replicate
23163 				 * the putnext rather than calling it before
23164 				 * the next_mp check in hopes of a little
23165 				 * tail-call action out of the compiler.
23166 				 */
23167 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23168 				    "ip_wput_ire_end: q %p (%S)",
23169 				    q, "last copy out(1)");
23170 				ire_refrele(ire);
23171 				if (conn_outgoing_ill != NULL)
23172 					ill_refrele(conn_outgoing_ill);
23173 				return;
23174 			}
23175 			/* More copies going out below. */
23176 		} else {
23177 			int offset;
23178 fragmentit:
23179 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23180 			/*
23181 			 * If this would generate a icmp_frag_needed message,
23182 			 * we need to handle it before we do the IPsec
23183 			 * processing. Otherwise, we need to strip the IPsec
23184 			 * headers before we send up the message to the ULPs
23185 			 * which becomes messy and difficult.
23186 			 */
23187 			if (ipsec_len != 0) {
23188 				if ((max_frag < (unsigned int)(LENGTH +
23189 				    ipsec_len)) && (offset & IPH_DF)) {
23190 					out_ill = (ill_t *)stq->q_ptr;
23191 					BUMP_MIB(out_ill->ill_ip_mib,
23192 					    ipIfStatsOutFragFails);
23193 					BUMP_MIB(out_ill->ill_ip_mib,
23194 					    ipIfStatsOutFragReqds);
23195 					ipha->ipha_hdr_checksum = 0;
23196 					ipha->ipha_hdr_checksum =
23197 					    (uint16_t)ip_csum_hdr(ipha);
23198 					icmp_frag_needed(ire->ire_stq, first_mp,
23199 					    max_frag, zoneid, ipst);
23200 					if (!next_mp) {
23201 						ire_refrele(ire);
23202 						if (conn_outgoing_ill != NULL) {
23203 							ill_refrele(
23204 							    conn_outgoing_ill);
23205 						}
23206 						return;
23207 					}
23208 				} else {
23209 					/*
23210 					 * This won't cause a icmp_frag_needed
23211 					 * message. to be generated. Send it on
23212 					 * the wire. Note that this could still
23213 					 * cause fragmentation and all we
23214 					 * do is the generation of the message
23215 					 * to the ULP if needed before IPsec.
23216 					 */
23217 					if (!next_mp) {
23218 						ipsec_out_process(q, first_mp,
23219 						    ire, ill_index);
23220 						TRACE_2(TR_FAC_IP,
23221 						    TR_IP_WPUT_IRE_END,
23222 						    "ip_wput_ire_end: q %p "
23223 						    "(%S)", q,
23224 						    "last ipsec_out_process");
23225 						ire_refrele(ire);
23226 						if (conn_outgoing_ill != NULL) {
23227 							ill_refrele(
23228 							    conn_outgoing_ill);
23229 						}
23230 						return;
23231 					}
23232 					ipsec_out_process(q, first_mp,
23233 					    ire, ill_index);
23234 				}
23235 			} else {
23236 				/*
23237 				 * Initiate IPPF processing. For
23238 				 * fragmentable packets we finish
23239 				 * all QOS packet processing before
23240 				 * calling:
23241 				 * ip_wput_ire_fragmentit->ip_wput_frag
23242 				 */
23243 
23244 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23245 					ip_process(IPP_LOCAL_OUT, &mp,
23246 					    ill_index);
23247 					if (mp == NULL) {
23248 						out_ill = (ill_t *)stq->q_ptr;
23249 						BUMP_MIB(out_ill->ill_ip_mib,
23250 						    ipIfStatsOutDiscards);
23251 						if (next_mp != NULL) {
23252 							freemsg(next_mp);
23253 							ire_refrele(ire1);
23254 						}
23255 						ire_refrele(ire);
23256 						TRACE_2(TR_FAC_IP,
23257 						    TR_IP_WPUT_IRE_END,
23258 						    "ip_wput_ire: q %p (%S)",
23259 						    q, "discard MDATA");
23260 						if (conn_outgoing_ill != NULL) {
23261 							ill_refrele(
23262 							    conn_outgoing_ill);
23263 						}
23264 						return;
23265 					}
23266 				}
23267 				if (!next_mp) {
23268 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23269 					    "ip_wput_ire_end: q %p (%S)",
23270 					    q, "last fragmentation");
23271 					ip_wput_ire_fragmentit(mp, ire,
23272 					    zoneid, ipst);
23273 					ire_refrele(ire);
23274 					if (conn_outgoing_ill != NULL)
23275 						ill_refrele(conn_outgoing_ill);
23276 					return;
23277 				}
23278 				ip_wput_ire_fragmentit(mp, ire, zoneid, ipst);
23279 			}
23280 		}
23281 	} else {
23282 nullstq:
23283 		/* A NULL stq means the destination address is local. */
23284 		UPDATE_OB_PKT_COUNT(ire);
23285 		ire->ire_last_used_time = lbolt;
23286 		ASSERT(ire->ire_ipif != NULL);
23287 		if (!next_mp) {
23288 			/*
23289 			 * Is there an "in" and "out" for traffic local
23290 			 * to a host (loopback)?  The code in Solaris doesn't
23291 			 * explicitly draw a line in its code for in vs out,
23292 			 * so we've had to draw a line in the sand: ip_wput_ire
23293 			 * is considered to be the "output" side and
23294 			 * ip_wput_local to be the "input" side.
23295 			 */
23296 			out_ill = ire_to_ill(ire);
23297 
23298 			DTRACE_PROBE4(ip4__loopback__out__start,
23299 			    ill_t *, NULL, ill_t *, out_ill,
23300 			    ipha_t *, ipha, mblk_t *, first_mp);
23301 
23302 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23303 			    ipst->ips_ipv4firewall_loopback_out,
23304 			    NULL, out_ill, ipha, first_mp, mp, ipst);
23305 
23306 			DTRACE_PROBE1(ip4__loopback__out_end,
23307 			    mblk_t *, first_mp);
23308 
23309 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23310 			    "ip_wput_ire_end: q %p (%S)",
23311 			    q, "local address");
23312 
23313 			if (first_mp != NULL)
23314 				ip_wput_local(q, out_ill, ipha,
23315 				    first_mp, ire, 0, ire->ire_zoneid);
23316 			ire_refrele(ire);
23317 			if (conn_outgoing_ill != NULL)
23318 				ill_refrele(conn_outgoing_ill);
23319 			return;
23320 		}
23321 
23322 		out_ill = ire_to_ill(ire);
23323 
23324 		DTRACE_PROBE4(ip4__loopback__out__start,
23325 		    ill_t *, NULL, ill_t *, out_ill,
23326 		    ipha_t *, ipha, mblk_t *, first_mp);
23327 
23328 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23329 		    ipst->ips_ipv4firewall_loopback_out,
23330 		    NULL, out_ill, ipha, first_mp, mp, ipst);
23331 
23332 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23333 
23334 		if (first_mp != NULL)
23335 			ip_wput_local(q, out_ill, ipha,
23336 			    first_mp, ire, 0, ire->ire_zoneid);
23337 	}
23338 next:
23339 	/*
23340 	 * More copies going out to additional interfaces.
23341 	 * ire1 has already been held. We don't need the
23342 	 * "ire" anymore.
23343 	 */
23344 	ire_refrele(ire);
23345 	ire = ire1;
23346 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23347 	mp = next_mp;
23348 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23349 	ill = ire_to_ill(ire);
23350 	first_mp = mp;
23351 	if (ipsec_len != 0) {
23352 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23353 		mp = mp->b_cont;
23354 	}
23355 	dst = ire->ire_addr;
23356 	ipha = (ipha_t *)mp->b_rptr;
23357 	/*
23358 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23359 	 * Restore ipha_ident "no checksum" flag.
23360 	 */
23361 	src = orig_src;
23362 	ipha->ipha_ident = ip_hdr_included;
23363 	goto another;
23364 
23365 #undef	rptr
23366 #undef	Q_TO_INDEX
23367 }
23368 
23369 /*
23370  * Routine to allocate a message that is used to notify the ULP about MDT.
23371  * The caller may provide a pointer to the link-layer MDT capabilities,
23372  * or NULL if MDT is to be disabled on the stream.
23373  */
23374 mblk_t *
23375 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23376 {
23377 	mblk_t *mp;
23378 	ip_mdt_info_t *mdti;
23379 	ill_mdt_capab_t *idst;
23380 
23381 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23382 		DB_TYPE(mp) = M_CTL;
23383 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23384 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23385 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23386 		idst = &(mdti->mdt_capab);
23387 
23388 		/*
23389 		 * If the caller provides us with the capability, copy
23390 		 * it over into our notification message; otherwise
23391 		 * we zero out the capability portion.
23392 		 */
23393 		if (isrc != NULL)
23394 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23395 		else
23396 			bzero((caddr_t)idst, sizeof (*idst));
23397 	}
23398 	return (mp);
23399 }
23400 
23401 /*
23402  * Routine which determines whether MDT can be enabled on the destination
23403  * IRE and IPC combination, and if so, allocates and returns the MDT
23404  * notification mblk that may be used by ULP.  We also check if we need to
23405  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23406  * MDT usage in the past have been lifted.  This gets called during IP
23407  * and ULP binding.
23408  */
23409 mblk_t *
23410 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23411     ill_mdt_capab_t *mdt_cap)
23412 {
23413 	mblk_t *mp;
23414 	boolean_t rc = B_FALSE;
23415 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23416 
23417 	ASSERT(dst_ire != NULL);
23418 	ASSERT(connp != NULL);
23419 	ASSERT(mdt_cap != NULL);
23420 
23421 	/*
23422 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23423 	 * Multidata, which is handled in tcp_multisend().  This
23424 	 * is the reason why we do all these checks here, to ensure
23425 	 * that we don't enable Multidata for the cases which we
23426 	 * can't handle at the moment.
23427 	 */
23428 	do {
23429 		/* Only do TCP at the moment */
23430 		if (connp->conn_ulp != IPPROTO_TCP)
23431 			break;
23432 
23433 		/*
23434 		 * IPsec outbound policy present?  Note that we get here
23435 		 * after calling ipsec_conn_cache_policy() where the global
23436 		 * policy checking is performed.  conn_latch will be
23437 		 * non-NULL as long as there's a policy defined,
23438 		 * i.e. conn_out_enforce_policy may be NULL in such case
23439 		 * when the connection is non-secure, and hence we check
23440 		 * further if the latch refers to an outbound policy.
23441 		 */
23442 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23443 			break;
23444 
23445 		/* CGTP (multiroute) is enabled? */
23446 		if (dst_ire->ire_flags & RTF_MULTIRT)
23447 			break;
23448 
23449 		/* Outbound IPQoS enabled? */
23450 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23451 			/*
23452 			 * In this case, we disable MDT for this and all
23453 			 * future connections going over the interface.
23454 			 */
23455 			mdt_cap->ill_mdt_on = 0;
23456 			break;
23457 		}
23458 
23459 		/* socket option(s) present? */
23460 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23461 			break;
23462 
23463 		rc = B_TRUE;
23464 	/* CONSTCOND */
23465 	} while (0);
23466 
23467 	/* Remember the result */
23468 	connp->conn_mdt_ok = rc;
23469 
23470 	if (!rc)
23471 		return (NULL);
23472 	else if (!mdt_cap->ill_mdt_on) {
23473 		/*
23474 		 * If MDT has been previously turned off in the past, and we
23475 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23476 		 * then enable it for this interface.
23477 		 */
23478 		mdt_cap->ill_mdt_on = 1;
23479 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23480 		    "interface %s\n", ill_name));
23481 	}
23482 
23483 	/* Allocate the MDT info mblk */
23484 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23485 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23486 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23487 		return (NULL);
23488 	}
23489 	return (mp);
23490 }
23491 
23492 /*
23493  * Routine to allocate a message that is used to notify the ULP about LSO.
23494  * The caller may provide a pointer to the link-layer LSO capabilities,
23495  * or NULL if LSO is to be disabled on the stream.
23496  */
23497 mblk_t *
23498 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23499 {
23500 	mblk_t *mp;
23501 	ip_lso_info_t *lsoi;
23502 	ill_lso_capab_t *idst;
23503 
23504 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23505 		DB_TYPE(mp) = M_CTL;
23506 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23507 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23508 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23509 		idst = &(lsoi->lso_capab);
23510 
23511 		/*
23512 		 * If the caller provides us with the capability, copy
23513 		 * it over into our notification message; otherwise
23514 		 * we zero out the capability portion.
23515 		 */
23516 		if (isrc != NULL)
23517 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23518 		else
23519 			bzero((caddr_t)idst, sizeof (*idst));
23520 	}
23521 	return (mp);
23522 }
23523 
23524 /*
23525  * Routine which determines whether LSO can be enabled on the destination
23526  * IRE and IPC combination, and if so, allocates and returns the LSO
23527  * notification mblk that may be used by ULP.  We also check if we need to
23528  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23529  * LSO usage in the past have been lifted.  This gets called during IP
23530  * and ULP binding.
23531  */
23532 mblk_t *
23533 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23534     ill_lso_capab_t *lso_cap)
23535 {
23536 	mblk_t *mp;
23537 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23538 
23539 	ASSERT(dst_ire != NULL);
23540 	ASSERT(connp != NULL);
23541 	ASSERT(lso_cap != NULL);
23542 
23543 	connp->conn_lso_ok = B_TRUE;
23544 
23545 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23546 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23547 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23548 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23549 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23550 		connp->conn_lso_ok = B_FALSE;
23551 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23552 			/*
23553 			 * Disable LSO for this and all future connections going
23554 			 * over the interface.
23555 			 */
23556 			lso_cap->ill_lso_on = 0;
23557 		}
23558 	}
23559 
23560 	if (!connp->conn_lso_ok)
23561 		return (NULL);
23562 	else if (!lso_cap->ill_lso_on) {
23563 		/*
23564 		 * If LSO has been previously turned off in the past, and we
23565 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23566 		 * then enable it for this interface.
23567 		 */
23568 		lso_cap->ill_lso_on = 1;
23569 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23570 		    ill_name));
23571 	}
23572 
23573 	/* Allocate the LSO info mblk */
23574 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23575 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23576 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23577 
23578 	return (mp);
23579 }
23580 
23581 /*
23582  * Create destination address attribute, and fill it with the physical
23583  * destination address and SAP taken from the template DL_UNITDATA_REQ
23584  * message block.
23585  */
23586 boolean_t
23587 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23588 {
23589 	dl_unitdata_req_t *dlurp;
23590 	pattr_t *pa;
23591 	pattrinfo_t pa_info;
23592 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23593 	uint_t das_len, das_off;
23594 
23595 	ASSERT(dlmp != NULL);
23596 
23597 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23598 	das_len = dlurp->dl_dest_addr_length;
23599 	das_off = dlurp->dl_dest_addr_offset;
23600 
23601 	pa_info.type = PATTR_DSTADDRSAP;
23602 	pa_info.len = sizeof (**das) + das_len - 1;
23603 
23604 	/* create and associate the attribute */
23605 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23606 	if (pa != NULL) {
23607 		ASSERT(*das != NULL);
23608 		(*das)->addr_is_group = 0;
23609 		(*das)->addr_len = (uint8_t)das_len;
23610 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23611 	}
23612 
23613 	return (pa != NULL);
23614 }
23615 
23616 /*
23617  * Create hardware checksum attribute and fill it with the values passed.
23618  */
23619 boolean_t
23620 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23621     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23622 {
23623 	pattr_t *pa;
23624 	pattrinfo_t pa_info;
23625 
23626 	ASSERT(mmd != NULL);
23627 
23628 	pa_info.type = PATTR_HCKSUM;
23629 	pa_info.len = sizeof (pattr_hcksum_t);
23630 
23631 	/* create and associate the attribute */
23632 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23633 	if (pa != NULL) {
23634 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23635 
23636 		hck->hcksum_start_offset = start_offset;
23637 		hck->hcksum_stuff_offset = stuff_offset;
23638 		hck->hcksum_end_offset = end_offset;
23639 		hck->hcksum_flags = flags;
23640 	}
23641 	return (pa != NULL);
23642 }
23643 
23644 /*
23645  * Create zerocopy attribute and fill it with the specified flags
23646  */
23647 boolean_t
23648 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23649 {
23650 	pattr_t *pa;
23651 	pattrinfo_t pa_info;
23652 
23653 	ASSERT(mmd != NULL);
23654 	pa_info.type = PATTR_ZCOPY;
23655 	pa_info.len = sizeof (pattr_zcopy_t);
23656 
23657 	/* create and associate the attribute */
23658 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23659 	if (pa != NULL) {
23660 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23661 
23662 		zcopy->zcopy_flags = flags;
23663 	}
23664 	return (pa != NULL);
23665 }
23666 
23667 /*
23668  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23669  * block chain. We could rewrite to handle arbitrary message block chains but
23670  * that would make the code complicated and slow. Right now there three
23671  * restrictions:
23672  *
23673  *   1. The first message block must contain the complete IP header and
23674  *	at least 1 byte of payload data.
23675  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23676  *	so that we can use a single Multidata message.
23677  *   3. No frag must be distributed over two or more message blocks so
23678  *	that we don't need more than two packet descriptors per frag.
23679  *
23680  * The above restrictions allow us to support userland applications (which
23681  * will send down a single message block) and NFS over UDP (which will
23682  * send down a chain of at most three message blocks).
23683  *
23684  * We also don't use MDT for payloads with less than or equal to
23685  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23686  */
23687 boolean_t
23688 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23689 {
23690 	int	blocks;
23691 	ssize_t	total, missing, size;
23692 
23693 	ASSERT(mp != NULL);
23694 	ASSERT(hdr_len > 0);
23695 
23696 	size = MBLKL(mp) - hdr_len;
23697 	if (size <= 0)
23698 		return (B_FALSE);
23699 
23700 	/* The first mblk contains the header and some payload. */
23701 	blocks = 1;
23702 	total = size;
23703 	size %= len;
23704 	missing = (size == 0) ? 0 : (len - size);
23705 	mp = mp->b_cont;
23706 
23707 	while (mp != NULL) {
23708 		/*
23709 		 * Give up if we encounter a zero length message block.
23710 		 * In practice, this should rarely happen and therefore
23711 		 * not worth the trouble of freeing and re-linking the
23712 		 * mblk from the chain to handle such case.
23713 		 */
23714 		if ((size = MBLKL(mp)) == 0)
23715 			return (B_FALSE);
23716 
23717 		/* Too many payload buffers for a single Multidata message? */
23718 		if (++blocks > MULTIDATA_MAX_PBUFS)
23719 			return (B_FALSE);
23720 
23721 		total += size;
23722 		/* Is a frag distributed over two or more message blocks? */
23723 		if (missing > size)
23724 			return (B_FALSE);
23725 		size -= missing;
23726 
23727 		size %= len;
23728 		missing = (size == 0) ? 0 : (len - size);
23729 
23730 		mp = mp->b_cont;
23731 	}
23732 
23733 	return (total > ip_wput_frag_mdt_min);
23734 }
23735 
23736 /*
23737  * Outbound IPv4 fragmentation routine using MDT.
23738  */
23739 static void
23740 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23741     uint32_t frag_flag, int offset)
23742 {
23743 	ipha_t		*ipha_orig;
23744 	int		i1, ip_data_end;
23745 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23746 	mblk_t		*hdr_mp, *md_mp = NULL;
23747 	unsigned char	*hdr_ptr, *pld_ptr;
23748 	multidata_t	*mmd;
23749 	ip_pdescinfo_t	pdi;
23750 	ill_t		*ill;
23751 	ip_stack_t	*ipst = ire->ire_ipst;
23752 
23753 	ASSERT(DB_TYPE(mp) == M_DATA);
23754 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23755 
23756 	ill = ire_to_ill(ire);
23757 	ASSERT(ill != NULL);
23758 
23759 	ipha_orig = (ipha_t *)mp->b_rptr;
23760 	mp->b_rptr += sizeof (ipha_t);
23761 
23762 	/* Calculate how many packets we will send out */
23763 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23764 	pkts = (i1 + len - 1) / len;
23765 	ASSERT(pkts > 1);
23766 
23767 	/* Allocate a message block which will hold all the IP Headers. */
23768 	wroff = ipst->ips_ip_wroff_extra;
23769 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23770 
23771 	i1 = pkts * hdr_chunk_len;
23772 	/*
23773 	 * Create the header buffer, Multidata and destination address
23774 	 * and SAP attribute that should be associated with it.
23775 	 */
23776 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23777 	    ((hdr_mp->b_wptr += i1),
23778 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23779 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23780 		freemsg(mp);
23781 		if (md_mp == NULL) {
23782 			freemsg(hdr_mp);
23783 		} else {
23784 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
23785 			freemsg(md_mp);
23786 		}
23787 		IP_STAT(ipst, ip_frag_mdt_allocfail);
23788 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
23789 		return;
23790 	}
23791 	IP_STAT(ipst, ip_frag_mdt_allocd);
23792 
23793 	/*
23794 	 * Add a payload buffer to the Multidata; this operation must not
23795 	 * fail, or otherwise our logic in this routine is broken.  There
23796 	 * is no memory allocation done by the routine, so any returned
23797 	 * failure simply tells us that we've done something wrong.
23798 	 *
23799 	 * A failure tells us that either we're adding the same payload
23800 	 * buffer more than once, or we're trying to add more buffers than
23801 	 * allowed.  None of the above cases should happen, and we panic
23802 	 * because either there's horrible heap corruption, and/or
23803 	 * programming mistake.
23804 	 */
23805 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23806 		goto pbuf_panic;
23807 
23808 	hdr_ptr = hdr_mp->b_rptr;
23809 	pld_ptr = mp->b_rptr;
23810 
23811 	/* Establish the ending byte offset, based on the starting offset. */
23812 	offset <<= 3;
23813 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23814 	    IP_SIMPLE_HDR_LENGTH;
23815 
23816 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23817 
23818 	while (pld_ptr < mp->b_wptr) {
23819 		ipha_t		*ipha;
23820 		uint16_t	offset_and_flags;
23821 		uint16_t	ip_len;
23822 		int		error;
23823 
23824 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23825 		ipha = (ipha_t *)(hdr_ptr + wroff);
23826 		ASSERT(OK_32PTR(ipha));
23827 		*ipha = *ipha_orig;
23828 
23829 		if (ip_data_end - offset > len) {
23830 			offset_and_flags = IPH_MF;
23831 		} else {
23832 			/*
23833 			 * Last frag. Set len to the length of this last piece.
23834 			 */
23835 			len = ip_data_end - offset;
23836 			/* A frag of a frag might have IPH_MF non-zero */
23837 			offset_and_flags =
23838 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23839 			    IPH_MF;
23840 		}
23841 		offset_and_flags |= (uint16_t)(offset >> 3);
23842 		offset_and_flags |= (uint16_t)frag_flag;
23843 		/* Store the offset and flags in the IP header. */
23844 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23845 
23846 		/* Store the length in the IP header. */
23847 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23848 		ipha->ipha_length = htons(ip_len);
23849 
23850 		/*
23851 		 * Set the IP header checksum.  Note that mp is just
23852 		 * the header, so this is easy to pass to ip_csum.
23853 		 */
23854 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23855 
23856 		/*
23857 		 * Record offset and size of header and data of the next packet
23858 		 * in the multidata message.
23859 		 */
23860 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
23861 		PDESC_PLD_INIT(&pdi);
23862 		i1 = MIN(mp->b_wptr - pld_ptr, len);
23863 		ASSERT(i1 > 0);
23864 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
23865 		if (i1 == len) {
23866 			pld_ptr += len;
23867 		} else {
23868 			i1 = len - i1;
23869 			mp = mp->b_cont;
23870 			ASSERT(mp != NULL);
23871 			ASSERT(MBLKL(mp) >= i1);
23872 			/*
23873 			 * Attach the next payload message block to the
23874 			 * multidata message.
23875 			 */
23876 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23877 				goto pbuf_panic;
23878 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
23879 			pld_ptr = mp->b_rptr + i1;
23880 		}
23881 
23882 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
23883 		    KM_NOSLEEP)) == NULL) {
23884 			/*
23885 			 * Any failure other than ENOMEM indicates that we
23886 			 * have passed in invalid pdesc info or parameters
23887 			 * to mmd_addpdesc, which must not happen.
23888 			 *
23889 			 * EINVAL is a result of failure on boundary checks
23890 			 * against the pdesc info contents.  It should not
23891 			 * happen, and we panic because either there's
23892 			 * horrible heap corruption, and/or programming
23893 			 * mistake.
23894 			 */
23895 			if (error != ENOMEM) {
23896 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
23897 				    "pdesc logic error detected for "
23898 				    "mmd %p pinfo %p (%d)\n",
23899 				    (void *)mmd, (void *)&pdi, error);
23900 				/* NOTREACHED */
23901 			}
23902 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
23903 			/* Free unattached payload message blocks as well */
23904 			md_mp->b_cont = mp->b_cont;
23905 			goto free_mmd;
23906 		}
23907 
23908 		/* Advance fragment offset. */
23909 		offset += len;
23910 
23911 		/* Advance to location for next header in the buffer. */
23912 		hdr_ptr += hdr_chunk_len;
23913 
23914 		/* Did we reach the next payload message block? */
23915 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
23916 			mp = mp->b_cont;
23917 			/*
23918 			 * Attach the next message block with payload
23919 			 * data to the multidata message.
23920 			 */
23921 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23922 				goto pbuf_panic;
23923 			pld_ptr = mp->b_rptr;
23924 		}
23925 	}
23926 
23927 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
23928 	ASSERT(mp->b_wptr == pld_ptr);
23929 
23930 	/* Update IP statistics */
23931 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
23932 
23933 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
23934 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
23935 
23936 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
23937 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
23938 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
23939 
23940 	if (pkt_type == OB_PKT) {
23941 		ire->ire_ob_pkt_count += pkts;
23942 		if (ire->ire_ipif != NULL)
23943 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
23944 	} else {
23945 		/* The type is IB_PKT in the forwarding path. */
23946 		ire->ire_ib_pkt_count += pkts;
23947 		ASSERT(!IRE_IS_LOCAL(ire));
23948 		if (ire->ire_type & IRE_BROADCAST) {
23949 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
23950 		} else {
23951 			UPDATE_MIB(ill->ill_ip_mib,
23952 			    ipIfStatsHCOutForwDatagrams, pkts);
23953 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
23954 		}
23955 	}
23956 	ire->ire_last_used_time = lbolt;
23957 	/* Send it down */
23958 	putnext(ire->ire_stq, md_mp);
23959 	return;
23960 
23961 pbuf_panic:
23962 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
23963 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
23964 	    pbuf_idx);
23965 	/* NOTREACHED */
23966 }
23967 
23968 /*
23969  * Outbound IP fragmentation routine.
23970  *
23971  * NOTE : This routine does not ire_refrele the ire that is passed in
23972  * as the argument.
23973  */
23974 static void
23975 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
23976     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst)
23977 {
23978 	int		i1;
23979 	mblk_t		*ll_hdr_mp;
23980 	int 		ll_hdr_len;
23981 	int		hdr_len;
23982 	mblk_t		*hdr_mp;
23983 	ipha_t		*ipha;
23984 	int		ip_data_end;
23985 	int		len;
23986 	mblk_t		*mp = mp_orig, *mp1;
23987 	int		offset;
23988 	queue_t		*q;
23989 	uint32_t	v_hlen_tos_len;
23990 	mblk_t		*first_mp;
23991 	boolean_t	mctl_present;
23992 	ill_t		*ill;
23993 	ill_t		*out_ill;
23994 	mblk_t		*xmit_mp;
23995 	mblk_t		*carve_mp;
23996 	ire_t		*ire1 = NULL;
23997 	ire_t		*save_ire = NULL;
23998 	mblk_t  	*next_mp = NULL;
23999 	boolean_t	last_frag = B_FALSE;
24000 	boolean_t	multirt_send = B_FALSE;
24001 	ire_t		*first_ire = NULL;
24002 	irb_t		*irb = NULL;
24003 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24004 
24005 	ill = ire_to_ill(ire);
24006 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24007 
24008 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24009 
24010 	if (max_frag == 0) {
24011 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24012 		    " -  dropping packet\n"));
24013 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24014 		freemsg(mp);
24015 		return;
24016 	}
24017 
24018 	/*
24019 	 * IPsec does not allow hw accelerated packets to be fragmented
24020 	 * This check is made in ip_wput_ipsec_out prior to coming here
24021 	 * via ip_wput_ire_fragmentit.
24022 	 *
24023 	 * If at this point we have an ire whose ARP request has not
24024 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24025 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24026 	 * This packet and all fragmentable packets for this ire will
24027 	 * continue to get dropped while ire_nce->nce_state remains in
24028 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24029 	 * ND_REACHABLE, all subsquent large packets for this ire will
24030 	 * get fragemented and sent out by this function.
24031 	 */
24032 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24033 		/* If nce_state is ND_INITIAL, trigger ARP query */
24034 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
24035 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24036 		    " -  dropping packet\n"));
24037 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24038 		freemsg(mp);
24039 		return;
24040 	}
24041 
24042 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24043 	    "ip_wput_frag_start:");
24044 
24045 	if (mp->b_datap->db_type == M_CTL) {
24046 		first_mp = mp;
24047 		mp_orig = mp = mp->b_cont;
24048 		mctl_present = B_TRUE;
24049 	} else {
24050 		first_mp = mp;
24051 		mctl_present = B_FALSE;
24052 	}
24053 
24054 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24055 	ipha = (ipha_t *)mp->b_rptr;
24056 
24057 	/*
24058 	 * If the Don't Fragment flag is on, generate an ICMP destination
24059 	 * unreachable, fragmentation needed.
24060 	 */
24061 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24062 	if (offset & IPH_DF) {
24063 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24064 		if (is_system_labeled()) {
24065 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24066 			    ire->ire_max_frag - max_frag, AF_INET);
24067 		}
24068 		/*
24069 		 * Need to compute hdr checksum if called from ip_wput_ire.
24070 		 * Note that ip_rput_forward verifies the checksum before
24071 		 * calling this routine so in that case this is a noop.
24072 		 */
24073 		ipha->ipha_hdr_checksum = 0;
24074 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24075 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24076 		    ipst);
24077 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24078 		    "ip_wput_frag_end:(%S)",
24079 		    "don't fragment");
24080 		return;
24081 	}
24082 	/*
24083 	 * Labeled systems adjust max_frag if they add a label
24084 	 * to send the correct path mtu.  We need the real mtu since we
24085 	 * are fragmenting the packet after label adjustment.
24086 	 */
24087 	if (is_system_labeled())
24088 		max_frag = ire->ire_max_frag;
24089 	if (mctl_present)
24090 		freeb(first_mp);
24091 	/*
24092 	 * Establish the starting offset.  May not be zero if we are fragging
24093 	 * a fragment that is being forwarded.
24094 	 */
24095 	offset = offset & IPH_OFFSET;
24096 
24097 	/* TODO why is this test needed? */
24098 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24099 	if (((max_frag - LENGTH) & ~7) < 8) {
24100 		/* TODO: notify ulp somehow */
24101 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24102 		freemsg(mp);
24103 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24104 		    "ip_wput_frag_end:(%S)",
24105 		    "len < 8");
24106 		return;
24107 	}
24108 
24109 	hdr_len = (V_HLEN & 0xF) << 2;
24110 
24111 	ipha->ipha_hdr_checksum = 0;
24112 
24113 	/*
24114 	 * Establish the number of bytes maximum per frag, after putting
24115 	 * in the header.
24116 	 */
24117 	len = (max_frag - hdr_len) & ~7;
24118 
24119 	/* Check if we can use MDT to send out the frags. */
24120 	ASSERT(!IRE_IS_LOCAL(ire));
24121 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24122 	    ipst->ips_ip_multidata_outbound &&
24123 	    !(ire->ire_flags & RTF_MULTIRT) &&
24124 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24125 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24126 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24127 		ASSERT(ill->ill_mdt_capab != NULL);
24128 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24129 			/*
24130 			 * If MDT has been previously turned off in the past,
24131 			 * and we currently can do MDT (due to IPQoS policy
24132 			 * removal, etc.) then enable it for this interface.
24133 			 */
24134 			ill->ill_mdt_capab->ill_mdt_on = 1;
24135 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24136 			    ill->ill_name));
24137 		}
24138 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24139 		    offset);
24140 		return;
24141 	}
24142 
24143 	/* Get a copy of the header for the trailing frags */
24144 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst);
24145 	if (!hdr_mp) {
24146 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24147 		freemsg(mp);
24148 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24149 		    "ip_wput_frag_end:(%S)",
24150 		    "couldn't copy hdr");
24151 		return;
24152 	}
24153 	if (DB_CRED(mp) != NULL)
24154 		mblk_setcred(hdr_mp, DB_CRED(mp));
24155 
24156 	/* Store the starting offset, with the MoreFrags flag. */
24157 	i1 = offset | IPH_MF | frag_flag;
24158 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24159 
24160 	/* Establish the ending byte offset, based on the starting offset. */
24161 	offset <<= 3;
24162 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24163 
24164 	/* Store the length of the first fragment in the IP header. */
24165 	i1 = len + hdr_len;
24166 	ASSERT(i1 <= IP_MAXPACKET);
24167 	ipha->ipha_length = htons((uint16_t)i1);
24168 
24169 	/*
24170 	 * Compute the IP header checksum for the first frag.  We have to
24171 	 * watch out that we stop at the end of the header.
24172 	 */
24173 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24174 
24175 	/*
24176 	 * Now carve off the first frag.  Note that this will include the
24177 	 * original IP header.
24178 	 */
24179 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24180 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24181 		freeb(hdr_mp);
24182 		freemsg(mp_orig);
24183 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24184 		    "ip_wput_frag_end:(%S)",
24185 		    "couldn't carve first");
24186 		return;
24187 	}
24188 
24189 	/*
24190 	 * Multirouting case. Each fragment is replicated
24191 	 * via all non-condemned RTF_MULTIRT routes
24192 	 * currently resolved.
24193 	 * We ensure that first_ire is the first RTF_MULTIRT
24194 	 * ire in the bucket.
24195 	 */
24196 	if (ire->ire_flags & RTF_MULTIRT) {
24197 		irb = ire->ire_bucket;
24198 		ASSERT(irb != NULL);
24199 
24200 		multirt_send = B_TRUE;
24201 
24202 		/* Make sure we do not omit any multiroute ire. */
24203 		IRB_REFHOLD(irb);
24204 		for (first_ire = irb->irb_ire;
24205 		    first_ire != NULL;
24206 		    first_ire = first_ire->ire_next) {
24207 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24208 			    (first_ire->ire_addr == ire->ire_addr) &&
24209 			    !(first_ire->ire_marks &
24210 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
24211 				break;
24212 			}
24213 		}
24214 
24215 		if (first_ire != NULL) {
24216 			if (first_ire != ire) {
24217 				IRE_REFHOLD(first_ire);
24218 				/*
24219 				 * Do not release the ire passed in
24220 				 * as the argument.
24221 				 */
24222 				ire = first_ire;
24223 			} else {
24224 				first_ire = NULL;
24225 			}
24226 		}
24227 		IRB_REFRELE(irb);
24228 
24229 		/*
24230 		 * Save the first ire; we will need to restore it
24231 		 * for the trailing frags.
24232 		 * We REFHOLD save_ire, as each iterated ire will be
24233 		 * REFRELEd.
24234 		 */
24235 		save_ire = ire;
24236 		IRE_REFHOLD(save_ire);
24237 	}
24238 
24239 	/*
24240 	 * First fragment emission loop.
24241 	 * In most cases, the emission loop below is entered only
24242 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24243 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24244 	 * bucket, and send the fragment through all crossed
24245 	 * RTF_MULTIRT routes.
24246 	 */
24247 	do {
24248 		if (ire->ire_flags & RTF_MULTIRT) {
24249 			/*
24250 			 * We are in a multiple send case, need to get
24251 			 * the next ire and make a copy of the packet.
24252 			 * ire1 holds here the next ire to process in the
24253 			 * bucket. If multirouting is expected,
24254 			 * any non-RTF_MULTIRT ire that has the
24255 			 * right destination address is ignored.
24256 			 *
24257 			 * We have to take into account the MTU of
24258 			 * each walked ire. max_frag is set by the
24259 			 * the caller and generally refers to
24260 			 * the primary ire entry. Here we ensure that
24261 			 * no route with a lower MTU will be used, as
24262 			 * fragments are carved once for all ires,
24263 			 * then replicated.
24264 			 */
24265 			ASSERT(irb != NULL);
24266 			IRB_REFHOLD(irb);
24267 			for (ire1 = ire->ire_next;
24268 			    ire1 != NULL;
24269 			    ire1 = ire1->ire_next) {
24270 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24271 					continue;
24272 				if (ire1->ire_addr != ire->ire_addr)
24273 					continue;
24274 				if (ire1->ire_marks &
24275 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24276 					continue;
24277 				/*
24278 				 * Ensure we do not exceed the MTU
24279 				 * of the next route.
24280 				 */
24281 				if (ire1->ire_max_frag < max_frag) {
24282 					ip_multirt_bad_mtu(ire1, max_frag);
24283 					continue;
24284 				}
24285 
24286 				/* Got one. */
24287 				IRE_REFHOLD(ire1);
24288 				break;
24289 			}
24290 			IRB_REFRELE(irb);
24291 
24292 			if (ire1 != NULL) {
24293 				next_mp = copyb(mp);
24294 				if ((next_mp == NULL) ||
24295 				    ((mp->b_cont != NULL) &&
24296 				    ((next_mp->b_cont =
24297 				    dupmsg(mp->b_cont)) == NULL))) {
24298 					freemsg(next_mp);
24299 					next_mp = NULL;
24300 					ire_refrele(ire1);
24301 					ire1 = NULL;
24302 				}
24303 			}
24304 
24305 			/* Last multiroute ire; don't loop anymore. */
24306 			if (ire1 == NULL) {
24307 				multirt_send = B_FALSE;
24308 			}
24309 		}
24310 
24311 		ll_hdr_len = 0;
24312 		LOCK_IRE_FP_MP(ire);
24313 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24314 		if (ll_hdr_mp != NULL) {
24315 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24316 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24317 		} else {
24318 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24319 		}
24320 
24321 		/* If there is a transmit header, get a copy for this frag. */
24322 		/*
24323 		 * TODO: should check db_ref before calling ip_carve_mp since
24324 		 * it might give us a dup.
24325 		 */
24326 		if (!ll_hdr_mp) {
24327 			/* No xmit header. */
24328 			xmit_mp = mp;
24329 
24330 		/* We have a link-layer header that can fit in our mblk. */
24331 		} else if (mp->b_datap->db_ref == 1 &&
24332 		    ll_hdr_len != 0 &&
24333 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24334 			/* M_DATA fastpath */
24335 			mp->b_rptr -= ll_hdr_len;
24336 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24337 			xmit_mp = mp;
24338 
24339 		/* Corner case if copyb has failed */
24340 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24341 			UNLOCK_IRE_FP_MP(ire);
24342 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24343 			freeb(hdr_mp);
24344 			freemsg(mp);
24345 			freemsg(mp_orig);
24346 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24347 			    "ip_wput_frag_end:(%S)",
24348 			    "discard");
24349 
24350 			if (multirt_send) {
24351 				ASSERT(ire1);
24352 				ASSERT(next_mp);
24353 
24354 				freemsg(next_mp);
24355 				ire_refrele(ire1);
24356 			}
24357 			if (save_ire != NULL)
24358 				IRE_REFRELE(save_ire);
24359 
24360 			if (first_ire != NULL)
24361 				ire_refrele(first_ire);
24362 			return;
24363 
24364 		/*
24365 		 * Case of res_mp OR the fastpath mp can't fit
24366 		 * in the mblk
24367 		 */
24368 		} else {
24369 			xmit_mp->b_cont = mp;
24370 			if (DB_CRED(mp) != NULL)
24371 				mblk_setcred(xmit_mp, DB_CRED(mp));
24372 			/*
24373 			 * Get priority marking, if any.
24374 			 * We propagate the CoS marking from the
24375 			 * original packet that went to QoS processing
24376 			 * in ip_wput_ire to the newly carved mp.
24377 			 */
24378 			if (DB_TYPE(xmit_mp) == M_DATA)
24379 				xmit_mp->b_band = mp->b_band;
24380 		}
24381 		UNLOCK_IRE_FP_MP(ire);
24382 
24383 		q = ire->ire_stq;
24384 		out_ill = (ill_t *)q->q_ptr;
24385 
24386 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24387 
24388 		DTRACE_PROBE4(ip4__physical__out__start,
24389 		    ill_t *, NULL, ill_t *, out_ill,
24390 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24391 
24392 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24393 		    ipst->ips_ipv4firewall_physical_out,
24394 		    NULL, out_ill, ipha, xmit_mp, mp, ipst);
24395 
24396 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24397 
24398 		if (xmit_mp != NULL) {
24399 			putnext(q, xmit_mp);
24400 
24401 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24402 			UPDATE_MIB(out_ill->ill_ip_mib,
24403 			    ipIfStatsHCOutOctets, i1);
24404 
24405 			if (pkt_type != OB_PKT) {
24406 				/*
24407 				 * Update the packet count and MIB stats
24408 				 * of trailing RTF_MULTIRT ires.
24409 				 */
24410 				UPDATE_OB_PKT_COUNT(ire);
24411 				BUMP_MIB(out_ill->ill_ip_mib,
24412 				    ipIfStatsOutFragReqds);
24413 			}
24414 		}
24415 
24416 		if (multirt_send) {
24417 			/*
24418 			 * We are in a multiple send case; look for
24419 			 * the next ire and re-enter the loop.
24420 			 */
24421 			ASSERT(ire1);
24422 			ASSERT(next_mp);
24423 			/* REFRELE the current ire before looping */
24424 			ire_refrele(ire);
24425 			ire = ire1;
24426 			ire1 = NULL;
24427 			mp = next_mp;
24428 			next_mp = NULL;
24429 		}
24430 	} while (multirt_send);
24431 
24432 	ASSERT(ire1 == NULL);
24433 
24434 	/* Restore the original ire; we need it for the trailing frags */
24435 	if (save_ire != NULL) {
24436 		/* REFRELE the last iterated ire */
24437 		ire_refrele(ire);
24438 		/* save_ire has been REFHOLDed */
24439 		ire = save_ire;
24440 		save_ire = NULL;
24441 		q = ire->ire_stq;
24442 	}
24443 
24444 	if (pkt_type == OB_PKT) {
24445 		UPDATE_OB_PKT_COUNT(ire);
24446 	} else {
24447 		out_ill = (ill_t *)q->q_ptr;
24448 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24449 		UPDATE_IB_PKT_COUNT(ire);
24450 	}
24451 
24452 	/* Advance the offset to the second frag starting point. */
24453 	offset += len;
24454 	/*
24455 	 * Update hdr_len from the copied header - there might be less options
24456 	 * in the later fragments.
24457 	 */
24458 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24459 	/* Loop until done. */
24460 	for (;;) {
24461 		uint16_t	offset_and_flags;
24462 		uint16_t	ip_len;
24463 
24464 		if (ip_data_end - offset > len) {
24465 			/*
24466 			 * Carve off the appropriate amount from the original
24467 			 * datagram.
24468 			 */
24469 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24470 				mp = NULL;
24471 				break;
24472 			}
24473 			/*
24474 			 * More frags after this one.  Get another copy
24475 			 * of the header.
24476 			 */
24477 			if (carve_mp->b_datap->db_ref == 1 &&
24478 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24479 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24480 				/* Inline IP header */
24481 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24482 				    hdr_mp->b_rptr;
24483 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24484 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24485 				mp = carve_mp;
24486 			} else {
24487 				if (!(mp = copyb(hdr_mp))) {
24488 					freemsg(carve_mp);
24489 					break;
24490 				}
24491 				/* Get priority marking, if any. */
24492 				mp->b_band = carve_mp->b_band;
24493 				mp->b_cont = carve_mp;
24494 			}
24495 			ipha = (ipha_t *)mp->b_rptr;
24496 			offset_and_flags = IPH_MF;
24497 		} else {
24498 			/*
24499 			 * Last frag.  Consume the header. Set len to
24500 			 * the length of this last piece.
24501 			 */
24502 			len = ip_data_end - offset;
24503 
24504 			/*
24505 			 * Carve off the appropriate amount from the original
24506 			 * datagram.
24507 			 */
24508 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24509 				mp = NULL;
24510 				break;
24511 			}
24512 			if (carve_mp->b_datap->db_ref == 1 &&
24513 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24514 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24515 				/* Inline IP header */
24516 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24517 				    hdr_mp->b_rptr;
24518 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24519 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24520 				mp = carve_mp;
24521 				freeb(hdr_mp);
24522 				hdr_mp = mp;
24523 			} else {
24524 				mp = hdr_mp;
24525 				/* Get priority marking, if any. */
24526 				mp->b_band = carve_mp->b_band;
24527 				mp->b_cont = carve_mp;
24528 			}
24529 			ipha = (ipha_t *)mp->b_rptr;
24530 			/* A frag of a frag might have IPH_MF non-zero */
24531 			offset_and_flags =
24532 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24533 			    IPH_MF;
24534 		}
24535 		offset_and_flags |= (uint16_t)(offset >> 3);
24536 		offset_and_flags |= (uint16_t)frag_flag;
24537 		/* Store the offset and flags in the IP header. */
24538 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24539 
24540 		/* Store the length in the IP header. */
24541 		ip_len = (uint16_t)(len + hdr_len);
24542 		ipha->ipha_length = htons(ip_len);
24543 
24544 		/*
24545 		 * Set the IP header checksum.	Note that mp is just
24546 		 * the header, so this is easy to pass to ip_csum.
24547 		 */
24548 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24549 
24550 		/* Attach a transmit header, if any, and ship it. */
24551 		if (pkt_type == OB_PKT) {
24552 			UPDATE_OB_PKT_COUNT(ire);
24553 		} else {
24554 			out_ill = (ill_t *)q->q_ptr;
24555 			BUMP_MIB(out_ill->ill_ip_mib,
24556 			    ipIfStatsHCOutForwDatagrams);
24557 			UPDATE_IB_PKT_COUNT(ire);
24558 		}
24559 
24560 		if (ire->ire_flags & RTF_MULTIRT) {
24561 			irb = ire->ire_bucket;
24562 			ASSERT(irb != NULL);
24563 
24564 			multirt_send = B_TRUE;
24565 
24566 			/*
24567 			 * Save the original ire; we will need to restore it
24568 			 * for the tailing frags.
24569 			 */
24570 			save_ire = ire;
24571 			IRE_REFHOLD(save_ire);
24572 		}
24573 		/*
24574 		 * Emission loop for this fragment, similar
24575 		 * to what is done for the first fragment.
24576 		 */
24577 		do {
24578 			if (multirt_send) {
24579 				/*
24580 				 * We are in a multiple send case, need to get
24581 				 * the next ire and make a copy of the packet.
24582 				 */
24583 				ASSERT(irb != NULL);
24584 				IRB_REFHOLD(irb);
24585 				for (ire1 = ire->ire_next;
24586 				    ire1 != NULL;
24587 				    ire1 = ire1->ire_next) {
24588 					if (!(ire1->ire_flags & RTF_MULTIRT))
24589 						continue;
24590 					if (ire1->ire_addr != ire->ire_addr)
24591 						continue;
24592 					if (ire1->ire_marks &
24593 					    (IRE_MARK_CONDEMNED|
24594 					    IRE_MARK_HIDDEN)) {
24595 						continue;
24596 					}
24597 					/*
24598 					 * Ensure we do not exceed the MTU
24599 					 * of the next route.
24600 					 */
24601 					if (ire1->ire_max_frag < max_frag) {
24602 						ip_multirt_bad_mtu(ire1,
24603 						    max_frag);
24604 						continue;
24605 					}
24606 
24607 					/* Got one. */
24608 					IRE_REFHOLD(ire1);
24609 					break;
24610 				}
24611 				IRB_REFRELE(irb);
24612 
24613 				if (ire1 != NULL) {
24614 					next_mp = copyb(mp);
24615 					if ((next_mp == NULL) ||
24616 					    ((mp->b_cont != NULL) &&
24617 					    ((next_mp->b_cont =
24618 					    dupmsg(mp->b_cont)) == NULL))) {
24619 						freemsg(next_mp);
24620 						next_mp = NULL;
24621 						ire_refrele(ire1);
24622 						ire1 = NULL;
24623 					}
24624 				}
24625 
24626 				/* Last multiroute ire; don't loop anymore. */
24627 				if (ire1 == NULL) {
24628 					multirt_send = B_FALSE;
24629 				}
24630 			}
24631 
24632 			/* Update transmit header */
24633 			ll_hdr_len = 0;
24634 			LOCK_IRE_FP_MP(ire);
24635 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24636 			if (ll_hdr_mp != NULL) {
24637 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24638 				ll_hdr_len = MBLKL(ll_hdr_mp);
24639 			} else {
24640 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24641 			}
24642 
24643 			if (!ll_hdr_mp) {
24644 				xmit_mp = mp;
24645 
24646 			/*
24647 			 * We have link-layer header that can fit in
24648 			 * our mblk.
24649 			 */
24650 			} else if (mp->b_datap->db_ref == 1 &&
24651 			    ll_hdr_len != 0 &&
24652 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24653 				/* M_DATA fastpath */
24654 				mp->b_rptr -= ll_hdr_len;
24655 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24656 				    ll_hdr_len);
24657 				xmit_mp = mp;
24658 
24659 			/*
24660 			 * Case of res_mp OR the fastpath mp can't fit
24661 			 * in the mblk
24662 			 */
24663 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24664 				xmit_mp->b_cont = mp;
24665 				if (DB_CRED(mp) != NULL)
24666 					mblk_setcred(xmit_mp, DB_CRED(mp));
24667 				/* Get priority marking, if any. */
24668 				if (DB_TYPE(xmit_mp) == M_DATA)
24669 					xmit_mp->b_band = mp->b_band;
24670 
24671 			/* Corner case if copyb failed */
24672 			} else {
24673 				/*
24674 				 * Exit both the replication and
24675 				 * fragmentation loops.
24676 				 */
24677 				UNLOCK_IRE_FP_MP(ire);
24678 				goto drop_pkt;
24679 			}
24680 			UNLOCK_IRE_FP_MP(ire);
24681 
24682 			mp1 = mp;
24683 			out_ill = (ill_t *)q->q_ptr;
24684 
24685 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24686 
24687 			DTRACE_PROBE4(ip4__physical__out__start,
24688 			    ill_t *, NULL, ill_t *, out_ill,
24689 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24690 
24691 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24692 			    ipst->ips_ipv4firewall_physical_out,
24693 			    NULL, out_ill, ipha, xmit_mp, mp, ipst);
24694 
24695 			DTRACE_PROBE1(ip4__physical__out__end,
24696 			    mblk_t *, xmit_mp);
24697 
24698 			if (mp != mp1 && hdr_mp == mp1)
24699 				hdr_mp = mp;
24700 			if (mp != mp1 && mp_orig == mp1)
24701 				mp_orig = mp;
24702 
24703 			if (xmit_mp != NULL) {
24704 				putnext(q, xmit_mp);
24705 
24706 				BUMP_MIB(out_ill->ill_ip_mib,
24707 				    ipIfStatsHCOutTransmits);
24708 				UPDATE_MIB(out_ill->ill_ip_mib,
24709 				    ipIfStatsHCOutOctets, ip_len);
24710 
24711 				if (pkt_type != OB_PKT) {
24712 					/*
24713 					 * Update the packet count of trailing
24714 					 * RTF_MULTIRT ires.
24715 					 */
24716 					UPDATE_OB_PKT_COUNT(ire);
24717 				}
24718 			}
24719 
24720 			/* All done if we just consumed the hdr_mp. */
24721 			if (mp == hdr_mp) {
24722 				last_frag = B_TRUE;
24723 				BUMP_MIB(out_ill->ill_ip_mib,
24724 				    ipIfStatsOutFragOKs);
24725 			}
24726 
24727 			if (multirt_send) {
24728 				/*
24729 				 * We are in a multiple send case; look for
24730 				 * the next ire and re-enter the loop.
24731 				 */
24732 				ASSERT(ire1);
24733 				ASSERT(next_mp);
24734 				/* REFRELE the current ire before looping */
24735 				ire_refrele(ire);
24736 				ire = ire1;
24737 				ire1 = NULL;
24738 				q = ire->ire_stq;
24739 				mp = next_mp;
24740 				next_mp = NULL;
24741 			}
24742 		} while (multirt_send);
24743 		/*
24744 		 * Restore the original ire; we need it for the
24745 		 * trailing frags
24746 		 */
24747 		if (save_ire != NULL) {
24748 			ASSERT(ire1 == NULL);
24749 			/* REFRELE the last iterated ire */
24750 			ire_refrele(ire);
24751 			/* save_ire has been REFHOLDed */
24752 			ire = save_ire;
24753 			q = ire->ire_stq;
24754 			save_ire = NULL;
24755 		}
24756 
24757 		if (last_frag) {
24758 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24759 			    "ip_wput_frag_end:(%S)",
24760 			    "consumed hdr_mp");
24761 
24762 			if (first_ire != NULL)
24763 				ire_refrele(first_ire);
24764 			return;
24765 		}
24766 		/* Otherwise, advance and loop. */
24767 		offset += len;
24768 	}
24769 
24770 drop_pkt:
24771 	/* Clean up following allocation failure. */
24772 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24773 	freemsg(mp);
24774 	if (mp != hdr_mp)
24775 		freeb(hdr_mp);
24776 	if (mp != mp_orig)
24777 		freemsg(mp_orig);
24778 
24779 	if (save_ire != NULL)
24780 		IRE_REFRELE(save_ire);
24781 	if (first_ire != NULL)
24782 		ire_refrele(first_ire);
24783 
24784 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24785 	    "ip_wput_frag_end:(%S)",
24786 	    "end--alloc failure");
24787 }
24788 
24789 /*
24790  * Copy the header plus those options which have the copy bit set
24791  */
24792 static mblk_t *
24793 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst)
24794 {
24795 	mblk_t	*mp;
24796 	uchar_t	*up;
24797 
24798 	/*
24799 	 * Quick check if we need to look for options without the copy bit
24800 	 * set
24801 	 */
24802 	mp = allocb(ipst->ips_ip_wroff_extra + hdr_len, BPRI_HI);
24803 	if (!mp)
24804 		return (mp);
24805 	mp->b_rptr += ipst->ips_ip_wroff_extra;
24806 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24807 		bcopy(rptr, mp->b_rptr, hdr_len);
24808 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
24809 		return (mp);
24810 	}
24811 	up  = mp->b_rptr;
24812 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24813 	up += IP_SIMPLE_HDR_LENGTH;
24814 	rptr += IP_SIMPLE_HDR_LENGTH;
24815 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24816 	while (hdr_len > 0) {
24817 		uint32_t optval;
24818 		uint32_t optlen;
24819 
24820 		optval = *rptr;
24821 		if (optval == IPOPT_EOL)
24822 			break;
24823 		if (optval == IPOPT_NOP)
24824 			optlen = 1;
24825 		else
24826 			optlen = rptr[1];
24827 		if (optval & IPOPT_COPY) {
24828 			bcopy(rptr, up, optlen);
24829 			up += optlen;
24830 		}
24831 		rptr += optlen;
24832 		hdr_len -= optlen;
24833 	}
24834 	/*
24835 	 * Make sure that we drop an even number of words by filling
24836 	 * with EOL to the next word boundary.
24837 	 */
24838 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
24839 	    hdr_len & 0x3; hdr_len++)
24840 		*up++ = IPOPT_EOL;
24841 	mp->b_wptr = up;
24842 	/* Update header length */
24843 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
24844 	return (mp);
24845 }
24846 
24847 /*
24848  * Delivery to local recipients including fanout to multiple recipients.
24849  * Does not do checksumming of UDP/TCP.
24850  * Note: q should be the read side queue for either the ill or conn.
24851  * Note: rq should be the read side q for the lower (ill) stream.
24852  * We don't send packets to IPPF processing, thus the last argument
24853  * to all the fanout calls are B_FALSE.
24854  */
24855 void
24856 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
24857     int fanout_flags, zoneid_t zoneid)
24858 {
24859 	uint32_t	protocol;
24860 	mblk_t		*first_mp;
24861 	boolean_t	mctl_present;
24862 	int		ire_type;
24863 #define	rptr	((uchar_t *)ipha)
24864 	ip_stack_t	*ipst = ill->ill_ipst;
24865 
24866 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
24867 	    "ip_wput_local_start: q %p", q);
24868 
24869 	if (ire != NULL) {
24870 		ire_type = ire->ire_type;
24871 	} else {
24872 		/*
24873 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
24874 		 * packet is not multicast, we can't tell the ire type.
24875 		 */
24876 		ASSERT(CLASSD(ipha->ipha_dst));
24877 		ire_type = IRE_BROADCAST;
24878 	}
24879 
24880 	first_mp = mp;
24881 	if (first_mp->b_datap->db_type == M_CTL) {
24882 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
24883 		if (!io->ipsec_out_secure) {
24884 			/*
24885 			 * This ipsec_out_t was allocated in ip_wput
24886 			 * for multicast packets to store the ill_index.
24887 			 * As this is being delivered locally, we don't
24888 			 * need this anymore.
24889 			 */
24890 			mp = first_mp->b_cont;
24891 			freeb(first_mp);
24892 			first_mp = mp;
24893 			mctl_present = B_FALSE;
24894 		} else {
24895 			/*
24896 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
24897 			 * security properties for the looped-back packet.
24898 			 */
24899 			mctl_present = B_TRUE;
24900 			mp = first_mp->b_cont;
24901 			ASSERT(mp != NULL);
24902 			ipsec_out_to_in(first_mp);
24903 		}
24904 	} else {
24905 		mctl_present = B_FALSE;
24906 	}
24907 
24908 	DTRACE_PROBE4(ip4__loopback__in__start,
24909 	    ill_t *, ill, ill_t *, NULL,
24910 	    ipha_t *, ipha, mblk_t *, first_mp);
24911 
24912 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
24913 	    ipst->ips_ipv4firewall_loopback_in,
24914 	    ill, NULL, ipha, first_mp, mp, ipst);
24915 
24916 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
24917 
24918 	if (first_mp == NULL)
24919 		return;
24920 
24921 	ipst->ips_loopback_packets++;
24922 
24923 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
24924 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
24925 	if (!IS_SIMPLE_IPH(ipha)) {
24926 		ip_wput_local_options(ipha, ipst);
24927 	}
24928 
24929 	protocol = ipha->ipha_protocol;
24930 	switch (protocol) {
24931 	case IPPROTO_ICMP: {
24932 		ire_t		*ire_zone;
24933 		ilm_t		*ilm;
24934 		mblk_t		*mp1;
24935 		zoneid_t	last_zoneid;
24936 
24937 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
24938 			ASSERT(ire_type == IRE_BROADCAST);
24939 			/*
24940 			 * In the multicast case, applications may have joined
24941 			 * the group from different zones, so we need to deliver
24942 			 * the packet to each of them. Loop through the
24943 			 * multicast memberships structures (ilm) on the receive
24944 			 * ill and send a copy of the packet up each matching
24945 			 * one. However, we don't do this for multicasts sent on
24946 			 * the loopback interface (PHYI_LOOPBACK flag set) as
24947 			 * they must stay in the sender's zone.
24948 			 *
24949 			 * ilm_add_v6() ensures that ilms in the same zone are
24950 			 * contiguous in the ill_ilm list. We use this property
24951 			 * to avoid sending duplicates needed when two
24952 			 * applications in the same zone join the same group on
24953 			 * different logical interfaces: we ignore the ilm if
24954 			 * it's zoneid is the same as the last matching one.
24955 			 * In addition, the sending of the packet for
24956 			 * ire_zoneid is delayed until all of the other ilms
24957 			 * have been exhausted.
24958 			 */
24959 			last_zoneid = -1;
24960 			ILM_WALKER_HOLD(ill);
24961 			for (ilm = ill->ill_ilm; ilm != NULL;
24962 			    ilm = ilm->ilm_next) {
24963 				if ((ilm->ilm_flags & ILM_DELETED) ||
24964 				    ipha->ipha_dst != ilm->ilm_addr ||
24965 				    ilm->ilm_zoneid == last_zoneid ||
24966 				    ilm->ilm_zoneid == zoneid ||
24967 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
24968 					continue;
24969 				mp1 = ip_copymsg(first_mp);
24970 				if (mp1 == NULL)
24971 					continue;
24972 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
24973 				    mctl_present, B_FALSE, ill,
24974 				    ilm->ilm_zoneid);
24975 				last_zoneid = ilm->ilm_zoneid;
24976 			}
24977 			ILM_WALKER_RELE(ill);
24978 			/*
24979 			 * Loopback case: the sending endpoint has
24980 			 * IP_MULTICAST_LOOP disabled, therefore we don't
24981 			 * dispatch the multicast packet to the sending zone.
24982 			 */
24983 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
24984 				freemsg(first_mp);
24985 				return;
24986 			}
24987 		} else if (ire_type == IRE_BROADCAST) {
24988 			/*
24989 			 * In the broadcast case, there may be many zones
24990 			 * which need a copy of the packet delivered to them.
24991 			 * There is one IRE_BROADCAST per broadcast address
24992 			 * and per zone; we walk those using a helper function.
24993 			 * In addition, the sending of the packet for zoneid is
24994 			 * delayed until all of the other ires have been
24995 			 * processed.
24996 			 */
24997 			IRB_REFHOLD(ire->ire_bucket);
24998 			ire_zone = NULL;
24999 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25000 			    ire)) != NULL) {
25001 				mp1 = ip_copymsg(first_mp);
25002 				if (mp1 == NULL)
25003 					continue;
25004 
25005 				UPDATE_IB_PKT_COUNT(ire_zone);
25006 				ire_zone->ire_last_used_time = lbolt;
25007 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25008 				    mctl_present, B_FALSE, ill,
25009 				    ire_zone->ire_zoneid);
25010 			}
25011 			IRB_REFRELE(ire->ire_bucket);
25012 		}
25013 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25014 		    0, mctl_present, B_FALSE, ill, zoneid);
25015 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25016 		    "ip_wput_local_end: q %p (%S)",
25017 		    q, "icmp");
25018 		return;
25019 	}
25020 	case IPPROTO_IGMP:
25021 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25022 			/* Bad packet - discarded by igmp_input */
25023 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25024 			    "ip_wput_local_end: q %p (%S)",
25025 			    q, "igmp_input--bad packet");
25026 			if (mctl_present)
25027 				freeb(first_mp);
25028 			return;
25029 		}
25030 		/*
25031 		 * igmp_input() may have returned the pulled up message.
25032 		 * So first_mp and ipha need to be reinitialized.
25033 		 */
25034 		ipha = (ipha_t *)mp->b_rptr;
25035 		if (mctl_present)
25036 			first_mp->b_cont = mp;
25037 		else
25038 			first_mp = mp;
25039 		/* deliver to local raw users */
25040 		break;
25041 	case IPPROTO_ENCAP:
25042 		/*
25043 		 * This case is covered by either ip_fanout_proto, or by
25044 		 * the above security processing for self-tunneled packets.
25045 		 */
25046 		break;
25047 	case IPPROTO_UDP: {
25048 		uint16_t	*up;
25049 		uint32_t	ports;
25050 
25051 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25052 		    UDP_PORTS_OFFSET);
25053 		/* Force a 'valid' checksum. */
25054 		up[3] = 0;
25055 
25056 		ports = *(uint32_t *)up;
25057 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25058 		    (ire_type == IRE_BROADCAST),
25059 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25060 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25061 		    ill, zoneid);
25062 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25063 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25064 		return;
25065 	}
25066 	case IPPROTO_TCP: {
25067 
25068 		/*
25069 		 * For TCP, discard broadcast packets.
25070 		 */
25071 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25072 			freemsg(first_mp);
25073 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25074 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25075 			return;
25076 		}
25077 
25078 		if (mp->b_datap->db_type == M_DATA) {
25079 			/*
25080 			 * M_DATA mblk, so init mblk (chain) for no struio().
25081 			 */
25082 			mblk_t	*mp1 = mp;
25083 
25084 			do {
25085 				mp1->b_datap->db_struioflag = 0;
25086 			} while ((mp1 = mp1->b_cont) != NULL);
25087 		}
25088 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25089 		    <= mp->b_wptr);
25090 		ip_fanout_tcp(q, first_mp, ill, ipha,
25091 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25092 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25093 		    mctl_present, B_FALSE, zoneid);
25094 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25095 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25096 		return;
25097 	}
25098 	case IPPROTO_SCTP:
25099 	{
25100 		uint32_t	ports;
25101 
25102 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25103 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25104 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25105 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25106 		return;
25107 	}
25108 
25109 	default:
25110 		break;
25111 	}
25112 	/*
25113 	 * Find a client for some other protocol.  We give
25114 	 * copies to multiple clients, if more than one is
25115 	 * bound.
25116 	 */
25117 	ip_fanout_proto(q, first_mp, ill, ipha,
25118 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25119 	    mctl_present, B_FALSE, ill, zoneid);
25120 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25121 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25122 #undef	rptr
25123 }
25124 
25125 /*
25126  * Update any source route, record route, or timestamp options.
25127  * Check that we are at end of strict source route.
25128  * The options have been sanity checked by ip_wput_options().
25129  */
25130 static void
25131 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25132 {
25133 	ipoptp_t	opts;
25134 	uchar_t		*opt;
25135 	uint8_t		optval;
25136 	uint8_t		optlen;
25137 	ipaddr_t	dst;
25138 	uint32_t	ts;
25139 	ire_t		*ire;
25140 	timestruc_t	now;
25141 
25142 	ip2dbg(("ip_wput_local_options\n"));
25143 	for (optval = ipoptp_first(&opts, ipha);
25144 	    optval != IPOPT_EOL;
25145 	    optval = ipoptp_next(&opts)) {
25146 		opt = opts.ipoptp_cur;
25147 		optlen = opts.ipoptp_len;
25148 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25149 		switch (optval) {
25150 			uint32_t off;
25151 		case IPOPT_SSRR:
25152 		case IPOPT_LSRR:
25153 			off = opt[IPOPT_OFFSET];
25154 			off--;
25155 			if (optlen < IP_ADDR_LEN ||
25156 			    off > optlen - IP_ADDR_LEN) {
25157 				/* End of source route */
25158 				break;
25159 			}
25160 			/*
25161 			 * This will only happen if two consecutive entries
25162 			 * in the source route contains our address or if
25163 			 * it is a packet with a loose source route which
25164 			 * reaches us before consuming the whole source route
25165 			 */
25166 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25167 			if (optval == IPOPT_SSRR) {
25168 				return;
25169 			}
25170 			/*
25171 			 * Hack: instead of dropping the packet truncate the
25172 			 * source route to what has been used by filling the
25173 			 * rest with IPOPT_NOP.
25174 			 */
25175 			opt[IPOPT_OLEN] = (uint8_t)off;
25176 			while (off < optlen) {
25177 				opt[off++] = IPOPT_NOP;
25178 			}
25179 			break;
25180 		case IPOPT_RR:
25181 			off = opt[IPOPT_OFFSET];
25182 			off--;
25183 			if (optlen < IP_ADDR_LEN ||
25184 			    off > optlen - IP_ADDR_LEN) {
25185 				/* No more room - ignore */
25186 				ip1dbg((
25187 				    "ip_wput_forward_options: end of RR\n"));
25188 				break;
25189 			}
25190 			dst = htonl(INADDR_LOOPBACK);
25191 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25192 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25193 			break;
25194 		case IPOPT_TS:
25195 			/* Insert timestamp if there is romm */
25196 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25197 			case IPOPT_TS_TSONLY:
25198 				off = IPOPT_TS_TIMELEN;
25199 				break;
25200 			case IPOPT_TS_PRESPEC:
25201 			case IPOPT_TS_PRESPEC_RFC791:
25202 				/* Verify that the address matched */
25203 				off = opt[IPOPT_OFFSET] - 1;
25204 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25205 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25206 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25207 				    ipst);
25208 				if (ire == NULL) {
25209 					/* Not for us */
25210 					break;
25211 				}
25212 				ire_refrele(ire);
25213 				/* FALLTHRU */
25214 			case IPOPT_TS_TSANDADDR:
25215 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25216 				break;
25217 			default:
25218 				/*
25219 				 * ip_*put_options should have already
25220 				 * dropped this packet.
25221 				 */
25222 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25223 				    "unknown IT - bug in ip_wput_options?\n");
25224 				return;	/* Keep "lint" happy */
25225 			}
25226 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25227 				/* Increase overflow counter */
25228 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25229 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25230 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25231 				    (off << 4);
25232 				break;
25233 			}
25234 			off = opt[IPOPT_OFFSET] - 1;
25235 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25236 			case IPOPT_TS_PRESPEC:
25237 			case IPOPT_TS_PRESPEC_RFC791:
25238 			case IPOPT_TS_TSANDADDR:
25239 				dst = htonl(INADDR_LOOPBACK);
25240 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25241 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25242 				/* FALLTHRU */
25243 			case IPOPT_TS_TSONLY:
25244 				off = opt[IPOPT_OFFSET] - 1;
25245 				/* Compute # of milliseconds since midnight */
25246 				gethrestime(&now);
25247 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25248 				    now.tv_nsec / (NANOSEC / MILLISEC);
25249 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25250 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25251 				break;
25252 			}
25253 			break;
25254 		}
25255 	}
25256 }
25257 
25258 /*
25259  * Send out a multicast packet on interface ipif.
25260  * The sender does not have an conn.
25261  * Caller verifies that this isn't a PHYI_LOOPBACK.
25262  */
25263 void
25264 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25265 {
25266 	ipha_t	*ipha;
25267 	ire_t	*ire;
25268 	ipaddr_t	dst;
25269 	mblk_t		*first_mp;
25270 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25271 
25272 	/* igmp_sendpkt always allocates a ipsec_out_t */
25273 	ASSERT(mp->b_datap->db_type == M_CTL);
25274 	ASSERT(!ipif->ipif_isv6);
25275 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25276 
25277 	first_mp = mp;
25278 	mp = first_mp->b_cont;
25279 	ASSERT(mp->b_datap->db_type == M_DATA);
25280 	ipha = (ipha_t *)mp->b_rptr;
25281 
25282 	/*
25283 	 * Find an IRE which matches the destination and the outgoing
25284 	 * queue (i.e. the outgoing interface.)
25285 	 */
25286 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25287 		dst = ipif->ipif_pp_dst_addr;
25288 	else
25289 		dst = ipha->ipha_dst;
25290 	/*
25291 	 * The source address has already been initialized by the
25292 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25293 	 * be sufficient rather than MATCH_IRE_IPIF.
25294 	 *
25295 	 * This function is used for sending IGMP packets. We need
25296 	 * to make sure that we send the packet out of the interface
25297 	 * (ipif->ipif_ill) where we joined the group. This is to
25298 	 * prevent from switches doing IGMP snooping to send us multicast
25299 	 * packets for a given group on the interface we have joined.
25300 	 * If we can't find an ire, igmp_sendpkt has already initialized
25301 	 * ipsec_out_attach_if so that this will not be load spread in
25302 	 * ip_newroute_ipif.
25303 	 */
25304 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25305 	    MATCH_IRE_ILL, ipst);
25306 	if (!ire) {
25307 		/*
25308 		 * Mark this packet to make it be delivered to
25309 		 * ip_wput_ire after the new ire has been
25310 		 * created.
25311 		 */
25312 		mp->b_prev = NULL;
25313 		mp->b_next = NULL;
25314 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25315 		    zoneid, &zero_info);
25316 		return;
25317 	}
25318 
25319 	/*
25320 	 * Honor the RTF_SETSRC flag; this is the only case
25321 	 * where we force this addr whatever the current src addr is,
25322 	 * because this address is set by igmp_sendpkt(), and
25323 	 * cannot be specified by any user.
25324 	 */
25325 	if (ire->ire_flags & RTF_SETSRC) {
25326 		ipha->ipha_src = ire->ire_src_addr;
25327 	}
25328 
25329 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25330 }
25331 
25332 /*
25333  * NOTE : This function does not ire_refrele the ire argument passed in.
25334  *
25335  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25336  * failure. The nce_fp_mp can vanish any time in the case of
25337  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25338  * the ire_lock to access the nce_fp_mp in this case.
25339  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25340  * prepending a fastpath message IPQoS processing must precede it, we also set
25341  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25342  * (IPQoS might have set the b_band for CoS marking).
25343  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25344  * must follow it so that IPQoS can mark the dl_priority field for CoS
25345  * marking, if needed.
25346  */
25347 static mblk_t *
25348 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
25349 {
25350 	uint_t	hlen;
25351 	ipha_t *ipha;
25352 	mblk_t *mp1;
25353 	boolean_t qos_done = B_FALSE;
25354 	uchar_t	*ll_hdr;
25355 	ip_stack_t	*ipst = ire->ire_ipst;
25356 
25357 #define	rptr	((uchar_t *)ipha)
25358 
25359 	ipha = (ipha_t *)mp->b_rptr;
25360 	hlen = 0;
25361 	LOCK_IRE_FP_MP(ire);
25362 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25363 		ASSERT(DB_TYPE(mp1) == M_DATA);
25364 		/* Initiate IPPF processing */
25365 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25366 			UNLOCK_IRE_FP_MP(ire);
25367 			ip_process(proc, &mp, ill_index);
25368 			if (mp == NULL)
25369 				return (NULL);
25370 
25371 			ipha = (ipha_t *)mp->b_rptr;
25372 			LOCK_IRE_FP_MP(ire);
25373 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25374 				qos_done = B_TRUE;
25375 				goto no_fp_mp;
25376 			}
25377 			ASSERT(DB_TYPE(mp1) == M_DATA);
25378 		}
25379 		hlen = MBLKL(mp1);
25380 		/*
25381 		 * Check if we have enough room to prepend fastpath
25382 		 * header
25383 		 */
25384 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25385 			ll_hdr = rptr - hlen;
25386 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25387 			/*
25388 			 * Set the b_rptr to the start of the link layer
25389 			 * header
25390 			 */
25391 			mp->b_rptr = ll_hdr;
25392 			mp1 = mp;
25393 		} else {
25394 			mp1 = copyb(mp1);
25395 			if (mp1 == NULL)
25396 				goto unlock_err;
25397 			mp1->b_band = mp->b_band;
25398 			mp1->b_cont = mp;
25399 			/*
25400 			 * certain system generated traffic may not
25401 			 * have cred/label in ip header block. This
25402 			 * is true even for a labeled system. But for
25403 			 * labeled traffic, inherit the label in the
25404 			 * new header.
25405 			 */
25406 			if (DB_CRED(mp) != NULL)
25407 				mblk_setcred(mp1, DB_CRED(mp));
25408 			/*
25409 			 * XXX disable ICK_VALID and compute checksum
25410 			 * here; can happen if nce_fp_mp changes and
25411 			 * it can't be copied now due to insufficient
25412 			 * space. (unlikely, fp mp can change, but it
25413 			 * does not increase in length)
25414 			 */
25415 		}
25416 		UNLOCK_IRE_FP_MP(ire);
25417 	} else {
25418 no_fp_mp:
25419 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25420 		if (mp1 == NULL) {
25421 unlock_err:
25422 			UNLOCK_IRE_FP_MP(ire);
25423 			freemsg(mp);
25424 			return (NULL);
25425 		}
25426 		UNLOCK_IRE_FP_MP(ire);
25427 		mp1->b_cont = mp;
25428 		/*
25429 		 * certain system generated traffic may not
25430 		 * have cred/label in ip header block. This
25431 		 * is true even for a labeled system. But for
25432 		 * labeled traffic, inherit the label in the
25433 		 * new header.
25434 		 */
25435 		if (DB_CRED(mp) != NULL)
25436 			mblk_setcred(mp1, DB_CRED(mp));
25437 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25438 			ip_process(proc, &mp1, ill_index);
25439 			if (mp1 == NULL)
25440 				return (NULL);
25441 		}
25442 	}
25443 	return (mp1);
25444 #undef rptr
25445 }
25446 
25447 /*
25448  * Finish the outbound IPsec processing for an IPv6 packet. This function
25449  * is called from ipsec_out_process() if the IPsec packet was processed
25450  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25451  * asynchronously.
25452  */
25453 void
25454 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25455     ire_t *ire_arg)
25456 {
25457 	in6_addr_t *v6dstp;
25458 	ire_t *ire;
25459 	mblk_t *mp;
25460 	ip6_t *ip6h1;
25461 	uint_t	ill_index;
25462 	ipsec_out_t *io;
25463 	boolean_t attach_if, hwaccel;
25464 	uint32_t flags = IP6_NO_IPPOLICY;
25465 	int match_flags;
25466 	zoneid_t zoneid;
25467 	boolean_t ill_need_rele = B_FALSE;
25468 	boolean_t ire_need_rele = B_FALSE;
25469 	ip_stack_t	*ipst;
25470 
25471 	mp = ipsec_mp->b_cont;
25472 	ip6h1 = (ip6_t *)mp->b_rptr;
25473 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25474 	ASSERT(io->ipsec_out_ns != NULL);
25475 	ipst = io->ipsec_out_ns->netstack_ip;
25476 	ill_index = io->ipsec_out_ill_index;
25477 	if (io->ipsec_out_reachable) {
25478 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25479 	}
25480 	attach_if = io->ipsec_out_attach_if;
25481 	hwaccel = io->ipsec_out_accelerated;
25482 	zoneid = io->ipsec_out_zoneid;
25483 	ASSERT(zoneid != ALL_ZONES);
25484 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25485 	/* Multicast addresses should have non-zero ill_index. */
25486 	v6dstp = &ip6h->ip6_dst;
25487 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25488 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25489 	ASSERT(!attach_if || ill_index != 0);
25490 	if (ill_index != 0) {
25491 		if (ill == NULL) {
25492 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
25493 			    B_TRUE, ipst);
25494 
25495 			/* Failure case frees things for us. */
25496 			if (ill == NULL)
25497 				return;
25498 
25499 			ill_need_rele = B_TRUE;
25500 		}
25501 		/*
25502 		 * If this packet needs to go out on a particular interface
25503 		 * honor it.
25504 		 */
25505 		if (attach_if) {
25506 			match_flags = MATCH_IRE_ILL;
25507 
25508 			/*
25509 			 * Check if we need an ire that will not be
25510 			 * looked up by anybody else i.e. HIDDEN.
25511 			 */
25512 			if (ill_is_probeonly(ill)) {
25513 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25514 			}
25515 		}
25516 	}
25517 	ASSERT(mp != NULL);
25518 
25519 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25520 		boolean_t unspec_src;
25521 		ipif_t	*ipif;
25522 
25523 		/*
25524 		 * Use the ill_index to get the right ill.
25525 		 */
25526 		unspec_src = io->ipsec_out_unspec_src;
25527 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25528 		if (ipif == NULL) {
25529 			if (ill_need_rele)
25530 				ill_refrele(ill);
25531 			freemsg(ipsec_mp);
25532 			return;
25533 		}
25534 
25535 		if (ire_arg != NULL) {
25536 			ire = ire_arg;
25537 		} else {
25538 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25539 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25540 			ire_need_rele = B_TRUE;
25541 		}
25542 		if (ire != NULL) {
25543 			ipif_refrele(ipif);
25544 			/*
25545 			 * XXX Do the multicast forwarding now, as the IPsec
25546 			 * processing has been done.
25547 			 */
25548 			goto send;
25549 		}
25550 
25551 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25552 		mp->b_prev = NULL;
25553 		mp->b_next = NULL;
25554 
25555 		/*
25556 		 * If the IPsec packet was processed asynchronously,
25557 		 * drop it now.
25558 		 */
25559 		if (q == NULL) {
25560 			if (ill_need_rele)
25561 				ill_refrele(ill);
25562 			freemsg(ipsec_mp);
25563 			return;
25564 		}
25565 
25566 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
25567 		    unspec_src, zoneid);
25568 		ipif_refrele(ipif);
25569 	} else {
25570 		if (attach_if) {
25571 			ipif_t	*ipif;
25572 
25573 			ipif = ipif_get_next_ipif(NULL, ill);
25574 			if (ipif == NULL) {
25575 				if (ill_need_rele)
25576 					ill_refrele(ill);
25577 				freemsg(ipsec_mp);
25578 				return;
25579 			}
25580 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25581 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25582 			ire_need_rele = B_TRUE;
25583 			ipif_refrele(ipif);
25584 		} else {
25585 			if (ire_arg != NULL) {
25586 				ire = ire_arg;
25587 			} else {
25588 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL,
25589 				    ipst);
25590 				ire_need_rele = B_TRUE;
25591 			}
25592 		}
25593 		if (ire != NULL)
25594 			goto send;
25595 		/*
25596 		 * ire disappeared underneath.
25597 		 *
25598 		 * What we need to do here is the ip_newroute
25599 		 * logic to get the ire without doing the IPsec
25600 		 * processing. Follow the same old path. But this
25601 		 * time, ip_wput or ire_add_then_send will call us
25602 		 * directly as all the IPsec operations are done.
25603 		 */
25604 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25605 		mp->b_prev = NULL;
25606 		mp->b_next = NULL;
25607 
25608 		/*
25609 		 * If the IPsec packet was processed asynchronously,
25610 		 * drop it now.
25611 		 */
25612 		if (q == NULL) {
25613 			if (ill_need_rele)
25614 				ill_refrele(ill);
25615 			freemsg(ipsec_mp);
25616 			return;
25617 		}
25618 
25619 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25620 		    zoneid, ipst);
25621 	}
25622 	if (ill != NULL && ill_need_rele)
25623 		ill_refrele(ill);
25624 	return;
25625 send:
25626 	if (ill != NULL && ill_need_rele)
25627 		ill_refrele(ill);
25628 
25629 	/* Local delivery */
25630 	if (ire->ire_stq == NULL) {
25631 		ill_t	*out_ill;
25632 		ASSERT(q != NULL);
25633 
25634 		/* PFHooks: LOOPBACK_OUT */
25635 		out_ill = ire_to_ill(ire);
25636 
25637 		DTRACE_PROBE4(ip6__loopback__out__start,
25638 		    ill_t *, NULL, ill_t *, out_ill,
25639 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25640 
25641 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25642 		    ipst->ips_ipv6firewall_loopback_out,
25643 		    NULL, out_ill, ip6h1, ipsec_mp, mp, ipst);
25644 
25645 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25646 
25647 		if (ipsec_mp != NULL)
25648 			ip_wput_local_v6(RD(q), out_ill,
25649 			    ip6h, ipsec_mp, ire, 0);
25650 		if (ire_need_rele)
25651 			ire_refrele(ire);
25652 		return;
25653 	}
25654 	/*
25655 	 * Everything is done. Send it out on the wire.
25656 	 * We force the insertion of a fragment header using the
25657 	 * IPH_FRAG_HDR flag in two cases:
25658 	 * - after reception of an ICMPv6 "packet too big" message
25659 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25660 	 * - for multirouted IPv6 packets, so that the receiver can
25661 	 *   discard duplicates according to their fragment identifier
25662 	 */
25663 	/* XXX fix flow control problems. */
25664 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25665 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25666 		if (hwaccel) {
25667 			/*
25668 			 * hardware acceleration does not handle these
25669 			 * "slow path" cases.
25670 			 */
25671 			/* IPsec KSTATS: should bump bean counter here. */
25672 			if (ire_need_rele)
25673 				ire_refrele(ire);
25674 			freemsg(ipsec_mp);
25675 			return;
25676 		}
25677 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25678 		    (mp->b_cont ? msgdsize(mp) :
25679 		    mp->b_wptr - (uchar_t *)ip6h)) {
25680 			/* IPsec KSTATS: should bump bean counter here. */
25681 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25682 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25683 			    msgdsize(mp)));
25684 			if (ire_need_rele)
25685 				ire_refrele(ire);
25686 			freemsg(ipsec_mp);
25687 			return;
25688 		}
25689 		ASSERT(mp->b_prev == NULL);
25690 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25691 		    ntohs(ip6h->ip6_plen) +
25692 		    IPV6_HDR_LEN, ire->ire_max_frag));
25693 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25694 		    ire->ire_max_frag);
25695 	} else {
25696 		UPDATE_OB_PKT_COUNT(ire);
25697 		ire->ire_last_used_time = lbolt;
25698 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25699 	}
25700 	if (ire_need_rele)
25701 		ire_refrele(ire);
25702 	freeb(ipsec_mp);
25703 }
25704 
25705 void
25706 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25707 {
25708 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25709 	da_ipsec_t *hada;	/* data attributes */
25710 	ill_t *ill = (ill_t *)q->q_ptr;
25711 
25712 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25713 
25714 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25715 		/* IPsec KSTATS: Bump lose counter here! */
25716 		freemsg(mp);
25717 		return;
25718 	}
25719 
25720 	/*
25721 	 * It's an IPsec packet that must be
25722 	 * accelerated by the Provider, and the
25723 	 * outbound ill is IPsec acceleration capable.
25724 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25725 	 * to the ill.
25726 	 * IPsec KSTATS: should bump packet counter here.
25727 	 */
25728 
25729 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25730 	if (hada_mp == NULL) {
25731 		/* IPsec KSTATS: should bump packet counter here. */
25732 		freemsg(mp);
25733 		return;
25734 	}
25735 
25736 	hada_mp->b_datap->db_type = M_CTL;
25737 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25738 	hada_mp->b_cont = mp;
25739 
25740 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25741 	bzero(hada, sizeof (da_ipsec_t));
25742 	hada->da_type = IPHADA_M_CTL;
25743 
25744 	putnext(q, hada_mp);
25745 }
25746 
25747 /*
25748  * Finish the outbound IPsec processing. This function is called from
25749  * ipsec_out_process() if the IPsec packet was processed
25750  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25751  * asynchronously.
25752  */
25753 void
25754 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25755     ire_t *ire_arg)
25756 {
25757 	uint32_t v_hlen_tos_len;
25758 	ipaddr_t	dst;
25759 	ipif_t	*ipif = NULL;
25760 	ire_t *ire;
25761 	ire_t *ire1 = NULL;
25762 	mblk_t *next_mp = NULL;
25763 	uint32_t max_frag;
25764 	boolean_t multirt_send = B_FALSE;
25765 	mblk_t *mp;
25766 	ipha_t *ipha1;
25767 	uint_t	ill_index;
25768 	ipsec_out_t *io;
25769 	boolean_t attach_if;
25770 	int match_flags;
25771 	irb_t *irb = NULL;
25772 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25773 	zoneid_t zoneid;
25774 	ipxmit_state_t	pktxmit_state;
25775 	ip_stack_t	*ipst;
25776 
25777 #ifdef	_BIG_ENDIAN
25778 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25779 #else
25780 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25781 #endif
25782 
25783 	mp = ipsec_mp->b_cont;
25784 	ipha1 = (ipha_t *)mp->b_rptr;
25785 	ASSERT(mp != NULL);
25786 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25787 	dst = ipha->ipha_dst;
25788 
25789 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25790 	ill_index = io->ipsec_out_ill_index;
25791 	attach_if = io->ipsec_out_attach_if;
25792 	zoneid = io->ipsec_out_zoneid;
25793 	ASSERT(zoneid != ALL_ZONES);
25794 	ipst = io->ipsec_out_ns->netstack_ip;
25795 	ASSERT(io->ipsec_out_ns != NULL);
25796 
25797 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25798 	if (ill_index != 0) {
25799 		if (ill == NULL) {
25800 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
25801 			    ill_index, B_FALSE, ipst);
25802 
25803 			/* Failure case frees things for us. */
25804 			if (ill == NULL)
25805 				return;
25806 
25807 			ill_need_rele = B_TRUE;
25808 		}
25809 		/*
25810 		 * If this packet needs to go out on a particular interface
25811 		 * honor it.
25812 		 */
25813 		if (attach_if) {
25814 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25815 
25816 			/*
25817 			 * Check if we need an ire that will not be
25818 			 * looked up by anybody else i.e. HIDDEN.
25819 			 */
25820 			if (ill_is_probeonly(ill)) {
25821 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25822 			}
25823 		}
25824 	}
25825 
25826 	if (CLASSD(dst)) {
25827 		boolean_t conn_dontroute;
25828 		/*
25829 		 * Use the ill_index to get the right ipif.
25830 		 */
25831 		conn_dontroute = io->ipsec_out_dontroute;
25832 		if (ill_index == 0)
25833 			ipif = ipif_lookup_group(dst, zoneid, ipst);
25834 		else
25835 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25836 		if (ipif == NULL) {
25837 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25838 			    " multicast\n"));
25839 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
25840 			freemsg(ipsec_mp);
25841 			goto done;
25842 		}
25843 		/*
25844 		 * ipha_src has already been intialized with the
25845 		 * value of the ipif in ip_wput. All we need now is
25846 		 * an ire to send this downstream.
25847 		 */
25848 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25849 		    MBLK_GETLABEL(mp), match_flags, ipst);
25850 		if (ire != NULL) {
25851 			ill_t *ill1;
25852 			/*
25853 			 * Do the multicast forwarding now, as the IPsec
25854 			 * processing has been done.
25855 			 */
25856 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
25857 			    (ill1 = ire_to_ill(ire))) {
25858 				if (ip_mforward(ill1, ipha, mp)) {
25859 					freemsg(ipsec_mp);
25860 					ip1dbg(("ip_wput_ipsec_out: mforward "
25861 					    "failed\n"));
25862 					ire_refrele(ire);
25863 					goto done;
25864 				}
25865 			}
25866 			goto send;
25867 		}
25868 
25869 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
25870 		mp->b_prev = NULL;
25871 		mp->b_next = NULL;
25872 
25873 		/*
25874 		 * If the IPsec packet was processed asynchronously,
25875 		 * drop it now.
25876 		 */
25877 		if (q == NULL) {
25878 			freemsg(ipsec_mp);
25879 			goto done;
25880 		}
25881 
25882 		/*
25883 		 * We may be using a wrong ipif to create the ire.
25884 		 * But it is okay as the source address is assigned
25885 		 * for the packet already. Next outbound packet would
25886 		 * create the IRE with the right IPIF in ip_wput.
25887 		 *
25888 		 * Also handle RTF_MULTIRT routes.
25889 		 */
25890 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
25891 		    zoneid, &zero_info);
25892 	} else {
25893 		if (attach_if) {
25894 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
25895 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25896 		} else {
25897 			if (ire_arg != NULL) {
25898 				ire = ire_arg;
25899 				ire_need_rele = B_FALSE;
25900 			} else {
25901 				ire = ire_cache_lookup(dst, zoneid,
25902 				    MBLK_GETLABEL(mp), ipst);
25903 			}
25904 		}
25905 		if (ire != NULL) {
25906 			goto send;
25907 		}
25908 
25909 		/*
25910 		 * ire disappeared underneath.
25911 		 *
25912 		 * What we need to do here is the ip_newroute
25913 		 * logic to get the ire without doing the IPsec
25914 		 * processing. Follow the same old path. But this
25915 		 * time, ip_wput or ire_add_then_put will call us
25916 		 * directly as all the IPsec operations are done.
25917 		 */
25918 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
25919 		mp->b_prev = NULL;
25920 		mp->b_next = NULL;
25921 
25922 		/*
25923 		 * If the IPsec packet was processed asynchronously,
25924 		 * drop it now.
25925 		 */
25926 		if (q == NULL) {
25927 			freemsg(ipsec_mp);
25928 			goto done;
25929 		}
25930 
25931 		/*
25932 		 * Since we're going through ip_newroute() again, we
25933 		 * need to make sure we don't:
25934 		 *
25935 		 *	1.) Trigger the ASSERT() with the ipha_ident
25936 		 *	    overloading.
25937 		 *	2.) Redo transport-layer checksumming, since we've
25938 		 *	    already done all that to get this far.
25939 		 *
25940 		 * The easiest way not do either of the above is to set
25941 		 * the ipha_ident field to IP_HDR_INCLUDED.
25942 		 */
25943 		ipha->ipha_ident = IP_HDR_INCLUDED;
25944 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
25945 		    zoneid, ipst);
25946 	}
25947 	goto done;
25948 send:
25949 	if (ire->ire_stq == NULL) {
25950 		ill_t	*out_ill;
25951 		/*
25952 		 * Loopbacks go through ip_wput_local except for one case.
25953 		 * We come here if we generate a icmp_frag_needed message
25954 		 * after IPsec processing is over. When this function calls
25955 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
25956 		 * icmp_frag_needed. The message generated comes back here
25957 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
25958 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
25959 		 * source address as it is usually set in ip_wput_ire. As
25960 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
25961 		 * and we end up here. We can't enter ip_wput_ire once the
25962 		 * IPsec processing is over and hence we need to do it here.
25963 		 */
25964 		ASSERT(q != NULL);
25965 		UPDATE_OB_PKT_COUNT(ire);
25966 		ire->ire_last_used_time = lbolt;
25967 		if (ipha->ipha_src == 0)
25968 			ipha->ipha_src = ire->ire_src_addr;
25969 
25970 		/* PFHooks: LOOPBACK_OUT */
25971 		out_ill = ire_to_ill(ire);
25972 
25973 		DTRACE_PROBE4(ip4__loopback__out__start,
25974 		    ill_t *, NULL, ill_t *, out_ill,
25975 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
25976 
25977 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
25978 		    ipst->ips_ipv4firewall_loopback_out,
25979 		    NULL, out_ill, ipha1, ipsec_mp, mp, ipst);
25980 
25981 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
25982 
25983 		if (ipsec_mp != NULL)
25984 			ip_wput_local(RD(q), out_ill,
25985 			    ipha, ipsec_mp, ire, 0, zoneid);
25986 		if (ire_need_rele)
25987 			ire_refrele(ire);
25988 		goto done;
25989 	}
25990 
25991 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
25992 		/*
25993 		 * We are through with IPsec processing.
25994 		 * Fragment this and send it on the wire.
25995 		 */
25996 		if (io->ipsec_out_accelerated) {
25997 			/*
25998 			 * The packet has been accelerated but must
25999 			 * be fragmented. This should not happen
26000 			 * since AH and ESP must not accelerate
26001 			 * packets that need fragmentation, however
26002 			 * the configuration could have changed
26003 			 * since the AH or ESP processing.
26004 			 * Drop packet.
26005 			 * IPsec KSTATS: bump bean counter here.
26006 			 */
26007 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26008 			    "fragmented accelerated packet!\n"));
26009 			freemsg(ipsec_mp);
26010 		} else {
26011 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid, ipst);
26012 		}
26013 		if (ire_need_rele)
26014 			ire_refrele(ire);
26015 		goto done;
26016 	}
26017 
26018 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26019 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26020 	    (void *)ire->ire_ipif, (void *)ipif));
26021 
26022 	/*
26023 	 * Multiroute the secured packet, unless IPsec really
26024 	 * requires the packet to go out only through a particular
26025 	 * interface.
26026 	 */
26027 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
26028 		ire_t *first_ire;
26029 		irb = ire->ire_bucket;
26030 		ASSERT(irb != NULL);
26031 		/*
26032 		 * This ire has been looked up as the one that
26033 		 * goes through the given ipif;
26034 		 * make sure we do not omit any other multiroute ire
26035 		 * that may be present in the bucket before this one.
26036 		 */
26037 		IRB_REFHOLD(irb);
26038 		for (first_ire = irb->irb_ire;
26039 		    first_ire != NULL;
26040 		    first_ire = first_ire->ire_next) {
26041 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26042 			    (first_ire->ire_addr == ire->ire_addr) &&
26043 			    !(first_ire->ire_marks &
26044 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
26045 				break;
26046 			}
26047 		}
26048 
26049 		if ((first_ire != NULL) && (first_ire != ire)) {
26050 			/*
26051 			 * Don't change the ire if the packet must
26052 			 * be fragmented if sent via this new one.
26053 			 */
26054 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26055 				IRE_REFHOLD(first_ire);
26056 				if (ire_need_rele)
26057 					ire_refrele(ire);
26058 				else
26059 					ire_need_rele = B_TRUE;
26060 				ire = first_ire;
26061 			}
26062 		}
26063 		IRB_REFRELE(irb);
26064 
26065 		multirt_send = B_TRUE;
26066 		max_frag = ire->ire_max_frag;
26067 	} else {
26068 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
26069 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
26070 			    "flag, attach_if %d\n", attach_if));
26071 		}
26072 	}
26073 
26074 	/*
26075 	 * In most cases, the emission loop below is entered only once.
26076 	 * Only in the case where the ire holds the RTF_MULTIRT
26077 	 * flag, we loop to process all RTF_MULTIRT ires in the
26078 	 * bucket, and send the packet through all crossed
26079 	 * RTF_MULTIRT routes.
26080 	 */
26081 	do {
26082 		if (multirt_send) {
26083 			/*
26084 			 * ire1 holds here the next ire to process in the
26085 			 * bucket. If multirouting is expected,
26086 			 * any non-RTF_MULTIRT ire that has the
26087 			 * right destination address is ignored.
26088 			 */
26089 			ASSERT(irb != NULL);
26090 			IRB_REFHOLD(irb);
26091 			for (ire1 = ire->ire_next;
26092 			    ire1 != NULL;
26093 			    ire1 = ire1->ire_next) {
26094 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26095 					continue;
26096 				if (ire1->ire_addr != ire->ire_addr)
26097 					continue;
26098 				if (ire1->ire_marks &
26099 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
26100 					continue;
26101 				/* No loopback here */
26102 				if (ire1->ire_stq == NULL)
26103 					continue;
26104 				/*
26105 				 * Ensure we do not exceed the MTU
26106 				 * of the next route.
26107 				 */
26108 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26109 					ip_multirt_bad_mtu(ire1, max_frag);
26110 					continue;
26111 				}
26112 
26113 				IRE_REFHOLD(ire1);
26114 				break;
26115 			}
26116 			IRB_REFRELE(irb);
26117 			if (ire1 != NULL) {
26118 				/*
26119 				 * We are in a multiple send case, need to
26120 				 * make a copy of the packet.
26121 				 */
26122 				next_mp = copymsg(ipsec_mp);
26123 				if (next_mp == NULL) {
26124 					ire_refrele(ire1);
26125 					ire1 = NULL;
26126 				}
26127 			}
26128 		}
26129 		/*
26130 		 * Everything is done. Send it out on the wire
26131 		 *
26132 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26133 		 * either send it on the wire or, in the case of
26134 		 * HW acceleration, call ipsec_hw_putnext.
26135 		 */
26136 		if (ire->ire_nce &&
26137 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26138 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26139 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26140 			/*
26141 			 * If ire's link-layer is unresolved (this
26142 			 * would only happen if the incomplete ire
26143 			 * was added to cachetable via forwarding path)
26144 			 * don't bother going to ip_xmit_v4. Just drop the
26145 			 * packet.
26146 			 * There is a slight risk here, in that, if we
26147 			 * have the forwarding path create an incomplete
26148 			 * IRE, then until the IRE is completed, any
26149 			 * transmitted IPsec packets will be dropped
26150 			 * instead of being queued waiting for resolution.
26151 			 *
26152 			 * But the likelihood of a forwarding packet and a wput
26153 			 * packet sending to the same dst at the same time
26154 			 * and there not yet be an ARP entry for it is small.
26155 			 * Furthermore, if this actually happens, it might
26156 			 * be likely that wput would generate multiple
26157 			 * packets (and forwarding would also have a train
26158 			 * of packets) for that destination. If this is
26159 			 * the case, some of them would have been dropped
26160 			 * anyway, since ARP only queues a few packets while
26161 			 * waiting for resolution
26162 			 *
26163 			 * NOTE: We should really call ip_xmit_v4,
26164 			 * and let it queue the packet and send the
26165 			 * ARP query and have ARP come back thus:
26166 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26167 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26168 			 * hw accel work. But it's too complex to get
26169 			 * the IPsec hw  acceleration approach to fit
26170 			 * well with ip_xmit_v4 doing ARP without
26171 			 * doing IPsec simplification. For now, we just
26172 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26173 			 * that we can continue with the send on the next
26174 			 * attempt.
26175 			 *
26176 			 * XXX THis should be revisited, when
26177 			 * the IPsec/IP interaction is cleaned up
26178 			 */
26179 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26180 			    " - dropping packet\n"));
26181 			freemsg(ipsec_mp);
26182 			/*
26183 			 * Call ip_xmit_v4() to trigger ARP query
26184 			 * in case the nce_state is ND_INITIAL
26185 			 */
26186 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26187 			goto drop_pkt;
26188 		}
26189 
26190 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26191 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26192 		    mblk_t *, ipsec_mp);
26193 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26194 		    ipst->ips_ipv4firewall_physical_out,
26195 		    NULL, ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, ipst);
26196 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26197 		if (ipsec_mp == NULL)
26198 			goto drop_pkt;
26199 
26200 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26201 		pktxmit_state = ip_xmit_v4(mp, ire,
26202 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
26203 
26204 		if ((pktxmit_state ==  SEND_FAILED) ||
26205 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26206 
26207 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26208 drop_pkt:
26209 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26210 			    ipIfStatsOutDiscards);
26211 			if (ire_need_rele)
26212 				ire_refrele(ire);
26213 			if (ire1 != NULL) {
26214 				ire_refrele(ire1);
26215 				freemsg(next_mp);
26216 			}
26217 			goto done;
26218 		}
26219 
26220 		freeb(ipsec_mp);
26221 		if (ire_need_rele)
26222 			ire_refrele(ire);
26223 
26224 		if (ire1 != NULL) {
26225 			ire = ire1;
26226 			ire_need_rele = B_TRUE;
26227 			ASSERT(next_mp);
26228 			ipsec_mp = next_mp;
26229 			mp = ipsec_mp->b_cont;
26230 			ire1 = NULL;
26231 			next_mp = NULL;
26232 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26233 		} else {
26234 			multirt_send = B_FALSE;
26235 		}
26236 	} while (multirt_send);
26237 done:
26238 	if (ill != NULL && ill_need_rele)
26239 		ill_refrele(ill);
26240 	if (ipif != NULL)
26241 		ipif_refrele(ipif);
26242 }
26243 
26244 /*
26245  * Get the ill corresponding to the specified ire, and compare its
26246  * capabilities with the protocol and algorithms specified by the
26247  * the SA obtained from ipsec_out. If they match, annotate the
26248  * ipsec_out structure to indicate that the packet needs acceleration.
26249  *
26250  *
26251  * A packet is eligible for outbound hardware acceleration if the
26252  * following conditions are satisfied:
26253  *
26254  * 1. the packet will not be fragmented
26255  * 2. the provider supports the algorithm
26256  * 3. there is no pending control message being exchanged
26257  * 4. snoop is not attached
26258  * 5. the destination address is not a broadcast or multicast address.
26259  *
26260  * Rationale:
26261  *	- Hardware drivers do not support fragmentation with
26262  *	  the current interface.
26263  *	- snoop, multicast, and broadcast may result in exposure of
26264  *	  a cleartext datagram.
26265  * We check all five of these conditions here.
26266  *
26267  * XXX would like to nuke "ire_t *" parameter here; problem is that
26268  * IRE is only way to figure out if a v4 address is a broadcast and
26269  * thus ineligible for acceleration...
26270  */
26271 static void
26272 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26273 {
26274 	ipsec_out_t *io;
26275 	mblk_t *data_mp;
26276 	uint_t plen, overhead;
26277 	ip_stack_t	*ipst;
26278 
26279 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26280 		return;
26281 
26282 	if (ill == NULL)
26283 		return;
26284 	ipst = ill->ill_ipst;
26285 	/*
26286 	 * Destination address is a broadcast or multicast.  Punt.
26287 	 */
26288 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26289 	    IRE_LOCAL)))
26290 		return;
26291 
26292 	data_mp = ipsec_mp->b_cont;
26293 
26294 	if (ill->ill_isv6) {
26295 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26296 
26297 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26298 			return;
26299 
26300 		plen = ip6h->ip6_plen;
26301 	} else {
26302 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26303 
26304 		if (CLASSD(ipha->ipha_dst))
26305 			return;
26306 
26307 		plen = ipha->ipha_length;
26308 	}
26309 	/*
26310 	 * Is there a pending DLPI control message being exchanged
26311 	 * between IP/IPsec and the DLS Provider? If there is, it
26312 	 * could be a SADB update, and the state of the DLS Provider
26313 	 * SADB might not be in sync with the SADB maintained by
26314 	 * IPsec. To avoid dropping packets or using the wrong keying
26315 	 * material, we do not accelerate this packet.
26316 	 */
26317 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26318 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26319 		    "ill_dlpi_pending! don't accelerate packet\n"));
26320 		return;
26321 	}
26322 
26323 	/*
26324 	 * Is the Provider in promiscous mode? If it does, we don't
26325 	 * accelerate the packet since it will bounce back up to the
26326 	 * listeners in the clear.
26327 	 */
26328 	if (ill->ill_promisc_on_phys) {
26329 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26330 		    "ill in promiscous mode, don't accelerate packet\n"));
26331 		return;
26332 	}
26333 
26334 	/*
26335 	 * Will the packet require fragmentation?
26336 	 */
26337 
26338 	/*
26339 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26340 	 * as is used elsewhere.
26341 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26342 	 *	+ 2-byte trailer
26343 	 */
26344 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26345 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26346 
26347 	if ((plen + overhead) > ill->ill_max_mtu)
26348 		return;
26349 
26350 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26351 
26352 	/*
26353 	 * Can the ill accelerate this IPsec protocol and algorithm
26354 	 * specified by the SA?
26355 	 */
26356 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26357 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26358 		return;
26359 	}
26360 
26361 	/*
26362 	 * Tell AH or ESP that the outbound ill is capable of
26363 	 * accelerating this packet.
26364 	 */
26365 	io->ipsec_out_is_capab_ill = B_TRUE;
26366 }
26367 
26368 /*
26369  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26370  *
26371  * If this function returns B_TRUE, the requested SA's have been filled
26372  * into the ipsec_out_*_sa pointers.
26373  *
26374  * If the function returns B_FALSE, the packet has been "consumed", most
26375  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26376  *
26377  * The SA references created by the protocol-specific "select"
26378  * function will be released when the ipsec_mp is freed, thanks to the
26379  * ipsec_out_free destructor -- see spd.c.
26380  */
26381 static boolean_t
26382 ipsec_out_select_sa(mblk_t *ipsec_mp)
26383 {
26384 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26385 	ipsec_out_t *io;
26386 	ipsec_policy_t *pp;
26387 	ipsec_action_t *ap;
26388 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26389 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26390 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26391 
26392 	if (!io->ipsec_out_secure) {
26393 		/*
26394 		 * We came here by mistake.
26395 		 * Don't bother with ipsec processing
26396 		 * We should "discourage" this path in the future.
26397 		 */
26398 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26399 		return (B_FALSE);
26400 	}
26401 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26402 	ASSERT((io->ipsec_out_policy != NULL) ||
26403 	    (io->ipsec_out_act != NULL));
26404 
26405 	ASSERT(io->ipsec_out_failed == B_FALSE);
26406 
26407 	/*
26408 	 * IPsec processing has started.
26409 	 */
26410 	io->ipsec_out_proc_begin = B_TRUE;
26411 	ap = io->ipsec_out_act;
26412 	if (ap == NULL) {
26413 		pp = io->ipsec_out_policy;
26414 		ASSERT(pp != NULL);
26415 		ap = pp->ipsp_act;
26416 		ASSERT(ap != NULL);
26417 	}
26418 
26419 	/*
26420 	 * We have an action.  now, let's select SA's.
26421 	 * (In the future, we can cache this in the conn_t..)
26422 	 */
26423 	if (ap->ipa_want_esp) {
26424 		if (io->ipsec_out_esp_sa == NULL) {
26425 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26426 			    IPPROTO_ESP);
26427 		}
26428 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26429 	}
26430 
26431 	if (ap->ipa_want_ah) {
26432 		if (io->ipsec_out_ah_sa == NULL) {
26433 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26434 			    IPPROTO_AH);
26435 		}
26436 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26437 		/*
26438 		 * The ESP and AH processing order needs to be preserved
26439 		 * when both protocols are required (ESP should be applied
26440 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26441 		 * when both ESP and AH are required, and an AH ACQUIRE
26442 		 * is needed.
26443 		 */
26444 		if (ap->ipa_want_esp && need_ah_acquire)
26445 			need_esp_acquire = B_TRUE;
26446 	}
26447 
26448 	/*
26449 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26450 	 * Release SAs that got referenced, but will not be used until we
26451 	 * acquire _all_ of the SAs we need.
26452 	 */
26453 	if (need_ah_acquire || need_esp_acquire) {
26454 		if (io->ipsec_out_ah_sa != NULL) {
26455 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26456 			io->ipsec_out_ah_sa = NULL;
26457 		}
26458 		if (io->ipsec_out_esp_sa != NULL) {
26459 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26460 			io->ipsec_out_esp_sa = NULL;
26461 		}
26462 
26463 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26464 		return (B_FALSE);
26465 	}
26466 
26467 	return (B_TRUE);
26468 }
26469 
26470 /*
26471  * Process an IPSEC_OUT message and see what you can
26472  * do with it.
26473  * IPQoS Notes:
26474  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26475  * IPsec.
26476  * XXX would like to nuke ire_t.
26477  * XXX ill_index better be "real"
26478  */
26479 void
26480 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26481 {
26482 	ipsec_out_t *io;
26483 	ipsec_policy_t *pp;
26484 	ipsec_action_t *ap;
26485 	ipha_t *ipha;
26486 	ip6_t *ip6h;
26487 	mblk_t *mp;
26488 	ill_t *ill;
26489 	zoneid_t zoneid;
26490 	ipsec_status_t ipsec_rc;
26491 	boolean_t ill_need_rele = B_FALSE;
26492 	ip_stack_t	*ipst;
26493 	ipsec_stack_t	*ipss;
26494 
26495 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26496 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26497 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26498 	ipst = io->ipsec_out_ns->netstack_ip;
26499 	mp = ipsec_mp->b_cont;
26500 
26501 	/*
26502 	 * Initiate IPPF processing. We do it here to account for packets
26503 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26504 	 * We can check for ipsec_out_proc_begin even for such packets, as
26505 	 * they will always be false (asserted below).
26506 	 */
26507 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26508 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26509 		    io->ipsec_out_ill_index : ill_index);
26510 		if (mp == NULL) {
26511 			ip2dbg(("ipsec_out_process: packet dropped "\
26512 			    "during IPPF processing\n"));
26513 			freeb(ipsec_mp);
26514 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26515 			return;
26516 		}
26517 	}
26518 
26519 	if (!io->ipsec_out_secure) {
26520 		/*
26521 		 * We came here by mistake.
26522 		 * Don't bother with ipsec processing
26523 		 * Should "discourage" this path in the future.
26524 		 */
26525 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26526 		goto done;
26527 	}
26528 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26529 	ASSERT((io->ipsec_out_policy != NULL) ||
26530 	    (io->ipsec_out_act != NULL));
26531 	ASSERT(io->ipsec_out_failed == B_FALSE);
26532 
26533 	ipss = ipst->ips_netstack->netstack_ipsec;
26534 	if (!ipsec_loaded(ipss)) {
26535 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26536 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26537 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26538 		} else {
26539 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26540 		}
26541 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26542 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26543 		    &ipss->ipsec_dropper);
26544 		return;
26545 	}
26546 
26547 	/*
26548 	 * IPsec processing has started.
26549 	 */
26550 	io->ipsec_out_proc_begin = B_TRUE;
26551 	ap = io->ipsec_out_act;
26552 	if (ap == NULL) {
26553 		pp = io->ipsec_out_policy;
26554 		ASSERT(pp != NULL);
26555 		ap = pp->ipsp_act;
26556 		ASSERT(ap != NULL);
26557 	}
26558 
26559 	/*
26560 	 * Save the outbound ill index. When the packet comes back
26561 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26562 	 * before sending it the accelerated packet.
26563 	 */
26564 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26565 		int ifindex;
26566 		ill = ire_to_ill(ire);
26567 		ifindex = ill->ill_phyint->phyint_ifindex;
26568 		io->ipsec_out_capab_ill_index = ifindex;
26569 	}
26570 
26571 	/*
26572 	 * The order of processing is first insert a IP header if needed.
26573 	 * Then insert the ESP header and then the AH header.
26574 	 */
26575 	if ((io->ipsec_out_se_done == B_FALSE) &&
26576 	    (ap->ipa_want_se)) {
26577 		/*
26578 		 * First get the outer IP header before sending
26579 		 * it to ESP.
26580 		 */
26581 		ipha_t *oipha, *iipha;
26582 		mblk_t *outer_mp, *inner_mp;
26583 
26584 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26585 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26586 			    "ipsec_out_process: "
26587 			    "Self-Encapsulation failed: Out of memory\n");
26588 			freemsg(ipsec_mp);
26589 			if (ill != NULL) {
26590 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26591 			} else {
26592 				BUMP_MIB(&ipst->ips_ip_mib,
26593 				    ipIfStatsOutDiscards);
26594 			}
26595 			return;
26596 		}
26597 		inner_mp = ipsec_mp->b_cont;
26598 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26599 		oipha = (ipha_t *)outer_mp->b_rptr;
26600 		iipha = (ipha_t *)inner_mp->b_rptr;
26601 		*oipha = *iipha;
26602 		outer_mp->b_wptr += sizeof (ipha_t);
26603 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26604 		    sizeof (ipha_t));
26605 		oipha->ipha_protocol = IPPROTO_ENCAP;
26606 		oipha->ipha_version_and_hdr_length =
26607 		    IP_SIMPLE_HDR_VERSION;
26608 		oipha->ipha_hdr_checksum = 0;
26609 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26610 		outer_mp->b_cont = inner_mp;
26611 		ipsec_mp->b_cont = outer_mp;
26612 
26613 		io->ipsec_out_se_done = B_TRUE;
26614 		io->ipsec_out_tunnel = B_TRUE;
26615 	}
26616 
26617 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26618 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26619 	    !ipsec_out_select_sa(ipsec_mp))
26620 		return;
26621 
26622 	/*
26623 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26624 	 * to do the heavy lifting.
26625 	 */
26626 	zoneid = io->ipsec_out_zoneid;
26627 	ASSERT(zoneid != ALL_ZONES);
26628 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26629 		ASSERT(io->ipsec_out_esp_sa != NULL);
26630 		io->ipsec_out_esp_done = B_TRUE;
26631 		/*
26632 		 * Note that since hw accel can only apply one transform,
26633 		 * not two, we skip hw accel for ESP if we also have AH
26634 		 * This is an design limitation of the interface
26635 		 * which should be revisited.
26636 		 */
26637 		ASSERT(ire != NULL);
26638 		if (io->ipsec_out_ah_sa == NULL) {
26639 			ill = (ill_t *)ire->ire_stq->q_ptr;
26640 			ipsec_out_is_accelerated(ipsec_mp,
26641 			    io->ipsec_out_esp_sa, ill, ire);
26642 		}
26643 
26644 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26645 		switch (ipsec_rc) {
26646 		case IPSEC_STATUS_SUCCESS:
26647 			break;
26648 		case IPSEC_STATUS_FAILED:
26649 			if (ill != NULL) {
26650 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26651 			} else {
26652 				BUMP_MIB(&ipst->ips_ip_mib,
26653 				    ipIfStatsOutDiscards);
26654 			}
26655 			/* FALLTHRU */
26656 		case IPSEC_STATUS_PENDING:
26657 			return;
26658 		}
26659 	}
26660 
26661 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26662 		ASSERT(io->ipsec_out_ah_sa != NULL);
26663 		io->ipsec_out_ah_done = B_TRUE;
26664 		if (ire == NULL) {
26665 			int idx = io->ipsec_out_capab_ill_index;
26666 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26667 			    NULL, NULL, NULL, NULL, ipst);
26668 			ill_need_rele = B_TRUE;
26669 		} else {
26670 			ill = (ill_t *)ire->ire_stq->q_ptr;
26671 		}
26672 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26673 		    ire);
26674 
26675 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26676 		switch (ipsec_rc) {
26677 		case IPSEC_STATUS_SUCCESS:
26678 			break;
26679 		case IPSEC_STATUS_FAILED:
26680 			if (ill != NULL) {
26681 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26682 			} else {
26683 				BUMP_MIB(&ipst->ips_ip_mib,
26684 				    ipIfStatsOutDiscards);
26685 			}
26686 			/* FALLTHRU */
26687 		case IPSEC_STATUS_PENDING:
26688 			if (ill != NULL && ill_need_rele)
26689 				ill_refrele(ill);
26690 			return;
26691 		}
26692 	}
26693 	/*
26694 	 * We are done with IPsec processing. Send it over
26695 	 * the wire.
26696 	 */
26697 done:
26698 	mp = ipsec_mp->b_cont;
26699 	ipha = (ipha_t *)mp->b_rptr;
26700 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26701 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
26702 	} else {
26703 		ip6h = (ip6_t *)ipha;
26704 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
26705 	}
26706 	if (ill != NULL && ill_need_rele)
26707 		ill_refrele(ill);
26708 }
26709 
26710 /* ARGSUSED */
26711 void
26712 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26713 {
26714 	opt_restart_t	*or;
26715 	int	err;
26716 	conn_t	*connp;
26717 
26718 	ASSERT(CONN_Q(q));
26719 	connp = Q_TO_CONN(q);
26720 
26721 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26722 	or = (opt_restart_t *)first_mp->b_rptr;
26723 	/*
26724 	 * We don't need to pass any credentials here since this is just
26725 	 * a restart. The credentials are passed in when svr4_optcom_req
26726 	 * is called the first time (from ip_wput_nondata).
26727 	 */
26728 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26729 		err = svr4_optcom_req(q, first_mp, NULL,
26730 		    &ip_opt_obj, B_FALSE);
26731 	} else {
26732 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26733 		err = tpi_optcom_req(q, first_mp, NULL,
26734 		    &ip_opt_obj, B_FALSE);
26735 	}
26736 	if (err != EINPROGRESS) {
26737 		/* operation is done */
26738 		CONN_OPER_PENDING_DONE(connp);
26739 	}
26740 }
26741 
26742 /*
26743  * ioctls that go through a down/up sequence may need to wait for the down
26744  * to complete. This involves waiting for the ire and ipif refcnts to go down
26745  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26746  */
26747 /* ARGSUSED */
26748 void
26749 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26750 {
26751 	struct iocblk *iocp;
26752 	mblk_t *mp1;
26753 	ip_ioctl_cmd_t *ipip;
26754 	int err;
26755 	sin_t	*sin;
26756 	struct lifreq *lifr;
26757 	struct ifreq *ifr;
26758 
26759 	iocp = (struct iocblk *)mp->b_rptr;
26760 	ASSERT(ipsq != NULL);
26761 	/* Existence of mp1 verified in ip_wput_nondata */
26762 	mp1 = mp->b_cont->b_cont;
26763 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26764 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26765 		/*
26766 		 * Special case where ipsq_current_ipif is not set:
26767 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26768 		 * ill could also have become part of a ipmp group in the
26769 		 * process, we are here as were not able to complete the
26770 		 * operation in ipif_set_values because we could not become
26771 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
26772 		 * will not be set so we need to set it.
26773 		 */
26774 		ill_t *ill = q->q_ptr;
26775 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
26776 	}
26777 	ASSERT(ipsq->ipsq_current_ipif != NULL);
26778 
26779 	if (ipip->ipi_cmd_type == IF_CMD) {
26780 		/* This a old style SIOC[GS]IF* command */
26781 		ifr = (struct ifreq *)mp1->b_rptr;
26782 		sin = (sin_t *)&ifr->ifr_addr;
26783 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26784 		/* This a new style SIOC[GS]LIF* command */
26785 		lifr = (struct lifreq *)mp1->b_rptr;
26786 		sin = (sin_t *)&lifr->lifr_addr;
26787 	} else {
26788 		sin = NULL;
26789 	}
26790 
26791 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_current_ipif, sin, q, mp,
26792 	    ipip, mp1->b_rptr);
26793 
26794 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26795 }
26796 
26797 /*
26798  * ioctl processing
26799  *
26800  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
26801  * the ioctl command in the ioctl tables, determines the copyin data size
26802  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
26803  *
26804  * ioctl processing then continues when the M_IOCDATA makes its way down to
26805  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
26806  * associated 'conn' is refheld till the end of the ioctl and the general
26807  * ioctl processing function ip_process_ioctl() is called to extract the
26808  * arguments and process the ioctl.  To simplify extraction, ioctl commands
26809  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
26810  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
26811  * is used to extract the ioctl's arguments.
26812  *
26813  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26814  * so goes thru the serialization primitive ipsq_try_enter. Then the
26815  * appropriate function to handle the ioctl is called based on the entry in
26816  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26817  * which also refreleases the 'conn' that was refheld at the start of the
26818  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26819  *
26820  * Many exclusive ioctls go thru an internal down up sequence as part of
26821  * the operation. For example an attempt to change the IP address of an
26822  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26823  * does all the cleanup such as deleting all ires that use this address.
26824  * Then we need to wait till all references to the interface go away.
26825  */
26826 void
26827 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26828 {
26829 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26830 	ip_ioctl_cmd_t *ipip = arg;
26831 	ip_extract_func_t *extract_funcp;
26832 	cmd_info_t ci;
26833 	int err;
26834 	boolean_t entered_ipsq = B_FALSE;
26835 
26836 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26837 
26838 	if (ipip == NULL)
26839 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26840 
26841 	/*
26842 	 * SIOCLIFADDIF needs to go thru a special path since the
26843 	 * ill may not exist yet. This happens in the case of lo0
26844 	 * which is created using this ioctl.
26845 	 */
26846 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26847 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26848 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26849 		return;
26850 	}
26851 
26852 	ci.ci_ipif = NULL;
26853 	if (ipip->ipi_cmd_type == MISC_CMD) {
26854 		/*
26855 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
26856 		 */
26857 		if (ipip->ipi_cmd == IF_UNITSEL) {
26858 			/* ioctl comes down the ill */
26859 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
26860 			ipif_refhold(ci.ci_ipif);
26861 		}
26862 		err = 0;
26863 		ci.ci_sin = NULL;
26864 		ci.ci_sin6 = NULL;
26865 		ci.ci_lifr = NULL;
26866 	} else {
26867 		switch (ipip->ipi_cmd_type) {
26868 		case IF_CMD:
26869 		case LIF_CMD:
26870 			extract_funcp = ip_extract_lifreq;
26871 			break;
26872 
26873 		case ARP_CMD:
26874 		case XARP_CMD:
26875 			extract_funcp = ip_extract_arpreq;
26876 			break;
26877 
26878 		case TUN_CMD:
26879 			extract_funcp = ip_extract_tunreq;
26880 			break;
26881 
26882 		case MSFILT_CMD:
26883 			extract_funcp = ip_extract_msfilter;
26884 			break;
26885 
26886 		default:
26887 			ASSERT(0);
26888 		}
26889 
26890 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
26891 		if (err != 0) {
26892 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26893 			return;
26894 		}
26895 
26896 		/*
26897 		 * All of the extraction functions return a refheld ipif.
26898 		 */
26899 		ASSERT(ci.ci_ipif != NULL);
26900 	}
26901 
26902 	/*
26903 	 * If ipsq is non-null, we are already being called exclusively
26904 	 */
26905 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
26906 	if (!(ipip->ipi_flags & IPI_WR)) {
26907 		/*
26908 		 * A return value of EINPROGRESS means the ioctl is
26909 		 * either queued and waiting for some reason or has
26910 		 * already completed.
26911 		 */
26912 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
26913 		    ci.ci_lifr);
26914 		if (ci.ci_ipif != NULL)
26915 			ipif_refrele(ci.ci_ipif);
26916 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26917 		return;
26918 	}
26919 
26920 	ASSERT(ci.ci_ipif != NULL);
26921 
26922 	if (ipsq == NULL) {
26923 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
26924 		    ip_process_ioctl, NEW_OP, B_TRUE);
26925 		entered_ipsq = B_TRUE;
26926 	}
26927 	/*
26928 	 * Release the ipif so that ipif_down and friends that wait for
26929 	 * references to go away are not misled about the current ipif_refcnt
26930 	 * values. We are writer so we can access the ipif even after releasing
26931 	 * the ipif.
26932 	 */
26933 	ipif_refrele(ci.ci_ipif);
26934 	if (ipsq == NULL)
26935 		return;
26936 
26937 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
26938 
26939 	/*
26940 	 * For most set ioctls that come here, this serves as a single point
26941 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
26942 	 * be any new references to the ipif. This helps functions that go
26943 	 * through this path and end up trying to wait for the refcnts
26944 	 * associated with the ipif to go down to zero. Some exceptions are
26945 	 * Failover, Failback, and Groupname commands that operate on more than
26946 	 * just the ci.ci_ipif. These commands internally determine the
26947 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
26948 	 * flags on that set. Another exception is the Removeif command that
26949 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
26950 	 * ipif to operate on.
26951 	 */
26952 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
26953 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
26954 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
26955 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
26956 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
26957 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
26958 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
26959 
26960 	/*
26961 	 * A return value of EINPROGRESS means the ioctl is
26962 	 * either queued and waiting for some reason or has
26963 	 * already completed.
26964 	 */
26965 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
26966 
26967 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26968 
26969 	if (entered_ipsq)
26970 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
26971 }
26972 
26973 /*
26974  * Complete the ioctl. Typically ioctls use the mi package and need to
26975  * do mi_copyout/mi_copy_done.
26976  */
26977 void
26978 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
26979 {
26980 	conn_t	*connp = NULL;
26981 
26982 	if (err == EINPROGRESS)
26983 		return;
26984 
26985 	if (CONN_Q(q)) {
26986 		connp = Q_TO_CONN(q);
26987 		ASSERT(connp->conn_ref >= 2);
26988 	}
26989 
26990 	switch (mode) {
26991 	case COPYOUT:
26992 		if (err == 0)
26993 			mi_copyout(q, mp);
26994 		else
26995 			mi_copy_done(q, mp, err);
26996 		break;
26997 
26998 	case NO_COPYOUT:
26999 		mi_copy_done(q, mp, err);
27000 		break;
27001 
27002 	default:
27003 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27004 		break;
27005 	}
27006 
27007 	/*
27008 	 * The refhold placed at the start of the ioctl is released here.
27009 	 */
27010 	if (connp != NULL)
27011 		CONN_OPER_PENDING_DONE(connp);
27012 
27013 	if (ipsq != NULL)
27014 		ipsq_current_finish(ipsq);
27015 }
27016 
27017 /*
27018  * This is called from ip_wput_nondata to resume a deferred TCP bind.
27019  */
27020 /* ARGSUSED */
27021 void
27022 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
27023 {
27024 	conn_t *connp = arg;
27025 	tcp_t	*tcp;
27026 
27027 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
27028 	tcp = connp->conn_tcp;
27029 
27030 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
27031 		freemsg(mp);
27032 	else
27033 		tcp_rput_other(tcp, mp);
27034 	CONN_OPER_PENDING_DONE(connp);
27035 }
27036 
27037 /* Called from ip_wput for all non data messages */
27038 /* ARGSUSED */
27039 void
27040 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27041 {
27042 	mblk_t		*mp1;
27043 	ire_t		*ire, *fake_ire;
27044 	ill_t		*ill;
27045 	struct iocblk	*iocp;
27046 	ip_ioctl_cmd_t	*ipip;
27047 	cred_t		*cr;
27048 	conn_t		*connp;
27049 	int		err;
27050 	nce_t		*nce;
27051 	ipif_t		*ipif;
27052 	ip_stack_t	*ipst;
27053 	char		*proto_str;
27054 
27055 	if (CONN_Q(q)) {
27056 		connp = Q_TO_CONN(q);
27057 		ipst = connp->conn_netstack->netstack_ip;
27058 	} else {
27059 		connp = NULL;
27060 		ipst = ILLQ_TO_IPST(q);
27061 	}
27062 
27063 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
27064 
27065 	switch (DB_TYPE(mp)) {
27066 	case M_IOCTL:
27067 		/*
27068 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27069 		 * will arrange to copy in associated control structures.
27070 		 */
27071 		ip_sioctl_copyin_setup(q, mp);
27072 		return;
27073 	case M_IOCDATA:
27074 		/*
27075 		 * Ensure that this is associated with one of our trans-
27076 		 * parent ioctls.  If it's not ours, discard it if we're
27077 		 * running as a driver, or pass it on if we're a module.
27078 		 */
27079 		iocp = (struct iocblk *)mp->b_rptr;
27080 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27081 		if (ipip == NULL) {
27082 			if (q->q_next == NULL) {
27083 				goto nak;
27084 			} else {
27085 				putnext(q, mp);
27086 			}
27087 			return;
27088 		}
27089 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
27090 			/*
27091 			 * the ioctl is one we recognise, but is not
27092 			 * consumed by IP as a module, pass M_IOCDATA
27093 			 * for processing downstream, but only for
27094 			 * common Streams ioctls.
27095 			 */
27096 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27097 				putnext(q, mp);
27098 				return;
27099 			} else {
27100 				goto nak;
27101 			}
27102 		}
27103 
27104 		/* IOCTL continuation following copyin or copyout. */
27105 		if (mi_copy_state(q, mp, NULL) == -1) {
27106 			/*
27107 			 * The copy operation failed.  mi_copy_state already
27108 			 * cleaned up, so we're out of here.
27109 			 */
27110 			return;
27111 		}
27112 		/*
27113 		 * If we just completed a copy in, we become writer and
27114 		 * continue processing in ip_sioctl_copyin_done.  If it
27115 		 * was a copy out, we call mi_copyout again.  If there is
27116 		 * nothing more to copy out, it will complete the IOCTL.
27117 		 */
27118 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27119 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27120 				mi_copy_done(q, mp, EPROTO);
27121 				return;
27122 			}
27123 			/*
27124 			 * Check for cases that need more copying.  A return
27125 			 * value of 0 means a second copyin has been started,
27126 			 * so we return; a return value of 1 means no more
27127 			 * copying is needed, so we continue.
27128 			 */
27129 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27130 			    MI_COPY_COUNT(mp) == 1) {
27131 				if (ip_copyin_msfilter(q, mp) == 0)
27132 					return;
27133 			}
27134 			/*
27135 			 * Refhold the conn, till the ioctl completes. This is
27136 			 * needed in case the ioctl ends up in the pending mp
27137 			 * list. Every mp in the ill_pending_mp list and
27138 			 * the ipsq_pending_mp must have a refhold on the conn
27139 			 * to resume processing. The refhold is released when
27140 			 * the ioctl completes. (normally or abnormally)
27141 			 * In all cases ip_ioctl_finish is called to finish
27142 			 * the ioctl.
27143 			 */
27144 			if (connp != NULL) {
27145 				/* This is not a reentry */
27146 				ASSERT(ipsq == NULL);
27147 				CONN_INC_REF(connp);
27148 			} else {
27149 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27150 					mi_copy_done(q, mp, EINVAL);
27151 					return;
27152 				}
27153 			}
27154 
27155 			ip_process_ioctl(ipsq, q, mp, ipip);
27156 
27157 		} else {
27158 			mi_copyout(q, mp);
27159 		}
27160 		return;
27161 nak:
27162 		iocp->ioc_error = EINVAL;
27163 		mp->b_datap->db_type = M_IOCNAK;
27164 		iocp->ioc_count = 0;
27165 		qreply(q, mp);
27166 		return;
27167 
27168 	case M_IOCNAK:
27169 		/*
27170 		 * The only way we could get here is if a resolver didn't like
27171 		 * an IOCTL we sent it.	 This shouldn't happen.
27172 		 */
27173 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27174 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27175 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27176 		freemsg(mp);
27177 		return;
27178 	case M_IOCACK:
27179 		/* /dev/ip shouldn't see this */
27180 		if (CONN_Q(q))
27181 			goto nak;
27182 
27183 		/* Finish socket ioctls passed through to ARP. */
27184 		ip_sioctl_iocack(q, mp);
27185 		return;
27186 	case M_FLUSH:
27187 		if (*mp->b_rptr & FLUSHW)
27188 			flushq(q, FLUSHALL);
27189 		if (q->q_next) {
27190 			putnext(q, mp);
27191 			return;
27192 		}
27193 		if (*mp->b_rptr & FLUSHR) {
27194 			*mp->b_rptr &= ~FLUSHW;
27195 			qreply(q, mp);
27196 			return;
27197 		}
27198 		freemsg(mp);
27199 		return;
27200 	case IRE_DB_REQ_TYPE:
27201 		if (connp == NULL) {
27202 			proto_str = "IRE_DB_REQ_TYPE";
27203 			goto protonak;
27204 		}
27205 		/* An Upper Level Protocol wants a copy of an IRE. */
27206 		ip_ire_req(q, mp);
27207 		return;
27208 	case M_CTL:
27209 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27210 			break;
27211 
27212 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27213 		    TUN_HELLO) {
27214 			ASSERT(connp != NULL);
27215 			connp->conn_flags |= IPCL_IPTUN;
27216 			freeb(mp);
27217 			return;
27218 		}
27219 
27220 		/* M_CTL messages are used by ARP to tell us things. */
27221 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27222 			break;
27223 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27224 		case AR_ENTRY_SQUERY:
27225 			ip_wput_ctl(q, mp);
27226 			return;
27227 		case AR_CLIENT_NOTIFY:
27228 			ip_arp_news(q, mp);
27229 			return;
27230 		case AR_DLPIOP_DONE:
27231 			ASSERT(q->q_next != NULL);
27232 			ill = (ill_t *)q->q_ptr;
27233 			/* qwriter_ip releases the refhold */
27234 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27235 			ill_refhold(ill);
27236 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27237 			return;
27238 		case AR_ARP_CLOSING:
27239 			/*
27240 			 * ARP (above us) is closing. If no ARP bringup is
27241 			 * currently pending, ack the message so that ARP
27242 			 * can complete its close. Also mark ill_arp_closing
27243 			 * so that new ARP bringups will fail. If any
27244 			 * ARP bringup is currently in progress, we will
27245 			 * ack this when the current ARP bringup completes.
27246 			 */
27247 			ASSERT(q->q_next != NULL);
27248 			ill = (ill_t *)q->q_ptr;
27249 			mutex_enter(&ill->ill_lock);
27250 			ill->ill_arp_closing = 1;
27251 			if (!ill->ill_arp_bringup_pending) {
27252 				mutex_exit(&ill->ill_lock);
27253 				qreply(q, mp);
27254 			} else {
27255 				mutex_exit(&ill->ill_lock);
27256 				freemsg(mp);
27257 			}
27258 			return;
27259 		case AR_ARP_EXTEND:
27260 			/*
27261 			 * The ARP module above us is capable of duplicate
27262 			 * address detection.  Old ATM drivers will not send
27263 			 * this message.
27264 			 */
27265 			ASSERT(q->q_next != NULL);
27266 			ill = (ill_t *)q->q_ptr;
27267 			ill->ill_arp_extend = B_TRUE;
27268 			freemsg(mp);
27269 			return;
27270 		default:
27271 			break;
27272 		}
27273 		break;
27274 	case M_PROTO:
27275 	case M_PCPROTO:
27276 		/*
27277 		 * The only PROTO messages we expect are ULP binds and
27278 		 * copies of option negotiation acknowledgements.
27279 		 */
27280 		switch (((union T_primitives *)mp->b_rptr)->type) {
27281 		case O_T_BIND_REQ:
27282 		case T_BIND_REQ: {
27283 			/* Request can get queued in bind */
27284 			if (connp == NULL) {
27285 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27286 				goto protonak;
27287 			}
27288 			/*
27289 			 * The transports except SCTP call ip_bind_{v4,v6}()
27290 			 * directly instead of a a putnext. SCTP doesn't
27291 			 * generate any T_BIND_REQ since it has its own
27292 			 * fanout data structures. However, ESP and AH
27293 			 * come in for regular binds; all other cases are
27294 			 * bind retries.
27295 			 */
27296 			ASSERT(!IPCL_IS_SCTP(connp));
27297 
27298 			/* Don't increment refcnt if this is a re-entry */
27299 			if (ipsq == NULL)
27300 				CONN_INC_REF(connp);
27301 
27302 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27303 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27304 			if (mp == NULL)
27305 				return;
27306 			if (IPCL_IS_TCP(connp)) {
27307 				/*
27308 				 * In the case of TCP endpoint we
27309 				 * come here only for bind retries
27310 				 */
27311 				ASSERT(ipsq != NULL);
27312 				CONN_INC_REF(connp);
27313 				squeue_fill(connp->conn_sqp, mp,
27314 				    ip_resume_tcp_bind, connp,
27315 				    SQTAG_BIND_RETRY);
27316 			} else if (IPCL_IS_UDP(connp)) {
27317 				/*
27318 				 * In the case of UDP endpoint we
27319 				 * come here only for bind retries
27320 				 */
27321 				ASSERT(ipsq != NULL);
27322 				udp_resume_bind(connp, mp);
27323 			} else if (IPCL_IS_RAWIP(connp)) {
27324 				/*
27325 				 * In the case of RAWIP endpoint we
27326 				 * come here only for bind retries
27327 				 */
27328 				ASSERT(ipsq != NULL);
27329 				rawip_resume_bind(connp, mp);
27330 			} else {
27331 				/* The case of AH and ESP */
27332 				qreply(q, mp);
27333 				CONN_OPER_PENDING_DONE(connp);
27334 			}
27335 			return;
27336 		}
27337 		case T_SVR4_OPTMGMT_REQ:
27338 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27339 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27340 
27341 			if (connp == NULL) {
27342 				proto_str = "T_SVR4_OPTMGMT_REQ";
27343 				goto protonak;
27344 			}
27345 
27346 			if (!snmpcom_req(q, mp, ip_snmp_set,
27347 			    ip_snmp_get, cr)) {
27348 				/*
27349 				 * Call svr4_optcom_req so that it can
27350 				 * generate the ack. We don't come here
27351 				 * if this operation is being restarted.
27352 				 * ip_restart_optmgmt will drop the conn ref.
27353 				 * In the case of ipsec option after the ipsec
27354 				 * load is complete conn_restart_ipsec_waiter
27355 				 * drops the conn ref.
27356 				 */
27357 				ASSERT(ipsq == NULL);
27358 				CONN_INC_REF(connp);
27359 				if (ip_check_for_ipsec_opt(q, mp))
27360 					return;
27361 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj,
27362 				    B_FALSE);
27363 				if (err != EINPROGRESS) {
27364 					/* Operation is done */
27365 					CONN_OPER_PENDING_DONE(connp);
27366 				}
27367 			}
27368 			return;
27369 		case T_OPTMGMT_REQ:
27370 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27371 			/*
27372 			 * Note: No snmpcom_req support through new
27373 			 * T_OPTMGMT_REQ.
27374 			 * Call tpi_optcom_req so that it can
27375 			 * generate the ack.
27376 			 */
27377 			if (connp == NULL) {
27378 				proto_str = "T_OPTMGMT_REQ";
27379 				goto protonak;
27380 			}
27381 
27382 			ASSERT(ipsq == NULL);
27383 			/*
27384 			 * We don't come here for restart. ip_restart_optmgmt
27385 			 * will drop the conn ref. In the case of ipsec option
27386 			 * after the ipsec load is complete
27387 			 * conn_restart_ipsec_waiter drops the conn ref.
27388 			 */
27389 			CONN_INC_REF(connp);
27390 			if (ip_check_for_ipsec_opt(q, mp))
27391 				return;
27392 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj, B_FALSE);
27393 			if (err != EINPROGRESS) {
27394 				/* Operation is done */
27395 				CONN_OPER_PENDING_DONE(connp);
27396 			}
27397 			return;
27398 		case T_UNBIND_REQ:
27399 			if (connp == NULL) {
27400 				proto_str = "T_UNBIND_REQ";
27401 				goto protonak;
27402 			}
27403 			mp = ip_unbind(q, mp);
27404 			qreply(q, mp);
27405 			return;
27406 		default:
27407 			/*
27408 			 * Have to drop any DLPI messages coming down from
27409 			 * arp (such as an info_req which would cause ip
27410 			 * to receive an extra info_ack if it was passed
27411 			 * through.
27412 			 */
27413 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27414 			    (int)*(uint_t *)mp->b_rptr));
27415 			freemsg(mp);
27416 			return;
27417 		}
27418 		/* NOTREACHED */
27419 	case IRE_DB_TYPE: {
27420 		nce_t		*nce;
27421 		ill_t		*ill;
27422 		in6_addr_t	gw_addr_v6;
27423 
27424 
27425 		/*
27426 		 * This is a response back from a resolver.  It
27427 		 * consists of a message chain containing:
27428 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27429 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27430 		 * The LL_HDR_MBLK is the DLPI header to use to get
27431 		 * the attached packet, and subsequent ones for the
27432 		 * same destination, transmitted.
27433 		 */
27434 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27435 			break;
27436 		/*
27437 		 * First, check to make sure the resolution succeeded.
27438 		 * If it failed, the second mblk will be empty.
27439 		 * If it is, free the chain, dropping the packet.
27440 		 * (We must ire_delete the ire; that frees the ire mblk)
27441 		 * We're doing this now to support PVCs for ATM; it's
27442 		 * a partial xresolv implementation. When we fully implement
27443 		 * xresolv interfaces, instead of freeing everything here
27444 		 * we'll initiate neighbor discovery.
27445 		 *
27446 		 * For v4 (ARP and other external resolvers) the resolver
27447 		 * frees the message, so no check is needed. This check
27448 		 * is required, though, for a full xresolve implementation.
27449 		 * Including this code here now both shows how external
27450 		 * resolvers can NACK a resolution request using an
27451 		 * existing design that has no specific provisions for NACKs,
27452 		 * and also takes into account that the current non-ARP
27453 		 * external resolver has been coded to use this method of
27454 		 * NACKing for all IPv6 (xresolv) cases,
27455 		 * whether our xresolv implementation is complete or not.
27456 		 *
27457 		 */
27458 		ire = (ire_t *)mp->b_rptr;
27459 		ill = ire_to_ill(ire);
27460 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27461 		if (mp1->b_rptr == mp1->b_wptr) {
27462 			if (ire->ire_ipversion == IPV6_VERSION) {
27463 				/*
27464 				 * XRESOLV interface.
27465 				 */
27466 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27467 				mutex_enter(&ire->ire_lock);
27468 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27469 				mutex_exit(&ire->ire_lock);
27470 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27471 					nce = ndp_lookup_v6(ill,
27472 					    &ire->ire_addr_v6, B_FALSE);
27473 				} else {
27474 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
27475 					    B_FALSE);
27476 				}
27477 				if (nce != NULL) {
27478 					nce_resolv_failed(nce);
27479 					ndp_delete(nce);
27480 					NCE_REFRELE(nce);
27481 				}
27482 			}
27483 			mp->b_cont = NULL;
27484 			freemsg(mp1);		/* frees the pkt as well */
27485 			ASSERT(ire->ire_nce == NULL);
27486 			ire_delete((ire_t *)mp->b_rptr);
27487 			return;
27488 		}
27489 
27490 		/*
27491 		 * Split them into IRE_MBLK and pkt and feed it into
27492 		 * ire_add_then_send. Then in ire_add_then_send
27493 		 * the IRE will be added, and then the packet will be
27494 		 * run back through ip_wput. This time it will make
27495 		 * it to the wire.
27496 		 */
27497 		mp->b_cont = NULL;
27498 		mp = mp1->b_cont;		/* now, mp points to pkt */
27499 		mp1->b_cont = NULL;
27500 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27501 		if (ire->ire_ipversion == IPV6_VERSION) {
27502 			/*
27503 			 * XRESOLV interface. Find the nce and put a copy
27504 			 * of the dl_unitdata_req in nce_res_mp
27505 			 */
27506 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27507 			mutex_enter(&ire->ire_lock);
27508 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27509 			mutex_exit(&ire->ire_lock);
27510 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27511 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
27512 				    B_FALSE);
27513 			} else {
27514 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
27515 			}
27516 			if (nce != NULL) {
27517 				/*
27518 				 * We have to protect nce_res_mp here
27519 				 * from being accessed by other threads
27520 				 * while we change the mblk pointer.
27521 				 * Other functions will also lock the nce when
27522 				 * accessing nce_res_mp.
27523 				 *
27524 				 * The reason we change the mblk pointer
27525 				 * here rather than copying the resolved address
27526 				 * into the template is that, unlike with
27527 				 * ethernet, we have no guarantee that the
27528 				 * resolved address length will be
27529 				 * smaller than or equal to the lla length
27530 				 * with which the template was allocated,
27531 				 * (for ethernet, they're equal)
27532 				 * so we have to use the actual resolved
27533 				 * address mblk - which holds the real
27534 				 * dl_unitdata_req with the resolved address.
27535 				 *
27536 				 * Doing this is the same behavior as was
27537 				 * previously used in the v4 ARP case.
27538 				 */
27539 				mutex_enter(&nce->nce_lock);
27540 				if (nce->nce_res_mp != NULL)
27541 					freemsg(nce->nce_res_mp);
27542 				nce->nce_res_mp = mp1;
27543 				mutex_exit(&nce->nce_lock);
27544 				/*
27545 				 * We do a fastpath probe here because
27546 				 * we have resolved the address without
27547 				 * using Neighbor Discovery.
27548 				 * In the non-XRESOLV v6 case, the fastpath
27549 				 * probe is done right after neighbor
27550 				 * discovery completes.
27551 				 */
27552 				if (nce->nce_res_mp != NULL) {
27553 					int res;
27554 					nce_fastpath_list_add(nce);
27555 					res = ill_fastpath_probe(ill,
27556 					    nce->nce_res_mp);
27557 					if (res != 0 && res != EAGAIN)
27558 						nce_fastpath_list_delete(nce);
27559 				}
27560 
27561 				ire_add_then_send(q, ire, mp);
27562 				/*
27563 				 * Now we have to clean out any packets
27564 				 * that may have been queued on the nce
27565 				 * while it was waiting for address resolution
27566 				 * to complete.
27567 				 */
27568 				mutex_enter(&nce->nce_lock);
27569 				mp1 = nce->nce_qd_mp;
27570 				nce->nce_qd_mp = NULL;
27571 				mutex_exit(&nce->nce_lock);
27572 				while (mp1 != NULL) {
27573 					mblk_t *nxt_mp;
27574 					queue_t *fwdq = NULL;
27575 					ill_t   *inbound_ill;
27576 					uint_t ifindex;
27577 
27578 					nxt_mp = mp1->b_next;
27579 					mp1->b_next = NULL;
27580 					/*
27581 					 * Retrieve ifindex stored in
27582 					 * ip_rput_data_v6()
27583 					 */
27584 					ifindex =
27585 					    (uint_t)(uintptr_t)mp1->b_prev;
27586 					inbound_ill =
27587 					    ill_lookup_on_ifindex(ifindex,
27588 					    B_TRUE, NULL, NULL, NULL,
27589 					    NULL, ipst);
27590 					mp1->b_prev = NULL;
27591 					if (inbound_ill != NULL)
27592 						fwdq = inbound_ill->ill_rq;
27593 
27594 					if (fwdq != NULL) {
27595 						put(fwdq, mp1);
27596 						ill_refrele(inbound_ill);
27597 					} else
27598 						put(WR(ill->ill_rq), mp1);
27599 					mp1 = nxt_mp;
27600 				}
27601 				NCE_REFRELE(nce);
27602 			} else {	/* nce is NULL; clean up */
27603 				ire_delete(ire);
27604 				freemsg(mp);
27605 				freemsg(mp1);
27606 				return;
27607 			}
27608 		} else {
27609 			nce_t *arpce;
27610 			/*
27611 			 * Link layer resolution succeeded. Recompute the
27612 			 * ire_nce.
27613 			 */
27614 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27615 			if ((arpce = ndp_lookup_v4(ill,
27616 			    (ire->ire_gateway_addr != INADDR_ANY ?
27617 			    &ire->ire_gateway_addr : &ire->ire_addr),
27618 			    B_FALSE)) == NULL) {
27619 				freeb(ire->ire_mp);
27620 				freeb(mp1);
27621 				freemsg(mp);
27622 				return;
27623 			}
27624 			mutex_enter(&arpce->nce_lock);
27625 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27626 			if (arpce->nce_state == ND_REACHABLE) {
27627 				/*
27628 				 * Someone resolved this before us;
27629 				 * cleanup the res_mp. Since ire has
27630 				 * not been added yet, the call to ire_add_v4
27631 				 * from ire_add_then_send (when a dup is
27632 				 * detected) will clean up the ire.
27633 				 */
27634 				freeb(mp1);
27635 			} else {
27636 				ASSERT(arpce->nce_res_mp == NULL);
27637 				arpce->nce_res_mp = mp1;
27638 				arpce->nce_state = ND_REACHABLE;
27639 			}
27640 			mutex_exit(&arpce->nce_lock);
27641 			if (ire->ire_marks & IRE_MARK_NOADD) {
27642 				/*
27643 				 * this ire will not be added to the ire
27644 				 * cache table, so we can set the ire_nce
27645 				 * here, as there are no atomicity constraints.
27646 				 */
27647 				ire->ire_nce = arpce;
27648 				/*
27649 				 * We are associating this nce with the ire
27650 				 * so change the nce ref taken in
27651 				 * ndp_lookup_v4() from
27652 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27653 				 */
27654 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27655 			} else {
27656 				NCE_REFRELE(arpce);
27657 			}
27658 			ire_add_then_send(q, ire, mp);
27659 		}
27660 		return;	/* All is well, the packet has been sent. */
27661 	}
27662 	case IRE_ARPRESOLVE_TYPE: {
27663 
27664 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27665 			break;
27666 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27667 		mp->b_cont = NULL;
27668 		/*
27669 		 * First, check to make sure the resolution succeeded.
27670 		 * If it failed, the second mblk will be empty.
27671 		 */
27672 		if (mp1->b_rptr == mp1->b_wptr) {
27673 			/* cleanup  the incomplete ire, free queued packets */
27674 			freemsg(mp); /* fake ire */
27675 			freeb(mp1);  /* dl_unitdata response */
27676 			return;
27677 		}
27678 
27679 		/*
27680 		 * update any incomplete nce_t found. we lookup the ctable
27681 		 * and find the nce from the ire->ire_nce because we need
27682 		 * to pass the ire to ip_xmit_v4 later, and can find both
27683 		 * ire and nce in one lookup from the ctable.
27684 		 */
27685 		fake_ire = (ire_t *)mp->b_rptr;
27686 		/*
27687 		 * By the time we come back here from ARP
27688 		 * the logical outgoing interface  of the incomplete ire
27689 		 * we added in ire_forward could have disappeared,
27690 		 * causing the incomplete ire to also have
27691 		 * dissapeared. So we need to retreive the
27692 		 * proper ipif for the ire  before looking
27693 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
27694 		 */
27695 		ill = q->q_ptr;
27696 
27697 		/* Get the outgoing ipif */
27698 		mutex_enter(&ill->ill_lock);
27699 		if (ill->ill_state_flags & ILL_CONDEMNED) {
27700 			mutex_exit(&ill->ill_lock);
27701 			freemsg(mp); /* fake ire */
27702 			freeb(mp1);  /* dl_unitdata response */
27703 			return;
27704 		}
27705 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27706 
27707 		if (ipif == NULL) {
27708 			mutex_exit(&ill->ill_lock);
27709 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27710 			freemsg(mp);
27711 			freeb(mp1);
27712 			return;
27713 		}
27714 		ipif_refhold_locked(ipif);
27715 		mutex_exit(&ill->ill_lock);
27716 		ire = ire_ctable_lookup(fake_ire->ire_addr,
27717 		    fake_ire->ire_gateway_addr, IRE_CACHE,
27718 		    ipif, fake_ire->ire_zoneid, NULL,
27719 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY), ipst);
27720 		ipif_refrele(ipif);
27721 		if (ire == NULL) {
27722 			/*
27723 			 * no ire was found; check if there is an nce
27724 			 * for this lookup; if it has no ire's pointing at it
27725 			 * cleanup.
27726 			 */
27727 			if ((nce = ndp_lookup_v4(ill,
27728 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27729 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27730 			    B_FALSE)) != NULL) {
27731 				/*
27732 				 * cleanup:
27733 				 * We check for refcnt 2 (one for the nce
27734 				 * hash list + 1 for the ref taken by
27735 				 * ndp_lookup_v4) to check that there are
27736 				 * no ire's pointing at the nce.
27737 				 */
27738 				if (nce->nce_refcnt == 2)
27739 					ndp_delete(nce);
27740 				NCE_REFRELE(nce);
27741 			}
27742 			freeb(mp1);  /* dl_unitdata response */
27743 			freemsg(mp); /* fake ire */
27744 			return;
27745 		}
27746 		nce = ire->ire_nce;
27747 		DTRACE_PROBE2(ire__arpresolve__type,
27748 		    ire_t *, ire, nce_t *, nce);
27749 		ASSERT(nce->nce_state != ND_INITIAL);
27750 		mutex_enter(&nce->nce_lock);
27751 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27752 		if (nce->nce_state == ND_REACHABLE) {
27753 			/*
27754 			 * Someone resolved this before us;
27755 			 * our response is not needed any more.
27756 			 */
27757 			mutex_exit(&nce->nce_lock);
27758 			freeb(mp1);  /* dl_unitdata response */
27759 		} else {
27760 			ASSERT(nce->nce_res_mp == NULL);
27761 			nce->nce_res_mp = mp1;
27762 			nce->nce_state = ND_REACHABLE;
27763 			mutex_exit(&nce->nce_lock);
27764 			nce_fastpath(nce);
27765 		}
27766 		/*
27767 		 * The cached nce_t has been updated to be reachable;
27768 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
27769 		 */
27770 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27771 		freemsg(mp);
27772 		/*
27773 		 * send out queued packets.
27774 		 */
27775 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
27776 
27777 		IRE_REFRELE(ire);
27778 		return;
27779 	}
27780 	default:
27781 		break;
27782 	}
27783 	if (q->q_next) {
27784 		putnext(q, mp);
27785 	} else
27786 		freemsg(mp);
27787 	return;
27788 
27789 protonak:
27790 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
27791 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
27792 		qreply(q, mp);
27793 }
27794 
27795 /*
27796  * Process IP options in an outbound packet.  Modify the destination if there
27797  * is a source route option.
27798  * Returns non-zero if something fails in which case an ICMP error has been
27799  * sent and mp freed.
27800  */
27801 static int
27802 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27803     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
27804 {
27805 	ipoptp_t	opts;
27806 	uchar_t		*opt;
27807 	uint8_t		optval;
27808 	uint8_t		optlen;
27809 	ipaddr_t	dst;
27810 	intptr_t	code = 0;
27811 	mblk_t		*mp;
27812 	ire_t		*ire = NULL;
27813 
27814 	ip2dbg(("ip_wput_options\n"));
27815 	mp = ipsec_mp;
27816 	if (mctl_present) {
27817 		mp = ipsec_mp->b_cont;
27818 	}
27819 
27820 	dst = ipha->ipha_dst;
27821 	for (optval = ipoptp_first(&opts, ipha);
27822 	    optval != IPOPT_EOL;
27823 	    optval = ipoptp_next(&opts)) {
27824 		opt = opts.ipoptp_cur;
27825 		optlen = opts.ipoptp_len;
27826 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27827 		    optval, optlen));
27828 		switch (optval) {
27829 			uint32_t off;
27830 		case IPOPT_SSRR:
27831 		case IPOPT_LSRR:
27832 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27833 				ip1dbg((
27834 				    "ip_wput_options: bad option offset\n"));
27835 				code = (char *)&opt[IPOPT_OLEN] -
27836 				    (char *)ipha;
27837 				goto param_prob;
27838 			}
27839 			off = opt[IPOPT_OFFSET];
27840 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27841 			    ntohl(dst)));
27842 			/*
27843 			 * For strict: verify that dst is directly
27844 			 * reachable.
27845 			 */
27846 			if (optval == IPOPT_SSRR) {
27847 				ire = ire_ftable_lookup(dst, 0, 0,
27848 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27849 				    MBLK_GETLABEL(mp),
27850 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
27851 				if (ire == NULL) {
27852 					ip1dbg(("ip_wput_options: SSRR not"
27853 					    " directly reachable: 0x%x\n",
27854 					    ntohl(dst)));
27855 					goto bad_src_route;
27856 				}
27857 				ire_refrele(ire);
27858 			}
27859 			break;
27860 		case IPOPT_RR:
27861 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27862 				ip1dbg((
27863 				    "ip_wput_options: bad option offset\n"));
27864 				code = (char *)&opt[IPOPT_OLEN] -
27865 				    (char *)ipha;
27866 				goto param_prob;
27867 			}
27868 			break;
27869 		case IPOPT_TS:
27870 			/*
27871 			 * Verify that length >=5 and that there is either
27872 			 * room for another timestamp or that the overflow
27873 			 * counter is not maxed out.
27874 			 */
27875 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
27876 			if (optlen < IPOPT_MINLEN_IT) {
27877 				goto param_prob;
27878 			}
27879 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27880 				ip1dbg((
27881 				    "ip_wput_options: bad option offset\n"));
27882 				code = (char *)&opt[IPOPT_OFFSET] -
27883 				    (char *)ipha;
27884 				goto param_prob;
27885 			}
27886 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
27887 			case IPOPT_TS_TSONLY:
27888 				off = IPOPT_TS_TIMELEN;
27889 				break;
27890 			case IPOPT_TS_TSANDADDR:
27891 			case IPOPT_TS_PRESPEC:
27892 			case IPOPT_TS_PRESPEC_RFC791:
27893 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
27894 				break;
27895 			default:
27896 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
27897 				    (char *)ipha;
27898 				goto param_prob;
27899 			}
27900 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
27901 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
27902 				/*
27903 				 * No room and the overflow counter is 15
27904 				 * already.
27905 				 */
27906 				goto param_prob;
27907 			}
27908 			break;
27909 		}
27910 	}
27911 
27912 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
27913 		return (0);
27914 
27915 	ip1dbg(("ip_wput_options: error processing IP options."));
27916 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
27917 
27918 param_prob:
27919 	/*
27920 	 * Since ip_wput() isn't close to finished, we fill
27921 	 * in enough of the header for credible error reporting.
27922 	 */
27923 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
27924 		/* Failed */
27925 		freemsg(ipsec_mp);
27926 		return (-1);
27927 	}
27928 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
27929 	return (-1);
27930 
27931 bad_src_route:
27932 	/*
27933 	 * Since ip_wput() isn't close to finished, we fill
27934 	 * in enough of the header for credible error reporting.
27935 	 */
27936 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
27937 		/* Failed */
27938 		freemsg(ipsec_mp);
27939 		return (-1);
27940 	}
27941 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
27942 	return (-1);
27943 }
27944 
27945 /*
27946  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
27947  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
27948  * thru /etc/system.
27949  */
27950 #define	CONN_MAXDRAINCNT	64
27951 
27952 static void
27953 conn_drain_init(ip_stack_t *ipst)
27954 {
27955 	int i;
27956 
27957 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
27958 
27959 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
27960 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
27961 		/*
27962 		 * Default value of the number of drainers is the
27963 		 * number of cpus, subject to maximum of 8 drainers.
27964 		 */
27965 		if (boot_max_ncpus != -1)
27966 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
27967 		else
27968 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
27969 	}
27970 
27971 	ipst->ips_conn_drain_list = kmem_zalloc(ipst->ips_conn_drain_list_cnt *
27972 	    sizeof (idl_t), KM_SLEEP);
27973 
27974 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
27975 		mutex_init(&ipst->ips_conn_drain_list[i].idl_lock, NULL,
27976 		    MUTEX_DEFAULT, NULL);
27977 	}
27978 }
27979 
27980 static void
27981 conn_drain_fini(ip_stack_t *ipst)
27982 {
27983 	int i;
27984 
27985 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++)
27986 		mutex_destroy(&ipst->ips_conn_drain_list[i].idl_lock);
27987 	kmem_free(ipst->ips_conn_drain_list,
27988 	    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
27989 	ipst->ips_conn_drain_list = NULL;
27990 }
27991 
27992 /*
27993  * Note: For an overview of how flowcontrol is handled in IP please see the
27994  * IP Flowcontrol notes at the top of this file.
27995  *
27996  * Flow control has blocked us from proceeding. Insert the given conn in one
27997  * of the conn drain lists. These conn wq's will be qenabled later on when
27998  * STREAMS flow control does a backenable. conn_walk_drain will enable
27999  * the first conn in each of these drain lists. Each of these qenabled conns
28000  * in turn enables the next in the list, after it runs, or when it closes,
28001  * thus sustaining the drain process.
28002  *
28003  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
28004  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
28005  * running at any time, on a given conn, since there can be only 1 service proc
28006  * running on a queue at any time.
28007  */
28008 void
28009 conn_drain_insert(conn_t *connp)
28010 {
28011 	idl_t	*idl;
28012 	uint_t	index;
28013 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28014 
28015 	mutex_enter(&connp->conn_lock);
28016 	if (connp->conn_state_flags & CONN_CLOSING) {
28017 		/*
28018 		 * The conn is closing as a result of which CONN_CLOSING
28019 		 * is set. Return.
28020 		 */
28021 		mutex_exit(&connp->conn_lock);
28022 		return;
28023 	} else if (connp->conn_idl == NULL) {
28024 		/*
28025 		 * Assign the next drain list round robin. We dont' use
28026 		 * a lock, and thus it may not be strictly round robin.
28027 		 * Atomicity of load/stores is enough to make sure that
28028 		 * conn_drain_list_index is always within bounds.
28029 		 */
28030 		index = ipst->ips_conn_drain_list_index;
28031 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28032 		connp->conn_idl = &ipst->ips_conn_drain_list[index];
28033 		index++;
28034 		if (index == ipst->ips_conn_drain_list_cnt)
28035 			index = 0;
28036 		ipst->ips_conn_drain_list_index = index;
28037 	}
28038 	mutex_exit(&connp->conn_lock);
28039 
28040 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28041 	if ((connp->conn_drain_prev != NULL) ||
28042 	    (connp->conn_state_flags & CONN_CLOSING)) {
28043 		/*
28044 		 * The conn is already in the drain list, OR
28045 		 * the conn is closing. We need to check again for
28046 		 * the closing case again since close can happen
28047 		 * after we drop the conn_lock, and before we
28048 		 * acquire the CONN_DRAIN_LIST_LOCK.
28049 		 */
28050 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28051 		return;
28052 	} else {
28053 		idl = connp->conn_idl;
28054 	}
28055 
28056 	/*
28057 	 * The conn is not in the drain list. Insert it at the
28058 	 * tail of the drain list. The drain list is circular
28059 	 * and doubly linked. idl_conn points to the 1st element
28060 	 * in the list.
28061 	 */
28062 	if (idl->idl_conn == NULL) {
28063 		idl->idl_conn = connp;
28064 		connp->conn_drain_next = connp;
28065 		connp->conn_drain_prev = connp;
28066 	} else {
28067 		conn_t *head = idl->idl_conn;
28068 
28069 		connp->conn_drain_next = head;
28070 		connp->conn_drain_prev = head->conn_drain_prev;
28071 		head->conn_drain_prev->conn_drain_next = connp;
28072 		head->conn_drain_prev = connp;
28073 	}
28074 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28075 }
28076 
28077 /*
28078  * This conn is closing, and we are called from ip_close. OR
28079  * This conn has been serviced by ip_wsrv, and we need to do the tail
28080  * processing.
28081  * If this conn is part of the drain list, we may need to sustain the drain
28082  * process by qenabling the next conn in the drain list. We may also need to
28083  * remove this conn from the list, if it is done.
28084  */
28085 static void
28086 conn_drain_tail(conn_t *connp, boolean_t closing)
28087 {
28088 	idl_t *idl;
28089 
28090 	/*
28091 	 * connp->conn_idl is stable at this point, and no lock is needed
28092 	 * to check it. If we are called from ip_close, close has already
28093 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28094 	 * called us only because conn_idl is non-null. If we are called thru
28095 	 * service, conn_idl could be null, but it cannot change because
28096 	 * service is single-threaded per queue, and there cannot be another
28097 	 * instance of service trying to call conn_drain_insert on this conn
28098 	 * now.
28099 	 */
28100 	ASSERT(!closing || (connp->conn_idl != NULL));
28101 
28102 	/*
28103 	 * If connp->conn_idl is null, the conn has not been inserted into any
28104 	 * drain list even once since creation of the conn. Just return.
28105 	 */
28106 	if (connp->conn_idl == NULL)
28107 		return;
28108 
28109 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28110 
28111 	if (connp->conn_drain_prev == NULL) {
28112 		/* This conn is currently not in the drain list.  */
28113 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28114 		return;
28115 	}
28116 	idl = connp->conn_idl;
28117 	if (idl->idl_conn_draining == connp) {
28118 		/*
28119 		 * This conn is the current drainer. If this is the last conn
28120 		 * in the drain list, we need to do more checks, in the 'if'
28121 		 * below. Otherwwise we need to just qenable the next conn,
28122 		 * to sustain the draining, and is handled in the 'else'
28123 		 * below.
28124 		 */
28125 		if (connp->conn_drain_next == idl->idl_conn) {
28126 			/*
28127 			 * This conn is the last in this list. This round
28128 			 * of draining is complete. If idl_repeat is set,
28129 			 * it means another flow enabling has happened from
28130 			 * the driver/streams and we need to another round
28131 			 * of draining.
28132 			 * If there are more than 2 conns in the drain list,
28133 			 * do a left rotate by 1, so that all conns except the
28134 			 * conn at the head move towards the head by 1, and the
28135 			 * the conn at the head goes to the tail. This attempts
28136 			 * a more even share for all queues that are being
28137 			 * drained.
28138 			 */
28139 			if ((connp->conn_drain_next != connp) &&
28140 			    (idl->idl_conn->conn_drain_next != connp)) {
28141 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28142 			}
28143 			if (idl->idl_repeat) {
28144 				qenable(idl->idl_conn->conn_wq);
28145 				idl->idl_conn_draining = idl->idl_conn;
28146 				idl->idl_repeat = 0;
28147 			} else {
28148 				idl->idl_conn_draining = NULL;
28149 			}
28150 		} else {
28151 			/*
28152 			 * If the next queue that we are now qenable'ing,
28153 			 * is closing, it will remove itself from this list
28154 			 * and qenable the subsequent queue in ip_close().
28155 			 * Serialization is acheived thru idl_lock.
28156 			 */
28157 			qenable(connp->conn_drain_next->conn_wq);
28158 			idl->idl_conn_draining = connp->conn_drain_next;
28159 		}
28160 	}
28161 	if (!connp->conn_did_putbq || closing) {
28162 		/*
28163 		 * Remove ourself from the drain list, if we did not do
28164 		 * a putbq, or if the conn is closing.
28165 		 * Note: It is possible that q->q_first is non-null. It means
28166 		 * that these messages landed after we did a enableok() in
28167 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28168 		 * service them.
28169 		 */
28170 		if (connp->conn_drain_next == connp) {
28171 			/* Singleton in the list */
28172 			ASSERT(connp->conn_drain_prev == connp);
28173 			idl->idl_conn = NULL;
28174 			idl->idl_conn_draining = NULL;
28175 		} else {
28176 			connp->conn_drain_prev->conn_drain_next =
28177 			    connp->conn_drain_next;
28178 			connp->conn_drain_next->conn_drain_prev =
28179 			    connp->conn_drain_prev;
28180 			if (idl->idl_conn == connp)
28181 				idl->idl_conn = connp->conn_drain_next;
28182 			ASSERT(idl->idl_conn_draining != connp);
28183 
28184 		}
28185 		connp->conn_drain_next = NULL;
28186 		connp->conn_drain_prev = NULL;
28187 	}
28188 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28189 }
28190 
28191 /*
28192  * Write service routine. Shared perimeter entry point.
28193  * ip_wsrv can be called in any of the following ways.
28194  * 1. The device queue's messages has fallen below the low water mark
28195  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28196  *    the drain lists and backenable the first conn in each list.
28197  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28198  *    qenabled non-tcp upper layers. We start dequeing messages and call
28199  *    ip_wput for each message.
28200  */
28201 
28202 void
28203 ip_wsrv(queue_t *q)
28204 {
28205 	conn_t	*connp;
28206 	ill_t	*ill;
28207 	mblk_t	*mp;
28208 
28209 	if (q->q_next) {
28210 		ill = (ill_t *)q->q_ptr;
28211 		if (ill->ill_state_flags == 0) {
28212 			/*
28213 			 * The device flow control has opened up.
28214 			 * Walk through conn drain lists and qenable the
28215 			 * first conn in each list. This makes sense only
28216 			 * if the stream is fully plumbed and setup.
28217 			 * Hence the if check above.
28218 			 */
28219 			ip1dbg(("ip_wsrv: walking\n"));
28220 			conn_walk_drain(ill->ill_ipst);
28221 		}
28222 		return;
28223 	}
28224 
28225 	connp = Q_TO_CONN(q);
28226 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28227 
28228 	/*
28229 	 * 1. Set conn_draining flag to signal that service is active.
28230 	 *
28231 	 * 2. ip_output determines whether it has been called from service,
28232 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28233 	 *    has been called from service.
28234 	 *
28235 	 * 3. Message ordering is preserved by the following logic.
28236 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28237 	 *    the message at the tail, if conn_draining is set (i.e. service
28238 	 *    is running) or if q->q_first is non-null.
28239 	 *
28240 	 *    ii. If ip_output is called from service, and if ip_output cannot
28241 	 *    putnext due to flow control, it does a putbq.
28242 	 *
28243 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28244 	 *    (causing an infinite loop).
28245 	 */
28246 	ASSERT(!connp->conn_did_putbq);
28247 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28248 		connp->conn_draining = 1;
28249 		noenable(q);
28250 		while ((mp = getq(q)) != NULL) {
28251 			ASSERT(CONN_Q(q));
28252 
28253 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28254 			if (connp->conn_did_putbq) {
28255 				/* ip_wput did a putbq */
28256 				break;
28257 			}
28258 		}
28259 		/*
28260 		 * At this point, a thread coming down from top, calling
28261 		 * ip_wput, may end up queueing the message. We have not yet
28262 		 * enabled the queue, so ip_wsrv won't be called again.
28263 		 * To avoid this race, check q->q_first again (in the loop)
28264 		 * If the other thread queued the message before we call
28265 		 * enableok(), we will catch it in the q->q_first check.
28266 		 * If the other thread queues the message after we call
28267 		 * enableok(), ip_wsrv will be called again by STREAMS.
28268 		 */
28269 		connp->conn_draining = 0;
28270 		enableok(q);
28271 	}
28272 
28273 	/* Enable the next conn for draining */
28274 	conn_drain_tail(connp, B_FALSE);
28275 
28276 	connp->conn_did_putbq = 0;
28277 }
28278 
28279 /*
28280  * Walk the list of all conn's calling the function provided with the
28281  * specified argument for each.	 Note that this only walks conn's that
28282  * have been bound.
28283  * Applies to both IPv4 and IPv6.
28284  */
28285 static void
28286 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28287 {
28288 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28289 	    ipst->ips_ipcl_udp_fanout_size,
28290 	    func, arg, zoneid);
28291 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28292 	    ipst->ips_ipcl_conn_fanout_size,
28293 	    func, arg, zoneid);
28294 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28295 	    ipst->ips_ipcl_bind_fanout_size,
28296 	    func, arg, zoneid);
28297 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28298 	    IPPROTO_MAX, func, arg, zoneid);
28299 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28300 	    IPPROTO_MAX, func, arg, zoneid);
28301 }
28302 
28303 /*
28304  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28305  * of conns that need to be drained, check if drain is already in progress.
28306  * If so set the idl_repeat bit, indicating that the last conn in the list
28307  * needs to reinitiate the drain once again, for the list. If drain is not
28308  * in progress for the list, initiate the draining, by qenabling the 1st
28309  * conn in the list. The drain is self-sustaining, each qenabled conn will
28310  * in turn qenable the next conn, when it is done/blocked/closing.
28311  */
28312 static void
28313 conn_walk_drain(ip_stack_t *ipst)
28314 {
28315 	int i;
28316 	idl_t *idl;
28317 
28318 	IP_STAT(ipst, ip_conn_walk_drain);
28319 
28320 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28321 		idl = &ipst->ips_conn_drain_list[i];
28322 		mutex_enter(&idl->idl_lock);
28323 		if (idl->idl_conn == NULL) {
28324 			mutex_exit(&idl->idl_lock);
28325 			continue;
28326 		}
28327 		/*
28328 		 * If this list is not being drained currently by
28329 		 * an ip_wsrv thread, start the process.
28330 		 */
28331 		if (idl->idl_conn_draining == NULL) {
28332 			ASSERT(idl->idl_repeat == 0);
28333 			qenable(idl->idl_conn->conn_wq);
28334 			idl->idl_conn_draining = idl->idl_conn;
28335 		} else {
28336 			idl->idl_repeat = 1;
28337 		}
28338 		mutex_exit(&idl->idl_lock);
28339 	}
28340 }
28341 
28342 /*
28343  * Walk an conn hash table of `count' buckets, calling func for each entry.
28344  */
28345 static void
28346 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28347     zoneid_t zoneid)
28348 {
28349 	conn_t	*connp;
28350 
28351 	while (count-- > 0) {
28352 		mutex_enter(&connfp->connf_lock);
28353 		for (connp = connfp->connf_head; connp != NULL;
28354 		    connp = connp->conn_next) {
28355 			if (zoneid == GLOBAL_ZONEID ||
28356 			    zoneid == connp->conn_zoneid) {
28357 				CONN_INC_REF(connp);
28358 				mutex_exit(&connfp->connf_lock);
28359 				(*func)(connp, arg);
28360 				mutex_enter(&connfp->connf_lock);
28361 				CONN_DEC_REF(connp);
28362 			}
28363 		}
28364 		mutex_exit(&connfp->connf_lock);
28365 		connfp++;
28366 	}
28367 }
28368 
28369 /* conn_walk_fanout routine invoked for ip_conn_report for each conn. */
28370 static void
28371 conn_report1(conn_t *connp, void *mp)
28372 {
28373 	char	buf1[INET6_ADDRSTRLEN];
28374 	char	buf2[INET6_ADDRSTRLEN];
28375 	uint_t	print_len, buf_len;
28376 
28377 	ASSERT(connp != NULL);
28378 
28379 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28380 	if (buf_len <= 0)
28381 		return;
28382 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1));
28383 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2));
28384 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28385 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28386 	    "%5d %s/%05d %s/%05d\n",
28387 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28388 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28389 	    buf1, connp->conn_lport,
28390 	    buf2, connp->conn_fport);
28391 	if (print_len < buf_len) {
28392 		((mblk_t *)mp)->b_wptr += print_len;
28393 	} else {
28394 		((mblk_t *)mp)->b_wptr += buf_len;
28395 	}
28396 }
28397 
28398 /*
28399  * Named Dispatch routine to produce a formatted report on all conns
28400  * that are listed in one of the fanout tables.
28401  * This report is accessed by using the ndd utility to "get" ND variable
28402  * "ip_conn_status".
28403  */
28404 /* ARGSUSED */
28405 static int
28406 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28407 {
28408 	conn_t *connp = Q_TO_CONN(q);
28409 
28410 	(void) mi_mpprintf(mp,
28411 	    "CONN      " MI_COL_HDRPAD_STR
28412 	    "rfq      " MI_COL_HDRPAD_STR
28413 	    "stq      " MI_COL_HDRPAD_STR
28414 	    " zone local                 remote");
28415 
28416 	/*
28417 	 * Because of the ndd constraint, at most we can have 64K buffer
28418 	 * to put in all conn info.  So to be more efficient, just
28419 	 * allocate a 64K buffer here, assuming we need that large buffer.
28420 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28421 	 */
28422 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28423 		/* The following may work even if we cannot get a large buf. */
28424 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28425 		return (0);
28426 	}
28427 
28428 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
28429 	    connp->conn_netstack->netstack_ip);
28430 	return (0);
28431 }
28432 
28433 /*
28434  * Determine if the ill and multicast aspects of that packets
28435  * "matches" the conn.
28436  */
28437 boolean_t
28438 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28439     zoneid_t zoneid)
28440 {
28441 	ill_t *in_ill;
28442 	boolean_t found;
28443 	ipif_t *ipif;
28444 	ire_t *ire;
28445 	ipaddr_t dst, src;
28446 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28447 
28448 	dst = ipha->ipha_dst;
28449 	src = ipha->ipha_src;
28450 
28451 	/*
28452 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28453 	 * unicast, broadcast and multicast reception to
28454 	 * conn_incoming_ill. conn_wantpacket itself is called
28455 	 * only for BROADCAST and multicast.
28456 	 *
28457 	 * 1) ip_rput supresses duplicate broadcasts if the ill
28458 	 *    is part of a group. Hence, we should be receiving
28459 	 *    just one copy of broadcast for the whole group.
28460 	 *    Thus, if it is part of the group the packet could
28461 	 *    come on any ill of the group and hence we need a
28462 	 *    match on the group. Otherwise, match on ill should
28463 	 *    be sufficient.
28464 	 *
28465 	 * 2) ip_rput does not suppress duplicate multicast packets.
28466 	 *    If there are two interfaces in a ill group and we have
28467 	 *    2 applications (conns) joined a multicast group G on
28468 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
28469 	 *    will give us two packets because we join G on both the
28470 	 *    interfaces rather than nominating just one interface
28471 	 *    for receiving multicast like broadcast above. So,
28472 	 *    we have to call ilg_lookup_ill to filter out duplicate
28473 	 *    copies, if ill is part of a group.
28474 	 */
28475 	in_ill = connp->conn_incoming_ill;
28476 	if (in_ill != NULL) {
28477 		if (in_ill->ill_group == NULL) {
28478 			if (in_ill != ill)
28479 				return (B_FALSE);
28480 		} else if (in_ill->ill_group != ill->ill_group) {
28481 			return (B_FALSE);
28482 		}
28483 	}
28484 
28485 	if (!CLASSD(dst)) {
28486 		if (IPCL_ZONE_MATCH(connp, zoneid))
28487 			return (B_TRUE);
28488 		/*
28489 		 * The conn is in a different zone; we need to check that this
28490 		 * broadcast address is configured in the application's zone and
28491 		 * on one ill in the group.
28492 		 */
28493 		ipif = ipif_get_next_ipif(NULL, ill);
28494 		if (ipif == NULL)
28495 			return (B_FALSE);
28496 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28497 		    connp->conn_zoneid, NULL,
28498 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
28499 		ipif_refrele(ipif);
28500 		if (ire != NULL) {
28501 			ire_refrele(ire);
28502 			return (B_TRUE);
28503 		} else {
28504 			return (B_FALSE);
28505 		}
28506 	}
28507 
28508 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28509 	    connp->conn_zoneid == zoneid) {
28510 		/*
28511 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28512 		 * disabled, therefore we don't dispatch the multicast packet to
28513 		 * the sending zone.
28514 		 */
28515 		return (B_FALSE);
28516 	}
28517 
28518 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28519 		/*
28520 		 * Multicast packet on the loopback interface: we only match
28521 		 * conns who joined the group in the specified zone.
28522 		 */
28523 		return (B_FALSE);
28524 	}
28525 
28526 	if (connp->conn_multi_router) {
28527 		/* multicast packet and multicast router socket: send up */
28528 		return (B_TRUE);
28529 	}
28530 
28531 	mutex_enter(&connp->conn_lock);
28532 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28533 	mutex_exit(&connp->conn_lock);
28534 	return (found);
28535 }
28536 
28537 /*
28538  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28539  */
28540 /* ARGSUSED */
28541 static void
28542 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28543 {
28544 	ill_t *ill = (ill_t *)q->q_ptr;
28545 	mblk_t	*mp1, *mp2;
28546 	ipif_t  *ipif;
28547 	int err = 0;
28548 	conn_t *connp = NULL;
28549 	ipsq_t	*ipsq;
28550 	arc_t	*arc;
28551 
28552 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28553 
28554 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28555 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28556 
28557 	ASSERT(IAM_WRITER_ILL(ill));
28558 	mp2 = mp->b_cont;
28559 	mp->b_cont = NULL;
28560 
28561 	/*
28562 	 * We have now received the arp bringup completion message
28563 	 * from ARP. Mark the arp bringup as done. Also if the arp
28564 	 * stream has already started closing, send up the AR_ARP_CLOSING
28565 	 * ack now since ARP is waiting in close for this ack.
28566 	 */
28567 	mutex_enter(&ill->ill_lock);
28568 	ill->ill_arp_bringup_pending = 0;
28569 	if (ill->ill_arp_closing) {
28570 		mutex_exit(&ill->ill_lock);
28571 		/* Let's reuse the mp for sending the ack */
28572 		arc = (arc_t *)mp->b_rptr;
28573 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28574 		arc->arc_cmd = AR_ARP_CLOSING;
28575 		qreply(q, mp);
28576 	} else {
28577 		mutex_exit(&ill->ill_lock);
28578 		freeb(mp);
28579 	}
28580 
28581 	ipsq = ill->ill_phyint->phyint_ipsq;
28582 	ipif = ipsq->ipsq_pending_ipif;
28583 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28584 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28585 	if (mp1 == NULL) {
28586 		/* bringup was aborted by the user */
28587 		freemsg(mp2);
28588 		return;
28589 	}
28590 
28591 	/*
28592 	 * If an IOCTL is waiting on this (ipsq_current_ioctl != 0), then we
28593 	 * must have an associated conn_t.  Otherwise, we're bringing this
28594 	 * interface back up as part of handling an asynchronous event (e.g.,
28595 	 * physical address change).
28596 	 */
28597 	if (ipsq->ipsq_current_ioctl != 0) {
28598 		ASSERT(connp != NULL);
28599 		q = CONNP_TO_WQ(connp);
28600 	} else {
28601 		ASSERT(connp == NULL);
28602 		q = ill->ill_rq;
28603 	}
28604 
28605 	/*
28606 	 * If the DL_BIND_REQ fails, it is noted
28607 	 * in arc_name_offset.
28608 	 */
28609 	err = *((int *)mp2->b_rptr);
28610 	if (err == 0) {
28611 		if (ipif->ipif_isv6) {
28612 			if ((err = ipif_up_done_v6(ipif)) != 0)
28613 				ip0dbg(("ip_arp_done: init failed\n"));
28614 		} else {
28615 			if ((err = ipif_up_done(ipif)) != 0)
28616 				ip0dbg(("ip_arp_done: init failed\n"));
28617 		}
28618 	} else {
28619 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28620 	}
28621 
28622 	freemsg(mp2);
28623 
28624 	if ((err == 0) && (ill->ill_up_ipifs)) {
28625 		err = ill_up_ipifs(ill, q, mp1);
28626 		if (err == EINPROGRESS)
28627 			return;
28628 	}
28629 
28630 	if (ill->ill_up_ipifs)
28631 		ill_group_cleanup(ill);
28632 
28633 	/*
28634 	 * The operation must complete without EINPROGRESS since
28635 	 * ipsq_pending_mp_get() has removed the mblk from ipsq_pending_mp.
28636 	 * Otherwise, the operation will be stuck forever in the ipsq.
28637 	 */
28638 	ASSERT(err != EINPROGRESS);
28639 	if (ipsq->ipsq_current_ioctl != 0)
28640 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28641 	else
28642 		ipsq_current_finish(ipsq);
28643 }
28644 
28645 /* Allocate the private structure */
28646 static int
28647 ip_priv_alloc(void **bufp)
28648 {
28649 	void	*buf;
28650 
28651 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28652 		return (ENOMEM);
28653 
28654 	*bufp = buf;
28655 	return (0);
28656 }
28657 
28658 /* Function to delete the private structure */
28659 void
28660 ip_priv_free(void *buf)
28661 {
28662 	ASSERT(buf != NULL);
28663 	kmem_free(buf, sizeof (ip_priv_t));
28664 }
28665 
28666 /*
28667  * The entry point for IPPF processing.
28668  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28669  * routine just returns.
28670  *
28671  * When called, ip_process generates an ipp_packet_t structure
28672  * which holds the state information for this packet and invokes the
28673  * the classifier (via ipp_packet_process). The classification, depending on
28674  * configured filters, results in a list of actions for this packet. Invoking
28675  * an action may cause the packet to be dropped, in which case the resulting
28676  * mblk (*mpp) is NULL. proc indicates the callout position for
28677  * this packet and ill_index is the interface this packet on or will leave
28678  * on (inbound and outbound resp.).
28679  */
28680 void
28681 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28682 {
28683 	mblk_t		*mp;
28684 	ip_priv_t	*priv;
28685 	ipp_action_id_t	aid;
28686 	int		rc = 0;
28687 	ipp_packet_t	*pp;
28688 #define	IP_CLASS	"ip"
28689 
28690 	/* If the classifier is not loaded, return  */
28691 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28692 		return;
28693 	}
28694 
28695 	mp = *mpp;
28696 	ASSERT(mp != NULL);
28697 
28698 	/* Allocate the packet structure */
28699 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28700 	if (rc != 0) {
28701 		*mpp = NULL;
28702 		freemsg(mp);
28703 		return;
28704 	}
28705 
28706 	/* Allocate the private structure */
28707 	rc = ip_priv_alloc((void **)&priv);
28708 	if (rc != 0) {
28709 		*mpp = NULL;
28710 		freemsg(mp);
28711 		ipp_packet_free(pp);
28712 		return;
28713 	}
28714 	priv->proc = proc;
28715 	priv->ill_index = ill_index;
28716 	ipp_packet_set_private(pp, priv, ip_priv_free);
28717 	ipp_packet_set_data(pp, mp);
28718 
28719 	/* Invoke the classifier */
28720 	rc = ipp_packet_process(&pp);
28721 	if (pp != NULL) {
28722 		mp = ipp_packet_get_data(pp);
28723 		ipp_packet_free(pp);
28724 		if (rc != 0) {
28725 			freemsg(mp);
28726 			*mpp = NULL;
28727 		}
28728 	} else {
28729 		*mpp = NULL;
28730 	}
28731 #undef	IP_CLASS
28732 }
28733 
28734 /*
28735  * Propagate a multicast group membership operation (add/drop) on
28736  * all the interfaces crossed by the related multirt routes.
28737  * The call is considered successful if the operation succeeds
28738  * on at least one interface.
28739  */
28740 static int
28741 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28742     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28743     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28744     mblk_t *first_mp)
28745 {
28746 	ire_t		*ire_gw;
28747 	irb_t		*irb;
28748 	int		error = 0;
28749 	opt_restart_t	*or;
28750 	ip_stack_t	*ipst = ire->ire_ipst;
28751 
28752 	irb = ire->ire_bucket;
28753 	ASSERT(irb != NULL);
28754 
28755 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28756 
28757 	or = (opt_restart_t *)first_mp->b_rptr;
28758 	IRB_REFHOLD(irb);
28759 	for (; ire != NULL; ire = ire->ire_next) {
28760 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28761 			continue;
28762 		if (ire->ire_addr != group)
28763 			continue;
28764 
28765 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28766 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28767 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
28768 		/* No resolver exists for the gateway; skip this ire. */
28769 		if (ire_gw == NULL)
28770 			continue;
28771 
28772 		/*
28773 		 * This function can return EINPROGRESS. If so the operation
28774 		 * will be restarted from ip_restart_optmgmt which will
28775 		 * call ip_opt_set and option processing will restart for
28776 		 * this option. So we may end up calling 'fn' more than once.
28777 		 * This requires that 'fn' is idempotent except for the
28778 		 * return value. The operation is considered a success if
28779 		 * it succeeds at least once on any one interface.
28780 		 */
28781 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28782 		    NULL, fmode, src, first_mp);
28783 		if (error == 0)
28784 			or->or_private = CGTP_MCAST_SUCCESS;
28785 
28786 		if (ip_debug > 0) {
28787 			ulong_t	off;
28788 			char	*ksym;
28789 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28790 			ip2dbg(("ip_multirt_apply_membership: "
28791 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28792 			    "error %d [success %u]\n",
28793 			    ksym ? ksym : "?",
28794 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28795 			    error, or->or_private));
28796 		}
28797 
28798 		ire_refrele(ire_gw);
28799 		if (error == EINPROGRESS) {
28800 			IRB_REFRELE(irb);
28801 			return (error);
28802 		}
28803 	}
28804 	IRB_REFRELE(irb);
28805 	/*
28806 	 * Consider the call as successful if we succeeded on at least
28807 	 * one interface. Otherwise, return the last encountered error.
28808 	 */
28809 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28810 }
28811 
28812 
28813 /*
28814  * Issue a warning regarding a route crossing an interface with an
28815  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28816  * amount of time is logged.
28817  */
28818 static void
28819 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28820 {
28821 	hrtime_t	current = gethrtime();
28822 	char		buf[INET_ADDRSTRLEN];
28823 	ip_stack_t	*ipst = ire->ire_ipst;
28824 
28825 	/* Convert interval in ms to hrtime in ns */
28826 	if (ipst->ips_multirt_bad_mtu_last_time +
28827 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
28828 	    current) {
28829 		cmn_err(CE_WARN, "ip: ignoring multiroute "
28830 		    "to %s, incorrect MTU %u (expected %u)\n",
28831 		    ip_dot_addr(ire->ire_addr, buf),
28832 		    ire->ire_max_frag, max_frag);
28833 
28834 		ipst->ips_multirt_bad_mtu_last_time = current;
28835 	}
28836 }
28837 
28838 
28839 /*
28840  * Get the CGTP (multirouting) filtering status.
28841  * If 0, the CGTP hooks are transparent.
28842  */
28843 /* ARGSUSED */
28844 static int
28845 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
28846 {
28847 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28848 
28849 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
28850 	return (0);
28851 }
28852 
28853 
28854 /*
28855  * Set the CGTP (multirouting) filtering status.
28856  * If the status is changed from active to transparent
28857  * or from transparent to active, forward the new status
28858  * to the filtering module (if loaded).
28859  */
28860 /* ARGSUSED */
28861 static int
28862 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
28863     cred_t *ioc_cr)
28864 {
28865 	long		new_value;
28866 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28867 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
28868 
28869 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
28870 		return (EPERM);
28871 
28872 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
28873 	    new_value < 0 || new_value > 1) {
28874 		return (EINVAL);
28875 	}
28876 
28877 	if ((!*ip_cgtp_filter_value) && new_value) {
28878 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
28879 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28880 		    " (module not loaded)" : "");
28881 	}
28882 	if (*ip_cgtp_filter_value && (!new_value)) {
28883 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
28884 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28885 		    " (module not loaded)" : "");
28886 	}
28887 
28888 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28889 		int	res;
28890 		netstackid_t stackid;
28891 
28892 		stackid = ipst->ips_netstack->netstack_stackid;
28893 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
28894 		    new_value);
28895 		if (res)
28896 			return (res);
28897 	}
28898 
28899 	*ip_cgtp_filter_value = (boolean_t)new_value;
28900 
28901 	return (0);
28902 }
28903 
28904 
28905 /*
28906  * Return the expected CGTP hooks version number.
28907  */
28908 int
28909 ip_cgtp_filter_supported(void)
28910 {
28911 	return (ip_cgtp_filter_rev);
28912 }
28913 
28914 
28915 /*
28916  * CGTP hooks can be registered by invoking this function.
28917  * Checks that the version number matches.
28918  */
28919 int
28920 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
28921 {
28922 	netstack_t *ns;
28923 	ip_stack_t *ipst;
28924 
28925 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
28926 		return (ENOTSUP);
28927 
28928 	ns = netstack_find_by_stackid(stackid);
28929 	if (ns == NULL)
28930 		return (EINVAL);
28931 	ipst = ns->netstack_ip;
28932 	ASSERT(ipst != NULL);
28933 
28934 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28935 		netstack_rele(ns);
28936 		return (EALREADY);
28937 	}
28938 
28939 	ipst->ips_ip_cgtp_filter_ops = ops;
28940 	netstack_rele(ns);
28941 	return (0);
28942 }
28943 
28944 /*
28945  * CGTP hooks can be unregistered by invoking this function.
28946  * Returns ENXIO if there was no registration.
28947  * Returns EBUSY if the ndd variable has not been turned off.
28948  */
28949 int
28950 ip_cgtp_filter_unregister(netstackid_t stackid)
28951 {
28952 	netstack_t *ns;
28953 	ip_stack_t *ipst;
28954 
28955 	ns = netstack_find_by_stackid(stackid);
28956 	if (ns == NULL)
28957 		return (EINVAL);
28958 	ipst = ns->netstack_ip;
28959 	ASSERT(ipst != NULL);
28960 
28961 	if (ipst->ips_ip_cgtp_filter) {
28962 		netstack_rele(ns);
28963 		return (EBUSY);
28964 	}
28965 
28966 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
28967 		netstack_rele(ns);
28968 		return (ENXIO);
28969 	}
28970 	ipst->ips_ip_cgtp_filter_ops = NULL;
28971 	netstack_rele(ns);
28972 	return (0);
28973 }
28974 
28975 /*
28976  * Check whether there is a CGTP filter registration.
28977  * Returns non-zero if there is a registration, otherwise returns zero.
28978  * Note: returns zero if bad stackid.
28979  */
28980 int
28981 ip_cgtp_filter_is_registered(netstackid_t stackid)
28982 {
28983 	netstack_t *ns;
28984 	ip_stack_t *ipst;
28985 	int ret;
28986 
28987 	ns = netstack_find_by_stackid(stackid);
28988 	if (ns == NULL)
28989 		return (0);
28990 	ipst = ns->netstack_ip;
28991 	ASSERT(ipst != NULL);
28992 
28993 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
28994 		ret = 1;
28995 	else
28996 		ret = 0;
28997 
28998 	netstack_rele(ns);
28999 	return (ret);
29000 }
29001 
29002 static squeue_func_t
29003 ip_squeue_switch(int val)
29004 {
29005 	squeue_func_t rval = squeue_fill;
29006 
29007 	switch (val) {
29008 	case IP_SQUEUE_ENTER_NODRAIN:
29009 		rval = squeue_enter_nodrain;
29010 		break;
29011 	case IP_SQUEUE_ENTER:
29012 		rval = squeue_enter;
29013 		break;
29014 	default:
29015 		break;
29016 	}
29017 	return (rval);
29018 }
29019 
29020 /* ARGSUSED */
29021 static int
29022 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29023     caddr_t addr, cred_t *cr)
29024 {
29025 	int *v = (int *)addr;
29026 	long new_value;
29027 
29028 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29029 		return (EPERM);
29030 
29031 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29032 		return (EINVAL);
29033 
29034 	ip_input_proc = ip_squeue_switch(new_value);
29035 	*v = new_value;
29036 	return (0);
29037 }
29038 
29039 /* ARGSUSED */
29040 static int
29041 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29042     caddr_t addr, cred_t *cr)
29043 {
29044 	int *v = (int *)addr;
29045 	long new_value;
29046 
29047 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29048 		return (EPERM);
29049 
29050 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29051 		return (EINVAL);
29052 
29053 	*v = new_value;
29054 	return (0);
29055 }
29056 
29057 /*
29058  * Handle changes to ipmp_hook_emulation ndd variable.
29059  * Need to update phyint_hook_ifindex.
29060  * Also generate a nic plumb event should a new ifidex be assigned to a group.
29061  */
29062 static void
29063 ipmp_hook_emulation_changed(ip_stack_t *ipst)
29064 {
29065 	phyint_t *phyi;
29066 	phyint_t *phyi_tmp;
29067 	char *groupname;
29068 	int namelen;
29069 	ill_t	*ill;
29070 	boolean_t new_group;
29071 
29072 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29073 	/*
29074 	 * Group indicies are stored in the phyint - a common structure
29075 	 * to both IPv4 and IPv6.
29076 	 */
29077 	phyi = avl_first(&ipst->ips_phyint_g_list->phyint_list_avl_by_index);
29078 	for (; phyi != NULL;
29079 	    phyi = avl_walk(&ipst->ips_phyint_g_list->phyint_list_avl_by_index,
29080 	    phyi, AVL_AFTER)) {
29081 		/* Ignore the ones that do not have a group */
29082 		if (phyi->phyint_groupname_len == 0)
29083 			continue;
29084 
29085 		/*
29086 		 * Look for other phyint in group.
29087 		 * Clear name/namelen so the lookup doesn't find ourselves.
29088 		 */
29089 		namelen = phyi->phyint_groupname_len;
29090 		groupname = phyi->phyint_groupname;
29091 		phyi->phyint_groupname_len = 0;
29092 		phyi->phyint_groupname = NULL;
29093 
29094 		phyi_tmp = phyint_lookup_group(groupname, B_FALSE, ipst);
29095 		/* Restore */
29096 		phyi->phyint_groupname_len = namelen;
29097 		phyi->phyint_groupname = groupname;
29098 
29099 		new_group = B_FALSE;
29100 		if (ipst->ips_ipmp_hook_emulation) {
29101 			/*
29102 			 * If the group already exists and has already
29103 			 * been assigned a group ifindex, we use the existing
29104 			 * group_ifindex, otherwise we pick a new group_ifindex
29105 			 * here.
29106 			 */
29107 			if (phyi_tmp != NULL &&
29108 			    phyi_tmp->phyint_group_ifindex != 0) {
29109 				phyi->phyint_group_ifindex =
29110 				    phyi_tmp->phyint_group_ifindex;
29111 			} else {
29112 				/* XXX We need a recovery strategy here. */
29113 				if (!ip_assign_ifindex(
29114 				    &phyi->phyint_group_ifindex, ipst))
29115 					cmn_err(CE_PANIC,
29116 					    "ip_assign_ifindex() failed");
29117 				new_group = B_TRUE;
29118 			}
29119 		} else {
29120 			phyi->phyint_group_ifindex = 0;
29121 		}
29122 		if (ipst->ips_ipmp_hook_emulation)
29123 			phyi->phyint_hook_ifindex = phyi->phyint_group_ifindex;
29124 		else
29125 			phyi->phyint_hook_ifindex = phyi->phyint_ifindex;
29126 
29127 		/*
29128 		 * For IP Filter to find out the relationship between
29129 		 * names and interface indicies, we need to generate
29130 		 * a NE_PLUMB event when a new group can appear.
29131 		 * We always generate events when a new interface appears
29132 		 * (even when ipmp_hook_emulation is set) so there
29133 		 * is no need to generate NE_PLUMB events when
29134 		 * ipmp_hook_emulation is turned off.
29135 		 * And since it isn't critical for IP Filter to get
29136 		 * the NE_UNPLUMB events we skip those here.
29137 		 */
29138 		if (new_group) {
29139 			/*
29140 			 * First phyint in group - generate group PLUMB event.
29141 			 * Since we are not running inside the ipsq we do
29142 			 * the dispatch immediately.
29143 			 */
29144 			if (phyi->phyint_illv4 != NULL)
29145 				ill = phyi->phyint_illv4;
29146 			else
29147 				ill = phyi->phyint_illv6;
29148 
29149 			if (ill != NULL) {
29150 				mutex_enter(&ill->ill_lock);
29151 				ill_nic_info_plumb(ill, B_TRUE);
29152 				ill_nic_info_dispatch(ill);
29153 				mutex_exit(&ill->ill_lock);
29154 			}
29155 		}
29156 	}
29157 	rw_exit(&ipst->ips_ill_g_lock);
29158 }
29159 
29160 /* ARGSUSED */
29161 static int
29162 ipmp_hook_emulation_set(queue_t *q, mblk_t *mp, char *value,
29163     caddr_t addr, cred_t *cr)
29164 {
29165 	int *v = (int *)addr;
29166 	long new_value;
29167 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29168 
29169 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29170 		return (EINVAL);
29171 
29172 	if (*v != new_value) {
29173 		*v = new_value;
29174 		ipmp_hook_emulation_changed(ipst);
29175 	}
29176 	return (0);
29177 }
29178 
29179 static void *
29180 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29181 {
29182 	kstat_t *ksp;
29183 
29184 	ip_stat_t template = {
29185 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29186 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29187 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29188 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29189 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29190 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29191 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29192 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29193 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29194 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29195 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29196 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29197 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29198 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29199 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29200 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29201 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29202 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29203 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29204 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29205 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29206 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29207 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29208 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29209 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29210 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29211 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29212 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29213 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29214 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29215 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29216 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29217 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29218 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29219 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29220 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29221 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29222 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29223 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29224 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29225 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29226 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29227 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29228 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29229 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29230 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29231 	};
29232 
29233 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29234 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29235 	    KSTAT_FLAG_VIRTUAL, stackid);
29236 
29237 	if (ksp == NULL)
29238 		return (NULL);
29239 
29240 	bcopy(&template, ip_statisticsp, sizeof (template));
29241 	ksp->ks_data = (void *)ip_statisticsp;
29242 	ksp->ks_private = (void *)(uintptr_t)stackid;
29243 
29244 	kstat_install(ksp);
29245 	return (ksp);
29246 }
29247 
29248 static void
29249 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29250 {
29251 	if (ksp != NULL) {
29252 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29253 		kstat_delete_netstack(ksp, stackid);
29254 	}
29255 }
29256 
29257 static void *
29258 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29259 {
29260 	kstat_t	*ksp;
29261 
29262 	ip_named_kstat_t template = {
29263 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29264 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29265 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29266 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29267 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29268 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29269 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29270 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29271 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29272 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29273 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29274 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29275 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29276 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29277 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29278 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29279 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29280 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29281 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29282 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29283 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29284 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29285 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29286 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29287 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29288 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29289 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29290 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29291 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29292 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29293 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29294 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29295 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29296 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29297 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29298 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29299 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29300 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29301 	};
29302 
29303 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29304 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29305 	if (ksp == NULL || ksp->ks_data == NULL)
29306 		return (NULL);
29307 
29308 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29309 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29310 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29311 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29312 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29313 
29314 	template.netToMediaEntrySize.value.i32 =
29315 	    sizeof (mib2_ipNetToMediaEntry_t);
29316 
29317 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29318 
29319 	bcopy(&template, ksp->ks_data, sizeof (template));
29320 	ksp->ks_update = ip_kstat_update;
29321 	ksp->ks_private = (void *)(uintptr_t)stackid;
29322 
29323 	kstat_install(ksp);
29324 	return (ksp);
29325 }
29326 
29327 static void
29328 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29329 {
29330 	if (ksp != NULL) {
29331 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29332 		kstat_delete_netstack(ksp, stackid);
29333 	}
29334 }
29335 
29336 static int
29337 ip_kstat_update(kstat_t *kp, int rw)
29338 {
29339 	ip_named_kstat_t *ipkp;
29340 	mib2_ipIfStatsEntry_t ipmib;
29341 	ill_walk_context_t ctx;
29342 	ill_t *ill;
29343 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29344 	netstack_t	*ns;
29345 	ip_stack_t	*ipst;
29346 
29347 	if (kp == NULL || kp->ks_data == NULL)
29348 		return (EIO);
29349 
29350 	if (rw == KSTAT_WRITE)
29351 		return (EACCES);
29352 
29353 	ns = netstack_find_by_stackid(stackid);
29354 	if (ns == NULL)
29355 		return (-1);
29356 	ipst = ns->netstack_ip;
29357 	if (ipst == NULL) {
29358 		netstack_rele(ns);
29359 		return (-1);
29360 	}
29361 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29362 
29363 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29364 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29365 	ill = ILL_START_WALK_V4(&ctx, ipst);
29366 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29367 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29368 	rw_exit(&ipst->ips_ill_g_lock);
29369 
29370 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29371 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29372 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29373 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29374 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29375 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29376 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29377 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29378 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29379 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29380 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29381 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29382 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29383 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29384 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29385 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29386 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29387 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29388 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29389 
29390 	ipkp->routingDiscards.value.ui32 =	0;
29391 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29392 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29393 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29394 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29395 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29396 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29397 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29398 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29399 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29400 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29401 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29402 
29403 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29404 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29405 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29406 
29407 	netstack_rele(ns);
29408 
29409 	return (0);
29410 }
29411 
29412 static void *
29413 icmp_kstat_init(netstackid_t stackid)
29414 {
29415 	kstat_t	*ksp;
29416 
29417 	icmp_named_kstat_t template = {
29418 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29419 		{ "inErrors",		KSTAT_DATA_UINT32 },
29420 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29421 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29422 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29423 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29424 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29425 		{ "inEchos",		KSTAT_DATA_UINT32 },
29426 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29427 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29428 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29429 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29430 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29431 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29432 		{ "outErrors",		KSTAT_DATA_UINT32 },
29433 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29434 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29435 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29436 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29437 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29438 		{ "outEchos",		KSTAT_DATA_UINT32 },
29439 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29440 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29441 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29442 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29443 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29444 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29445 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29446 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29447 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29448 		{ "outDrops",		KSTAT_DATA_UINT32 },
29449 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29450 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29451 	};
29452 
29453 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29454 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29455 	if (ksp == NULL || ksp->ks_data == NULL)
29456 		return (NULL);
29457 
29458 	bcopy(&template, ksp->ks_data, sizeof (template));
29459 
29460 	ksp->ks_update = icmp_kstat_update;
29461 	ksp->ks_private = (void *)(uintptr_t)stackid;
29462 
29463 	kstat_install(ksp);
29464 	return (ksp);
29465 }
29466 
29467 static void
29468 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29469 {
29470 	if (ksp != NULL) {
29471 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29472 		kstat_delete_netstack(ksp, stackid);
29473 	}
29474 }
29475 
29476 static int
29477 icmp_kstat_update(kstat_t *kp, int rw)
29478 {
29479 	icmp_named_kstat_t *icmpkp;
29480 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29481 	netstack_t	*ns;
29482 	ip_stack_t	*ipst;
29483 
29484 	if ((kp == NULL) || (kp->ks_data == NULL))
29485 		return (EIO);
29486 
29487 	if (rw == KSTAT_WRITE)
29488 		return (EACCES);
29489 
29490 	ns = netstack_find_by_stackid(stackid);
29491 	if (ns == NULL)
29492 		return (-1);
29493 	ipst = ns->netstack_ip;
29494 	if (ipst == NULL) {
29495 		netstack_rele(ns);
29496 		return (-1);
29497 	}
29498 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29499 
29500 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29501 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29502 	icmpkp->inDestUnreachs.value.ui32 =
29503 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29504 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29505 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29506 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29507 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29508 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29509 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29510 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29511 	icmpkp->inTimestampReps.value.ui32 =
29512 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29513 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29514 	icmpkp->inAddrMaskReps.value.ui32 =
29515 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29516 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29517 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29518 	icmpkp->outDestUnreachs.value.ui32 =
29519 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29520 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29521 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29522 	icmpkp->outSrcQuenchs.value.ui32 =
29523 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29524 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29525 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29526 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29527 	icmpkp->outTimestamps.value.ui32 =
29528 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29529 	icmpkp->outTimestampReps.value.ui32 =
29530 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29531 	icmpkp->outAddrMasks.value.ui32 =
29532 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29533 	icmpkp->outAddrMaskReps.value.ui32 =
29534 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29535 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29536 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29537 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29538 	icmpkp->outFragNeeded.value.ui32 =
29539 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29540 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29541 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29542 	icmpkp->inBadRedirects.value.ui32 =
29543 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29544 
29545 	netstack_rele(ns);
29546 	return (0);
29547 }
29548 
29549 /*
29550  * This is the fanout function for raw socket opened for SCTP.  Note
29551  * that it is called after SCTP checks that there is no socket which
29552  * wants a packet.  Then before SCTP handles this out of the blue packet,
29553  * this function is called to see if there is any raw socket for SCTP.
29554  * If there is and it is bound to the correct address, the packet will
29555  * be sent to that socket.  Note that only one raw socket can be bound to
29556  * a port.  This is assured in ipcl_sctp_hash_insert();
29557  */
29558 void
29559 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29560     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29561     zoneid_t zoneid)
29562 {
29563 	conn_t		*connp;
29564 	queue_t		*rq;
29565 	mblk_t		*first_mp;
29566 	boolean_t	secure;
29567 	ip6_t		*ip6h;
29568 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29569 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29570 
29571 	first_mp = mp;
29572 	if (mctl_present) {
29573 		mp = first_mp->b_cont;
29574 		secure = ipsec_in_is_secure(first_mp);
29575 		ASSERT(mp != NULL);
29576 	} else {
29577 		secure = B_FALSE;
29578 	}
29579 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29580 
29581 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29582 	if (connp == NULL) {
29583 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29584 		return;
29585 	}
29586 	rq = connp->conn_rq;
29587 	if (!canputnext(rq)) {
29588 		CONN_DEC_REF(connp);
29589 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29590 		freemsg(first_mp);
29591 		return;
29592 	}
29593 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29594 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29595 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29596 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29597 		if (first_mp == NULL) {
29598 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29599 			CONN_DEC_REF(connp);
29600 			return;
29601 		}
29602 	}
29603 	/*
29604 	 * We probably should not send M_CTL message up to
29605 	 * raw socket.
29606 	 */
29607 	if (mctl_present)
29608 		freeb(first_mp);
29609 
29610 	/* Initiate IPPF processing here if needed. */
29611 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29612 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29613 		ip_process(IPP_LOCAL_IN, &mp,
29614 		    recv_ill->ill_phyint->phyint_ifindex);
29615 		if (mp == NULL) {
29616 			CONN_DEC_REF(connp);
29617 			return;
29618 		}
29619 	}
29620 
29621 	if (connp->conn_recvif || connp->conn_recvslla ||
29622 	    ((connp->conn_ip_recvpktinfo ||
29623 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29624 	    (flags & IP_FF_IPINFO))) {
29625 		int in_flags = 0;
29626 
29627 		/*
29628 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29629 		 * IPF_RECVIF.
29630 		 */
29631 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29632 			in_flags = IPF_RECVIF;
29633 		}
29634 		if (connp->conn_recvslla) {
29635 			in_flags |= IPF_RECVSLLA;
29636 		}
29637 		if (isv4) {
29638 			mp = ip_add_info(mp, recv_ill, in_flags,
29639 			    IPCL_ZONEID(connp), ipst);
29640 		} else {
29641 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29642 			if (mp == NULL) {
29643 				BUMP_MIB(recv_ill->ill_ip_mib,
29644 				    ipIfStatsInDiscards);
29645 				CONN_DEC_REF(connp);
29646 				return;
29647 			}
29648 		}
29649 	}
29650 
29651 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29652 	/*
29653 	 * We are sending the IPSEC_IN message also up. Refer
29654 	 * to comments above this function.
29655 	 * This is the SOCK_RAW, IPPROTO_SCTP case.
29656 	 */
29657 	(connp->conn_recv)(connp, mp, NULL);
29658 	CONN_DEC_REF(connp);
29659 }
29660 
29661 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29662 {									\
29663 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29664 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29665 }
29666 /*
29667  * This function should be called only if all packet processing
29668  * including fragmentation is complete. Callers of this function
29669  * must set mp->b_prev to one of these values:
29670  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29671  * prior to handing over the mp as first argument to this function.
29672  *
29673  * If the ire passed by caller is incomplete, this function
29674  * queues the packet and if necessary, sends ARP request and bails.
29675  * If the ire passed is fully resolved, we simply prepend
29676  * the link-layer header to the packet, do ipsec hw acceleration
29677  * work if necessary, and send the packet out on the wire.
29678  *
29679  * NOTE: IPsec will only call this function with fully resolved
29680  * ires if hw acceleration is involved.
29681  * TODO list :
29682  * 	a Handle M_MULTIDATA so that
29683  *	  tcp_multisend->tcp_multisend_data can
29684  *	  call ip_xmit_v4 directly
29685  *	b Handle post-ARP work for fragments so that
29686  *	  ip_wput_frag can call this function.
29687  */
29688 ipxmit_state_t
29689 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
29690 {
29691 	nce_t		*arpce;
29692 	queue_t		*q;
29693 	int		ill_index;
29694 	mblk_t		*nxt_mp, *first_mp;
29695 	boolean_t	xmit_drop = B_FALSE;
29696 	ip_proc_t	proc;
29697 	ill_t		*out_ill;
29698 	int		pkt_len;
29699 
29700 	arpce = ire->ire_nce;
29701 	ASSERT(arpce != NULL);
29702 
29703 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29704 
29705 	mutex_enter(&arpce->nce_lock);
29706 	switch (arpce->nce_state) {
29707 	case ND_REACHABLE:
29708 		/* If there are other queued packets, queue this packet */
29709 		if (arpce->nce_qd_mp != NULL) {
29710 			if (mp != NULL)
29711 				nce_queue_mp_common(arpce, mp, B_FALSE);
29712 			mp = arpce->nce_qd_mp;
29713 		}
29714 		arpce->nce_qd_mp = NULL;
29715 		mutex_exit(&arpce->nce_lock);
29716 
29717 		/*
29718 		 * Flush the queue.  In the common case, where the
29719 		 * ARP is already resolved,  it will go through the
29720 		 * while loop only once.
29721 		 */
29722 		while (mp != NULL) {
29723 
29724 			nxt_mp = mp->b_next;
29725 			mp->b_next = NULL;
29726 			ASSERT(mp->b_datap->db_type != M_CTL);
29727 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29728 			/*
29729 			 * This info is needed for IPQOS to do COS marking
29730 			 * in ip_wput_attach_llhdr->ip_process.
29731 			 */
29732 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29733 			mp->b_prev = NULL;
29734 
29735 			/* set up ill index for outbound qos processing */
29736 			out_ill = ire_to_ill(ire);
29737 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29738 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29739 			    ill_index);
29740 			if (first_mp == NULL) {
29741 				xmit_drop = B_TRUE;
29742 				BUMP_MIB(out_ill->ill_ip_mib,
29743 				    ipIfStatsOutDiscards);
29744 				goto next_mp;
29745 			}
29746 			/* non-ipsec hw accel case */
29747 			if (io == NULL || !io->ipsec_out_accelerated) {
29748 				/* send it */
29749 				q = ire->ire_stq;
29750 				if (proc == IPP_FWD_OUT) {
29751 					UPDATE_IB_PKT_COUNT(ire);
29752 				} else {
29753 					UPDATE_OB_PKT_COUNT(ire);
29754 				}
29755 				ire->ire_last_used_time = lbolt;
29756 
29757 				if (flow_ctl_enabled || canputnext(q)) {
29758 					if (proc == IPP_FWD_OUT) {
29759 
29760 					BUMP_MIB(out_ill->ill_ip_mib,
29761 					    ipIfStatsHCOutForwDatagrams);
29762 
29763 					}
29764 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29765 					    pkt_len);
29766 
29767 					putnext(q, first_mp);
29768 				} else {
29769 					BUMP_MIB(out_ill->ill_ip_mib,
29770 					    ipIfStatsOutDiscards);
29771 					xmit_drop = B_TRUE;
29772 					freemsg(first_mp);
29773 				}
29774 			} else {
29775 				/*
29776 				 * Safety Pup says: make sure this
29777 				 *  is going to the right interface!
29778 				 */
29779 				ill_t *ill1 =
29780 				    (ill_t *)ire->ire_stq->q_ptr;
29781 				int ifindex =
29782 				    ill1->ill_phyint->phyint_ifindex;
29783 				if (ifindex !=
29784 				    io->ipsec_out_capab_ill_index) {
29785 					xmit_drop = B_TRUE;
29786 					freemsg(mp);
29787 				} else {
29788 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
29789 					    pkt_len);
29790 					ipsec_hw_putnext(ire->ire_stq, mp);
29791 				}
29792 			}
29793 next_mp:
29794 			mp = nxt_mp;
29795 		} /* while (mp != NULL) */
29796 		if (xmit_drop)
29797 			return (SEND_FAILED);
29798 		else
29799 			return (SEND_PASSED);
29800 
29801 	case ND_INITIAL:
29802 	case ND_INCOMPLETE:
29803 
29804 		/*
29805 		 * While we do send off packets to dests that
29806 		 * use fully-resolved CGTP routes, we do not
29807 		 * handle unresolved CGTP routes.
29808 		 */
29809 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
29810 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
29811 
29812 		if (mp != NULL) {
29813 			/* queue the packet */
29814 			nce_queue_mp_common(arpce, mp, B_FALSE);
29815 		}
29816 
29817 		if (arpce->nce_state == ND_INCOMPLETE) {
29818 			mutex_exit(&arpce->nce_lock);
29819 			DTRACE_PROBE3(ip__xmit__incomplete,
29820 			    (ire_t *), ire, (mblk_t *), mp,
29821 			    (ipsec_out_t *), io);
29822 			return (LOOKUP_IN_PROGRESS);
29823 		}
29824 
29825 		arpce->nce_state = ND_INCOMPLETE;
29826 		mutex_exit(&arpce->nce_lock);
29827 		/*
29828 		 * Note that ire_add() (called from ire_forward())
29829 		 * holds a ref on the ire until ARP is completed.
29830 		 */
29831 
29832 		ire_arpresolve(ire, ire_to_ill(ire));
29833 		return (LOOKUP_IN_PROGRESS);
29834 	default:
29835 		ASSERT(0);
29836 		mutex_exit(&arpce->nce_lock);
29837 		return (LLHDR_RESLV_FAILED);
29838 	}
29839 }
29840 
29841 #undef	UPDATE_IP_MIB_OB_COUNTERS
29842 
29843 /*
29844  * Return B_TRUE if the buffers differ in length or content.
29845  * This is used for comparing extension header buffers.
29846  * Note that an extension header would be declared different
29847  * even if all that changed was the next header value in that header i.e.
29848  * what really changed is the next extension header.
29849  */
29850 boolean_t
29851 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
29852     uint_t blen)
29853 {
29854 	if (!b_valid)
29855 		blen = 0;
29856 
29857 	if (alen != blen)
29858 		return (B_TRUE);
29859 	if (alen == 0)
29860 		return (B_FALSE);	/* Both zero length */
29861 	return (bcmp(abuf, bbuf, alen));
29862 }
29863 
29864 /*
29865  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
29866  * Return B_FALSE if memory allocation fails - don't change any state!
29867  */
29868 boolean_t
29869 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29870     const void *src, uint_t srclen)
29871 {
29872 	void *dst;
29873 
29874 	if (!src_valid)
29875 		srclen = 0;
29876 
29877 	ASSERT(*dstlenp == 0);
29878 	if (src != NULL && srclen != 0) {
29879 		dst = mi_alloc(srclen, BPRI_MED);
29880 		if (dst == NULL)
29881 			return (B_FALSE);
29882 	} else {
29883 		dst = NULL;
29884 	}
29885 	if (*dstp != NULL)
29886 		mi_free(*dstp);
29887 	*dstp = dst;
29888 	*dstlenp = dst == NULL ? 0 : srclen;
29889 	return (B_TRUE);
29890 }
29891 
29892 /*
29893  * Replace what is in *dst, *dstlen with the source.
29894  * Assumes ip_allocbuf has already been called.
29895  */
29896 void
29897 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29898     const void *src, uint_t srclen)
29899 {
29900 	if (!src_valid)
29901 		srclen = 0;
29902 
29903 	ASSERT(*dstlenp == srclen);
29904 	if (src != NULL && srclen != 0)
29905 		bcopy(src, *dstp, srclen);
29906 }
29907 
29908 /*
29909  * Free the storage pointed to by the members of an ip6_pkt_t.
29910  */
29911 void
29912 ip6_pkt_free(ip6_pkt_t *ipp)
29913 {
29914 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
29915 
29916 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
29917 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
29918 		ipp->ipp_hopopts = NULL;
29919 		ipp->ipp_hopoptslen = 0;
29920 	}
29921 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
29922 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
29923 		ipp->ipp_rtdstopts = NULL;
29924 		ipp->ipp_rtdstoptslen = 0;
29925 	}
29926 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
29927 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
29928 		ipp->ipp_dstopts = NULL;
29929 		ipp->ipp_dstoptslen = 0;
29930 	}
29931 	if (ipp->ipp_fields & IPPF_RTHDR) {
29932 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
29933 		ipp->ipp_rthdr = NULL;
29934 		ipp->ipp_rthdrlen = 0;
29935 	}
29936 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
29937 	    IPPF_RTHDR);
29938 }
29939