xref: /titanic_52/usr/src/uts/common/inet/ip/ip.c (revision d46ed901a1027484eb470062f803f4aad62b8650)
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_mrtdebug"},
823 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
824 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
825 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
826 	{  1,	255,	255,	"ip_def_ttl" },
827 	{  0,	1,	0,	"ip_forward_src_routed"},
828 	{  0,	256,	32,	"ip_wroff_extra" },
829 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
830 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
831 	{  0,	1,	1,	"ip_path_mtu_discovery" },
832 	{  0,	240,	30,	"ip_ignore_delete_time" },
833 	{  0,	1,	0,	"ip_ignore_redirect" },
834 	{  0,	1,	1,	"ip_output_queue" },
835 	{  1,	254,	1,	"ip_broadcast_ttl" },
836 	{  0,	99999,	100,	"ip_icmp_err_interval" },
837 	{  1,	99999,	10,	"ip_icmp_err_burst" },
838 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
839 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
840 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
841 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
842 	{  0,	1,	1,	"icmp_accept_clear_messages" },
843 	{  0,	1,	1,	"igmp_accept_clear_messages" },
844 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
845 				"ip_ndp_delay_first_probe_time"},
846 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
847 				"ip_ndp_max_unicast_solicit"},
848 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
849 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
850 	{  0,	1,	0,	"ip6_forward_src_routed"},
851 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
852 	{  0,	1,	1,	"ip6_send_redirects"},
853 	{  0,	1,	0,	"ip6_ignore_redirect" },
854 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
855 
856 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
857 
858 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
859 
860 	{  0,	1,	1,	"pim_accept_clear_messages" },
861 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
862 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
863 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
864 	{  0,	15,	0,	"ip_policy_mask" },
865 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
866 	{  0,	255,	1,	"ip_multirt_ttl" },
867 	{  0,	1,	1,	"ip_multidata_outbound" },
868 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
869 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
870 	{  0,	1000,	1,	"ip_max_temp_defend" },
871 	{  0,	1000,	3,	"ip_max_defend" },
872 	{  0,	999999,	30,	"ip_defend_interval" },
873 	{  0,	3600000, 300000, "ip_dup_recovery" },
874 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
875 	{  0,	1,	1,	"ip_lso_outbound" },
876 	{  IGMP_V1_ROUTER, IGMP_V3_ROUTER, IGMP_V3_ROUTER, "igmp_max_version" },
877 	{  MLD_V1_ROUTER, MLD_V2_ROUTER, MLD_V2_ROUTER, "mld_max_version" },
878 #ifdef DEBUG
879 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
880 #else
881 	{  0,	0,	0,	"" },
882 #endif
883 };
884 
885 /*
886  * Extended NDP table
887  * The addresses for the first two are filled in to be ips_ip_g_forward
888  * and ips_ipv6_forward at init time.
889  */
890 static ipndp_t	lcl_ndp_arr[] = {
891 	/* getf			setf		data			name */
892 #define	IPNDP_IP_FORWARDING_OFFSET	0
893 	{  ip_param_generic_get,	ip_forward_set,	NULL,
894 	    "ip_forwarding" },
895 #define	IPNDP_IP6_FORWARDING_OFFSET	1
896 	{  ip_param_generic_get,	ip_forward_set,	NULL,
897 	    "ip6_forwarding" },
898 	{  ip_ill_report,	NULL,		NULL,
899 	    "ip_ill_status" },
900 	{  ip_ipif_report,	NULL,		NULL,
901 	    "ip_ipif_status" },
902 	{  ip_ire_report,	NULL,		NULL,
903 	    "ipv4_ire_status" },
904 	{  ip_ire_report_v6,	NULL,		NULL,
905 	    "ipv6_ire_status" },
906 	{  ip_conn_report,	NULL,		NULL,
907 	    "ip_conn_status" },
908 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
909 	    "ip_rput_pullups" },
910 	{  ndp_report,		NULL,		NULL,
911 	    "ip_ndp_cache_report" },
912 	{  ip_srcid_report,	NULL,		NULL,
913 	    "ip_srcid_status" },
914 	{ ip_param_generic_get, ip_squeue_profile_set,
915 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
916 	{ ip_param_generic_get, ip_squeue_bind_set,
917 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
918 	{ ip_param_generic_get, ip_input_proc_set,
919 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
920 	{ ip_param_generic_get, ip_int_set,
921 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
922 #define	IPNDP_CGTP_FILTER_OFFSET	14
923 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
924 	    "ip_cgtp_filter" },
925 	{ ip_param_generic_get, ip_int_set,
926 	    (caddr_t)&ip_soft_rings_cnt, "ip_soft_rings_cnt" },
927 #define	IPNDP_IPMP_HOOK_OFFSET	16
928 	{  ip_param_generic_get, ipmp_hook_emulation_set, NULL,
929 	    "ipmp_hook_emulation" },
930 	{  ip_param_generic_get, ip_int_set, (caddr_t)&ip_debug,
931 	    "ip_debug" },
932 };
933 
934 /*
935  * Table of IP ioctls encoding the various properties of the ioctl and
936  * indexed based on the last byte of the ioctl command. Occasionally there
937  * is a clash, and there is more than 1 ioctl with the same last byte.
938  * In such a case 1 ioctl is encoded in the ndx table and the remaining
939  * ioctls are encoded in the misc table. An entry in the ndx table is
940  * retrieved by indexing on the last byte of the ioctl command and comparing
941  * the ioctl command with the value in the ndx table. In the event of a
942  * mismatch the misc table is then searched sequentially for the desired
943  * ioctl command.
944  *
945  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
946  */
947 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
948 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
949 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
950 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
951 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
952 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
953 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
954 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
955 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
956 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
957 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
958 
959 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
960 			MISC_CMD, ip_siocaddrt, NULL },
961 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
962 			MISC_CMD, ip_siocdelrt, NULL },
963 
964 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
965 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
966 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
967 			IF_CMD, ip_sioctl_get_addr, NULL },
968 
969 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
970 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
971 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
972 			IPI_GET_CMD | IPI_REPL,
973 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
974 
975 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
976 			IPI_PRIV | IPI_WR | IPI_REPL,
977 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
978 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
979 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
980 			IF_CMD, ip_sioctl_get_flags, NULL },
981 
982 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
983 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
984 
985 	/* copyin size cannot be coded for SIOCGIFCONF */
986 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
987 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
988 
989 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
990 			IF_CMD, ip_sioctl_mtu, NULL },
991 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
992 			IF_CMD, ip_sioctl_get_mtu, NULL },
993 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
994 			IPI_GET_CMD | IPI_REPL,
995 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
996 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
997 			IF_CMD, ip_sioctl_brdaddr, NULL },
998 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
999 			IPI_GET_CMD | IPI_REPL,
1000 			IF_CMD, ip_sioctl_get_netmask, NULL },
1001 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1002 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1003 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1004 			IPI_GET_CMD | IPI_REPL,
1005 			IF_CMD, ip_sioctl_get_metric, NULL },
1006 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1007 			IF_CMD, ip_sioctl_metric, NULL },
1008 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1009 
1010 	/* See 166-168 below for extended SIOC*XARP ioctls */
1011 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1012 			ARP_CMD, ip_sioctl_arp, NULL },
1013 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1014 			ARP_CMD, ip_sioctl_arp, NULL },
1015 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1016 			ARP_CMD, ip_sioctl_arp, NULL },
1017 
1018 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1019 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1020 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1021 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1022 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1023 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1024 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1025 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1026 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1027 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1028 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1029 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1030 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1031 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1032 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1033 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1034 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1035 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1036 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1037 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1038 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1039 
1040 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1041 			MISC_CMD, if_unitsel, if_unitsel_restart },
1042 
1043 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1044 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1045 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1046 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1047 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1048 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1049 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1050 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1051 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1052 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1053 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1054 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1055 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1056 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1057 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1058 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1059 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1060 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1061 
1062 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1063 			IPI_PRIV | IPI_WR | IPI_MODOK,
1064 			IF_CMD, ip_sioctl_sifname, NULL },
1065 
1066 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1067 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1068 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1069 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1070 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1071 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1072 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1073 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1074 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1075 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1076 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1077 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1078 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1079 
1080 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1081 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1082 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1083 			IF_CMD, ip_sioctl_get_muxid, NULL },
1084 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1085 			IPI_PRIV | IPI_WR | IPI_REPL,
1086 			IF_CMD, ip_sioctl_muxid, NULL },
1087 
1088 	/* Both if and lif variants share same func */
1089 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1090 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1091 	/* Both if and lif variants share same func */
1092 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1093 			IPI_PRIV | IPI_WR | IPI_REPL,
1094 			IF_CMD, ip_sioctl_slifindex, NULL },
1095 
1096 	/* copyin size cannot be coded for SIOCGIFCONF */
1097 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
1098 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1099 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1100 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1101 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1102 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1103 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1104 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1105 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1106 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1109 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1110 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1111 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1112 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1113 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1114 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1115 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1116 
1117 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1118 			IPI_PRIV | IPI_WR | IPI_REPL,
1119 			LIF_CMD, ip_sioctl_removeif,
1120 			ip_sioctl_removeif_restart },
1121 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1122 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1123 			LIF_CMD, ip_sioctl_addif, NULL },
1124 #define	SIOCLIFADDR_NDX 112
1125 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1126 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1127 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1128 			IPI_GET_CMD | IPI_REPL,
1129 			LIF_CMD, ip_sioctl_get_addr, NULL },
1130 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1131 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1132 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1133 			IPI_GET_CMD | IPI_REPL,
1134 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1135 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1136 			IPI_PRIV | IPI_WR | IPI_REPL,
1137 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1138 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1139 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1140 			LIF_CMD, ip_sioctl_get_flags, NULL },
1141 
1142 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1143 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1144 
1145 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1146 			ip_sioctl_get_lifconf, NULL },
1147 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1148 			LIF_CMD, ip_sioctl_mtu, NULL },
1149 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1150 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1151 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1152 			IPI_GET_CMD | IPI_REPL,
1153 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1154 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1155 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1156 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1157 			IPI_GET_CMD | IPI_REPL,
1158 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1159 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1160 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1161 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1162 			IPI_GET_CMD | IPI_REPL,
1163 			LIF_CMD, ip_sioctl_get_metric, NULL },
1164 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1165 			LIF_CMD, ip_sioctl_metric, NULL },
1166 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1167 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1168 			LIF_CMD, ip_sioctl_slifname,
1169 			ip_sioctl_slifname_restart },
1170 
1171 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1172 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1173 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1174 			IPI_GET_CMD | IPI_REPL,
1175 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1176 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1177 			IPI_PRIV | IPI_WR | IPI_REPL,
1178 			LIF_CMD, ip_sioctl_muxid, NULL },
1179 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1180 			IPI_GET_CMD | IPI_REPL,
1181 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1182 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1183 			IPI_PRIV | IPI_WR | IPI_REPL,
1184 			LIF_CMD, ip_sioctl_slifindex, 0 },
1185 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1186 			LIF_CMD, ip_sioctl_token, NULL },
1187 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1188 			IPI_GET_CMD | IPI_REPL,
1189 			LIF_CMD, ip_sioctl_get_token, NULL },
1190 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1191 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1192 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1193 			IPI_GET_CMD | IPI_REPL,
1194 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1195 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1196 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1197 
1198 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1199 			IPI_GET_CMD | IPI_REPL,
1200 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1201 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1202 			LIF_CMD, ip_siocdelndp_v6, NULL },
1203 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1204 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1205 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1206 			LIF_CMD, ip_siocsetndp_v6, NULL },
1207 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1208 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1209 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1210 			MISC_CMD, ip_sioctl_tonlink, NULL },
1211 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1212 			MISC_CMD, ip_sioctl_tmysite, NULL },
1213 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1214 			TUN_CMD, ip_sioctl_tunparam, NULL },
1215 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1216 			IPI_PRIV | IPI_WR,
1217 			TUN_CMD, ip_sioctl_tunparam, NULL },
1218 
1219 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1220 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1221 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1222 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1223 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1224 
1225 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1226 			IPI_PRIV | IPI_WR | IPI_REPL,
1227 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1228 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1229 			IPI_PRIV | IPI_WR | IPI_REPL,
1230 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1231 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1232 			IPI_PRIV | IPI_WR,
1233 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1234 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1235 			IPI_GET_CMD | IPI_REPL,
1236 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1237 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1238 			IPI_GET_CMD | IPI_REPL,
1239 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1240 
1241 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1242 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1243 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1244 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1245 
1246 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1247 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1248 
1249 	/* These are handled in ip_sioctl_copyin_setup itself */
1250 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1251 			MISC_CMD, NULL, NULL },
1252 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1253 			MISC_CMD, NULL, NULL },
1254 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1255 
1256 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1257 			ip_sioctl_get_lifconf, NULL },
1258 
1259 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1260 			XARP_CMD, ip_sioctl_arp, NULL },
1261 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1262 			XARP_CMD, ip_sioctl_arp, NULL },
1263 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1264 			XARP_CMD, ip_sioctl_arp, NULL },
1265 
1266 	/* SIOCPOPSOCKFS is not handled by IP */
1267 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1268 
1269 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1270 			IPI_GET_CMD | IPI_REPL,
1271 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1272 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1273 			IPI_PRIV | IPI_WR | IPI_REPL,
1274 			LIF_CMD, ip_sioctl_slifzone,
1275 			ip_sioctl_slifzone_restart },
1276 	/* 172-174 are SCTP ioctls and not handled by IP */
1277 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1278 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1279 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1280 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1281 			IPI_GET_CMD, LIF_CMD,
1282 			ip_sioctl_get_lifusesrc, 0 },
1283 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1284 			IPI_PRIV | IPI_WR,
1285 			LIF_CMD, ip_sioctl_slifusesrc,
1286 			NULL },
1287 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1288 			ip_sioctl_get_lifsrcof, NULL },
1289 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1290 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1291 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1292 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1293 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1294 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1295 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1296 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1297 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1298 			ip_sioctl_set_ipmpfailback, NULL },
1299 	/* SIOCSENABLESDP is handled by SDP */
1300 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1301 };
1302 
1303 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1304 
1305 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1306 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1307 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1308 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1309 		TUN_CMD, ip_sioctl_tunparam, NULL },
1310 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1311 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1312 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1313 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1314 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1315 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1316 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1317 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1318 		MISC_CMD, mrt_ioctl},
1319 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1320 		MISC_CMD, mrt_ioctl},
1321 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1322 		MISC_CMD, mrt_ioctl}
1323 };
1324 
1325 int ip_misc_ioctl_count =
1326     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1327 
1328 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1329 					/* Settable in /etc/system */
1330 /* Defined in ip_ire.c */
1331 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1332 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1333 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1334 
1335 static nv_t	ire_nv_arr[] = {
1336 	{ IRE_BROADCAST, "BROADCAST" },
1337 	{ IRE_LOCAL, "LOCAL" },
1338 	{ IRE_LOOPBACK, "LOOPBACK" },
1339 	{ IRE_CACHE, "CACHE" },
1340 	{ IRE_DEFAULT, "DEFAULT" },
1341 	{ IRE_PREFIX, "PREFIX" },
1342 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1343 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1344 	{ IRE_HOST, "HOST" },
1345 	{ 0 }
1346 };
1347 
1348 nv_t	*ire_nv_tbl = ire_nv_arr;
1349 
1350 /* Defined in ip_netinfo.c */
1351 extern ddi_taskq_t	*eventq_queue_nic;
1352 
1353 /* Simple ICMP IP Header Template */
1354 static ipha_t icmp_ipha = {
1355 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1356 };
1357 
1358 struct module_info ip_mod_info = {
1359 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1360 };
1361 
1362 /*
1363  * Duplicate static symbols within a module confuses mdb; so we avoid the
1364  * problem by making the symbols here distinct from those in udp.c.
1365  */
1366 
1367 /*
1368  * Entry points for IP as a device and as a module.
1369  * FIXME: down the road we might want a separate module and driver qinit.
1370  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1371  */
1372 static struct qinit iprinitv4 = {
1373 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1374 	&ip_mod_info
1375 };
1376 
1377 struct qinit iprinitv6 = {
1378 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1379 	&ip_mod_info
1380 };
1381 
1382 static struct qinit ipwinitv4 = {
1383 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1384 	&ip_mod_info
1385 };
1386 
1387 struct qinit ipwinitv6 = {
1388 	(pfi_t)ip_wput_v6, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1389 	&ip_mod_info
1390 };
1391 
1392 static struct qinit iplrinit = {
1393 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1394 	&ip_mod_info
1395 };
1396 
1397 static struct qinit iplwinit = {
1398 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1399 	&ip_mod_info
1400 };
1401 
1402 /* For AF_INET aka /dev/ip */
1403 struct streamtab ipinfov4 = {
1404 	&iprinitv4, &ipwinitv4, &iplrinit, &iplwinit
1405 };
1406 
1407 /* For AF_INET6 aka /dev/ip6 */
1408 struct streamtab ipinfov6 = {
1409 	&iprinitv6, &ipwinitv6, &iplrinit, &iplwinit
1410 };
1411 
1412 #ifdef	DEBUG
1413 static boolean_t skip_sctp_cksum = B_FALSE;
1414 #endif
1415 
1416 /*
1417  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1418  * ip_rput_v6(), ip_output(), etc.  If the message
1419  * block already has a M_CTL at the front of it, then simply set the zoneid
1420  * appropriately.
1421  */
1422 mblk_t *
1423 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1424 {
1425 	mblk_t		*first_mp;
1426 	ipsec_out_t	*io;
1427 
1428 	ASSERT(zoneid != ALL_ZONES);
1429 	if (mp->b_datap->db_type == M_CTL) {
1430 		io = (ipsec_out_t *)mp->b_rptr;
1431 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1432 		io->ipsec_out_zoneid = zoneid;
1433 		return (mp);
1434 	}
1435 
1436 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1437 	if (first_mp == NULL)
1438 		return (NULL);
1439 	io = (ipsec_out_t *)first_mp->b_rptr;
1440 	/* This is not a secure packet */
1441 	io->ipsec_out_secure = B_FALSE;
1442 	io->ipsec_out_zoneid = zoneid;
1443 	first_mp->b_cont = mp;
1444 	return (first_mp);
1445 }
1446 
1447 /*
1448  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1449  */
1450 mblk_t *
1451 ip_copymsg(mblk_t *mp)
1452 {
1453 	mblk_t *nmp;
1454 	ipsec_info_t *in;
1455 
1456 	if (mp->b_datap->db_type != M_CTL)
1457 		return (copymsg(mp));
1458 
1459 	in = (ipsec_info_t *)mp->b_rptr;
1460 
1461 	/*
1462 	 * Note that M_CTL is also used for delivering ICMP error messages
1463 	 * upstream to transport layers.
1464 	 */
1465 	if (in->ipsec_info_type != IPSEC_OUT &&
1466 	    in->ipsec_info_type != IPSEC_IN)
1467 		return (copymsg(mp));
1468 
1469 	nmp = copymsg(mp->b_cont);
1470 
1471 	if (in->ipsec_info_type == IPSEC_OUT) {
1472 		return (ipsec_out_tag(mp, nmp,
1473 		    ((ipsec_out_t *)in)->ipsec_out_ns));
1474 	} else {
1475 		return (ipsec_in_tag(mp, nmp,
1476 		    ((ipsec_in_t *)in)->ipsec_in_ns));
1477 	}
1478 }
1479 
1480 /* Generate an ICMP fragmentation needed message. */
1481 static void
1482 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1483     ip_stack_t *ipst)
1484 {
1485 	icmph_t	icmph;
1486 	mblk_t *first_mp;
1487 	boolean_t mctl_present;
1488 
1489 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1490 
1491 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1492 		if (mctl_present)
1493 			freeb(first_mp);
1494 		return;
1495 	}
1496 
1497 	bzero(&icmph, sizeof (icmph_t));
1498 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1499 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1500 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1501 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1502 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1503 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1504 	    ipst);
1505 }
1506 
1507 /*
1508  * icmp_inbound deals with ICMP messages in the following ways.
1509  *
1510  * 1) It needs to send a reply back and possibly delivering it
1511  *    to the "interested" upper clients.
1512  * 2) It needs to send it to the upper clients only.
1513  * 3) It needs to change some values in IP only.
1514  * 4) It needs to change some values in IP and upper layers e.g TCP.
1515  *
1516  * We need to accomodate icmp messages coming in clear until we get
1517  * everything secure from the wire. If icmp_accept_clear_messages
1518  * is zero we check with the global policy and act accordingly. If
1519  * it is non-zero, we accept the message without any checks. But
1520  * *this does not mean* that this will be delivered to the upper
1521  * clients. By accepting we might send replies back, change our MTU
1522  * value etc. but delivery to the ULP/clients depends on their policy
1523  * dispositions.
1524  *
1525  * We handle the above 4 cases in the context of IPsec in the
1526  * following way :
1527  *
1528  * 1) Send the reply back in the same way as the request came in.
1529  *    If it came in encrypted, it goes out encrypted. If it came in
1530  *    clear, it goes out in clear. Thus, this will prevent chosen
1531  *    plain text attack.
1532  * 2) The client may or may not expect things to come in secure.
1533  *    If it comes in secure, the policy constraints are checked
1534  *    before delivering it to the upper layers. If it comes in
1535  *    clear, ipsec_inbound_accept_clear will decide whether to
1536  *    accept this in clear or not. In both the cases, if the returned
1537  *    message (IP header + 8 bytes) that caused the icmp message has
1538  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1539  *    sending up. If there are only 8 bytes of returned message, then
1540  *    upper client will not be notified.
1541  * 3) Check with global policy to see whether it matches the constaints.
1542  *    But this will be done only if icmp_accept_messages_in_clear is
1543  *    zero.
1544  * 4) If we need to change both in IP and ULP, then the decision taken
1545  *    while affecting the values in IP and while delivering up to TCP
1546  *    should be the same.
1547  *
1548  * 	There are two cases.
1549  *
1550  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1551  *	   failed), we will not deliver it to the ULP, even though they
1552  *	   are *willing* to accept in *clear*. This is fine as our global
1553  *	   disposition to icmp messages asks us reject the datagram.
1554  *
1555  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1556  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1557  *	   to deliver it to ULP (policy failed), it can lead to
1558  *	   consistency problems. The cases known at this time are
1559  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1560  *	   values :
1561  *
1562  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1563  *	     and Upper layer rejects. Then the communication will
1564  *	     come to a stop. This is solved by making similar decisions
1565  *	     at both levels. Currently, when we are unable to deliver
1566  *	     to the Upper Layer (due to policy failures) while IP has
1567  *	     adjusted ire_max_frag, the next outbound datagram would
1568  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1569  *	     will be with the right level of protection. Thus the right
1570  *	     value will be communicated even if we are not able to
1571  *	     communicate when we get from the wire initially. But this
1572  *	     assumes there would be at least one outbound datagram after
1573  *	     IP has adjusted its ire_max_frag value. To make things
1574  *	     simpler, we accept in clear after the validation of
1575  *	     AH/ESP headers.
1576  *
1577  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1578  *	     upper layer depending on the level of protection the upper
1579  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1580  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1581  *	     should be accepted in clear when the Upper layer expects secure.
1582  *	     Thus the communication may get aborted by some bad ICMP
1583  *	     packets.
1584  *
1585  * IPQoS Notes:
1586  * The only instance when a packet is sent for processing is when there
1587  * isn't an ICMP client and if we are interested in it.
1588  * If there is a client, IPPF processing will take place in the
1589  * ip_fanout_proto routine.
1590  *
1591  * Zones notes:
1592  * The packet is only processed in the context of the specified zone: typically
1593  * only this zone will reply to an echo request, and only interested clients in
1594  * this zone will receive a copy of the packet. This means that the caller must
1595  * call icmp_inbound() for each relevant zone.
1596  */
1597 static void
1598 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1599     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1600     ill_t *recv_ill, zoneid_t zoneid)
1601 {
1602 	icmph_t	*icmph;
1603 	ipha_t	*ipha;
1604 	int	iph_hdr_length;
1605 	int	hdr_length;
1606 	boolean_t	interested;
1607 	uint32_t	ts;
1608 	uchar_t	*wptr;
1609 	ipif_t	*ipif;
1610 	mblk_t *first_mp;
1611 	ipsec_in_t *ii;
1612 	ire_t *src_ire;
1613 	boolean_t onlink;
1614 	timestruc_t now;
1615 	uint32_t ill_index;
1616 	ip_stack_t *ipst;
1617 
1618 	ASSERT(ill != NULL);
1619 	ipst = ill->ill_ipst;
1620 
1621 	first_mp = mp;
1622 	if (mctl_present) {
1623 		mp = first_mp->b_cont;
1624 		ASSERT(mp != NULL);
1625 	}
1626 
1627 	ipha = (ipha_t *)mp->b_rptr;
1628 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1629 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1630 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1631 		if (first_mp == NULL)
1632 			return;
1633 	}
1634 
1635 	/*
1636 	 * On a labeled system, we have to check whether the zone itself is
1637 	 * permitted to receive raw traffic.
1638 	 */
1639 	if (is_system_labeled()) {
1640 		if (zoneid == ALL_ZONES)
1641 			zoneid = tsol_packet_to_zoneid(mp);
1642 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1643 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1644 			    zoneid));
1645 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1646 			freemsg(first_mp);
1647 			return;
1648 		}
1649 	}
1650 
1651 	/*
1652 	 * We have accepted the ICMP message. It means that we will
1653 	 * respond to the packet if needed. It may not be delivered
1654 	 * to the upper client depending on the policy constraints
1655 	 * and the disposition in ipsec_inbound_accept_clear.
1656 	 */
1657 
1658 	ASSERT(ill != NULL);
1659 
1660 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1661 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1662 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1663 		/* Last chance to get real. */
1664 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1665 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1666 			freemsg(first_mp);
1667 			return;
1668 		}
1669 		/* Refresh iph following the pullup. */
1670 		ipha = (ipha_t *)mp->b_rptr;
1671 	}
1672 	/* ICMP header checksum, including checksum field, should be zero. */
1673 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1674 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1675 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1676 		freemsg(first_mp);
1677 		return;
1678 	}
1679 	/* The IP header will always be a multiple of four bytes */
1680 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1681 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1682 	    icmph->icmph_code));
1683 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1684 	/* We will set "interested" to "true" if we want a copy */
1685 	interested = B_FALSE;
1686 	switch (icmph->icmph_type) {
1687 	case ICMP_ECHO_REPLY:
1688 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1689 		break;
1690 	case ICMP_DEST_UNREACHABLE:
1691 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1692 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1693 		interested = B_TRUE;	/* Pass up to transport */
1694 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1695 		break;
1696 	case ICMP_SOURCE_QUENCH:
1697 		interested = B_TRUE;	/* Pass up to transport */
1698 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1699 		break;
1700 	case ICMP_REDIRECT:
1701 		if (!ipst->ips_ip_ignore_redirect)
1702 			interested = B_TRUE;
1703 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1704 		break;
1705 	case ICMP_ECHO_REQUEST:
1706 		/*
1707 		 * Whether to respond to echo requests that come in as IP
1708 		 * broadcasts or as IP multicast is subject to debate
1709 		 * (what isn't?).  We aim to please, you pick it.
1710 		 * Default is do it.
1711 		 */
1712 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1713 			/* unicast: always respond */
1714 			interested = B_TRUE;
1715 		} else if (CLASSD(ipha->ipha_dst)) {
1716 			/* multicast: respond based on tunable */
1717 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1718 		} else if (broadcast) {
1719 			/* broadcast: respond based on tunable */
1720 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1721 		}
1722 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1723 		break;
1724 	case ICMP_ROUTER_ADVERTISEMENT:
1725 	case ICMP_ROUTER_SOLICITATION:
1726 		break;
1727 	case ICMP_TIME_EXCEEDED:
1728 		interested = B_TRUE;	/* Pass up to transport */
1729 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1730 		break;
1731 	case ICMP_PARAM_PROBLEM:
1732 		interested = B_TRUE;	/* Pass up to transport */
1733 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1734 		break;
1735 	case ICMP_TIME_STAMP_REQUEST:
1736 		/* Response to Time Stamp Requests is local policy. */
1737 		if (ipst->ips_ip_g_resp_to_timestamp &&
1738 		    /* So is whether to respond if it was an IP broadcast. */
1739 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1740 			int tstamp_len = 3 * sizeof (uint32_t);
1741 
1742 			if (wptr +  tstamp_len > mp->b_wptr) {
1743 				if (!pullupmsg(mp, wptr + tstamp_len -
1744 				    mp->b_rptr)) {
1745 					BUMP_MIB(ill->ill_ip_mib,
1746 					    ipIfStatsInDiscards);
1747 					freemsg(first_mp);
1748 					return;
1749 				}
1750 				/* Refresh ipha following the pullup. */
1751 				ipha = (ipha_t *)mp->b_rptr;
1752 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1753 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1754 			}
1755 			interested = B_TRUE;
1756 		}
1757 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1758 		break;
1759 	case ICMP_TIME_STAMP_REPLY:
1760 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1761 		break;
1762 	case ICMP_INFO_REQUEST:
1763 		/* Per RFC 1122 3.2.2.7, ignore this. */
1764 	case ICMP_INFO_REPLY:
1765 		break;
1766 	case ICMP_ADDRESS_MASK_REQUEST:
1767 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1768 		    !broadcast) &&
1769 		    /* TODO m_pullup of complete header? */
1770 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN) {
1771 			interested = B_TRUE;
1772 		}
1773 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1774 		break;
1775 	case ICMP_ADDRESS_MASK_REPLY:
1776 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1777 		break;
1778 	default:
1779 		interested = B_TRUE;	/* Pass up to transport */
1780 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1781 		break;
1782 	}
1783 	/* See if there is an ICMP client. */
1784 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1785 		/* If there is an ICMP client and we want one too, copy it. */
1786 		mblk_t *first_mp1;
1787 
1788 		if (!interested) {
1789 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1790 			    ip_policy, recv_ill, zoneid);
1791 			return;
1792 		}
1793 		first_mp1 = ip_copymsg(first_mp);
1794 		if (first_mp1 != NULL) {
1795 			ip_fanout_proto(q, first_mp1, ill, ipha,
1796 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1797 		}
1798 	} else if (!interested) {
1799 		freemsg(first_mp);
1800 		return;
1801 	} else {
1802 		/*
1803 		 * Initiate policy processing for this packet if ip_policy
1804 		 * is true.
1805 		 */
1806 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1807 			ill_index = ill->ill_phyint->phyint_ifindex;
1808 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1809 			if (mp == NULL) {
1810 				if (mctl_present) {
1811 					freeb(first_mp);
1812 				}
1813 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1814 				return;
1815 			}
1816 		}
1817 	}
1818 	/* We want to do something with it. */
1819 	/* Check db_ref to make sure we can modify the packet. */
1820 	if (mp->b_datap->db_ref > 1) {
1821 		mblk_t	*first_mp1;
1822 
1823 		first_mp1 = ip_copymsg(first_mp);
1824 		freemsg(first_mp);
1825 		if (!first_mp1) {
1826 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1827 			return;
1828 		}
1829 		first_mp = first_mp1;
1830 		if (mctl_present) {
1831 			mp = first_mp->b_cont;
1832 			ASSERT(mp != NULL);
1833 		} else {
1834 			mp = first_mp;
1835 		}
1836 		ipha = (ipha_t *)mp->b_rptr;
1837 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1838 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1839 	}
1840 	switch (icmph->icmph_type) {
1841 	case ICMP_ADDRESS_MASK_REQUEST:
1842 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1843 		if (ipif == NULL) {
1844 			freemsg(first_mp);
1845 			return;
1846 		}
1847 		/*
1848 		 * outging interface must be IPv4
1849 		 */
1850 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1851 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1852 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1853 		ipif_refrele(ipif);
1854 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1855 		break;
1856 	case ICMP_ECHO_REQUEST:
1857 		icmph->icmph_type = ICMP_ECHO_REPLY;
1858 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1859 		break;
1860 	case ICMP_TIME_STAMP_REQUEST: {
1861 		uint32_t *tsp;
1862 
1863 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1864 		tsp = (uint32_t *)wptr;
1865 		tsp++;		/* Skip past 'originate time' */
1866 		/* Compute # of milliseconds since midnight */
1867 		gethrestime(&now);
1868 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1869 		    now.tv_nsec / (NANOSEC / MILLISEC);
1870 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1871 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1872 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1873 		break;
1874 	}
1875 	default:
1876 		ipha = (ipha_t *)&icmph[1];
1877 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1878 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1879 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1880 				freemsg(first_mp);
1881 				return;
1882 			}
1883 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1884 			ipha = (ipha_t *)&icmph[1];
1885 		}
1886 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1887 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1888 			freemsg(first_mp);
1889 			return;
1890 		}
1891 		hdr_length = IPH_HDR_LENGTH(ipha);
1892 		if (hdr_length < sizeof (ipha_t)) {
1893 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1894 			freemsg(first_mp);
1895 			return;
1896 		}
1897 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1898 			if (!pullupmsg(mp,
1899 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1900 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1901 				freemsg(first_mp);
1902 				return;
1903 			}
1904 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1905 			ipha = (ipha_t *)&icmph[1];
1906 		}
1907 		switch (icmph->icmph_type) {
1908 		case ICMP_REDIRECT:
1909 			/*
1910 			 * As there is no upper client to deliver, we don't
1911 			 * need the first_mp any more.
1912 			 */
1913 			if (mctl_present) {
1914 				freeb(first_mp);
1915 			}
1916 			icmp_redirect(ill, mp);
1917 			return;
1918 		case ICMP_DEST_UNREACHABLE:
1919 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1920 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1921 				    zoneid, mp, iph_hdr_length, ipst)) {
1922 					freemsg(first_mp);
1923 					return;
1924 				}
1925 				/*
1926 				 * icmp_inbound_too_big() may alter mp.
1927 				 * Resynch ipha and icmph accordingly.
1928 				 */
1929 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1930 				ipha = (ipha_t *)&icmph[1];
1931 			}
1932 			/* FALLTHRU */
1933 		default :
1934 			/*
1935 			 * IPQoS notes: Since we have already done IPQoS
1936 			 * processing we don't want to do it again in
1937 			 * the fanout routines called by
1938 			 * icmp_inbound_error_fanout, hence the last
1939 			 * argument, ip_policy, is B_FALSE.
1940 			 */
1941 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1942 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1943 			    B_FALSE, recv_ill, zoneid);
1944 		}
1945 		return;
1946 	}
1947 	/* Send out an ICMP packet */
1948 	icmph->icmph_checksum = 0;
1949 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1950 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1951 		ipif_t	*ipif_chosen;
1952 		/*
1953 		 * Make it look like it was directed to us, so we don't look
1954 		 * like a fool with a broadcast or multicast source address.
1955 		 */
1956 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1957 		/*
1958 		 * Make sure that we haven't grabbed an interface that's DOWN.
1959 		 */
1960 		if (ipif != NULL) {
1961 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
1962 			    ipha->ipha_src, zoneid);
1963 			if (ipif_chosen != NULL) {
1964 				ipif_refrele(ipif);
1965 				ipif = ipif_chosen;
1966 			}
1967 		}
1968 		if (ipif == NULL) {
1969 			ip0dbg(("icmp_inbound: "
1970 			    "No source for broadcast/multicast:\n"
1971 			    "\tsrc 0x%x dst 0x%x ill %p "
1972 			    "ipif_lcl_addr 0x%x\n",
1973 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
1974 			    (void *)ill,
1975 			    ill->ill_ipif->ipif_lcl_addr));
1976 			freemsg(first_mp);
1977 			return;
1978 		}
1979 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1980 		ipha->ipha_dst = ipif->ipif_src_addr;
1981 		ipif_refrele(ipif);
1982 	}
1983 	/* Reset time to live. */
1984 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1985 	{
1986 		/* Swap source and destination addresses */
1987 		ipaddr_t tmp;
1988 
1989 		tmp = ipha->ipha_src;
1990 		ipha->ipha_src = ipha->ipha_dst;
1991 		ipha->ipha_dst = tmp;
1992 	}
1993 	ipha->ipha_ident = 0;
1994 	if (!IS_SIMPLE_IPH(ipha))
1995 		icmp_options_update(ipha);
1996 
1997 	/*
1998 	 * ICMP echo replies should go out on the same interface
1999 	 * the request came on as probes used by in.mpathd for detecting
2000 	 * NIC failures are ECHO packets. We turn-off load spreading
2001 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
2002 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
2003 	 * function. This is in turn handled by ip_wput and ip_newroute
2004 	 * to make sure that the packet goes out on the interface it came
2005 	 * in on. If we don't turnoff load spreading, the packets might get
2006 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
2007 	 * to go out and in.mpathd would wrongly detect a failure or
2008 	 * mis-detect a NIC failure for link failure. As load spreading
2009 	 * can happen only if ill_group is not NULL, we do only for
2010 	 * that case and this does not affect the normal case.
2011 	 *
2012 	 * We turn off load spreading only on echo packets that came from
2013 	 * on-link hosts. If the interface route has been deleted, this will
2014 	 * not be enforced as we can't do much. For off-link hosts, as the
2015 	 * default routes in IPv4 does not typically have an ire_ipif
2016 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2017 	 * Moreover, expecting a default route through this interface may
2018 	 * not be correct. We use ipha_dst because of the swap above.
2019 	 */
2020 	onlink = B_FALSE;
2021 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2022 		/*
2023 		 * First, we need to make sure that it is not one of our
2024 		 * local addresses. If we set onlink when it is one of
2025 		 * our local addresses, we will end up creating IRE_CACHES
2026 		 * for one of our local addresses. Then, we will never
2027 		 * accept packets for them afterwards.
2028 		 */
2029 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2030 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2031 		if (src_ire == NULL) {
2032 			ipif = ipif_get_next_ipif(NULL, ill);
2033 			if (ipif == NULL) {
2034 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2035 				freemsg(mp);
2036 				return;
2037 			}
2038 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2039 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2040 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE, ipst);
2041 			ipif_refrele(ipif);
2042 			if (src_ire != NULL) {
2043 				onlink = B_TRUE;
2044 				ire_refrele(src_ire);
2045 			}
2046 		} else {
2047 			ire_refrele(src_ire);
2048 		}
2049 	}
2050 	if (!mctl_present) {
2051 		/*
2052 		 * This packet should go out the same way as it
2053 		 * came in i.e in clear. To make sure that global
2054 		 * policy will not be applied to this in ip_wput_ire,
2055 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2056 		 */
2057 		ASSERT(first_mp == mp);
2058 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2059 		if (first_mp == NULL) {
2060 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2061 			freemsg(mp);
2062 			return;
2063 		}
2064 		ii = (ipsec_in_t *)first_mp->b_rptr;
2065 
2066 		/* This is not a secure packet */
2067 		ii->ipsec_in_secure = B_FALSE;
2068 		if (onlink) {
2069 			ii->ipsec_in_attach_if = B_TRUE;
2070 			ii->ipsec_in_ill_index =
2071 			    ill->ill_phyint->phyint_ifindex;
2072 			ii->ipsec_in_rill_index =
2073 			    recv_ill->ill_phyint->phyint_ifindex;
2074 		}
2075 		first_mp->b_cont = mp;
2076 	} else if (onlink) {
2077 		ii = (ipsec_in_t *)first_mp->b_rptr;
2078 		ii->ipsec_in_attach_if = B_TRUE;
2079 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2080 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2081 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2082 	} else {
2083 		ii = (ipsec_in_t *)first_mp->b_rptr;
2084 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2085 	}
2086 	ii->ipsec_in_zoneid = zoneid;
2087 	ASSERT(zoneid != ALL_ZONES);
2088 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2089 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2090 		return;
2091 	}
2092 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2093 	put(WR(q), first_mp);
2094 }
2095 
2096 static ipaddr_t
2097 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2098 {
2099 	conn_t *connp;
2100 	connf_t *connfp;
2101 	ipaddr_t nexthop_addr = INADDR_ANY;
2102 	int hdr_length = IPH_HDR_LENGTH(ipha);
2103 	uint16_t *up;
2104 	uint32_t ports;
2105 	ip_stack_t *ipst = ill->ill_ipst;
2106 
2107 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2108 	switch (ipha->ipha_protocol) {
2109 		case IPPROTO_TCP:
2110 		{
2111 			tcph_t *tcph;
2112 
2113 			/* do a reverse lookup */
2114 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2115 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2116 			    TCPS_LISTEN, ipst);
2117 			break;
2118 		}
2119 		case IPPROTO_UDP:
2120 		{
2121 			uint32_t dstport, srcport;
2122 
2123 			((uint16_t *)&ports)[0] = up[1];
2124 			((uint16_t *)&ports)[1] = up[0];
2125 
2126 			/* Extract ports in net byte order */
2127 			dstport = htons(ntohl(ports) & 0xFFFF);
2128 			srcport = htons(ntohl(ports) >> 16);
2129 
2130 			connfp = &ipst->ips_ipcl_udp_fanout[
2131 			    IPCL_UDP_HASH(dstport, ipst)];
2132 			mutex_enter(&connfp->connf_lock);
2133 			connp = connfp->connf_head;
2134 
2135 			/* do a reverse lookup */
2136 			while ((connp != NULL) &&
2137 			    (!IPCL_UDP_MATCH(connp, dstport,
2138 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2139 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2140 				connp = connp->conn_next;
2141 			}
2142 			if (connp != NULL)
2143 				CONN_INC_REF(connp);
2144 			mutex_exit(&connfp->connf_lock);
2145 			break;
2146 		}
2147 		case IPPROTO_SCTP:
2148 		{
2149 			in6_addr_t map_src, map_dst;
2150 
2151 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2152 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2153 			((uint16_t *)&ports)[0] = up[1];
2154 			((uint16_t *)&ports)[1] = up[0];
2155 
2156 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2157 			    zoneid, ipst->ips_netstack->netstack_sctp);
2158 			if (connp == NULL) {
2159 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2160 				    zoneid, ports, ipha, ipst);
2161 			} else {
2162 				CONN_INC_REF(connp);
2163 				SCTP_REFRELE(CONN2SCTP(connp));
2164 			}
2165 			break;
2166 		}
2167 		default:
2168 		{
2169 			ipha_t ripha;
2170 
2171 			ripha.ipha_src = ipha->ipha_dst;
2172 			ripha.ipha_dst = ipha->ipha_src;
2173 			ripha.ipha_protocol = ipha->ipha_protocol;
2174 
2175 			connfp = &ipst->ips_ipcl_proto_fanout[
2176 			    ipha->ipha_protocol];
2177 			mutex_enter(&connfp->connf_lock);
2178 			connp = connfp->connf_head;
2179 			for (connp = connfp->connf_head; connp != NULL;
2180 			    connp = connp->conn_next) {
2181 				if (IPCL_PROTO_MATCH(connp,
2182 				    ipha->ipha_protocol, &ripha, ill,
2183 				    0, zoneid)) {
2184 					CONN_INC_REF(connp);
2185 					break;
2186 				}
2187 			}
2188 			mutex_exit(&connfp->connf_lock);
2189 		}
2190 	}
2191 	if (connp != NULL) {
2192 		if (connp->conn_nexthop_set)
2193 			nexthop_addr = connp->conn_nexthop_v4;
2194 		CONN_DEC_REF(connp);
2195 	}
2196 	return (nexthop_addr);
2197 }
2198 
2199 /* Table from RFC 1191 */
2200 static int icmp_frag_size_table[] =
2201 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2202 
2203 /*
2204  * Process received ICMP Packet too big.
2205  * After updating any IRE it does the fanout to any matching transport streams.
2206  * Assumes the message has been pulled up till the IP header that caused
2207  * the error.
2208  *
2209  * Returns B_FALSE on failure and B_TRUE on success.
2210  */
2211 static boolean_t
2212 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2213     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2214     ip_stack_t *ipst)
2215 {
2216 	ire_t	*ire, *first_ire;
2217 	int	mtu;
2218 	int	hdr_length;
2219 	ipaddr_t nexthop_addr;
2220 
2221 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2222 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2223 	ASSERT(ill != NULL);
2224 
2225 	hdr_length = IPH_HDR_LENGTH(ipha);
2226 
2227 	/* Drop if the original packet contained a source route */
2228 	if (ip_source_route_included(ipha)) {
2229 		return (B_FALSE);
2230 	}
2231 	/*
2232 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2233 	 * header.
2234 	 */
2235 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2236 	    mp->b_wptr) {
2237 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2238 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2239 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2240 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2241 			return (B_FALSE);
2242 		}
2243 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2244 		ipha = (ipha_t *)&icmph[1];
2245 	}
2246 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2247 	if (nexthop_addr != INADDR_ANY) {
2248 		/* nexthop set */
2249 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2250 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2251 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2252 	} else {
2253 		/* nexthop not set */
2254 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2255 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2256 	}
2257 
2258 	if (!first_ire) {
2259 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2260 		    ntohl(ipha->ipha_dst)));
2261 		return (B_FALSE);
2262 	}
2263 	/* Check for MTU discovery advice as described in RFC 1191 */
2264 	mtu = ntohs(icmph->icmph_du_mtu);
2265 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2266 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2267 	    ire = ire->ire_next) {
2268 		/*
2269 		 * Look for the connection to which this ICMP message is
2270 		 * directed. If it has the IP_NEXTHOP option set, then the
2271 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2272 		 * option. Else the search is limited to regular IREs.
2273 		 */
2274 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2275 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2276 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2277 		    (nexthop_addr != INADDR_ANY)))
2278 			continue;
2279 
2280 		mutex_enter(&ire->ire_lock);
2281 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2282 			/* Reduce the IRE max frag value as advised. */
2283 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2284 			    mtu, ire->ire_max_frag));
2285 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2286 		} else {
2287 			uint32_t length;
2288 			int	i;
2289 
2290 			/*
2291 			 * Use the table from RFC 1191 to figure out
2292 			 * the next "plateau" based on the length in
2293 			 * the original IP packet.
2294 			 */
2295 			length = ntohs(ipha->ipha_length);
2296 			if (ire->ire_max_frag <= length &&
2297 			    ire->ire_max_frag >= length - hdr_length) {
2298 				/*
2299 				 * Handle broken BSD 4.2 systems that
2300 				 * return the wrong iph_length in ICMP
2301 				 * errors.
2302 				 */
2303 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2304 				    length, ire->ire_max_frag));
2305 				length -= hdr_length;
2306 			}
2307 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2308 				if (length > icmp_frag_size_table[i])
2309 					break;
2310 			}
2311 			if (i == A_CNT(icmp_frag_size_table)) {
2312 				/* Smaller than 68! */
2313 				ip1dbg(("Too big for packet size %d\n",
2314 				    length));
2315 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2316 				ire->ire_frag_flag = 0;
2317 			} else {
2318 				mtu = icmp_frag_size_table[i];
2319 				ip1dbg(("Calculated mtu %d, packet size %d, "
2320 				    "before %d", mtu, length,
2321 				    ire->ire_max_frag));
2322 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2323 				ip1dbg((", after %d\n", ire->ire_max_frag));
2324 			}
2325 			/* Record the new max frag size for the ULP. */
2326 			icmph->icmph_du_zero = 0;
2327 			icmph->icmph_du_mtu =
2328 			    htons((uint16_t)ire->ire_max_frag);
2329 		}
2330 		mutex_exit(&ire->ire_lock);
2331 	}
2332 	rw_exit(&first_ire->ire_bucket->irb_lock);
2333 	ire_refrele(first_ire);
2334 	return (B_TRUE);
2335 }
2336 
2337 /*
2338  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2339  * calls this function.
2340  */
2341 static mblk_t *
2342 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2343 {
2344 	ipha_t *ipha;
2345 	icmph_t *icmph;
2346 	ipha_t *in_ipha;
2347 	int length;
2348 
2349 	ASSERT(mp->b_datap->db_type == M_DATA);
2350 
2351 	/*
2352 	 * For Self-encapsulated packets, we added an extra IP header
2353 	 * without the options. Inner IP header is the one from which
2354 	 * the outer IP header was formed. Thus, we need to remove the
2355 	 * outer IP header. To do this, we pullup the whole message
2356 	 * and overlay whatever follows the outer IP header over the
2357 	 * outer IP header.
2358 	 */
2359 
2360 	if (!pullupmsg(mp, -1))
2361 		return (NULL);
2362 
2363 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2364 	ipha = (ipha_t *)&icmph[1];
2365 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2366 
2367 	/*
2368 	 * The length that we want to overlay is following the inner
2369 	 * IP header. Subtracting the IP header + icmp header + outer
2370 	 * IP header's length should give us the length that we want to
2371 	 * overlay.
2372 	 */
2373 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2374 	    hdr_length;
2375 	/*
2376 	 * Overlay whatever follows the inner header over the
2377 	 * outer header.
2378 	 */
2379 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2380 
2381 	/* Set the wptr to account for the outer header */
2382 	mp->b_wptr -= hdr_length;
2383 	return (mp);
2384 }
2385 
2386 /*
2387  * Try to pass the ICMP message upstream in case the ULP cares.
2388  *
2389  * If the packet that caused the ICMP error is secure, we send
2390  * it to AH/ESP to make sure that the attached packet has a
2391  * valid association. ipha in the code below points to the
2392  * IP header of the packet that caused the error.
2393  *
2394  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2395  * in the context of IPsec. Normally we tell the upper layer
2396  * whenever we send the ire (including ip_bind), the IPsec header
2397  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2398  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2399  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2400  * same thing. As TCP has the IPsec options size that needs to be
2401  * adjusted, we just pass the MTU unchanged.
2402  *
2403  * IFN could have been generated locally or by some router.
2404  *
2405  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2406  *	    This happens because IP adjusted its value of MTU on an
2407  *	    earlier IFN message and could not tell the upper layer,
2408  *	    the new adjusted value of MTU e.g. Packet was encrypted
2409  *	    or there was not enough information to fanout to upper
2410  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2411  *	    generates the IFN, where IPsec processing has *not* been
2412  *	    done.
2413  *
2414  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2415  *	    could have generated this. This happens because ire_max_frag
2416  *	    value in IP was set to a new value, while the IPsec processing
2417  *	    was being done and after we made the fragmentation check in
2418  *	    ip_wput_ire. Thus on return from IPsec processing,
2419  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2420  *	    and generates the IFN. As IPsec processing is over, we fanout
2421  *	    to AH/ESP to remove the header.
2422  *
2423  *	    In both these cases, ipsec_in_loopback will be set indicating
2424  *	    that IFN was generated locally.
2425  *
2426  * ROUTER : IFN could be secure or non-secure.
2427  *
2428  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2429  *	      packet in error has AH/ESP headers to validate the AH/ESP
2430  *	      headers. AH/ESP will verify whether there is a valid SA or
2431  *	      not and send it back. We will fanout again if we have more
2432  *	      data in the packet.
2433  *
2434  *	      If the packet in error does not have AH/ESP, we handle it
2435  *	      like any other case.
2436  *
2437  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2438  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2439  *	      for validation. AH/ESP will verify whether there is a
2440  *	      valid SA or not and send it back. We will fanout again if
2441  *	      we have more data in the packet.
2442  *
2443  *	      If the packet in error does not have AH/ESP, we handle it
2444  *	      like any other case.
2445  */
2446 static void
2447 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2448     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2449     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2450     zoneid_t zoneid)
2451 {
2452 	uint16_t *up;	/* Pointer to ports in ULP header */
2453 	uint32_t ports;	/* reversed ports for fanout */
2454 	ipha_t ripha;	/* With reversed addresses */
2455 	mblk_t *first_mp;
2456 	ipsec_in_t *ii;
2457 	tcph_t	*tcph;
2458 	conn_t	*connp;
2459 	ip_stack_t *ipst;
2460 
2461 	ASSERT(ill != NULL);
2462 
2463 	ASSERT(recv_ill != NULL);
2464 	ipst = recv_ill->ill_ipst;
2465 
2466 	first_mp = mp;
2467 	if (mctl_present) {
2468 		mp = first_mp->b_cont;
2469 		ASSERT(mp != NULL);
2470 
2471 		ii = (ipsec_in_t *)first_mp->b_rptr;
2472 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2473 	} else {
2474 		ii = NULL;
2475 	}
2476 
2477 	switch (ipha->ipha_protocol) {
2478 	case IPPROTO_UDP:
2479 		/*
2480 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2481 		 * transport header.
2482 		 */
2483 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2484 		    mp->b_wptr) {
2485 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2486 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2487 				goto discard_pkt;
2488 			}
2489 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2490 			ipha = (ipha_t *)&icmph[1];
2491 		}
2492 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2493 
2494 		/*
2495 		 * Attempt to find a client stream based on port.
2496 		 * Note that we do a reverse lookup since the header is
2497 		 * in the form we sent it out.
2498 		 * The ripha header is only used for the IP_UDP_MATCH and we
2499 		 * only set the src and dst addresses and protocol.
2500 		 */
2501 		ripha.ipha_src = ipha->ipha_dst;
2502 		ripha.ipha_dst = ipha->ipha_src;
2503 		ripha.ipha_protocol = ipha->ipha_protocol;
2504 		((uint16_t *)&ports)[0] = up[1];
2505 		((uint16_t *)&ports)[1] = up[0];
2506 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2507 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2508 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2509 		    icmph->icmph_type, icmph->icmph_code));
2510 
2511 		/* Have to change db_type after any pullupmsg */
2512 		DB_TYPE(mp) = M_CTL;
2513 
2514 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2515 		    mctl_present, ip_policy, recv_ill, zoneid);
2516 		return;
2517 
2518 	case IPPROTO_TCP:
2519 		/*
2520 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2521 		 * transport header.
2522 		 */
2523 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2524 		    mp->b_wptr) {
2525 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2526 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2527 				goto discard_pkt;
2528 			}
2529 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2530 			ipha = (ipha_t *)&icmph[1];
2531 		}
2532 		/*
2533 		 * Find a TCP client stream for this packet.
2534 		 * Note that we do a reverse lookup since the header is
2535 		 * in the form we sent it out.
2536 		 */
2537 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2538 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2539 		    ipst);
2540 		if (connp == NULL)
2541 			goto discard_pkt;
2542 
2543 		/* Have to change db_type after any pullupmsg */
2544 		DB_TYPE(mp) = M_CTL;
2545 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2546 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2547 		return;
2548 
2549 	case IPPROTO_SCTP:
2550 		/*
2551 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2552 		 * transport header.
2553 		 */
2554 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2555 		    mp->b_wptr) {
2556 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2557 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2558 				goto discard_pkt;
2559 			}
2560 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2561 			ipha = (ipha_t *)&icmph[1];
2562 		}
2563 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2564 		/*
2565 		 * Find a SCTP client stream for this packet.
2566 		 * Note that we do a reverse lookup since the header is
2567 		 * in the form we sent it out.
2568 		 * The ripha header is only used for the matching and we
2569 		 * only set the src and dst addresses, protocol, and version.
2570 		 */
2571 		ripha.ipha_src = ipha->ipha_dst;
2572 		ripha.ipha_dst = ipha->ipha_src;
2573 		ripha.ipha_protocol = ipha->ipha_protocol;
2574 		ripha.ipha_version_and_hdr_length =
2575 		    ipha->ipha_version_and_hdr_length;
2576 		((uint16_t *)&ports)[0] = up[1];
2577 		((uint16_t *)&ports)[1] = up[0];
2578 
2579 		/* Have to change db_type after any pullupmsg */
2580 		DB_TYPE(mp) = M_CTL;
2581 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2582 		    mctl_present, ip_policy, zoneid);
2583 		return;
2584 
2585 	case IPPROTO_ESP:
2586 	case IPPROTO_AH: {
2587 		int ipsec_rc;
2588 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2589 
2590 		/*
2591 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2592 		 * We will re-use the IPSEC_IN if it is already present as
2593 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2594 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2595 		 * one and attach it in the front.
2596 		 */
2597 		if (ii != NULL) {
2598 			/*
2599 			 * ip_fanout_proto_again converts the ICMP errors
2600 			 * that come back from AH/ESP to M_DATA so that
2601 			 * if it is non-AH/ESP and we do a pullupmsg in
2602 			 * this function, it would work. Convert it back
2603 			 * to M_CTL before we send up as this is a ICMP
2604 			 * error. This could have been generated locally or
2605 			 * by some router. Validate the inner IPsec
2606 			 * headers.
2607 			 *
2608 			 * NOTE : ill_index is used by ip_fanout_proto_again
2609 			 * to locate the ill.
2610 			 */
2611 			ASSERT(ill != NULL);
2612 			ii->ipsec_in_ill_index =
2613 			    ill->ill_phyint->phyint_ifindex;
2614 			ii->ipsec_in_rill_index =
2615 			    recv_ill->ill_phyint->phyint_ifindex;
2616 			DB_TYPE(first_mp->b_cont) = M_CTL;
2617 		} else {
2618 			/*
2619 			 * IPSEC_IN is not present. We attach a ipsec_in
2620 			 * message and send up to IPsec for validating
2621 			 * and removing the IPsec headers. Clear
2622 			 * ipsec_in_secure so that when we return
2623 			 * from IPsec, we don't mistakenly think that this
2624 			 * is a secure packet came from the network.
2625 			 *
2626 			 * NOTE : ill_index is used by ip_fanout_proto_again
2627 			 * to locate the ill.
2628 			 */
2629 			ASSERT(first_mp == mp);
2630 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2631 			if (first_mp == NULL) {
2632 				freemsg(mp);
2633 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2634 				return;
2635 			}
2636 			ii = (ipsec_in_t *)first_mp->b_rptr;
2637 
2638 			/* This is not a secure packet */
2639 			ii->ipsec_in_secure = B_FALSE;
2640 			first_mp->b_cont = mp;
2641 			DB_TYPE(mp) = M_CTL;
2642 			ASSERT(ill != NULL);
2643 			ii->ipsec_in_ill_index =
2644 			    ill->ill_phyint->phyint_ifindex;
2645 			ii->ipsec_in_rill_index =
2646 			    recv_ill->ill_phyint->phyint_ifindex;
2647 		}
2648 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2649 
2650 		if (!ipsec_loaded(ipss)) {
2651 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2652 			return;
2653 		}
2654 
2655 		if (ipha->ipha_protocol == IPPROTO_ESP)
2656 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2657 		else
2658 			ipsec_rc = ipsecah_icmp_error(first_mp);
2659 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2660 			return;
2661 
2662 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2663 		return;
2664 	}
2665 	default:
2666 		/*
2667 		 * The ripha header is only used for the lookup and we
2668 		 * only set the src and dst addresses and protocol.
2669 		 */
2670 		ripha.ipha_src = ipha->ipha_dst;
2671 		ripha.ipha_dst = ipha->ipha_src;
2672 		ripha.ipha_protocol = ipha->ipha_protocol;
2673 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2674 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2675 		    ntohl(ipha->ipha_dst),
2676 		    icmph->icmph_type, icmph->icmph_code));
2677 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2678 			ipha_t *in_ipha;
2679 
2680 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2681 			    mp->b_wptr) {
2682 				if (!pullupmsg(mp, (uchar_t *)ipha +
2683 				    hdr_length + sizeof (ipha_t) -
2684 				    mp->b_rptr)) {
2685 					goto discard_pkt;
2686 				}
2687 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2688 				ipha = (ipha_t *)&icmph[1];
2689 			}
2690 			/*
2691 			 * Caller has verified that length has to be
2692 			 * at least the size of IP header.
2693 			 */
2694 			ASSERT(hdr_length >= sizeof (ipha_t));
2695 			/*
2696 			 * Check the sanity of the inner IP header like
2697 			 * we did for the outer header.
2698 			 */
2699 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2700 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2701 				goto discard_pkt;
2702 			}
2703 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2704 				goto discard_pkt;
2705 			}
2706 			/* Check for Self-encapsulated tunnels */
2707 			if (in_ipha->ipha_src == ipha->ipha_src &&
2708 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2709 
2710 				mp = icmp_inbound_self_encap_error(mp,
2711 				    iph_hdr_length, hdr_length);
2712 				if (mp == NULL)
2713 					goto discard_pkt;
2714 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2715 				ipha = (ipha_t *)&icmph[1];
2716 				hdr_length = IPH_HDR_LENGTH(ipha);
2717 				/*
2718 				 * The packet in error is self-encapsualted.
2719 				 * And we are finding it further encapsulated
2720 				 * which we could not have possibly generated.
2721 				 */
2722 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2723 					goto discard_pkt;
2724 				}
2725 				icmp_inbound_error_fanout(q, ill, first_mp,
2726 				    icmph, ipha, iph_hdr_length, hdr_length,
2727 				    mctl_present, ip_policy, recv_ill, zoneid);
2728 				return;
2729 			}
2730 		}
2731 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2732 		    ipha->ipha_protocol == IPPROTO_IPV6) &&
2733 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2734 		    ii != NULL &&
2735 		    ii->ipsec_in_loopback &&
2736 		    ii->ipsec_in_secure) {
2737 			/*
2738 			 * For IP tunnels that get a looped-back
2739 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2740 			 * reported new MTU to take into account the IPsec
2741 			 * headers protecting this configured tunnel.
2742 			 *
2743 			 * This allows the tunnel module (tun.c) to blindly
2744 			 * accept the MTU reported in an ICMP "too big"
2745 			 * message.
2746 			 *
2747 			 * Non-looped back ICMP messages will just be
2748 			 * handled by the security protocols (if needed),
2749 			 * and the first subsequent packet will hit this
2750 			 * path.
2751 			 */
2752 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2753 			    ipsec_in_extra_length(first_mp));
2754 		}
2755 		/* Have to change db_type after any pullupmsg */
2756 		DB_TYPE(mp) = M_CTL;
2757 
2758 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2759 		    ip_policy, recv_ill, zoneid);
2760 		return;
2761 	}
2762 	/* NOTREACHED */
2763 discard_pkt:
2764 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2765 drop_pkt:;
2766 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2767 	freemsg(first_mp);
2768 }
2769 
2770 /*
2771  * Common IP options parser.
2772  *
2773  * Setup routine: fill in *optp with options-parsing state, then
2774  * tail-call ipoptp_next to return the first option.
2775  */
2776 uint8_t
2777 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2778 {
2779 	uint32_t totallen; /* total length of all options */
2780 
2781 	totallen = ipha->ipha_version_and_hdr_length -
2782 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2783 	totallen <<= 2;
2784 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2785 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2786 	optp->ipoptp_flags = 0;
2787 	return (ipoptp_next(optp));
2788 }
2789 
2790 /*
2791  * Common IP options parser: extract next option.
2792  */
2793 uint8_t
2794 ipoptp_next(ipoptp_t *optp)
2795 {
2796 	uint8_t *end = optp->ipoptp_end;
2797 	uint8_t *cur = optp->ipoptp_next;
2798 	uint8_t opt, len, pointer;
2799 
2800 	/*
2801 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2802 	 * has been corrupted.
2803 	 */
2804 	ASSERT(cur <= end);
2805 
2806 	if (cur == end)
2807 		return (IPOPT_EOL);
2808 
2809 	opt = cur[IPOPT_OPTVAL];
2810 
2811 	/*
2812 	 * Skip any NOP options.
2813 	 */
2814 	while (opt == IPOPT_NOP) {
2815 		cur++;
2816 		if (cur == end)
2817 			return (IPOPT_EOL);
2818 		opt = cur[IPOPT_OPTVAL];
2819 	}
2820 
2821 	if (opt == IPOPT_EOL)
2822 		return (IPOPT_EOL);
2823 
2824 	/*
2825 	 * Option requiring a length.
2826 	 */
2827 	if ((cur + 1) >= end) {
2828 		optp->ipoptp_flags |= IPOPTP_ERROR;
2829 		return (IPOPT_EOL);
2830 	}
2831 	len = cur[IPOPT_OLEN];
2832 	if (len < 2) {
2833 		optp->ipoptp_flags |= IPOPTP_ERROR;
2834 		return (IPOPT_EOL);
2835 	}
2836 	optp->ipoptp_cur = cur;
2837 	optp->ipoptp_len = len;
2838 	optp->ipoptp_next = cur + len;
2839 	if (cur + len > end) {
2840 		optp->ipoptp_flags |= IPOPTP_ERROR;
2841 		return (IPOPT_EOL);
2842 	}
2843 
2844 	/*
2845 	 * For the options which require a pointer field, make sure
2846 	 * its there, and make sure it points to either something
2847 	 * inside this option, or the end of the option.
2848 	 */
2849 	switch (opt) {
2850 	case IPOPT_RR:
2851 	case IPOPT_TS:
2852 	case IPOPT_LSRR:
2853 	case IPOPT_SSRR:
2854 		if (len <= IPOPT_OFFSET) {
2855 			optp->ipoptp_flags |= IPOPTP_ERROR;
2856 			return (opt);
2857 		}
2858 		pointer = cur[IPOPT_OFFSET];
2859 		if (pointer - 1 > len) {
2860 			optp->ipoptp_flags |= IPOPTP_ERROR;
2861 			return (opt);
2862 		}
2863 		break;
2864 	}
2865 
2866 	/*
2867 	 * Sanity check the pointer field based on the type of the
2868 	 * option.
2869 	 */
2870 	switch (opt) {
2871 	case IPOPT_RR:
2872 	case IPOPT_SSRR:
2873 	case IPOPT_LSRR:
2874 		if (pointer < IPOPT_MINOFF_SR)
2875 			optp->ipoptp_flags |= IPOPTP_ERROR;
2876 		break;
2877 	case IPOPT_TS:
2878 		if (pointer < IPOPT_MINOFF_IT)
2879 			optp->ipoptp_flags |= IPOPTP_ERROR;
2880 		/*
2881 		 * Note that the Internet Timestamp option also
2882 		 * contains two four bit fields (the Overflow field,
2883 		 * and the Flag field), which follow the pointer
2884 		 * field.  We don't need to check that these fields
2885 		 * fall within the length of the option because this
2886 		 * was implicitely done above.  We've checked that the
2887 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2888 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2889 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2890 		 */
2891 		ASSERT(len > IPOPT_POS_OV_FLG);
2892 		break;
2893 	}
2894 
2895 	return (opt);
2896 }
2897 
2898 /*
2899  * Use the outgoing IP header to create an IP_OPTIONS option the way
2900  * it was passed down from the application.
2901  */
2902 int
2903 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2904 {
2905 	ipoptp_t	opts;
2906 	const uchar_t	*opt;
2907 	uint8_t		optval;
2908 	uint8_t		optlen;
2909 	uint32_t	len = 0;
2910 	uchar_t	*buf1 = buf;
2911 
2912 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2913 	len += IP_ADDR_LEN;
2914 	bzero(buf1, IP_ADDR_LEN);
2915 
2916 	/*
2917 	 * OK to cast away const here, as we don't store through the returned
2918 	 * opts.ipoptp_cur pointer.
2919 	 */
2920 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2921 	    optval != IPOPT_EOL;
2922 	    optval = ipoptp_next(&opts)) {
2923 		int	off;
2924 
2925 		opt = opts.ipoptp_cur;
2926 		optlen = opts.ipoptp_len;
2927 		switch (optval) {
2928 		case IPOPT_SSRR:
2929 		case IPOPT_LSRR:
2930 
2931 			/*
2932 			 * Insert ipha_dst as the first entry in the source
2933 			 * route and move down the entries on step.
2934 			 * The last entry gets placed at buf1.
2935 			 */
2936 			buf[IPOPT_OPTVAL] = optval;
2937 			buf[IPOPT_OLEN] = optlen;
2938 			buf[IPOPT_OFFSET] = optlen;
2939 
2940 			off = optlen - IP_ADDR_LEN;
2941 			if (off < 0) {
2942 				/* No entries in source route */
2943 				break;
2944 			}
2945 			/* Last entry in source route */
2946 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2947 			off -= IP_ADDR_LEN;
2948 
2949 			while (off > 0) {
2950 				bcopy(opt + off,
2951 				    buf + off + IP_ADDR_LEN,
2952 				    IP_ADDR_LEN);
2953 				off -= IP_ADDR_LEN;
2954 			}
2955 			/* ipha_dst into first slot */
2956 			bcopy(&ipha->ipha_dst,
2957 			    buf + off + IP_ADDR_LEN,
2958 			    IP_ADDR_LEN);
2959 			buf += optlen;
2960 			len += optlen;
2961 			break;
2962 
2963 		case IPOPT_COMSEC:
2964 		case IPOPT_SECURITY:
2965 			/* if passing up a label is not ok, then remove */
2966 			if (is_system_labeled())
2967 				break;
2968 			/* FALLTHROUGH */
2969 		default:
2970 			bcopy(opt, buf, optlen);
2971 			buf += optlen;
2972 			len += optlen;
2973 			break;
2974 		}
2975 	}
2976 done:
2977 	/* Pad the resulting options */
2978 	while (len & 0x3) {
2979 		*buf++ = IPOPT_EOL;
2980 		len++;
2981 	}
2982 	return (len);
2983 }
2984 
2985 /*
2986  * Update any record route or timestamp options to include this host.
2987  * Reverse any source route option.
2988  * This routine assumes that the options are well formed i.e. that they
2989  * have already been checked.
2990  */
2991 static void
2992 icmp_options_update(ipha_t *ipha)
2993 {
2994 	ipoptp_t	opts;
2995 	uchar_t		*opt;
2996 	uint8_t		optval;
2997 	ipaddr_t	src;		/* Our local address */
2998 	ipaddr_t	dst;
2999 
3000 	ip2dbg(("icmp_options_update\n"));
3001 	src = ipha->ipha_src;
3002 	dst = ipha->ipha_dst;
3003 
3004 	for (optval = ipoptp_first(&opts, ipha);
3005 	    optval != IPOPT_EOL;
3006 	    optval = ipoptp_next(&opts)) {
3007 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
3008 		opt = opts.ipoptp_cur;
3009 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
3010 		    optval, opts.ipoptp_len));
3011 		switch (optval) {
3012 			int off1, off2;
3013 		case IPOPT_SSRR:
3014 		case IPOPT_LSRR:
3015 			/*
3016 			 * Reverse the source route.  The first entry
3017 			 * should be the next to last one in the current
3018 			 * source route (the last entry is our address).
3019 			 * The last entry should be the final destination.
3020 			 */
3021 			off1 = IPOPT_MINOFF_SR - 1;
3022 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3023 			if (off2 < 0) {
3024 				/* No entries in source route */
3025 				ip1dbg((
3026 				    "icmp_options_update: bad src route\n"));
3027 				break;
3028 			}
3029 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3030 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3031 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3032 			off2 -= IP_ADDR_LEN;
3033 
3034 			while (off1 < off2) {
3035 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3036 				bcopy((char *)opt + off2, (char *)opt + off1,
3037 				    IP_ADDR_LEN);
3038 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3039 				off1 += IP_ADDR_LEN;
3040 				off2 -= IP_ADDR_LEN;
3041 			}
3042 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3043 			break;
3044 		}
3045 	}
3046 }
3047 
3048 /*
3049  * Process received ICMP Redirect messages.
3050  */
3051 static void
3052 icmp_redirect(ill_t *ill, mblk_t *mp)
3053 {
3054 	ipha_t	*ipha;
3055 	int	iph_hdr_length;
3056 	icmph_t	*icmph;
3057 	ipha_t	*ipha_err;
3058 	ire_t	*ire;
3059 	ire_t	*prev_ire;
3060 	ire_t	*save_ire;
3061 	ipaddr_t  src, dst, gateway;
3062 	iulp_t	ulp_info = { 0 };
3063 	int	error;
3064 	ip_stack_t *ipst;
3065 
3066 	ASSERT(ill != NULL);
3067 	ipst = ill->ill_ipst;
3068 
3069 	ipha = (ipha_t *)mp->b_rptr;
3070 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3071 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3072 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3073 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3074 		freemsg(mp);
3075 		return;
3076 	}
3077 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3078 	ipha_err = (ipha_t *)&icmph[1];
3079 	src = ipha->ipha_src;
3080 	dst = ipha_err->ipha_dst;
3081 	gateway = icmph->icmph_rd_gateway;
3082 	/* Make sure the new gateway is reachable somehow. */
3083 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3084 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3085 	/*
3086 	 * Make sure we had a route for the dest in question and that
3087 	 * that route was pointing to the old gateway (the source of the
3088 	 * redirect packet.)
3089 	 */
3090 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3091 	    NULL, MATCH_IRE_GW, ipst);
3092 	/*
3093 	 * Check that
3094 	 *	the redirect was not from ourselves
3095 	 *	the new gateway and the old gateway are directly reachable
3096 	 */
3097 	if (!prev_ire ||
3098 	    !ire ||
3099 	    ire->ire_type == IRE_LOCAL) {
3100 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3101 		freemsg(mp);
3102 		if (ire != NULL)
3103 			ire_refrele(ire);
3104 		if (prev_ire != NULL)
3105 			ire_refrele(prev_ire);
3106 		return;
3107 	}
3108 
3109 	/*
3110 	 * Should we use the old ULP info to create the new gateway?  From
3111 	 * a user's perspective, we should inherit the info so that it
3112 	 * is a "smooth" transition.  If we do not do that, then new
3113 	 * connections going thru the new gateway will have no route metrics,
3114 	 * which is counter-intuitive to user.  From a network point of
3115 	 * view, this may or may not make sense even though the new gateway
3116 	 * is still directly connected to us so the route metrics should not
3117 	 * change much.
3118 	 *
3119 	 * But if the old ire_uinfo is not initialized, we do another
3120 	 * recursive lookup on the dest using the new gateway.  There may
3121 	 * be a route to that.  If so, use it to initialize the redirect
3122 	 * route.
3123 	 */
3124 	if (prev_ire->ire_uinfo.iulp_set) {
3125 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3126 	} else {
3127 		ire_t *tmp_ire;
3128 		ire_t *sire;
3129 
3130 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3131 		    ALL_ZONES, 0, NULL,
3132 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3133 		    ipst);
3134 		if (sire != NULL) {
3135 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3136 			/*
3137 			 * If sire != NULL, ire_ftable_lookup() should not
3138 			 * return a NULL value.
3139 			 */
3140 			ASSERT(tmp_ire != NULL);
3141 			ire_refrele(tmp_ire);
3142 			ire_refrele(sire);
3143 		} else if (tmp_ire != NULL) {
3144 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3145 			    sizeof (iulp_t));
3146 			ire_refrele(tmp_ire);
3147 		}
3148 	}
3149 	if (prev_ire->ire_type == IRE_CACHE)
3150 		ire_delete(prev_ire);
3151 	ire_refrele(prev_ire);
3152 	/*
3153 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3154 	 * require TOS routing
3155 	 */
3156 	switch (icmph->icmph_code) {
3157 	case 0:
3158 	case 1:
3159 		/* TODO: TOS specificity for cases 2 and 3 */
3160 	case 2:
3161 	case 3:
3162 		break;
3163 	default:
3164 		freemsg(mp);
3165 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3166 		ire_refrele(ire);
3167 		return;
3168 	}
3169 	/*
3170 	 * Create a Route Association.  This will allow us to remember that
3171 	 * someone we believe told us to use the particular gateway.
3172 	 */
3173 	save_ire = ire;
3174 	ire = ire_create(
3175 	    (uchar_t *)&dst,			/* dest addr */
3176 	    (uchar_t *)&ip_g_all_ones,		/* mask */
3177 	    (uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3178 	    (uchar_t *)&gateway,		/* gateway addr */
3179 	    &save_ire->ire_max_frag,		/* max frag */
3180 	    NULL,				/* no src nce */
3181 	    NULL,				/* no rfq */
3182 	    NULL,				/* no stq */
3183 	    IRE_HOST,
3184 	    NULL,				/* ipif */
3185 	    0,					/* cmask */
3186 	    0,					/* phandle */
3187 	    0,					/* ihandle */
3188 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3189 	    &ulp_info,
3190 	    NULL,				/* tsol_gc_t */
3191 	    NULL,				/* gcgrp */
3192 	    ipst);
3193 
3194 	if (ire == NULL) {
3195 		freemsg(mp);
3196 		ire_refrele(save_ire);
3197 		return;
3198 	}
3199 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3200 	ire_refrele(save_ire);
3201 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3202 
3203 	if (error == 0) {
3204 		ire_refrele(ire);		/* Held in ire_add_v4 */
3205 		/* tell routing sockets that we received a redirect */
3206 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3207 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3208 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3209 	}
3210 
3211 	/*
3212 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3213 	 * This together with the added IRE has the effect of
3214 	 * modifying an existing redirect.
3215 	 */
3216 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3217 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3218 	if (prev_ire != NULL) {
3219 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3220 			ire_delete(prev_ire);
3221 		ire_refrele(prev_ire);
3222 	}
3223 
3224 	freemsg(mp);
3225 }
3226 
3227 /*
3228  * Generate an ICMP parameter problem message.
3229  */
3230 static void
3231 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3232 	ip_stack_t *ipst)
3233 {
3234 	icmph_t	icmph;
3235 	boolean_t mctl_present;
3236 	mblk_t *first_mp;
3237 
3238 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3239 
3240 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3241 		if (mctl_present)
3242 			freeb(first_mp);
3243 		return;
3244 	}
3245 
3246 	bzero(&icmph, sizeof (icmph_t));
3247 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3248 	icmph.icmph_pp_ptr = ptr;
3249 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3250 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3251 	    ipst);
3252 }
3253 
3254 /*
3255  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3256  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3257  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3258  * an icmp error packet can be sent.
3259  * Assigns an appropriate source address to the packet. If ipha_dst is
3260  * one of our addresses use it for source. Otherwise pick a source based
3261  * on a route lookup back to ipha_src.
3262  * Note that ipha_src must be set here since the
3263  * packet is likely to arrive on an ill queue in ip_wput() which will
3264  * not set a source address.
3265  */
3266 static void
3267 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3268     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3269 {
3270 	ipaddr_t dst;
3271 	icmph_t	*icmph;
3272 	ipha_t	*ipha;
3273 	uint_t	len_needed;
3274 	size_t	msg_len;
3275 	mblk_t	*mp1;
3276 	ipaddr_t src;
3277 	ire_t	*ire;
3278 	mblk_t *ipsec_mp;
3279 	ipsec_out_t	*io = NULL;
3280 
3281 	if (mctl_present) {
3282 		/*
3283 		 * If it is :
3284 		 *
3285 		 * 1) a IPSEC_OUT, then this is caused by outbound
3286 		 *    datagram originating on this host. IPsec processing
3287 		 *    may or may not have been done. Refer to comments above
3288 		 *    icmp_inbound_error_fanout for details.
3289 		 *
3290 		 * 2) a IPSEC_IN if we are generating a icmp_message
3291 		 *    for an incoming datagram destined for us i.e called
3292 		 *    from ip_fanout_send_icmp.
3293 		 */
3294 		ipsec_info_t *in;
3295 		ipsec_mp = mp;
3296 		mp = ipsec_mp->b_cont;
3297 
3298 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3299 		ipha = (ipha_t *)mp->b_rptr;
3300 
3301 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3302 		    in->ipsec_info_type == IPSEC_IN);
3303 
3304 		if (in->ipsec_info_type == IPSEC_IN) {
3305 			/*
3306 			 * Convert the IPSEC_IN to IPSEC_OUT.
3307 			 */
3308 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3309 				BUMP_MIB(&ipst->ips_ip_mib,
3310 				    ipIfStatsOutDiscards);
3311 				return;
3312 			}
3313 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3314 		} else {
3315 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3316 			io = (ipsec_out_t *)in;
3317 			/*
3318 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3319 			 * ire lookup.
3320 			 */
3321 			io->ipsec_out_proc_begin = B_FALSE;
3322 		}
3323 		ASSERT(zoneid == io->ipsec_out_zoneid);
3324 		ASSERT(zoneid != ALL_ZONES);
3325 	} else {
3326 		/*
3327 		 * This is in clear. The icmp message we are building
3328 		 * here should go out in clear.
3329 		 *
3330 		 * Pardon the convolution of it all, but it's easier to
3331 		 * allocate a "use cleartext" IPSEC_IN message and convert
3332 		 * it than it is to allocate a new one.
3333 		 */
3334 		ipsec_in_t *ii;
3335 		ASSERT(DB_TYPE(mp) == M_DATA);
3336 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3337 		if (ipsec_mp == NULL) {
3338 			freemsg(mp);
3339 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3340 			return;
3341 		}
3342 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3343 
3344 		/* This is not a secure packet */
3345 		ii->ipsec_in_secure = B_FALSE;
3346 		/*
3347 		 * For trusted extensions using a shared IP address we can
3348 		 * send using any zoneid.
3349 		 */
3350 		if (zoneid == ALL_ZONES)
3351 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3352 		else
3353 			ii->ipsec_in_zoneid = zoneid;
3354 		ipsec_mp->b_cont = mp;
3355 		ipha = (ipha_t *)mp->b_rptr;
3356 		/*
3357 		 * Convert the IPSEC_IN to IPSEC_OUT.
3358 		 */
3359 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3360 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3361 			return;
3362 		}
3363 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3364 	}
3365 
3366 	/* Remember our eventual destination */
3367 	dst = ipha->ipha_src;
3368 
3369 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3370 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3371 	if (ire != NULL &&
3372 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3373 		src = ipha->ipha_dst;
3374 	} else {
3375 		if (ire != NULL)
3376 			ire_refrele(ire);
3377 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3378 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3379 		    ipst);
3380 		if (ire == NULL) {
3381 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3382 			freemsg(ipsec_mp);
3383 			return;
3384 		}
3385 		src = ire->ire_src_addr;
3386 	}
3387 
3388 	if (ire != NULL)
3389 		ire_refrele(ire);
3390 
3391 	/*
3392 	 * Check if we can send back more then 8 bytes in addition to
3393 	 * the IP header.  We try to send 64 bytes of data and the internal
3394 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3395 	 */
3396 	len_needed = IPH_HDR_LENGTH(ipha);
3397 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3398 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3399 
3400 		if (!pullupmsg(mp, -1)) {
3401 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3402 			freemsg(ipsec_mp);
3403 			return;
3404 		}
3405 		ipha = (ipha_t *)mp->b_rptr;
3406 
3407 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3408 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3409 			    len_needed));
3410 		} else {
3411 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3412 
3413 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3414 			len_needed += ip_hdr_length_v6(mp, ip6h);
3415 		}
3416 	}
3417 	len_needed += ipst->ips_ip_icmp_return;
3418 	msg_len = msgdsize(mp);
3419 	if (msg_len > len_needed) {
3420 		(void) adjmsg(mp, len_needed - msg_len);
3421 		msg_len = len_needed;
3422 	}
3423 	mp1 = allocb_tmpl(sizeof (icmp_ipha) + len, mp);
3424 	if (mp1 == NULL) {
3425 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3426 		freemsg(ipsec_mp);
3427 		return;
3428 	}
3429 	mp1->b_cont = mp;
3430 	mp = mp1;
3431 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3432 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3433 	    io->ipsec_out_type == IPSEC_OUT);
3434 	ipsec_mp->b_cont = mp;
3435 
3436 	/*
3437 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3438 	 * node generates be accepted in peace by all on-host destinations.
3439 	 * If we do NOT assume that all on-host destinations trust
3440 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3441 	 * (Look for ipsec_out_icmp_loopback).
3442 	 */
3443 	io->ipsec_out_icmp_loopback = B_TRUE;
3444 
3445 	ipha = (ipha_t *)mp->b_rptr;
3446 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3447 	*ipha = icmp_ipha;
3448 	ipha->ipha_src = src;
3449 	ipha->ipha_dst = dst;
3450 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3451 	msg_len += sizeof (icmp_ipha) + len;
3452 	if (msg_len > IP_MAXPACKET) {
3453 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3454 		msg_len = IP_MAXPACKET;
3455 	}
3456 	ipha->ipha_length = htons((uint16_t)msg_len);
3457 	icmph = (icmph_t *)&ipha[1];
3458 	bcopy(stuff, icmph, len);
3459 	icmph->icmph_checksum = 0;
3460 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3461 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3462 	put(q, ipsec_mp);
3463 }
3464 
3465 /*
3466  * Determine if an ICMP error packet can be sent given the rate limit.
3467  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3468  * in milliseconds) and a burst size. Burst size number of packets can
3469  * be sent arbitrarely closely spaced.
3470  * The state is tracked using two variables to implement an approximate
3471  * token bucket filter:
3472  *	icmp_pkt_err_last - lbolt value when the last burst started
3473  *	icmp_pkt_err_sent - number of packets sent in current burst
3474  */
3475 boolean_t
3476 icmp_err_rate_limit(ip_stack_t *ipst)
3477 {
3478 	clock_t now = TICK_TO_MSEC(lbolt);
3479 	uint_t refilled; /* Number of packets refilled in tbf since last */
3480 	/* Guard against changes by loading into local variable */
3481 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3482 
3483 	if (err_interval == 0)
3484 		return (B_FALSE);
3485 
3486 	if (ipst->ips_icmp_pkt_err_last > now) {
3487 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3488 		ipst->ips_icmp_pkt_err_last = 0;
3489 		ipst->ips_icmp_pkt_err_sent = 0;
3490 	}
3491 	/*
3492 	 * If we are in a burst update the token bucket filter.
3493 	 * Update the "last" time to be close to "now" but make sure
3494 	 * we don't loose precision.
3495 	 */
3496 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3497 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3498 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3499 			ipst->ips_icmp_pkt_err_sent = 0;
3500 		} else {
3501 			ipst->ips_icmp_pkt_err_sent -= refilled;
3502 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3503 		}
3504 	}
3505 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3506 		/* Start of new burst */
3507 		ipst->ips_icmp_pkt_err_last = now;
3508 	}
3509 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3510 		ipst->ips_icmp_pkt_err_sent++;
3511 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3512 		    ipst->ips_icmp_pkt_err_sent));
3513 		return (B_FALSE);
3514 	}
3515 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3516 	return (B_TRUE);
3517 }
3518 
3519 /*
3520  * Check if it is ok to send an IPv4 ICMP error packet in
3521  * response to the IPv4 packet in mp.
3522  * Free the message and return null if no
3523  * ICMP error packet should be sent.
3524  */
3525 static mblk_t *
3526 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3527 {
3528 	icmph_t	*icmph;
3529 	ipha_t	*ipha;
3530 	uint_t	len_needed;
3531 	ire_t	*src_ire;
3532 	ire_t	*dst_ire;
3533 
3534 	if (!mp)
3535 		return (NULL);
3536 	ipha = (ipha_t *)mp->b_rptr;
3537 	if (ip_csum_hdr(ipha)) {
3538 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3539 		freemsg(mp);
3540 		return (NULL);
3541 	}
3542 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3543 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3544 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3545 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3546 	if (src_ire != NULL || dst_ire != NULL ||
3547 	    CLASSD(ipha->ipha_dst) ||
3548 	    CLASSD(ipha->ipha_src) ||
3549 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3550 		/* Note: only errors to the fragment with offset 0 */
3551 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3552 		freemsg(mp);
3553 		if (src_ire != NULL)
3554 			ire_refrele(src_ire);
3555 		if (dst_ire != NULL)
3556 			ire_refrele(dst_ire);
3557 		return (NULL);
3558 	}
3559 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3560 		/*
3561 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3562 		 * errors in response to any ICMP errors.
3563 		 */
3564 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3565 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3566 			if (!pullupmsg(mp, len_needed)) {
3567 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3568 				freemsg(mp);
3569 				return (NULL);
3570 			}
3571 			ipha = (ipha_t *)mp->b_rptr;
3572 		}
3573 		icmph = (icmph_t *)
3574 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3575 		switch (icmph->icmph_type) {
3576 		case ICMP_DEST_UNREACHABLE:
3577 		case ICMP_SOURCE_QUENCH:
3578 		case ICMP_TIME_EXCEEDED:
3579 		case ICMP_PARAM_PROBLEM:
3580 		case ICMP_REDIRECT:
3581 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3582 			freemsg(mp);
3583 			return (NULL);
3584 		default:
3585 			break;
3586 		}
3587 	}
3588 	/*
3589 	 * If this is a labeled system, then check to see if we're allowed to
3590 	 * send a response to this particular sender.  If not, then just drop.
3591 	 */
3592 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3593 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3594 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3595 		freemsg(mp);
3596 		return (NULL);
3597 	}
3598 	if (icmp_err_rate_limit(ipst)) {
3599 		/*
3600 		 * Only send ICMP error packets every so often.
3601 		 * This should be done on a per port/source basis,
3602 		 * but for now this will suffice.
3603 		 */
3604 		freemsg(mp);
3605 		return (NULL);
3606 	}
3607 	return (mp);
3608 }
3609 
3610 /*
3611  * Generate an ICMP redirect message.
3612  */
3613 static void
3614 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3615 {
3616 	icmph_t	icmph;
3617 
3618 	/*
3619 	 * We are called from ip_rput where we could
3620 	 * not have attached an IPSEC_IN.
3621 	 */
3622 	ASSERT(mp->b_datap->db_type == M_DATA);
3623 
3624 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3625 		return;
3626 	}
3627 
3628 	bzero(&icmph, sizeof (icmph_t));
3629 	icmph.icmph_type = ICMP_REDIRECT;
3630 	icmph.icmph_code = 1;
3631 	icmph.icmph_rd_gateway = gateway;
3632 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3633 	/* Redirects sent by router, and router is global zone */
3634 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3635 }
3636 
3637 /*
3638  * Generate an ICMP time exceeded message.
3639  */
3640 void
3641 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3642     ip_stack_t *ipst)
3643 {
3644 	icmph_t	icmph;
3645 	boolean_t mctl_present;
3646 	mblk_t *first_mp;
3647 
3648 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3649 
3650 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3651 		if (mctl_present)
3652 			freeb(first_mp);
3653 		return;
3654 	}
3655 
3656 	bzero(&icmph, sizeof (icmph_t));
3657 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3658 	icmph.icmph_code = code;
3659 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3660 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3661 	    ipst);
3662 }
3663 
3664 /*
3665  * Generate an ICMP unreachable message.
3666  */
3667 void
3668 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3669     ip_stack_t *ipst)
3670 {
3671 	icmph_t	icmph;
3672 	mblk_t *first_mp;
3673 	boolean_t mctl_present;
3674 
3675 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3676 
3677 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3678 		if (mctl_present)
3679 			freeb(first_mp);
3680 		return;
3681 	}
3682 
3683 	bzero(&icmph, sizeof (icmph_t));
3684 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3685 	icmph.icmph_code = code;
3686 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3687 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3688 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3689 	    zoneid, ipst);
3690 }
3691 
3692 /*
3693  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3694  * duplicate.  As long as someone else holds the address, the interface will
3695  * stay down.  When that conflict goes away, the interface is brought back up.
3696  * This is done so that accidental shutdowns of addresses aren't made
3697  * permanent.  Your server will recover from a failure.
3698  *
3699  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3700  * user space process (dhcpagent).
3701  *
3702  * Recovery completes if ARP reports that the address is now ours (via
3703  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3704  *
3705  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3706  */
3707 static void
3708 ipif_dup_recovery(void *arg)
3709 {
3710 	ipif_t *ipif = arg;
3711 	ill_t *ill = ipif->ipif_ill;
3712 	mblk_t *arp_add_mp;
3713 	mblk_t *arp_del_mp;
3714 	area_t *area;
3715 	ip_stack_t *ipst = ill->ill_ipst;
3716 
3717 	ipif->ipif_recovery_id = 0;
3718 
3719 	/*
3720 	 * No lock needed for moving or condemned check, as this is just an
3721 	 * optimization.
3722 	 */
3723 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3724 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3725 	    (ipif->ipif_state_flags & (IPIF_MOVING | IPIF_CONDEMNED))) {
3726 		/* No reason to try to bring this address back. */
3727 		return;
3728 	}
3729 
3730 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3731 		goto alloc_fail;
3732 
3733 	if (ipif->ipif_arp_del_mp == NULL) {
3734 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3735 			goto alloc_fail;
3736 		ipif->ipif_arp_del_mp = arp_del_mp;
3737 	}
3738 
3739 	/* Setting the 'unverified' flag restarts DAD */
3740 	area = (area_t *)arp_add_mp->b_rptr;
3741 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3742 	    ACE_F_UNVERIFIED;
3743 	putnext(ill->ill_rq, arp_add_mp);
3744 	return;
3745 
3746 alloc_fail:
3747 	/*
3748 	 * On allocation failure, just restart the timer.  Note that the ipif
3749 	 * is down here, so no other thread could be trying to start a recovery
3750 	 * timer.  The ill_lock protects the condemned flag and the recovery
3751 	 * timer ID.
3752 	 */
3753 	freemsg(arp_add_mp);
3754 	mutex_enter(&ill->ill_lock);
3755 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3756 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3757 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3758 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3759 	}
3760 	mutex_exit(&ill->ill_lock);
3761 }
3762 
3763 /*
3764  * This is for exclusive changes due to ARP.  Either tear down an interface due
3765  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3766  */
3767 /* ARGSUSED */
3768 static void
3769 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3770 {
3771 	ill_t	*ill = rq->q_ptr;
3772 	arh_t *arh;
3773 	ipaddr_t src;
3774 	ipif_t	*ipif;
3775 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3776 	char hbuf[MAC_STR_LEN];
3777 	char sbuf[INET_ADDRSTRLEN];
3778 	const char *failtype;
3779 	boolean_t bring_up;
3780 	ip_stack_t *ipst = ill->ill_ipst;
3781 
3782 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3783 	case AR_CN_READY:
3784 		failtype = NULL;
3785 		bring_up = B_TRUE;
3786 		break;
3787 	case AR_CN_FAILED:
3788 		failtype = "in use";
3789 		bring_up = B_FALSE;
3790 		break;
3791 	default:
3792 		failtype = "claimed";
3793 		bring_up = B_FALSE;
3794 		break;
3795 	}
3796 
3797 	arh = (arh_t *)mp->b_cont->b_rptr;
3798 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3799 
3800 	/* Handle failures due to probes */
3801 	if (src == 0) {
3802 		bcopy((char *)&arh[1] + 2 * arh->arh_hlen + IP_ADDR_LEN, &src,
3803 		    IP_ADDR_LEN);
3804 	}
3805 
3806 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3807 	    sizeof (hbuf));
3808 	(void) ip_dot_addr(src, sbuf);
3809 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3810 
3811 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3812 		    ipif->ipif_lcl_addr != src) {
3813 			continue;
3814 		}
3815 
3816 		/*
3817 		 * If we failed on a recovery probe, then restart the timer to
3818 		 * try again later.
3819 		 */
3820 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3821 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3822 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3823 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3824 		    ipst->ips_ip_dup_recovery > 0 &&
3825 		    ipif->ipif_recovery_id == 0) {
3826 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3827 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3828 			continue;
3829 		}
3830 
3831 		/*
3832 		 * If what we're trying to do has already been done, then do
3833 		 * nothing.
3834 		 */
3835 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3836 			continue;
3837 
3838 		ipif_get_name(ipif, ibuf, sizeof (ibuf));
3839 
3840 		if (failtype == NULL) {
3841 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3842 			    ibuf);
3843 		} else {
3844 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3845 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3846 		}
3847 
3848 		if (bring_up) {
3849 			ASSERT(ill->ill_dl_up);
3850 			/*
3851 			 * Free up the ARP delete message so we can allocate
3852 			 * a fresh one through the normal path.
3853 			 */
3854 			freemsg(ipif->ipif_arp_del_mp);
3855 			ipif->ipif_arp_del_mp = NULL;
3856 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3857 			    EINPROGRESS) {
3858 				ipif->ipif_addr_ready = 1;
3859 				(void) ipif_up_done(ipif);
3860 			}
3861 			continue;
3862 		}
3863 
3864 		mutex_enter(&ill->ill_lock);
3865 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3866 		ipif->ipif_flags |= IPIF_DUPLICATE;
3867 		ill->ill_ipif_dup_count++;
3868 		mutex_exit(&ill->ill_lock);
3869 		/*
3870 		 * Already exclusive on the ill; no need to handle deferred
3871 		 * processing here.
3872 		 */
3873 		(void) ipif_down(ipif, NULL, NULL);
3874 		ipif_down_tail(ipif);
3875 		mutex_enter(&ill->ill_lock);
3876 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3877 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3878 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3879 		    ipst->ips_ip_dup_recovery > 0) {
3880 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3881 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3882 		}
3883 		mutex_exit(&ill->ill_lock);
3884 	}
3885 	freemsg(mp);
3886 }
3887 
3888 /* ARGSUSED */
3889 static void
3890 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3891 {
3892 	ill_t	*ill = rq->q_ptr;
3893 	arh_t *arh;
3894 	ipaddr_t src;
3895 	ipif_t	*ipif;
3896 
3897 	arh = (arh_t *)mp->b_cont->b_rptr;
3898 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3899 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3900 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3901 			(void) ipif_resolver_up(ipif, Res_act_defend);
3902 	}
3903 	freemsg(mp);
3904 }
3905 
3906 /*
3907  * News from ARP.  ARP sends notification of interesting events down
3908  * to its clients using M_CTL messages with the interesting ARP packet
3909  * attached via b_cont.
3910  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3911  * queue as opposed to ARP sending the message to all the clients, i.e. all
3912  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3913  * table if a cache IRE is found to delete all the entries for the address in
3914  * the packet.
3915  */
3916 static void
3917 ip_arp_news(queue_t *q, mblk_t *mp)
3918 {
3919 	arcn_t		*arcn;
3920 	arh_t		*arh;
3921 	ire_t		*ire = NULL;
3922 	char		hbuf[MAC_STR_LEN];
3923 	char		sbuf[INET_ADDRSTRLEN];
3924 	ipaddr_t	src;
3925 	in6_addr_t	v6src;
3926 	boolean_t	isv6 = B_FALSE;
3927 	ipif_t		*ipif;
3928 	ill_t		*ill;
3929 	ip_stack_t	*ipst;
3930 
3931 	if (CONN_Q(q)) {
3932 		conn_t *connp = Q_TO_CONN(q);
3933 
3934 		ipst = connp->conn_netstack->netstack_ip;
3935 	} else {
3936 		ill_t *ill = (ill_t *)q->q_ptr;
3937 
3938 		ipst = ill->ill_ipst;
3939 	}
3940 
3941 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3942 		if (q->q_next) {
3943 			putnext(q, mp);
3944 		} else
3945 			freemsg(mp);
3946 		return;
3947 	}
3948 	arh = (arh_t *)mp->b_cont->b_rptr;
3949 	/* Is it one we are interested in? */
3950 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3951 		isv6 = B_TRUE;
3952 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3953 		    IPV6_ADDR_LEN);
3954 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3955 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3956 		    IP_ADDR_LEN);
3957 	} else {
3958 		freemsg(mp);
3959 		return;
3960 	}
3961 
3962 	ill = q->q_ptr;
3963 
3964 	arcn = (arcn_t *)mp->b_rptr;
3965 	switch (arcn->arcn_code) {
3966 	case AR_CN_BOGON:
3967 		/*
3968 		 * Someone is sending ARP packets with a source protocol
3969 		 * address that we have published and for which we believe our
3970 		 * entry is authoritative and (when ill_arp_extend is set)
3971 		 * verified to be unique on the network.
3972 		 *
3973 		 * The ARP module internally handles the cases where the sender
3974 		 * is just probing (for DAD) and where the hardware address of
3975 		 * a non-authoritative entry has changed.  Thus, these are the
3976 		 * real conflicts, and we have to do resolution.
3977 		 *
3978 		 * We back away quickly from the address if it's from DHCP or
3979 		 * otherwise temporary and hasn't been used recently (or at
3980 		 * all).  We'd like to include "deprecated" addresses here as
3981 		 * well (as there's no real reason to defend something we're
3982 		 * discarding), but IPMP "reuses" this flag to mean something
3983 		 * other than the standard meaning.
3984 		 *
3985 		 * If the ARP module above is not extended (meaning that it
3986 		 * doesn't know how to defend the address), then we just log
3987 		 * the problem as we always did and continue on.  It's not
3988 		 * right, but there's little else we can do, and those old ATM
3989 		 * users are going away anyway.
3990 		 */
3991 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
3992 		    hbuf, sizeof (hbuf));
3993 		(void) ip_dot_addr(src, sbuf);
3994 		if (isv6) {
3995 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
3996 			    ipst);
3997 		} else {
3998 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
3999 		}
4000 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
4001 			uint32_t now;
4002 			uint32_t maxage;
4003 			clock_t lused;
4004 			uint_t maxdefense;
4005 			uint_t defs;
4006 
4007 			/*
4008 			 * First, figure out if this address hasn't been used
4009 			 * in a while.  If it hasn't, then it's a better
4010 			 * candidate for abandoning.
4011 			 */
4012 			ipif = ire->ire_ipif;
4013 			ASSERT(ipif != NULL);
4014 			now = gethrestime_sec();
4015 			maxage = now - ire->ire_create_time;
4016 			if (maxage > ipst->ips_ip_max_temp_idle)
4017 				maxage = ipst->ips_ip_max_temp_idle;
4018 			lused = drv_hztousec(ddi_get_lbolt() -
4019 			    ire->ire_last_used_time) / MICROSEC + 1;
4020 			if (lused >= maxage && (ipif->ipif_flags &
4021 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4022 				maxdefense = ipst->ips_ip_max_temp_defend;
4023 			else
4024 				maxdefense = ipst->ips_ip_max_defend;
4025 
4026 			/*
4027 			 * Now figure out how many times we've defended
4028 			 * ourselves.  Ignore defenses that happened long in
4029 			 * the past.
4030 			 */
4031 			mutex_enter(&ire->ire_lock);
4032 			if ((defs = ire->ire_defense_count) > 0 &&
4033 			    now - ire->ire_defense_time >
4034 			    ipst->ips_ip_defend_interval) {
4035 				ire->ire_defense_count = defs = 0;
4036 			}
4037 			ire->ire_defense_count++;
4038 			ire->ire_defense_time = now;
4039 			mutex_exit(&ire->ire_lock);
4040 			ill_refhold(ill);
4041 			ire_refrele(ire);
4042 
4043 			/*
4044 			 * If we've defended ourselves too many times already,
4045 			 * then give up and tear down the interface(s) using
4046 			 * this address.  Otherwise, defend by sending out a
4047 			 * gratuitous ARP.
4048 			 */
4049 			if (defs >= maxdefense && ill->ill_arp_extend) {
4050 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4051 				    B_FALSE);
4052 			} else {
4053 				cmn_err(CE_WARN,
4054 				    "node %s is using our IP address %s on %s",
4055 				    hbuf, sbuf, ill->ill_name);
4056 				/*
4057 				 * If this is an old (ATM) ARP module, then
4058 				 * don't try to defend the address.  Remain
4059 				 * compatible with the old behavior.  Defend
4060 				 * only with new ARP.
4061 				 */
4062 				if (ill->ill_arp_extend) {
4063 					qwriter_ip(ill, q, mp, ip_arp_defend,
4064 					    NEW_OP, B_FALSE);
4065 				} else {
4066 					ill_refrele(ill);
4067 				}
4068 			}
4069 			return;
4070 		}
4071 		cmn_err(CE_WARN,
4072 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4073 		    hbuf, sbuf, ill->ill_name);
4074 		if (ire != NULL)
4075 			ire_refrele(ire);
4076 		break;
4077 	case AR_CN_ANNOUNCE:
4078 		if (isv6) {
4079 			/*
4080 			 * For XRESOLV interfaces.
4081 			 * Delete the IRE cache entry and NCE for this
4082 			 * v6 address
4083 			 */
4084 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4085 			/*
4086 			 * If v6src is a non-zero, it's a router address
4087 			 * as below. Do the same sort of thing to clean
4088 			 * out off-net IRE_CACHE entries that go through
4089 			 * the router.
4090 			 */
4091 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4092 				ire_walk_v6(ire_delete_cache_gw_v6,
4093 				    (char *)&v6src, ALL_ZONES, ipst);
4094 			}
4095 		} else {
4096 			nce_hw_map_t hwm;
4097 
4098 			/*
4099 			 * ARP gives us a copy of any packet where it thinks
4100 			 * the address has changed, so that we can update our
4101 			 * caches.  We're responsible for caching known answers
4102 			 * in the current design.  We check whether the
4103 			 * hardware address really has changed in all of our
4104 			 * entries that have cached this mapping, and if so, we
4105 			 * blow them away.  This way we will immediately pick
4106 			 * up the rare case of a host changing hardware
4107 			 * address.
4108 			 */
4109 			if (src == 0)
4110 				break;
4111 			hwm.hwm_addr = src;
4112 			hwm.hwm_hwlen = arh->arh_hlen;
4113 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4114 			NDP_HW_CHANGE_INCR(ipst->ips_ndp4);
4115 			ndp_walk_common(ipst->ips_ndp4, NULL,
4116 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4117 			NDP_HW_CHANGE_DECR(ipst->ips_ndp4);
4118 		}
4119 		break;
4120 	case AR_CN_READY:
4121 		/* No external v6 resolver has a contract to use this */
4122 		if (isv6)
4123 			break;
4124 		/* If the link is down, we'll retry this later */
4125 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4126 			break;
4127 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4128 		    NULL, NULL, ipst);
4129 		if (ipif != NULL) {
4130 			/*
4131 			 * If this is a duplicate recovery, then we now need to
4132 			 * go exclusive to bring this thing back up.
4133 			 */
4134 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4135 			    IPIF_DUPLICATE) {
4136 				ipif_refrele(ipif);
4137 				ill_refhold(ill);
4138 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4139 				    B_FALSE);
4140 				return;
4141 			}
4142 			/*
4143 			 * If this is the first notice that this address is
4144 			 * ready, then let the user know now.
4145 			 */
4146 			if ((ipif->ipif_flags & IPIF_UP) &&
4147 			    !ipif->ipif_addr_ready) {
4148 				ipif_mask_reply(ipif);
4149 				ip_rts_ifmsg(ipif);
4150 				ip_rts_newaddrmsg(RTM_ADD, 0, ipif);
4151 				sctp_update_ipif(ipif, SCTP_IPIF_UP);
4152 			}
4153 			ipif->ipif_addr_ready = 1;
4154 			ipif_refrele(ipif);
4155 		}
4156 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp), ipst);
4157 		if (ire != NULL) {
4158 			ire->ire_defense_count = 0;
4159 			ire_refrele(ire);
4160 		}
4161 		break;
4162 	case AR_CN_FAILED:
4163 		/* No external v6 resolver has a contract to use this */
4164 		if (isv6)
4165 			break;
4166 		ill_refhold(ill);
4167 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, B_FALSE);
4168 		return;
4169 	}
4170 	freemsg(mp);
4171 }
4172 
4173 /*
4174  * Create a mblk suitable for carrying the interface index and/or source link
4175  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4176  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4177  * application.
4178  */
4179 mblk_t *
4180 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4181     ip_stack_t *ipst)
4182 {
4183 	mblk_t		*mp;
4184 	ip_pktinfo_t	*pinfo;
4185 	ipha_t *ipha;
4186 	struct ether_header *pether;
4187 
4188 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4189 	if (mp == NULL) {
4190 		ip1dbg(("ip_add_info: allocation failure.\n"));
4191 		return (data_mp);
4192 	}
4193 
4194 	ipha	= (ipha_t *)data_mp->b_rptr;
4195 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4196 	bzero(pinfo, sizeof (ip_pktinfo_t));
4197 	pinfo->ip_pkt_flags = (uchar_t)flags;
4198 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4199 
4200 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4201 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4202 	if (flags & IPF_RECVADDR) {
4203 		ipif_t	*ipif;
4204 		ire_t	*ire;
4205 
4206 		/*
4207 		 * Only valid for V4
4208 		 */
4209 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4210 		    (IPV4_VERSION << 4));
4211 
4212 		ipif = ipif_get_next_ipif(NULL, ill);
4213 		if (ipif != NULL) {
4214 			/*
4215 			 * Since a decision has already been made to deliver the
4216 			 * packet, there is no need to test for SECATTR and
4217 			 * ZONEONLY.
4218 			 * When a multicast packet is transmitted
4219 			 * a cache entry is created for the multicast address.
4220 			 * When delivering a copy of the packet or when new
4221 			 * packets are received we do not want to match on the
4222 			 * cached entry so explicitly match on
4223 			 * IRE_LOCAL and IRE_LOOPBACK
4224 			 */
4225 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4226 			    IRE_LOCAL | IRE_LOOPBACK,
4227 			    ipif, zoneid, NULL,
4228 			    MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP, ipst);
4229 			if (ire == NULL) {
4230 				/*
4231 				 * packet must have come on a different
4232 				 * interface.
4233 				 * Since a decision has already been made to
4234 				 * deliver the packet, there is no need to test
4235 				 * for SECATTR and ZONEONLY.
4236 				 * Only match on local and broadcast ire's.
4237 				 * See detailed comment above.
4238 				 */
4239 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4240 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4241 				    NULL, MATCH_IRE_TYPE, ipst);
4242 			}
4243 
4244 			if (ire == NULL) {
4245 				/*
4246 				 * This is either a multicast packet or
4247 				 * the address has been removed since
4248 				 * the packet was received.
4249 				 * Return INADDR_ANY so that normal source
4250 				 * selection occurs for the response.
4251 				 */
4252 
4253 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4254 			} else {
4255 				pinfo->ip_pkt_match_addr.s_addr =
4256 				    ire->ire_src_addr;
4257 				ire_refrele(ire);
4258 			}
4259 			ipif_refrele(ipif);
4260 		} else {
4261 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4262 		}
4263 	}
4264 
4265 	pether = (struct ether_header *)((char *)ipha
4266 	    - sizeof (struct ether_header));
4267 	/*
4268 	 * Make sure the interface is an ethernet type, since this option
4269 	 * is currently supported only on this type of interface. Also make
4270 	 * sure we are pointing correctly above db_base.
4271 	 */
4272 
4273 	if ((flags & IPF_RECVSLLA) &&
4274 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4275 	    (ill->ill_type == IFT_ETHER) &&
4276 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4277 
4278 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4279 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4280 		    (uchar_t *)pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4281 	} else {
4282 		/*
4283 		 * Clear the bit. Indicate to upper layer that IP is not
4284 		 * sending this ancillary info.
4285 		 */
4286 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4287 	}
4288 
4289 	mp->b_datap->db_type = M_CTL;
4290 	mp->b_wptr += sizeof (ip_pktinfo_t);
4291 	mp->b_cont = data_mp;
4292 
4293 	return (mp);
4294 }
4295 
4296 /*
4297  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4298  * part of the bind request.
4299  */
4300 
4301 boolean_t
4302 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4303 {
4304 	ipsec_in_t *ii;
4305 
4306 	ASSERT(policy_mp != NULL);
4307 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4308 
4309 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4310 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4311 
4312 	connp->conn_policy = ii->ipsec_in_policy;
4313 	ii->ipsec_in_policy = NULL;
4314 
4315 	if (ii->ipsec_in_action != NULL) {
4316 		if (connp->conn_latch == NULL) {
4317 			connp->conn_latch = iplatch_create();
4318 			if (connp->conn_latch == NULL)
4319 				return (B_FALSE);
4320 		}
4321 		ipsec_latch_inbound(connp->conn_latch, ii);
4322 	}
4323 	return (B_TRUE);
4324 }
4325 
4326 /*
4327  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4328  * and to arrange for power-fanout assist.  The ULP is identified by
4329  * adding a single byte at the end of the original bind message.
4330  * A ULP other than UDP or TCP that wishes to be recognized passes
4331  * down a bind with a zero length address.
4332  *
4333  * The binding works as follows:
4334  * - A zero byte address means just bind to the protocol.
4335  * - A four byte address is treated as a request to validate
4336  *   that the address is a valid local address, appropriate for
4337  *   an application to bind to. This does not affect any fanout
4338  *   information in IP.
4339  * - A sizeof sin_t byte address is used to bind to only the local address
4340  *   and port.
4341  * - A sizeof ipa_conn_t byte address contains complete fanout information
4342  *   consisting of local and remote addresses and ports.  In
4343  *   this case, the addresses are both validated as appropriate
4344  *   for this operation, and, if so, the information is retained
4345  *   for use in the inbound fanout.
4346  *
4347  * The ULP (except in the zero-length bind) can append an
4348  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4349  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4350  * a copy of the source or destination IRE (source for local bind;
4351  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4352  * policy information contained should be copied on to the conn.
4353  *
4354  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4355  */
4356 mblk_t *
4357 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4358 {
4359 	ssize_t		len;
4360 	struct T_bind_req	*tbr;
4361 	sin_t		*sin;
4362 	ipa_conn_t	*ac;
4363 	uchar_t		*ucp;
4364 	mblk_t		*mp1;
4365 	boolean_t	ire_requested;
4366 	boolean_t	ipsec_policy_set = B_FALSE;
4367 	int		error = 0;
4368 	int		protocol;
4369 	ipa_conn_x_t	*acx;
4370 
4371 	ASSERT(!connp->conn_af_isv6);
4372 	connp->conn_pkt_isv6 = B_FALSE;
4373 
4374 	len = MBLKL(mp);
4375 	if (len < (sizeof (*tbr) + 1)) {
4376 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4377 		    "ip_bind: bogus msg, len %ld", len);
4378 		/* XXX: Need to return something better */
4379 		goto bad_addr;
4380 	}
4381 	/* Back up and extract the protocol identifier. */
4382 	mp->b_wptr--;
4383 	protocol = *mp->b_wptr & 0xFF;
4384 	tbr = (struct T_bind_req *)mp->b_rptr;
4385 	/* Reset the message type in preparation for shipping it back. */
4386 	DB_TYPE(mp) = M_PCPROTO;
4387 
4388 	connp->conn_ulp = (uint8_t)protocol;
4389 
4390 	/*
4391 	 * Check for a zero length address.  This is from a protocol that
4392 	 * wants to register to receive all packets of its type.
4393 	 */
4394 	if (tbr->ADDR_length == 0) {
4395 		/*
4396 		 * These protocols are now intercepted in ip_bind_v6().
4397 		 * Reject protocol-level binds here for now.
4398 		 *
4399 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4400 		 * so that the protocol type cannot be SCTP.
4401 		 */
4402 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4403 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4404 			goto bad_addr;
4405 		}
4406 
4407 		/*
4408 		 *
4409 		 * The udp module never sends down a zero-length address,
4410 		 * and allowing this on a labeled system will break MLP
4411 		 * functionality.
4412 		 */
4413 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4414 			goto bad_addr;
4415 
4416 		if (connp->conn_mac_exempt)
4417 			goto bad_addr;
4418 
4419 		/* No hash here really.  The table is big enough. */
4420 		connp->conn_srcv6 = ipv6_all_zeros;
4421 
4422 		ipcl_proto_insert(connp, protocol);
4423 
4424 		tbr->PRIM_type = T_BIND_ACK;
4425 		return (mp);
4426 	}
4427 
4428 	/* Extract the address pointer from the message. */
4429 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4430 	    tbr->ADDR_length);
4431 	if (ucp == NULL) {
4432 		ip1dbg(("ip_bind: no address\n"));
4433 		goto bad_addr;
4434 	}
4435 	if (!OK_32PTR(ucp)) {
4436 		ip1dbg(("ip_bind: unaligned address\n"));
4437 		goto bad_addr;
4438 	}
4439 	/*
4440 	 * Check for trailing mps.
4441 	 */
4442 
4443 	mp1 = mp->b_cont;
4444 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4445 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4446 
4447 	switch (tbr->ADDR_length) {
4448 	default:
4449 		ip1dbg(("ip_bind: bad address length %d\n",
4450 		    (int)tbr->ADDR_length));
4451 		goto bad_addr;
4452 
4453 	case IP_ADDR_LEN:
4454 		/* Verification of local address only */
4455 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4456 		    ire_requested, ipsec_policy_set, B_FALSE);
4457 		break;
4458 
4459 	case sizeof (sin_t):
4460 		sin = (sin_t *)ucp;
4461 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4462 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4463 		break;
4464 
4465 	case sizeof (ipa_conn_t):
4466 		ac = (ipa_conn_t *)ucp;
4467 		/* For raw socket, the local port is not set. */
4468 		if (ac->ac_lport == 0)
4469 			ac->ac_lport = connp->conn_lport;
4470 		/* Always verify destination reachability. */
4471 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4472 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4473 		    ipsec_policy_set, B_TRUE, B_TRUE);
4474 		break;
4475 
4476 	case sizeof (ipa_conn_x_t):
4477 		acx = (ipa_conn_x_t *)ucp;
4478 		/*
4479 		 * Whether or not to verify destination reachability depends
4480 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4481 		 */
4482 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4483 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4484 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4485 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4486 		break;
4487 	}
4488 	if (error == EINPROGRESS)
4489 		return (NULL);
4490 	else if (error != 0)
4491 		goto bad_addr;
4492 	/*
4493 	 * Pass the IPsec headers size in ire_ipsec_overhead.
4494 	 * We can't do this in ip_bind_insert_ire because the policy
4495 	 * may not have been inherited at that point in time and hence
4496 	 * conn_out_enforce_policy may not be set.
4497 	 */
4498 	mp1 = mp->b_cont;
4499 	if (ire_requested && connp->conn_out_enforce_policy &&
4500 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4501 		ire_t *ire = (ire_t *)mp1->b_rptr;
4502 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4503 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4504 	}
4505 
4506 	/* Send it home. */
4507 	mp->b_datap->db_type = M_PCPROTO;
4508 	tbr->PRIM_type = T_BIND_ACK;
4509 	return (mp);
4510 
4511 bad_addr:
4512 	/*
4513 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4514 	 * a unix errno.
4515 	 */
4516 	if (error > 0)
4517 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4518 	else
4519 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4520 	return (mp);
4521 }
4522 
4523 /*
4524  * Here address is verified to be a valid local address.
4525  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4526  * address is also considered a valid local address.
4527  * In the case of a broadcast/multicast address, however, the
4528  * upper protocol is expected to reset the src address
4529  * to 0 if it sees a IRE_BROADCAST type returned so that
4530  * no packets are emitted with broadcast/multicast address as
4531  * source address (that violates hosts requirements RFC1122)
4532  * The addresses valid for bind are:
4533  *	(1) - INADDR_ANY (0)
4534  *	(2) - IP address of an UP interface
4535  *	(3) - IP address of a DOWN interface
4536  *	(4) - valid local IP broadcast addresses. In this case
4537  *	the conn will only receive packets destined to
4538  *	the specified broadcast address.
4539  *	(5) - a multicast address. In this case
4540  *	the conn will only receive packets destined to
4541  *	the specified multicast address. Note: the
4542  *	application still has to issue an
4543  *	IP_ADD_MEMBERSHIP socket option.
4544  *
4545  * On error, return -1 for TBADADDR otherwise pass the
4546  * errno with TSYSERR reply.
4547  *
4548  * In all the above cases, the bound address must be valid in the current zone.
4549  * When the address is loopback, multicast or broadcast, there might be many
4550  * matching IREs so bind has to look up based on the zone.
4551  *
4552  * Note: lport is in network byte order.
4553  */
4554 int
4555 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4556     boolean_t ire_requested, boolean_t ipsec_policy_set,
4557     boolean_t fanout_insert)
4558 {
4559 	int		error = 0;
4560 	ire_t		*src_ire;
4561 	mblk_t		*policy_mp;
4562 	ipif_t		*ipif;
4563 	zoneid_t	zoneid;
4564 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4565 
4566 	if (ipsec_policy_set) {
4567 		policy_mp = mp->b_cont;
4568 	}
4569 
4570 	/*
4571 	 * If it was previously connected, conn_fully_bound would have
4572 	 * been set.
4573 	 */
4574 	connp->conn_fully_bound = B_FALSE;
4575 
4576 	src_ire = NULL;
4577 	ipif = NULL;
4578 
4579 	zoneid = IPCL_ZONEID(connp);
4580 
4581 	if (src_addr) {
4582 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4583 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4584 		/*
4585 		 * If an address other than 0.0.0.0 is requested,
4586 		 * we verify that it is a valid address for bind
4587 		 * Note: Following code is in if-else-if form for
4588 		 * readability compared to a condition check.
4589 		 */
4590 		/* LINTED - statement has no consequent */
4591 		if (IRE_IS_LOCAL(src_ire)) {
4592 			/*
4593 			 * (2) Bind to address of local UP interface
4594 			 */
4595 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4596 			/*
4597 			 * (4) Bind to broadcast address
4598 			 * Note: permitted only from transports that
4599 			 * request IRE
4600 			 */
4601 			if (!ire_requested)
4602 				error = EADDRNOTAVAIL;
4603 		} else {
4604 			/*
4605 			 * (3) Bind to address of local DOWN interface
4606 			 * (ipif_lookup_addr() looks up all interfaces
4607 			 * but we do not get here for UP interfaces
4608 			 * - case (2) above)
4609 			 * We put the protocol byte back into the mblk
4610 			 * since we may come back via ip_wput_nondata()
4611 			 * later with this mblk if ipif_lookup_addr chooses
4612 			 * to defer processing.
4613 			 */
4614 			*mp->b_wptr++ = (char)connp->conn_ulp;
4615 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4616 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4617 			    &error, ipst)) != NULL) {
4618 				ipif_refrele(ipif);
4619 			} else if (error == EINPROGRESS) {
4620 				if (src_ire != NULL)
4621 					ire_refrele(src_ire);
4622 				return (EINPROGRESS);
4623 			} else if (CLASSD(src_addr)) {
4624 				error = 0;
4625 				if (src_ire != NULL)
4626 					ire_refrele(src_ire);
4627 				/*
4628 				 * (5) bind to multicast address.
4629 				 * Fake out the IRE returned to upper
4630 				 * layer to be a broadcast IRE.
4631 				 */
4632 				src_ire = ire_ctable_lookup(
4633 				    INADDR_BROADCAST, INADDR_ANY,
4634 				    IRE_BROADCAST, NULL, zoneid, NULL,
4635 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4636 				    ipst);
4637 				if (src_ire == NULL || !ire_requested)
4638 					error = EADDRNOTAVAIL;
4639 			} else {
4640 				/*
4641 				 * Not a valid address for bind
4642 				 */
4643 				error = EADDRNOTAVAIL;
4644 			}
4645 			/*
4646 			 * Just to keep it consistent with the processing in
4647 			 * ip_bind_v4()
4648 			 */
4649 			mp->b_wptr--;
4650 		}
4651 		if (error) {
4652 			/* Red Alert!  Attempting to be a bogon! */
4653 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4654 			    ntohl(src_addr)));
4655 			goto bad_addr;
4656 		}
4657 	}
4658 
4659 	/*
4660 	 * Allow setting new policies. For example, disconnects come
4661 	 * down as ipa_t bind. As we would have set conn_policy_cached
4662 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4663 	 * can change after the disconnect.
4664 	 */
4665 	connp->conn_policy_cached = B_FALSE;
4666 
4667 	/*
4668 	 * If not fanout_insert this was just an address verification
4669 	 */
4670 	if (fanout_insert) {
4671 		/*
4672 		 * The addresses have been verified. Time to insert in
4673 		 * the correct fanout list.
4674 		 */
4675 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4676 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4677 		connp->conn_lport = lport;
4678 		connp->conn_fport = 0;
4679 		/*
4680 		 * Do we need to add a check to reject Multicast packets
4681 		 */
4682 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4683 	}
4684 
4685 	if (error == 0) {
4686 		if (ire_requested) {
4687 			if (!ip_bind_insert_ire(mp, src_ire, NULL, ipst)) {
4688 				error = -1;
4689 				/* Falls through to bad_addr */
4690 			}
4691 		} else if (ipsec_policy_set) {
4692 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4693 				error = -1;
4694 				/* Falls through to bad_addr */
4695 			}
4696 		}
4697 	}
4698 bad_addr:
4699 	if (error != 0) {
4700 		if (connp->conn_anon_port) {
4701 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4702 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4703 			    B_FALSE);
4704 		}
4705 		connp->conn_mlp_type = mlptSingle;
4706 	}
4707 	if (src_ire != NULL)
4708 		IRE_REFRELE(src_ire);
4709 	if (ipsec_policy_set) {
4710 		ASSERT(policy_mp == mp->b_cont);
4711 		ASSERT(policy_mp != NULL);
4712 		freeb(policy_mp);
4713 		/*
4714 		 * As of now assume that nothing else accompanies
4715 		 * IPSEC_POLICY_SET.
4716 		 */
4717 		mp->b_cont = NULL;
4718 	}
4719 	return (error);
4720 }
4721 
4722 /*
4723  * Verify that both the source and destination addresses
4724  * are valid.  If verify_dst is false, then the destination address may be
4725  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4726  * destination reachability, while tunnels do not.
4727  * Note that we allow connect to broadcast and multicast
4728  * addresses when ire_requested is set. Thus the ULP
4729  * has to check for IRE_BROADCAST and multicast.
4730  *
4731  * Returns zero if ok.
4732  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4733  * (for use with TSYSERR reply).
4734  *
4735  * Note: lport and fport are in network byte order.
4736  */
4737 int
4738 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4739     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4740     boolean_t ire_requested, boolean_t ipsec_policy_set,
4741     boolean_t fanout_insert, boolean_t verify_dst)
4742 {
4743 	ire_t		*src_ire;
4744 	ire_t		*dst_ire;
4745 	int		error = 0;
4746 	int 		protocol;
4747 	mblk_t		*policy_mp;
4748 	ire_t		*sire = NULL;
4749 	ire_t		*md_dst_ire = NULL;
4750 	ire_t		*lso_dst_ire = NULL;
4751 	ill_t		*ill = NULL;
4752 	zoneid_t	zoneid;
4753 	ipaddr_t	src_addr = *src_addrp;
4754 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4755 
4756 	src_ire = dst_ire = NULL;
4757 	protocol = *mp->b_wptr & 0xFF;
4758 
4759 	/*
4760 	 * If we never got a disconnect before, clear it now.
4761 	 */
4762 	connp->conn_fully_bound = B_FALSE;
4763 
4764 	if (ipsec_policy_set) {
4765 		policy_mp = mp->b_cont;
4766 	}
4767 
4768 	zoneid = IPCL_ZONEID(connp);
4769 
4770 	if (CLASSD(dst_addr)) {
4771 		/* Pick up an IRE_BROADCAST */
4772 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4773 		    NULL, zoneid, MBLK_GETLABEL(mp),
4774 		    (MATCH_IRE_RECURSIVE |
4775 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4776 		    MATCH_IRE_SECATTR), ipst);
4777 	} else {
4778 		/*
4779 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4780 		 * and onlink ipif is not found set ENETUNREACH error.
4781 		 */
4782 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4783 			ipif_t *ipif;
4784 
4785 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4786 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4787 			if (ipif == NULL) {
4788 				error = ENETUNREACH;
4789 				goto bad_addr;
4790 			}
4791 			ipif_refrele(ipif);
4792 		}
4793 
4794 		if (connp->conn_nexthop_set) {
4795 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4796 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4797 			    MATCH_IRE_SECATTR, ipst);
4798 		} else {
4799 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4800 			    &sire, zoneid, MBLK_GETLABEL(mp),
4801 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4802 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4803 			    MATCH_IRE_SECATTR), ipst);
4804 		}
4805 	}
4806 	/*
4807 	 * dst_ire can't be a broadcast when not ire_requested.
4808 	 * We also prevent ire's with src address INADDR_ANY to
4809 	 * be used, which are created temporarily for
4810 	 * sending out packets from endpoints that have
4811 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4812 	 * reachable.  If verify_dst is false, the destination needn't be
4813 	 * reachable.
4814 	 *
4815 	 * If we match on a reject or black hole, then we've got a
4816 	 * local failure.  May as well fail out the connect() attempt,
4817 	 * since it's never going to succeed.
4818 	 */
4819 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4820 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4821 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4822 		/*
4823 		 * If we're verifying destination reachability, we always want
4824 		 * to complain here.
4825 		 *
4826 		 * If we're not verifying destination reachability but the
4827 		 * destination has a route, we still want to fail on the
4828 		 * temporary address and broadcast address tests.
4829 		 */
4830 		if (verify_dst || (dst_ire != NULL)) {
4831 			if (ip_debug > 2) {
4832 				pr_addr_dbg("ip_bind_connected: bad connected "
4833 				    "dst %s\n", AF_INET, &dst_addr);
4834 			}
4835 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4836 				error = ENETUNREACH;
4837 			else
4838 				error = EHOSTUNREACH;
4839 			goto bad_addr;
4840 		}
4841 	}
4842 
4843 	/*
4844 	 * We now know that routing will allow us to reach the destination.
4845 	 * Check whether Trusted Solaris policy allows communication with this
4846 	 * host, and pretend that the destination is unreachable if not.
4847 	 *
4848 	 * This is never a problem for TCP, since that transport is known to
4849 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4850 	 * handling.  If the remote is unreachable, it will be detected at that
4851 	 * point, so there's no reason to check it here.
4852 	 *
4853 	 * Note that for sendto (and other datagram-oriented friends), this
4854 	 * check is done as part of the data path label computation instead.
4855 	 * The check here is just to make non-TCP connect() report the right
4856 	 * error.
4857 	 */
4858 	if (dst_ire != NULL && is_system_labeled() &&
4859 	    !IPCL_IS_TCP(connp) &&
4860 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4861 	    connp->conn_mac_exempt, ipst) != 0) {
4862 		error = EHOSTUNREACH;
4863 		if (ip_debug > 2) {
4864 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4865 			    AF_INET, &dst_addr);
4866 		}
4867 		goto bad_addr;
4868 	}
4869 
4870 	/*
4871 	 * If the app does a connect(), it means that it will most likely
4872 	 * send more than 1 packet to the destination.  It makes sense
4873 	 * to clear the temporary flag.
4874 	 */
4875 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4876 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4877 		irb_t *irb = dst_ire->ire_bucket;
4878 
4879 		rw_enter(&irb->irb_lock, RW_WRITER);
4880 		/*
4881 		 * We need to recheck for IRE_MARK_TEMPORARY after acquiring
4882 		 * the lock to guarantee irb_tmp_ire_cnt.
4883 		 */
4884 		if (dst_ire->ire_marks & IRE_MARK_TEMPORARY) {
4885 			dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4886 			irb->irb_tmp_ire_cnt--;
4887 		}
4888 		rw_exit(&irb->irb_lock);
4889 	}
4890 
4891 	/*
4892 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4893 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4894 	 * eligibility tests for passive connects are handled separately
4895 	 * through tcp_adapt_ire().  We do this before the source address
4896 	 * selection, because dst_ire may change after a call to
4897 	 * ipif_select_source().  This is a best-effort check, as the
4898 	 * packet for this connection may not actually go through
4899 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4900 	 * calling ip_newroute().  This is why we further check on the
4901 	 * IRE during LSO/Multidata packet transmission in
4902 	 * tcp_lsosend()/tcp_multisend().
4903 	 */
4904 	if (!ipsec_policy_set && dst_ire != NULL &&
4905 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4906 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4907 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4908 			lso_dst_ire = dst_ire;
4909 			IRE_REFHOLD(lso_dst_ire);
4910 		} else if (ipst->ips_ip_multidata_outbound &&
4911 		    ILL_MDT_CAPABLE(ill)) {
4912 			md_dst_ire = dst_ire;
4913 			IRE_REFHOLD(md_dst_ire);
4914 		}
4915 	}
4916 
4917 	if (dst_ire != NULL &&
4918 	    dst_ire->ire_type == IRE_LOCAL &&
4919 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4920 		/*
4921 		 * If the IRE belongs to a different zone, look for a matching
4922 		 * route in the forwarding table and use the source address from
4923 		 * that route.
4924 		 */
4925 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4926 		    zoneid, 0, NULL,
4927 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4928 		    MATCH_IRE_RJ_BHOLE, ipst);
4929 		if (src_ire == NULL) {
4930 			error = EHOSTUNREACH;
4931 			goto bad_addr;
4932 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4933 			if (!(src_ire->ire_type & IRE_HOST))
4934 				error = ENETUNREACH;
4935 			else
4936 				error = EHOSTUNREACH;
4937 			goto bad_addr;
4938 		}
4939 		if (src_addr == INADDR_ANY)
4940 			src_addr = src_ire->ire_src_addr;
4941 		ire_refrele(src_ire);
4942 		src_ire = NULL;
4943 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4944 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4945 			src_addr = sire->ire_src_addr;
4946 			ire_refrele(dst_ire);
4947 			dst_ire = sire;
4948 			sire = NULL;
4949 		} else {
4950 			/*
4951 			 * Pick a source address so that a proper inbound
4952 			 * load spreading would happen.
4953 			 */
4954 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4955 			ipif_t *src_ipif = NULL;
4956 			ire_t *ipif_ire;
4957 
4958 			/*
4959 			 * Supply a local source address such that inbound
4960 			 * load spreading happens.
4961 			 *
4962 			 * Determine the best source address on this ill for
4963 			 * the destination.
4964 			 *
4965 			 * 1) For broadcast, we should return a broadcast ire
4966 			 *    found above so that upper layers know that the
4967 			 *    destination address is a broadcast address.
4968 			 *
4969 			 * 2) If this is part of a group, select a better
4970 			 *    source address so that better inbound load
4971 			 *    balancing happens. Do the same if the ipif
4972 			 *    is DEPRECATED.
4973 			 *
4974 			 * 3) If the outgoing interface is part of a usesrc
4975 			 *    group, then try selecting a source address from
4976 			 *    the usesrc ILL.
4977 			 */
4978 			if ((dst_ire->ire_zoneid != zoneid &&
4979 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4980 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4981 			    ((dst_ill->ill_group != NULL) ||
4982 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4983 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4984 				/*
4985 				 * If the destination is reachable via a
4986 				 * given gateway, the selected source address
4987 				 * should be in the same subnet as the gateway.
4988 				 * Otherwise, the destination is not reachable.
4989 				 *
4990 				 * If there are no interfaces on the same subnet
4991 				 * as the destination, ipif_select_source gives
4992 				 * first non-deprecated interface which might be
4993 				 * on a different subnet than the gateway.
4994 				 * This is not desirable. Hence pass the dst_ire
4995 				 * source address to ipif_select_source.
4996 				 * It is sure that the destination is reachable
4997 				 * with the dst_ire source address subnet.
4998 				 * So passing dst_ire source address to
4999 				 * ipif_select_source will make sure that the
5000 				 * selected source will be on the same subnet
5001 				 * as dst_ire source address.
5002 				 */
5003 				ipaddr_t saddr =
5004 				    dst_ire->ire_ipif->ipif_src_addr;
5005 				src_ipif = ipif_select_source(dst_ill,
5006 				    saddr, zoneid);
5007 				if (src_ipif != NULL) {
5008 					if (IS_VNI(src_ipif->ipif_ill)) {
5009 						/*
5010 						 * For VNI there is no
5011 						 * interface route
5012 						 */
5013 						src_addr =
5014 						    src_ipif->ipif_src_addr;
5015 					} else {
5016 						ipif_ire =
5017 						    ipif_to_ire(src_ipif);
5018 						if (ipif_ire != NULL) {
5019 							IRE_REFRELE(dst_ire);
5020 							dst_ire = ipif_ire;
5021 						}
5022 						src_addr =
5023 						    dst_ire->ire_src_addr;
5024 					}
5025 					ipif_refrele(src_ipif);
5026 				} else {
5027 					src_addr = dst_ire->ire_src_addr;
5028 				}
5029 			} else {
5030 				src_addr = dst_ire->ire_src_addr;
5031 			}
5032 		}
5033 	}
5034 
5035 	/*
5036 	 * We do ire_route_lookup() here (and not
5037 	 * interface lookup as we assert that
5038 	 * src_addr should only come from an
5039 	 * UP interface for hard binding.
5040 	 */
5041 	ASSERT(src_ire == NULL);
5042 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5043 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5044 	/* src_ire must be a local|loopback */
5045 	if (!IRE_IS_LOCAL(src_ire)) {
5046 		if (ip_debug > 2) {
5047 			pr_addr_dbg("ip_bind_connected: bad connected "
5048 			    "src %s\n", AF_INET, &src_addr);
5049 		}
5050 		error = EADDRNOTAVAIL;
5051 		goto bad_addr;
5052 	}
5053 
5054 	/*
5055 	 * If the source address is a loopback address, the
5056 	 * destination had best be local or multicast.
5057 	 * The transports that can't handle multicast will reject
5058 	 * those addresses.
5059 	 */
5060 	if (src_ire->ire_type == IRE_LOOPBACK &&
5061 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5062 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5063 		error = -1;
5064 		goto bad_addr;
5065 	}
5066 
5067 	/*
5068 	 * Allow setting new policies. For example, disconnects come
5069 	 * down as ipa_t bind. As we would have set conn_policy_cached
5070 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5071 	 * can change after the disconnect.
5072 	 */
5073 	connp->conn_policy_cached = B_FALSE;
5074 
5075 	/*
5076 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5077 	 * can handle their passed-in conn's.
5078 	 */
5079 
5080 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5081 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5082 	connp->conn_lport = lport;
5083 	connp->conn_fport = fport;
5084 	*src_addrp = src_addr;
5085 
5086 	ASSERT(!(ipsec_policy_set && ire_requested));
5087 	if (ire_requested) {
5088 		iulp_t *ulp_info = NULL;
5089 
5090 		/*
5091 		 * Note that sire will not be NULL if this is an off-link
5092 		 * connection and there is not cache for that dest yet.
5093 		 *
5094 		 * XXX Because of an existing bug, if there are multiple
5095 		 * default routes, the IRE returned now may not be the actual
5096 		 * default route used (default routes are chosen in a
5097 		 * round robin fashion).  So if the metrics for different
5098 		 * default routes are different, we may return the wrong
5099 		 * metrics.  This will not be a problem if the existing
5100 		 * bug is fixed.
5101 		 */
5102 		if (sire != NULL) {
5103 			ulp_info = &(sire->ire_uinfo);
5104 		}
5105 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info, ipst)) {
5106 			error = -1;
5107 			goto bad_addr;
5108 		}
5109 	} else if (ipsec_policy_set) {
5110 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5111 			error = -1;
5112 			goto bad_addr;
5113 		}
5114 	}
5115 
5116 	/*
5117 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5118 	 * we'll cache that.  If we don't, we'll inherit global policy.
5119 	 *
5120 	 * We can't insert until the conn reflects the policy. Note that
5121 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5122 	 * connections where we don't have a policy. This is to prevent
5123 	 * global policy lookups in the inbound path.
5124 	 *
5125 	 * If we insert before we set conn_policy_cached,
5126 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5127 	 * because global policy cound be non-empty. We normally call
5128 	 * ipsec_check_policy() for conn_policy_cached connections only if
5129 	 * ipc_in_enforce_policy is set. But in this case,
5130 	 * conn_policy_cached can get set anytime since we made the
5131 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5132 	 * called, which will make the above assumption false.  Thus, we
5133 	 * need to insert after we set conn_policy_cached.
5134 	 */
5135 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5136 		goto bad_addr;
5137 
5138 	if (fanout_insert) {
5139 		/*
5140 		 * The addresses have been verified. Time to insert in
5141 		 * the correct fanout list.
5142 		 */
5143 		error = ipcl_conn_insert(connp, protocol, src_addr,
5144 		    dst_addr, connp->conn_ports);
5145 	}
5146 
5147 	if (error == 0) {
5148 		connp->conn_fully_bound = B_TRUE;
5149 		/*
5150 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5151 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5152 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5153 		 * ip_xxinfo_return(), which performs further checks
5154 		 * against them and upon success, returns the LSO/MDT info
5155 		 * mblk which we will attach to the bind acknowledgment.
5156 		 */
5157 		if (lso_dst_ire != NULL) {
5158 			mblk_t *lsoinfo_mp;
5159 
5160 			ASSERT(ill->ill_lso_capab != NULL);
5161 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5162 			    ill->ill_name, ill->ill_lso_capab)) != NULL)
5163 				linkb(mp, lsoinfo_mp);
5164 		} else if (md_dst_ire != NULL) {
5165 			mblk_t *mdinfo_mp;
5166 
5167 			ASSERT(ill->ill_mdt_capab != NULL);
5168 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5169 			    ill->ill_name, ill->ill_mdt_capab)) != NULL)
5170 				linkb(mp, mdinfo_mp);
5171 		}
5172 	}
5173 bad_addr:
5174 	if (ipsec_policy_set) {
5175 		ASSERT(policy_mp == mp->b_cont);
5176 		ASSERT(policy_mp != NULL);
5177 		freeb(policy_mp);
5178 		/*
5179 		 * As of now assume that nothing else accompanies
5180 		 * IPSEC_POLICY_SET.
5181 		 */
5182 		mp->b_cont = NULL;
5183 	}
5184 	if (src_ire != NULL)
5185 		IRE_REFRELE(src_ire);
5186 	if (dst_ire != NULL)
5187 		IRE_REFRELE(dst_ire);
5188 	if (sire != NULL)
5189 		IRE_REFRELE(sire);
5190 	if (md_dst_ire != NULL)
5191 		IRE_REFRELE(md_dst_ire);
5192 	if (lso_dst_ire != NULL)
5193 		IRE_REFRELE(lso_dst_ire);
5194 	return (error);
5195 }
5196 
5197 /*
5198  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5199  * Prefers dst_ire over src_ire.
5200  */
5201 static boolean_t
5202 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5203 {
5204 	mblk_t	*mp1;
5205 	ire_t *ret_ire = NULL;
5206 
5207 	mp1 = mp->b_cont;
5208 	ASSERT(mp1 != NULL);
5209 
5210 	if (ire != NULL) {
5211 		/*
5212 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5213 		 * appended mblk. Its <upper protocol>'s
5214 		 * job to make sure there is room.
5215 		 */
5216 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5217 			return (0);
5218 
5219 		mp1->b_datap->db_type = IRE_DB_TYPE;
5220 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5221 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5222 		ret_ire = (ire_t *)mp1->b_rptr;
5223 		/*
5224 		 * Pass the latest setting of the ip_path_mtu_discovery and
5225 		 * copy the ulp info if any.
5226 		 */
5227 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5228 		    IPH_DF : 0;
5229 		if (ulp_info != NULL) {
5230 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5231 			    sizeof (iulp_t));
5232 		}
5233 		ret_ire->ire_mp = mp1;
5234 	} else {
5235 		/*
5236 		 * No IRE was found. Remove IRE mblk.
5237 		 */
5238 		mp->b_cont = mp1->b_cont;
5239 		freeb(mp1);
5240 	}
5241 
5242 	return (1);
5243 }
5244 
5245 /*
5246  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5247  * the final piece where we don't.  Return a pointer to the first mblk in the
5248  * result, and update the pointer to the next mblk to chew on.  If anything
5249  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5250  * NULL pointer.
5251  */
5252 mblk_t *
5253 ip_carve_mp(mblk_t **mpp, ssize_t len)
5254 {
5255 	mblk_t	*mp0;
5256 	mblk_t	*mp1;
5257 	mblk_t	*mp2;
5258 
5259 	if (!len || !mpp || !(mp0 = *mpp))
5260 		return (NULL);
5261 	/* If we aren't going to consume the first mblk, we need a dup. */
5262 	if (mp0->b_wptr - mp0->b_rptr > len) {
5263 		mp1 = dupb(mp0);
5264 		if (mp1) {
5265 			/* Partition the data between the two mblks. */
5266 			mp1->b_wptr = mp1->b_rptr + len;
5267 			mp0->b_rptr = mp1->b_wptr;
5268 			/*
5269 			 * after adjustments if mblk not consumed is now
5270 			 * unaligned, try to align it. If this fails free
5271 			 * all messages and let upper layer recover.
5272 			 */
5273 			if (!OK_32PTR(mp0->b_rptr)) {
5274 				if (!pullupmsg(mp0, -1)) {
5275 					freemsg(mp0);
5276 					freemsg(mp1);
5277 					*mpp = NULL;
5278 					return (NULL);
5279 				}
5280 			}
5281 		}
5282 		return (mp1);
5283 	}
5284 	/* Eat through as many mblks as we need to get len bytes. */
5285 	len -= mp0->b_wptr - mp0->b_rptr;
5286 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5287 		if (mp2->b_wptr - mp2->b_rptr > len) {
5288 			/*
5289 			 * We won't consume the entire last mblk.  Like
5290 			 * above, dup and partition it.
5291 			 */
5292 			mp1->b_cont = dupb(mp2);
5293 			mp1 = mp1->b_cont;
5294 			if (!mp1) {
5295 				/*
5296 				 * Trouble.  Rather than go to a lot of
5297 				 * trouble to clean up, we free the messages.
5298 				 * This won't be any worse than losing it on
5299 				 * the wire.
5300 				 */
5301 				freemsg(mp0);
5302 				freemsg(mp2);
5303 				*mpp = NULL;
5304 				return (NULL);
5305 			}
5306 			mp1->b_wptr = mp1->b_rptr + len;
5307 			mp2->b_rptr = mp1->b_wptr;
5308 			/*
5309 			 * after adjustments if mblk not consumed is now
5310 			 * unaligned, try to align it. If this fails free
5311 			 * all messages and let upper layer recover.
5312 			 */
5313 			if (!OK_32PTR(mp2->b_rptr)) {
5314 				if (!pullupmsg(mp2, -1)) {
5315 					freemsg(mp0);
5316 					freemsg(mp2);
5317 					*mpp = NULL;
5318 					return (NULL);
5319 				}
5320 			}
5321 			*mpp = mp2;
5322 			return (mp0);
5323 		}
5324 		/* Decrement len by the amount we just got. */
5325 		len -= mp2->b_wptr - mp2->b_rptr;
5326 	}
5327 	/*
5328 	 * len should be reduced to zero now.  If not our caller has
5329 	 * screwed up.
5330 	 */
5331 	if (len) {
5332 		/* Shouldn't happen! */
5333 		freemsg(mp0);
5334 		*mpp = NULL;
5335 		return (NULL);
5336 	}
5337 	/*
5338 	 * We consumed up to exactly the end of an mblk.  Detach the part
5339 	 * we are returning from the rest of the chain.
5340 	 */
5341 	mp1->b_cont = NULL;
5342 	*mpp = mp2;
5343 	return (mp0);
5344 }
5345 
5346 /* The ill stream is being unplumbed. Called from ip_close */
5347 int
5348 ip_modclose(ill_t *ill)
5349 {
5350 	boolean_t success;
5351 	ipsq_t	*ipsq;
5352 	ipif_t	*ipif;
5353 	queue_t	*q = ill->ill_rq;
5354 	ip_stack_t	*ipst = ill->ill_ipst;
5355 	clock_t timeout;
5356 
5357 	/*
5358 	 * Wait for the ACKs of all deferred control messages to be processed.
5359 	 * In particular, we wait for a potential capability reset initiated
5360 	 * in ip_sioctl_plink() to complete before proceeding.
5361 	 *
5362 	 * Note: we wait for at most ip_modclose_ackwait_ms (by default 3000 ms)
5363 	 * in case the driver never replies.
5364 	 */
5365 	timeout = lbolt + MSEC_TO_TICK(ip_modclose_ackwait_ms);
5366 	mutex_enter(&ill->ill_lock);
5367 	while (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
5368 		if (cv_timedwait(&ill->ill_cv, &ill->ill_lock, timeout) < 0) {
5369 			/* Timeout */
5370 			break;
5371 		}
5372 	}
5373 	mutex_exit(&ill->ill_lock);
5374 
5375 	/*
5376 	 * Forcibly enter the ipsq after some delay. This is to take
5377 	 * care of the case when some ioctl does not complete because
5378 	 * we sent a control message to the driver and it did not
5379 	 * send us a reply. We want to be able to at least unplumb
5380 	 * and replumb rather than force the user to reboot the system.
5381 	 */
5382 	success = ipsq_enter(ill, B_FALSE);
5383 
5384 	/*
5385 	 * Open/close/push/pop is guaranteed to be single threaded
5386 	 * per stream by STREAMS. FS guarantees that all references
5387 	 * from top are gone before close is called. So there can't
5388 	 * be another close thread that has set CONDEMNED on this ill.
5389 	 * and cause ipsq_enter to return failure.
5390 	 */
5391 	ASSERT(success);
5392 	ipsq = ill->ill_phyint->phyint_ipsq;
5393 
5394 	/*
5395 	 * Mark it condemned. No new reference will be made to this ill.
5396 	 * Lookup functions will return an error. Threads that try to
5397 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5398 	 * that the refcnt will drop down to zero.
5399 	 */
5400 	mutex_enter(&ill->ill_lock);
5401 	ill->ill_state_flags |= ILL_CONDEMNED;
5402 	for (ipif = ill->ill_ipif; ipif != NULL;
5403 	    ipif = ipif->ipif_next) {
5404 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5405 	}
5406 	/*
5407 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5408 	 * returns  error if ILL_CONDEMNED is set
5409 	 */
5410 	cv_broadcast(&ill->ill_cv);
5411 	mutex_exit(&ill->ill_lock);
5412 
5413 	/*
5414 	 * Send all the deferred DLPI messages downstream which came in
5415 	 * during the small window right before ipsq_enter(). We do this
5416 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5417 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5418 	 */
5419 	ill_dlpi_send_deferred(ill);
5420 
5421 	/*
5422 	 * Shut down fragmentation reassembly.
5423 	 * ill_frag_timer won't start a timer again.
5424 	 * Now cancel any existing timer
5425 	 */
5426 	(void) untimeout(ill->ill_frag_timer_id);
5427 	(void) ill_frag_timeout(ill, 0);
5428 
5429 	/*
5430 	 * If MOVE was in progress, clear the
5431 	 * move_in_progress fields also.
5432 	 */
5433 	if (ill->ill_move_in_progress) {
5434 		ILL_CLEAR_MOVE(ill);
5435 	}
5436 
5437 	/*
5438 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5439 	 * this ill. Then wait for the refcnts to drop to zero.
5440 	 * ill_is_quiescent checks whether the ill is really quiescent.
5441 	 * Then make sure that threads that are waiting to enter the
5442 	 * ipsq have seen the error returned by ipsq_enter and have
5443 	 * gone away. Then we call ill_delete_tail which does the
5444 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5445 	 */
5446 	ill_delete(ill);
5447 	mutex_enter(&ill->ill_lock);
5448 	while (!ill_is_quiescent(ill))
5449 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5450 	while (ill->ill_waiters)
5451 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5452 
5453 	mutex_exit(&ill->ill_lock);
5454 
5455 	/*
5456 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5457 	 * it held until the end of the function since the cleanup
5458 	 * below needs to be able to use the ip_stack_t.
5459 	 */
5460 	netstack_hold(ipst->ips_netstack);
5461 
5462 	/* qprocsoff is called in ill_delete_tail */
5463 	ill_delete_tail(ill);
5464 	ASSERT(ill->ill_ipst == NULL);
5465 
5466 	/*
5467 	 * Walk through all upper (conn) streams and qenable
5468 	 * those that have queued data.
5469 	 * close synchronization needs this to
5470 	 * be done to ensure that all upper layers blocked
5471 	 * due to flow control to the closing device
5472 	 * get unblocked.
5473 	 */
5474 	ip1dbg(("ip_wsrv: walking\n"));
5475 	conn_walk_drain(ipst);
5476 
5477 	mutex_enter(&ipst->ips_ip_mi_lock);
5478 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5479 	mutex_exit(&ipst->ips_ip_mi_lock);
5480 
5481 	/*
5482 	 * credp could be null if the open didn't succeed and ip_modopen
5483 	 * itself calls ip_close.
5484 	 */
5485 	if (ill->ill_credp != NULL)
5486 		crfree(ill->ill_credp);
5487 
5488 	mutex_enter(&ill->ill_lock);
5489 	ill_nic_info_dispatch(ill);
5490 	mutex_exit(&ill->ill_lock);
5491 
5492 	/*
5493 	 * Now we are done with the module close pieces that
5494 	 * need the netstack_t.
5495 	 */
5496 	netstack_rele(ipst->ips_netstack);
5497 
5498 	mi_close_free((IDP)ill);
5499 	q->q_ptr = WR(q)->q_ptr = NULL;
5500 
5501 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5502 
5503 	return (0);
5504 }
5505 
5506 /*
5507  * This is called as part of close() for IP, UDP, ICMP, and RTS
5508  * in order to quiesce the conn.
5509  */
5510 void
5511 ip_quiesce_conn(conn_t *connp)
5512 {
5513 	boolean_t	drain_cleanup_reqd = B_FALSE;
5514 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5515 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5516 	ip_stack_t	*ipst;
5517 
5518 	ASSERT(!IPCL_IS_TCP(connp));
5519 	ipst = connp->conn_netstack->netstack_ip;
5520 
5521 	/*
5522 	 * Mark the conn as closing, and this conn must not be
5523 	 * inserted in future into any list. Eg. conn_drain_insert(),
5524 	 * won't insert this conn into the conn_drain_list.
5525 	 * Similarly ill_pending_mp_add() will not add any mp to
5526 	 * the pending mp list, after this conn has started closing.
5527 	 *
5528 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5529 	 * cannot get set henceforth.
5530 	 */
5531 	mutex_enter(&connp->conn_lock);
5532 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5533 	connp->conn_state_flags |= CONN_CLOSING;
5534 	if (connp->conn_idl != NULL)
5535 		drain_cleanup_reqd = B_TRUE;
5536 	if (connp->conn_oper_pending_ill != NULL)
5537 		conn_ioctl_cleanup_reqd = B_TRUE;
5538 	if (connp->conn_dhcpinit_ill != NULL) {
5539 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
5540 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
5541 		connp->conn_dhcpinit_ill = NULL;
5542 	}
5543 	if (connp->conn_ilg_inuse != 0)
5544 		ilg_cleanup_reqd = B_TRUE;
5545 	mutex_exit(&connp->conn_lock);
5546 
5547 	if (conn_ioctl_cleanup_reqd)
5548 		conn_ioctl_cleanup(connp);
5549 
5550 	if (is_system_labeled() && connp->conn_anon_port) {
5551 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5552 		    connp->conn_mlp_type, connp->conn_ulp,
5553 		    ntohs(connp->conn_lport), B_FALSE);
5554 		connp->conn_anon_port = 0;
5555 	}
5556 	connp->conn_mlp_type = mlptSingle;
5557 
5558 	/*
5559 	 * Remove this conn from any fanout list it is on.
5560 	 * and then wait for any threads currently operating
5561 	 * on this endpoint to finish
5562 	 */
5563 	ipcl_hash_remove(connp);
5564 
5565 	/*
5566 	 * Remove this conn from the drain list, and do
5567 	 * any other cleanup that may be required.
5568 	 * (Only non-tcp streams may have a non-null conn_idl.
5569 	 * TCP streams are never flow controlled, and
5570 	 * conn_idl will be null)
5571 	 */
5572 	if (drain_cleanup_reqd)
5573 		conn_drain_tail(connp, B_TRUE);
5574 
5575 	if (connp == ipst->ips_ip_g_mrouter)
5576 		(void) ip_mrouter_done(NULL, ipst);
5577 
5578 	if (ilg_cleanup_reqd)
5579 		ilg_delete_all(connp);
5580 
5581 	conn_delete_ire(connp, NULL);
5582 
5583 	/*
5584 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5585 	 * callers from write side can't be there now because close
5586 	 * is in progress. The only other caller is ipcl_walk
5587 	 * which checks for the condemned flag.
5588 	 */
5589 	mutex_enter(&connp->conn_lock);
5590 	connp->conn_state_flags |= CONN_CONDEMNED;
5591 	while (connp->conn_ref != 1)
5592 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5593 	connp->conn_state_flags |= CONN_QUIESCED;
5594 	mutex_exit(&connp->conn_lock);
5595 }
5596 
5597 /* ARGSUSED */
5598 int
5599 ip_close(queue_t *q, int flags)
5600 {
5601 	conn_t		*connp;
5602 
5603 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5604 
5605 	/*
5606 	 * Call the appropriate delete routine depending on whether this is
5607 	 * a module or device.
5608 	 */
5609 	if (WR(q)->q_next != NULL) {
5610 		/* This is a module close */
5611 		return (ip_modclose((ill_t *)q->q_ptr));
5612 	}
5613 
5614 	connp = q->q_ptr;
5615 	ip_quiesce_conn(connp);
5616 
5617 	qprocsoff(q);
5618 
5619 	/*
5620 	 * Now we are truly single threaded on this stream, and can
5621 	 * delete the things hanging off the connp, and finally the connp.
5622 	 * We removed this connp from the fanout list, it cannot be
5623 	 * accessed thru the fanouts, and we already waited for the
5624 	 * conn_ref to drop to 0. We are already in close, so
5625 	 * there cannot be any other thread from the top. qprocsoff
5626 	 * has completed, and service has completed or won't run in
5627 	 * future.
5628 	 */
5629 	ASSERT(connp->conn_ref == 1);
5630 
5631 	inet_minor_free(ip_minor_arena, connp->conn_dev);
5632 
5633 	connp->conn_ref--;
5634 	ipcl_conn_destroy(connp);
5635 
5636 	q->q_ptr = WR(q)->q_ptr = NULL;
5637 	return (0);
5638 }
5639 
5640 /*
5641  * Wapper around putnext() so that ip_rts_request can merely use
5642  * conn_recv.
5643  */
5644 /*ARGSUSED2*/
5645 static void
5646 ip_conn_input(void *arg1, mblk_t *mp, void *arg2)
5647 {
5648 	conn_t *connp = (conn_t *)arg1;
5649 
5650 	putnext(connp->conn_rq, mp);
5651 }
5652 
5653 /* Return the IP checksum for the IP header at "iph". */
5654 uint16_t
5655 ip_csum_hdr(ipha_t *ipha)
5656 {
5657 	uint16_t	*uph;
5658 	uint32_t	sum;
5659 	int		opt_len;
5660 
5661 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5662 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5663 	uph = (uint16_t *)ipha;
5664 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5665 	    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5666 	if (opt_len > 0) {
5667 		do {
5668 			sum += uph[10];
5669 			sum += uph[11];
5670 			uph += 2;
5671 		} while (--opt_len);
5672 	}
5673 	sum = (sum & 0xFFFF) + (sum >> 16);
5674 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5675 	if (sum == 0xffff)
5676 		sum = 0;
5677 	return ((uint16_t)sum);
5678 }
5679 
5680 /*
5681  * Called when the module is about to be unloaded
5682  */
5683 void
5684 ip_ddi_destroy(void)
5685 {
5686 	tnet_fini();
5687 
5688 	icmp_ddi_destroy();
5689 	rts_ddi_destroy();
5690 	udp_ddi_destroy();
5691 	sctp_ddi_g_destroy();
5692 	tcp_ddi_g_destroy();
5693 	ipsec_policy_g_destroy();
5694 	ipcl_g_destroy();
5695 	ip_net_g_destroy();
5696 	ip_ire_g_fini();
5697 	inet_minor_destroy(ip_minor_arena);
5698 
5699 #ifdef DEBUG
5700 	list_destroy(&ip_thread_list);
5701 	rw_destroy(&ip_thread_rwlock);
5702 	tsd_destroy(&ip_thread_data);
5703 #endif
5704 
5705 	netstack_unregister(NS_IP);
5706 }
5707 
5708 /*
5709  * First step in cleanup.
5710  */
5711 /* ARGSUSED */
5712 static void
5713 ip_stack_shutdown(netstackid_t stackid, void *arg)
5714 {
5715 	ip_stack_t *ipst = (ip_stack_t *)arg;
5716 
5717 #ifdef NS_DEBUG
5718 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5719 #endif
5720 
5721 	/* Get rid of loopback interfaces and their IREs */
5722 	ip_loopback_cleanup(ipst);
5723 }
5724 
5725 /*
5726  * Free the IP stack instance.
5727  */
5728 static void
5729 ip_stack_fini(netstackid_t stackid, void *arg)
5730 {
5731 	ip_stack_t *ipst = (ip_stack_t *)arg;
5732 	int ret;
5733 
5734 #ifdef NS_DEBUG
5735 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5736 #endif
5737 	ipv4_hook_destroy(ipst);
5738 	ipv6_hook_destroy(ipst);
5739 	ip_net_destroy(ipst);
5740 
5741 	rw_destroy(&ipst->ips_srcid_lock);
5742 
5743 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5744 	ipst->ips_ip_mibkp = NULL;
5745 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5746 	ipst->ips_icmp_mibkp = NULL;
5747 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5748 	ipst->ips_ip_kstat = NULL;
5749 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5750 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5751 	ipst->ips_ip6_kstat = NULL;
5752 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5753 
5754 	nd_free(&ipst->ips_ip_g_nd);
5755 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5756 	ipst->ips_param_arr = NULL;
5757 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5758 	ipst->ips_ndp_arr = NULL;
5759 
5760 	ip_mrouter_stack_destroy(ipst);
5761 
5762 	mutex_destroy(&ipst->ips_ip_mi_lock);
5763 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5764 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5765 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5766 
5767 	ret = untimeout(ipst->ips_igmp_timeout_id);
5768 	if (ret == -1) {
5769 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5770 	} else {
5771 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5772 		ipst->ips_igmp_timeout_id = 0;
5773 	}
5774 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5775 	if (ret == -1) {
5776 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5777 	} else {
5778 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5779 		ipst->ips_igmp_slowtimeout_id = 0;
5780 	}
5781 	ret = untimeout(ipst->ips_mld_timeout_id);
5782 	if (ret == -1) {
5783 		ASSERT(ipst->ips_mld_timeout_id == 0);
5784 	} else {
5785 		ASSERT(ipst->ips_mld_timeout_id != 0);
5786 		ipst->ips_mld_timeout_id = 0;
5787 	}
5788 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5789 	if (ret == -1) {
5790 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5791 	} else {
5792 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5793 		ipst->ips_mld_slowtimeout_id = 0;
5794 	}
5795 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5796 	if (ret == -1) {
5797 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5798 	} else {
5799 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5800 		ipst->ips_ip_ire_expire_id = 0;
5801 	}
5802 
5803 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5804 	mutex_destroy(&ipst->ips_mld_timer_lock);
5805 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5806 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5807 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5808 	rw_destroy(&ipst->ips_ill_g_lock);
5809 
5810 	ip_ire_fini(ipst);
5811 	ip6_asp_free(ipst);
5812 	conn_drain_fini(ipst);
5813 	ipcl_destroy(ipst);
5814 
5815 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5816 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5817 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5818 	ipst->ips_ndp4 = NULL;
5819 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5820 	ipst->ips_ndp6 = NULL;
5821 
5822 	if (ipst->ips_loopback_ksp != NULL) {
5823 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5824 		ipst->ips_loopback_ksp = NULL;
5825 	}
5826 
5827 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5828 	ipst->ips_phyint_g_list = NULL;
5829 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5830 	ipst->ips_ill_g_heads = NULL;
5831 
5832 	kmem_free(ipst, sizeof (*ipst));
5833 }
5834 
5835 /*
5836  * This function is called from the TSD destructor, and is used to debug
5837  * reference count issues in IP. See block comment in <inet/ip_if.h> for
5838  * details.
5839  */
5840 static void
5841 ip_thread_exit(void *phash)
5842 {
5843 	th_hash_t *thh = phash;
5844 
5845 	rw_enter(&ip_thread_rwlock, RW_WRITER);
5846 	list_remove(&ip_thread_list, thh);
5847 	rw_exit(&ip_thread_rwlock);
5848 	mod_hash_destroy_hash(thh->thh_hash);
5849 	kmem_free(thh, sizeof (*thh));
5850 }
5851 
5852 /*
5853  * Called when the IP kernel module is loaded into the kernel
5854  */
5855 void
5856 ip_ddi_init(void)
5857 {
5858 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5859 
5860 	/*
5861 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5862 	 * initial devices: ip, ip6, tcp, tcp6.
5863 	 */
5864 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
5865 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
5866 		cmn_err(CE_PANIC,
5867 		    "ip_ddi_init: ip_minor_arena creation failed\n");
5868 	}
5869 
5870 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5871 
5872 	ipcl_g_init();
5873 	ip_ire_g_init();
5874 	ip_net_g_init();
5875 
5876 #ifdef DEBUG
5877 	tsd_create(&ip_thread_data, ip_thread_exit);
5878 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
5879 	list_create(&ip_thread_list, sizeof (th_hash_t),
5880 	    offsetof(th_hash_t, thh_link));
5881 #endif
5882 
5883 	/*
5884 	 * We want to be informed each time a stack is created or
5885 	 * destroyed in the kernel, so we can maintain the
5886 	 * set of udp_stack_t's.
5887 	 */
5888 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5889 	    ip_stack_fini);
5890 
5891 	ipsec_policy_g_init();
5892 	tcp_ddi_g_init();
5893 	sctp_ddi_g_init();
5894 
5895 	tnet_init();
5896 
5897 	udp_ddi_init();
5898 	rts_ddi_init();
5899 	icmp_ddi_init();
5900 }
5901 
5902 /*
5903  * Initialize the IP stack instance.
5904  */
5905 static void *
5906 ip_stack_init(netstackid_t stackid, netstack_t *ns)
5907 {
5908 	ip_stack_t	*ipst;
5909 	ipparam_t	*pa;
5910 	ipndp_t		*na;
5911 
5912 #ifdef NS_DEBUG
5913 	printf("ip_stack_init(stack %d)\n", stackid);
5914 #endif
5915 
5916 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
5917 	ipst->ips_netstack = ns;
5918 
5919 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
5920 	    KM_SLEEP);
5921 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
5922 	    KM_SLEEP);
5923 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5924 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5925 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5926 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5927 
5928 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5929 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5930 	ipst->ips_igmp_deferred_next = INFINITY;
5931 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5932 	ipst->ips_mld_deferred_next = INFINITY;
5933 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5934 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5935 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5936 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5937 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
5938 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5939 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5940 
5941 	ipcl_init(ipst);
5942 	ip_ire_init(ipst);
5943 	ip6_asp_init(ipst);
5944 	ipif_init(ipst);
5945 	conn_drain_init(ipst);
5946 	ip_mrouter_stack_init(ipst);
5947 
5948 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
5949 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
5950 
5951 	ipst->ips_ip_multirt_log_interval = 1000;
5952 
5953 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
5954 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
5955 	ipst->ips_ill_index = 1;
5956 
5957 	ipst->ips_saved_ip_g_forward = -1;
5958 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
5959 
5960 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
5961 	ipst->ips_param_arr = pa;
5962 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
5963 
5964 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
5965 	ipst->ips_ndp_arr = na;
5966 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5967 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
5968 	    (caddr_t)&ipst->ips_ip_g_forward;
5969 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
5970 	    (caddr_t)&ipst->ips_ipv6_forward;
5971 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
5972 	    "ip_cgtp_filter") == 0);
5973 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
5974 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
5975 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_name,
5976 	    "ipmp_hook_emulation") == 0);
5977 	ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_data =
5978 	    (caddr_t)&ipst->ips_ipmp_hook_emulation;
5979 
5980 	(void) ip_param_register(&ipst->ips_ip_g_nd,
5981 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
5982 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
5983 
5984 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
5985 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
5986 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
5987 	ipst->ips_ip6_kstat =
5988 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
5989 
5990 	ipst->ips_ipmp_enable_failback = B_TRUE;
5991 
5992 	ipst->ips_ip_src_id = 1;
5993 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
5994 
5995 	ip_net_init(ipst, ns);
5996 	ipv4_hook_init(ipst);
5997 	ipv6_hook_init(ipst);
5998 
5999 	return (ipst);
6000 }
6001 
6002 /*
6003  * Allocate and initialize a DLPI template of the specified length.  (May be
6004  * called as writer.)
6005  */
6006 mblk_t *
6007 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6008 {
6009 	mblk_t	*mp;
6010 
6011 	mp = allocb(len, BPRI_MED);
6012 	if (!mp)
6013 		return (NULL);
6014 
6015 	/*
6016 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6017 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6018 	 * that other DLPI are M_PROTO.
6019 	 */
6020 	if (prim == DL_INFO_REQ) {
6021 		mp->b_datap->db_type = M_PCPROTO;
6022 	} else {
6023 		mp->b_datap->db_type = M_PROTO;
6024 	}
6025 
6026 	mp->b_wptr = mp->b_rptr + len;
6027 	bzero(mp->b_rptr, len);
6028 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6029 	return (mp);
6030 }
6031 
6032 const char *
6033 dlpi_prim_str(int prim)
6034 {
6035 	switch (prim) {
6036 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
6037 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
6038 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
6039 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
6040 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
6041 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
6042 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
6043 	case DL_OK_ACK:		return ("DL_OK_ACK");
6044 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
6045 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
6046 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
6047 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
6048 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
6049 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
6050 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
6051 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
6052 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
6053 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
6054 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
6055 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
6056 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
6057 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
6058 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
6059 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
6060 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
6061 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
6062 	default:		return ("<unknown primitive>");
6063 	}
6064 }
6065 
6066 const char *
6067 dlpi_err_str(int err)
6068 {
6069 	switch (err) {
6070 	case DL_ACCESS:		return ("DL_ACCESS");
6071 	case DL_BADADDR:	return ("DL_BADADDR");
6072 	case DL_BADCORR:	return ("DL_BADCORR");
6073 	case DL_BADDATA:	return ("DL_BADDATA");
6074 	case DL_BADPPA:		return ("DL_BADPPA");
6075 	case DL_BADPRIM:	return ("DL_BADPRIM");
6076 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
6077 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
6078 	case DL_BADSAP:		return ("DL_BADSAP");
6079 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
6080 	case DL_BOUND:		return ("DL_BOUND");
6081 	case DL_INITFAILED:	return ("DL_INITFAILED");
6082 	case DL_NOADDR:		return ("DL_NOADDR");
6083 	case DL_NOTINIT:	return ("DL_NOTINIT");
6084 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
6085 	case DL_SYSERR:		return ("DL_SYSERR");
6086 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
6087 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
6088 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
6089 	case DL_TOOMANY:	return ("DL_TOOMANY");
6090 	case DL_NOTENAB:	return ("DL_NOTENAB");
6091 	case DL_BUSY:		return ("DL_BUSY");
6092 	case DL_NOAUTO:		return ("DL_NOAUTO");
6093 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
6094 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
6095 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
6096 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
6097 	case DL_PENDING:	return ("DL_PENDING");
6098 	default:		return ("<unknown error>");
6099 	}
6100 }
6101 
6102 /*
6103  * Debug formatting routine.  Returns a character string representation of the
6104  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6105  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6106  *
6107  * Once the ndd table-printing interfaces are removed, this can be changed to
6108  * standard dotted-decimal form.
6109  */
6110 char *
6111 ip_dot_addr(ipaddr_t addr, char *buf)
6112 {
6113 	uint8_t *ap = (uint8_t *)&addr;
6114 
6115 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6116 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6117 	return (buf);
6118 }
6119 
6120 /*
6121  * Write the given MAC address as a printable string in the usual colon-
6122  * separated format.
6123  */
6124 const char *
6125 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6126 {
6127 	char *bp;
6128 
6129 	if (alen == 0 || buflen < 4)
6130 		return ("?");
6131 	bp = buf;
6132 	for (;;) {
6133 		/*
6134 		 * If there are more MAC address bytes available, but we won't
6135 		 * have any room to print them, then add "..." to the string
6136 		 * instead.  See below for the 'magic number' explanation.
6137 		 */
6138 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6139 			(void) strcpy(bp, "...");
6140 			break;
6141 		}
6142 		(void) sprintf(bp, "%02x", *addr++);
6143 		bp += 2;
6144 		if (--alen == 0)
6145 			break;
6146 		*bp++ = ':';
6147 		buflen -= 3;
6148 		/*
6149 		 * At this point, based on the first 'if' statement above,
6150 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6151 		 * buflen >= 4.  The first case leaves room for the final "xx"
6152 		 * number and trailing NUL byte.  The second leaves room for at
6153 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6154 		 * that statement.
6155 		 */
6156 	}
6157 	return (buf);
6158 }
6159 
6160 /*
6161  * Send an ICMP error after patching up the packet appropriately.  Returns
6162  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6163  */
6164 static boolean_t
6165 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6166     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6167     zoneid_t zoneid, ip_stack_t *ipst)
6168 {
6169 	ipha_t *ipha;
6170 	mblk_t *first_mp;
6171 	boolean_t secure;
6172 	unsigned char db_type;
6173 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6174 
6175 	first_mp = mp;
6176 	if (mctl_present) {
6177 		mp = mp->b_cont;
6178 		secure = ipsec_in_is_secure(first_mp);
6179 		ASSERT(mp != NULL);
6180 	} else {
6181 		/*
6182 		 * If this is an ICMP error being reported - which goes
6183 		 * up as M_CTLs, we need to convert them to M_DATA till
6184 		 * we finish checking with global policy because
6185 		 * ipsec_check_global_policy() assumes M_DATA as clear
6186 		 * and M_CTL as secure.
6187 		 */
6188 		db_type = DB_TYPE(mp);
6189 		DB_TYPE(mp) = M_DATA;
6190 		secure = B_FALSE;
6191 	}
6192 	/*
6193 	 * We are generating an icmp error for some inbound packet.
6194 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6195 	 * Before we generate an error, check with global policy
6196 	 * to see whether this is allowed to enter the system. As
6197 	 * there is no "conn", we are checking with global policy.
6198 	 */
6199 	ipha = (ipha_t *)mp->b_rptr;
6200 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6201 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6202 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6203 		if (first_mp == NULL)
6204 			return (B_FALSE);
6205 	}
6206 
6207 	if (!mctl_present)
6208 		DB_TYPE(mp) = db_type;
6209 
6210 	if (flags & IP_FF_SEND_ICMP) {
6211 		if (flags & IP_FF_HDR_COMPLETE) {
6212 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6213 				freemsg(first_mp);
6214 				return (B_TRUE);
6215 			}
6216 		}
6217 		if (flags & IP_FF_CKSUM) {
6218 			/*
6219 			 * Have to correct checksum since
6220 			 * the packet might have been
6221 			 * fragmented and the reassembly code in ip_rput
6222 			 * does not restore the IP checksum.
6223 			 */
6224 			ipha->ipha_hdr_checksum = 0;
6225 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6226 		}
6227 		switch (icmp_type) {
6228 		case ICMP_DEST_UNREACHABLE:
6229 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6230 			    ipst);
6231 			break;
6232 		default:
6233 			freemsg(first_mp);
6234 			break;
6235 		}
6236 	} else {
6237 		freemsg(first_mp);
6238 		return (B_FALSE);
6239 	}
6240 
6241 	return (B_TRUE);
6242 }
6243 
6244 /*
6245  * Used to send an ICMP error message when a packet is received for
6246  * a protocol that is not supported. The mblk passed as argument
6247  * is consumed by this function.
6248  */
6249 void
6250 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6251     ip_stack_t *ipst)
6252 {
6253 	mblk_t *mp;
6254 	ipha_t *ipha;
6255 	ill_t *ill;
6256 	ipsec_in_t *ii;
6257 
6258 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6259 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6260 
6261 	mp = ipsec_mp->b_cont;
6262 	ipsec_mp->b_cont = NULL;
6263 	ipha = (ipha_t *)mp->b_rptr;
6264 	/* Get ill from index in ipsec_in_t. */
6265 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6266 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6267 	    ipst);
6268 	if (ill != NULL) {
6269 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6270 			if (ip_fanout_send_icmp(q, mp, flags,
6271 			    ICMP_DEST_UNREACHABLE,
6272 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6273 				BUMP_MIB(ill->ill_ip_mib,
6274 				    ipIfStatsInUnknownProtos);
6275 			}
6276 		} else {
6277 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6278 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6279 			    0, B_FALSE, zoneid, ipst)) {
6280 				BUMP_MIB(ill->ill_ip_mib,
6281 				    ipIfStatsInUnknownProtos);
6282 			}
6283 		}
6284 		ill_refrele(ill);
6285 	} else { /* re-link for the freemsg() below. */
6286 		ipsec_mp->b_cont = mp;
6287 	}
6288 
6289 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6290 	freemsg(ipsec_mp);
6291 }
6292 
6293 /*
6294  * See if the inbound datagram has had IPsec processing applied to it.
6295  */
6296 boolean_t
6297 ipsec_in_is_secure(mblk_t *ipsec_mp)
6298 {
6299 	ipsec_in_t *ii;
6300 
6301 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6302 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6303 
6304 	if (ii->ipsec_in_loopback) {
6305 		return (ii->ipsec_in_secure);
6306 	} else {
6307 		return (ii->ipsec_in_ah_sa != NULL ||
6308 		    ii->ipsec_in_esp_sa != NULL ||
6309 		    ii->ipsec_in_decaps);
6310 	}
6311 }
6312 
6313 /*
6314  * Handle protocols with which IP is less intimate.  There
6315  * can be more than one stream bound to a particular
6316  * protocol.  When this is the case, normally each one gets a copy
6317  * of any incoming packets.
6318  *
6319  * IPsec NOTE :
6320  *
6321  * Don't allow a secure packet going up a non-secure connection.
6322  * We don't allow this because
6323  *
6324  * 1) Reply might go out in clear which will be dropped at
6325  *    the sending side.
6326  * 2) If the reply goes out in clear it will give the
6327  *    adversary enough information for getting the key in
6328  *    most of the cases.
6329  *
6330  * Moreover getting a secure packet when we expect clear
6331  * implies that SA's were added without checking for
6332  * policy on both ends. This should not happen once ISAKMP
6333  * is used to negotiate SAs as SAs will be added only after
6334  * verifying the policy.
6335  *
6336  * NOTE : If the packet was tunneled and not multicast we only send
6337  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6338  * back to delivering packets to AF_INET6 raw sockets.
6339  *
6340  * IPQoS Notes:
6341  * Once we have determined the client, invoke IPPF processing.
6342  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6343  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6344  * ip_policy will be false.
6345  *
6346  * Zones notes:
6347  * Currently only applications in the global zone can create raw sockets for
6348  * protocols other than ICMP. So unlike the broadcast / multicast case of
6349  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6350  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6351  */
6352 static void
6353 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6354     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6355     zoneid_t zoneid)
6356 {
6357 	queue_t	*rq;
6358 	mblk_t	*mp1, *first_mp1;
6359 	uint_t	protocol = ipha->ipha_protocol;
6360 	ipaddr_t dst;
6361 	boolean_t one_only;
6362 	mblk_t *first_mp = mp;
6363 	boolean_t secure;
6364 	uint32_t ill_index;
6365 	conn_t	*connp, *first_connp, *next_connp;
6366 	connf_t	*connfp;
6367 	boolean_t shared_addr;
6368 	mib2_ipIfStatsEntry_t *mibptr;
6369 	ip_stack_t *ipst = recv_ill->ill_ipst;
6370 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6371 
6372 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6373 	if (mctl_present) {
6374 		mp = first_mp->b_cont;
6375 		secure = ipsec_in_is_secure(first_mp);
6376 		ASSERT(mp != NULL);
6377 	} else {
6378 		secure = B_FALSE;
6379 	}
6380 	dst = ipha->ipha_dst;
6381 	/*
6382 	 * If the packet was tunneled and not multicast we only send to it
6383 	 * the first match.
6384 	 */
6385 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6386 	    !CLASSD(dst));
6387 
6388 	shared_addr = (zoneid == ALL_ZONES);
6389 	if (shared_addr) {
6390 		/*
6391 		 * We don't allow multilevel ports for raw IP, so no need to
6392 		 * check for that here.
6393 		 */
6394 		zoneid = tsol_packet_to_zoneid(mp);
6395 	}
6396 
6397 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6398 	mutex_enter(&connfp->connf_lock);
6399 	connp = connfp->connf_head;
6400 	for (connp = connfp->connf_head; connp != NULL;
6401 	    connp = connp->conn_next) {
6402 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6403 		    zoneid) &&
6404 		    (!is_system_labeled() ||
6405 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6406 		    connp))) {
6407 			break;
6408 		}
6409 	}
6410 
6411 	if (connp == NULL || connp->conn_upq == NULL) {
6412 		/*
6413 		 * No one bound to these addresses.  Is
6414 		 * there a client that wants all
6415 		 * unclaimed datagrams?
6416 		 */
6417 		mutex_exit(&connfp->connf_lock);
6418 		/*
6419 		 * Check for IPPROTO_ENCAP...
6420 		 */
6421 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6422 			/*
6423 			 * If an IPsec mblk is here on a multicast
6424 			 * tunnel (using ip_mroute stuff), check policy here,
6425 			 * THEN ship off to ip_mroute_decap().
6426 			 *
6427 			 * BTW,  If I match a configured IP-in-IP
6428 			 * tunnel, this path will not be reached, and
6429 			 * ip_mroute_decap will never be called.
6430 			 */
6431 			first_mp = ipsec_check_global_policy(first_mp, connp,
6432 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6433 			if (first_mp != NULL) {
6434 				if (mctl_present)
6435 					freeb(first_mp);
6436 				ip_mroute_decap(q, mp, ill);
6437 			} /* Else we already freed everything! */
6438 		} else {
6439 			/*
6440 			 * Otherwise send an ICMP protocol unreachable.
6441 			 */
6442 			if (ip_fanout_send_icmp(q, first_mp, flags,
6443 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6444 			    mctl_present, zoneid, ipst)) {
6445 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6446 			}
6447 		}
6448 		return;
6449 	}
6450 	CONN_INC_REF(connp);
6451 	first_connp = connp;
6452 
6453 	/*
6454 	 * Only send message to one tunnel driver by immediately
6455 	 * terminating the loop.
6456 	 */
6457 	connp = one_only ? NULL : connp->conn_next;
6458 
6459 	for (;;) {
6460 		while (connp != NULL) {
6461 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6462 			    flags, zoneid) &&
6463 			    (!is_system_labeled() ||
6464 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6465 			    shared_addr, connp)))
6466 				break;
6467 			connp = connp->conn_next;
6468 		}
6469 
6470 		/*
6471 		 * Copy the packet.
6472 		 */
6473 		if (connp == NULL || connp->conn_upq == NULL ||
6474 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6475 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6476 			/*
6477 			 * No more interested clients or memory
6478 			 * allocation failed
6479 			 */
6480 			connp = first_connp;
6481 			break;
6482 		}
6483 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6484 		CONN_INC_REF(connp);
6485 		mutex_exit(&connfp->connf_lock);
6486 		rq = connp->conn_rq;
6487 		if (!canputnext(rq)) {
6488 			if (flags & IP_FF_RAWIP) {
6489 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6490 			} else {
6491 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6492 			}
6493 
6494 			freemsg(first_mp1);
6495 		} else {
6496 			/*
6497 			 * Don't enforce here if we're an actual tunnel -
6498 			 * let "tun" do it instead.
6499 			 */
6500 			if (!IPCL_IS_IPTUN(connp) &&
6501 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6502 			    secure)) {
6503 				first_mp1 = ipsec_check_inbound_policy
6504 				    (first_mp1, connp, ipha, NULL,
6505 				    mctl_present);
6506 			}
6507 			if (first_mp1 != NULL) {
6508 				int in_flags = 0;
6509 				/*
6510 				 * ip_fanout_proto also gets called from
6511 				 * icmp_inbound_error_fanout, in which case
6512 				 * the msg type is M_CTL.  Don't add info
6513 				 * in this case for the time being. In future
6514 				 * when there is a need for knowing the
6515 				 * inbound iface index for ICMP error msgs,
6516 				 * then this can be changed.
6517 				 */
6518 				if (connp->conn_recvif)
6519 					in_flags = IPF_RECVIF;
6520 				/*
6521 				 * The ULP may support IP_RECVPKTINFO for both
6522 				 * IP v4 and v6 so pass the appropriate argument
6523 				 * based on conn IP version.
6524 				 */
6525 				if (connp->conn_ip_recvpktinfo) {
6526 					if (connp->conn_af_isv6) {
6527 						/*
6528 						 * V6 only needs index
6529 						 */
6530 						in_flags |= IPF_RECVIF;
6531 					} else {
6532 						/*
6533 						 * V4 needs index +
6534 						 * matching address.
6535 						 */
6536 						in_flags |= IPF_RECVADDR;
6537 					}
6538 				}
6539 				if ((in_flags != 0) &&
6540 				    (mp->b_datap->db_type != M_CTL)) {
6541 					/*
6542 					 * the actual data will be
6543 					 * contained in b_cont upon
6544 					 * successful return of the
6545 					 * following call else
6546 					 * original mblk is returned
6547 					 */
6548 					ASSERT(recv_ill != NULL);
6549 					mp1 = ip_add_info(mp1, recv_ill,
6550 					    in_flags, IPCL_ZONEID(connp), ipst);
6551 				}
6552 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6553 				if (mctl_present)
6554 					freeb(first_mp1);
6555 				(connp->conn_recv)(connp, mp1, NULL);
6556 			}
6557 		}
6558 		mutex_enter(&connfp->connf_lock);
6559 		/* Follow the next pointer before releasing the conn. */
6560 		next_connp = connp->conn_next;
6561 		CONN_DEC_REF(connp);
6562 		connp = next_connp;
6563 	}
6564 
6565 	/* Last one.  Send it upstream. */
6566 	mutex_exit(&connfp->connf_lock);
6567 
6568 	/*
6569 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6570 	 * will be set to false.
6571 	 */
6572 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6573 		ill_index = ill->ill_phyint->phyint_ifindex;
6574 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6575 		if (mp == NULL) {
6576 			CONN_DEC_REF(connp);
6577 			if (mctl_present) {
6578 				freeb(first_mp);
6579 			}
6580 			return;
6581 		}
6582 	}
6583 
6584 	rq = connp->conn_rq;
6585 	if (!canputnext(rq)) {
6586 		if (flags & IP_FF_RAWIP) {
6587 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6588 		} else {
6589 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6590 		}
6591 
6592 		freemsg(first_mp);
6593 	} else {
6594 		if (IPCL_IS_IPTUN(connp)) {
6595 			/*
6596 			 * Tunneled packet.  We enforce policy in the tunnel
6597 			 * module itself.
6598 			 *
6599 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6600 			 * a policy check.
6601 			 * FIXME to use conn_recv for tun later.
6602 			 */
6603 			putnext(rq, first_mp);
6604 			CONN_DEC_REF(connp);
6605 			return;
6606 		}
6607 
6608 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6609 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6610 			    ipha, NULL, mctl_present);
6611 		}
6612 
6613 		if (first_mp != NULL) {
6614 			int in_flags = 0;
6615 
6616 			/*
6617 			 * ip_fanout_proto also gets called
6618 			 * from icmp_inbound_error_fanout, in
6619 			 * which case the msg type is M_CTL.
6620 			 * Don't add info in this case for time
6621 			 * being. In future when there is a
6622 			 * need for knowing the inbound iface
6623 			 * index for ICMP error msgs, then this
6624 			 * can be changed
6625 			 */
6626 			if (connp->conn_recvif)
6627 				in_flags = IPF_RECVIF;
6628 			if (connp->conn_ip_recvpktinfo) {
6629 				if (connp->conn_af_isv6) {
6630 					/*
6631 					 * V6 only needs index
6632 					 */
6633 					in_flags |= IPF_RECVIF;
6634 				} else {
6635 					/*
6636 					 * V4 needs index +
6637 					 * matching address.
6638 					 */
6639 					in_flags |= IPF_RECVADDR;
6640 				}
6641 			}
6642 			if ((in_flags != 0) &&
6643 			    (mp->b_datap->db_type != M_CTL)) {
6644 
6645 				/*
6646 				 * the actual data will be contained in
6647 				 * b_cont upon successful return
6648 				 * of the following call else original
6649 				 * mblk is returned
6650 				 */
6651 				ASSERT(recv_ill != NULL);
6652 				mp = ip_add_info(mp, recv_ill,
6653 				    in_flags, IPCL_ZONEID(connp), ipst);
6654 			}
6655 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6656 			(connp->conn_recv)(connp, mp, NULL);
6657 			if (mctl_present)
6658 				freeb(first_mp);
6659 		}
6660 	}
6661 	CONN_DEC_REF(connp);
6662 }
6663 
6664 /*
6665  * Fanout for TCP packets
6666  * The caller puts <fport, lport> in the ports parameter.
6667  *
6668  * IPQoS Notes
6669  * Before sending it to the client, invoke IPPF processing.
6670  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6671  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6672  * ip_policy is false.
6673  */
6674 static void
6675 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6676     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6677 {
6678 	mblk_t  *first_mp;
6679 	boolean_t secure;
6680 	uint32_t ill_index;
6681 	int	ip_hdr_len;
6682 	tcph_t	*tcph;
6683 	boolean_t syn_present = B_FALSE;
6684 	conn_t	*connp;
6685 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6686 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6687 
6688 	ASSERT(recv_ill != NULL);
6689 
6690 	first_mp = mp;
6691 	if (mctl_present) {
6692 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6693 		mp = first_mp->b_cont;
6694 		secure = ipsec_in_is_secure(first_mp);
6695 		ASSERT(mp != NULL);
6696 	} else {
6697 		secure = B_FALSE;
6698 	}
6699 
6700 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6701 
6702 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6703 	    zoneid, ipst)) == NULL) {
6704 		/*
6705 		 * No connected connection or listener. Send a
6706 		 * TH_RST via tcp_xmit_listeners_reset.
6707 		 */
6708 
6709 		/* Initiate IPPf processing, if needed. */
6710 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6711 			uint32_t ill_index;
6712 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6713 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6714 			if (first_mp == NULL)
6715 				return;
6716 		}
6717 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6718 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6719 		    zoneid));
6720 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6721 		    ipst->ips_netstack->netstack_tcp, NULL);
6722 		return;
6723 	}
6724 
6725 	/*
6726 	 * Allocate the SYN for the TCP connection here itself
6727 	 */
6728 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6729 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6730 		if (IPCL_IS_TCP(connp)) {
6731 			squeue_t *sqp;
6732 
6733 			/*
6734 			 * For fused tcp loopback, assign the eager's
6735 			 * squeue to be that of the active connect's.
6736 			 * Note that we don't check for IP_FF_LOOPBACK
6737 			 * here since this routine gets called only
6738 			 * for loopback (unlike the IPv6 counterpart).
6739 			 */
6740 			ASSERT(Q_TO_CONN(q) != NULL);
6741 			if (do_tcp_fusion &&
6742 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6743 			    !secure &&
6744 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6745 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6746 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6747 				sqp = Q_TO_CONN(q)->conn_sqp;
6748 			} else {
6749 				sqp = IP_SQUEUE_GET(lbolt);
6750 			}
6751 
6752 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6753 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6754 			syn_present = B_TRUE;
6755 		}
6756 	}
6757 
6758 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6759 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6760 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6761 		if ((flags & TH_RST) || (flags & TH_URG)) {
6762 			CONN_DEC_REF(connp);
6763 			freemsg(first_mp);
6764 			return;
6765 		}
6766 		if (flags & TH_ACK) {
6767 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6768 			    ipst->ips_netstack->netstack_tcp, connp);
6769 			CONN_DEC_REF(connp);
6770 			return;
6771 		}
6772 
6773 		CONN_DEC_REF(connp);
6774 		freemsg(first_mp);
6775 		return;
6776 	}
6777 
6778 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6779 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6780 		    NULL, mctl_present);
6781 		if (first_mp == NULL) {
6782 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6783 			CONN_DEC_REF(connp);
6784 			return;
6785 		}
6786 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6787 			ASSERT(syn_present);
6788 			if (mctl_present) {
6789 				ASSERT(first_mp != mp);
6790 				first_mp->b_datap->db_struioflag |=
6791 				    STRUIO_POLICY;
6792 			} else {
6793 				ASSERT(first_mp == mp);
6794 				mp->b_datap->db_struioflag &=
6795 				    ~STRUIO_EAGER;
6796 				mp->b_datap->db_struioflag |=
6797 				    STRUIO_POLICY;
6798 			}
6799 		} else {
6800 			/*
6801 			 * Discard first_mp early since we're dealing with a
6802 			 * fully-connected conn_t and tcp doesn't do policy in
6803 			 * this case.
6804 			 */
6805 			if (mctl_present) {
6806 				freeb(first_mp);
6807 				mctl_present = B_FALSE;
6808 			}
6809 			first_mp = mp;
6810 		}
6811 	}
6812 
6813 	/*
6814 	 * Initiate policy processing here if needed. If we get here from
6815 	 * icmp_inbound_error_fanout, ip_policy is false.
6816 	 */
6817 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6818 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6819 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6820 		if (mp == NULL) {
6821 			CONN_DEC_REF(connp);
6822 			if (mctl_present)
6823 				freeb(first_mp);
6824 			return;
6825 		} else if (mctl_present) {
6826 			ASSERT(first_mp != mp);
6827 			first_mp->b_cont = mp;
6828 		} else {
6829 			first_mp = mp;
6830 		}
6831 	}
6832 
6833 
6834 
6835 	/* Handle socket options. */
6836 	if (!syn_present &&
6837 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6838 		/* Add header */
6839 		ASSERT(recv_ill != NULL);
6840 		/*
6841 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6842 		 * IPF_RECVIF.
6843 		 */
6844 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6845 		    ipst);
6846 		if (mp == NULL) {
6847 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6848 			CONN_DEC_REF(connp);
6849 			if (mctl_present)
6850 				freeb(first_mp);
6851 			return;
6852 		} else if (mctl_present) {
6853 			/*
6854 			 * ip_add_info might return a new mp.
6855 			 */
6856 			ASSERT(first_mp != mp);
6857 			first_mp->b_cont = mp;
6858 		} else {
6859 			first_mp = mp;
6860 		}
6861 	}
6862 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6863 	if (IPCL_IS_TCP(connp)) {
6864 		/* do not drain, certain use cases can blow the stack */
6865 		squeue_enter_nodrain(connp->conn_sqp, first_mp,
6866 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6867 	} else {
6868 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
6869 		(connp->conn_recv)(connp, first_mp, NULL);
6870 		CONN_DEC_REF(connp);
6871 	}
6872 }
6873 
6874 /*
6875  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
6876  * pass it along to ESP if the SPI is non-zero.  Returns TRUE if the mblk
6877  * is not consumed.
6878  *
6879  * One of four things can happen, all of which affect the passed-in mblk:
6880  *
6881  * 1.) ICMP messages that go through here just get returned TRUE.
6882  *
6883  * 2.) The packet is stock UDP and gets its zero-SPI stripped.  Return TRUE.
6884  *
6885  * 3.) The packet is ESP-in-UDP, gets transformed into an equivalent
6886  *     ESP packet, and is passed along to ESP for consumption.  Return FALSE.
6887  *
6888  * 4.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
6889  */
6890 static boolean_t
6891 zero_spi_check(queue_t *q, mblk_t *mp, ire_t *ire, ill_t *recv_ill,
6892     ipsec_stack_t *ipss)
6893 {
6894 	int shift, plen, iph_len;
6895 	ipha_t *ipha;
6896 	udpha_t *udpha;
6897 	uint32_t *spi;
6898 	uint8_t *orptr;
6899 	boolean_t udp_pkt, free_ire;
6900 
6901 	if (DB_TYPE(mp) == M_CTL) {
6902 		/*
6903 		 * ICMP message with UDP inside.  Don't bother stripping, just
6904 		 * send it up.
6905 		 *
6906 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
6907 		 * to ignore errors set by ICMP anyway ('cause they might be
6908 		 * forged), but that's the app's decision, not ours.
6909 		 */
6910 
6911 		/* Bunch of reality checks for DEBUG kernels... */
6912 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
6913 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
6914 
6915 		return (B_TRUE);
6916 	}
6917 
6918 	ipha = (ipha_t *)mp->b_rptr;
6919 	iph_len = IPH_HDR_LENGTH(ipha);
6920 	plen = ntohs(ipha->ipha_length);
6921 
6922 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
6923 		/*
6924 		 * Most likely a keepalive for the benefit of an intervening
6925 		 * NAT.  These aren't for us, per se, so drop it.
6926 		 *
6927 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
6928 		 * byte packets (keepalives are 1-byte), but we'll drop them
6929 		 * also.
6930 		 */
6931 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6932 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
6933 		return (B_FALSE);
6934 	}
6935 
6936 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
6937 		/* might as well pull it all up - it might be ESP. */
6938 		if (!pullupmsg(mp, -1)) {
6939 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6940 			    DROPPER(ipss, ipds_esp_nomem),
6941 			    &ipss->ipsec_dropper);
6942 			return (B_FALSE);
6943 		}
6944 
6945 		ipha = (ipha_t *)mp->b_rptr;
6946 	}
6947 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
6948 	if (*spi == 0) {
6949 		/* UDP packet - remove 0-spi. */
6950 		shift = sizeof (uint32_t);
6951 	} else {
6952 		/* ESP-in-UDP packet - reduce to ESP. */
6953 		ipha->ipha_protocol = IPPROTO_ESP;
6954 		shift = sizeof (udpha_t);
6955 	}
6956 
6957 	/* Fix IP header */
6958 	ipha->ipha_length = htons(plen - shift);
6959 	ipha->ipha_hdr_checksum = 0;
6960 
6961 	orptr = mp->b_rptr;
6962 	mp->b_rptr += shift;
6963 
6964 	if (*spi == 0) {
6965 		ASSERT((uint8_t *)ipha == orptr);
6966 		udpha = (udpha_t *)(orptr + iph_len);
6967 		udpha->uha_length = htons(plen - shift - iph_len);
6968 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
6969 		udp_pkt = B_TRUE;
6970 	} else {
6971 		udp_pkt = B_FALSE;
6972 	}
6973 	ovbcopy(orptr, orptr + shift, iph_len);
6974 	if (!udp_pkt) /* Punt up for ESP processing. */ {
6975 		ipha = (ipha_t *)(orptr + shift);
6976 
6977 		free_ire = (ire == NULL);
6978 		if (free_ire) {
6979 			/* Re-acquire ire. */
6980 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
6981 			    ipss->ipsec_netstack->netstack_ip);
6982 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
6983 				if (ire != NULL)
6984 					ire_refrele(ire);
6985 				/*
6986 				 * Do a regular freemsg(), as this is an IP
6987 				 * error (no local route) not an IPsec one.
6988 				 */
6989 				freemsg(mp);
6990 			}
6991 		}
6992 
6993 		ip_proto_input(q, mp, ipha, ire, recv_ill, B_TRUE);
6994 		if (free_ire)
6995 			ire_refrele(ire);
6996 	}
6997 
6998 	return (udp_pkt);
6999 }
7000 
7001 /*
7002  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
7003  * We are responsible for disposing of mp, such as by freemsg() or putnext()
7004  * Caller is responsible for dropping references to the conn, and freeing
7005  * first_mp.
7006  *
7007  * IPQoS Notes
7008  * Before sending it to the client, invoke IPPF processing. Policy processing
7009  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
7010  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
7011  * ip_wput_local, ip_policy is false.
7012  */
7013 static void
7014 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
7015     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
7016     boolean_t ip_policy)
7017 {
7018 	boolean_t	mctl_present = (first_mp != NULL);
7019 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
7020 	uint32_t	ill_index;
7021 	ip_stack_t	*ipst = recv_ill->ill_ipst;
7022 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
7023 
7024 	ASSERT(ill != NULL);
7025 
7026 	if (mctl_present)
7027 		first_mp->b_cont = mp;
7028 	else
7029 		first_mp = mp;
7030 
7031 	if (CONN_UDP_FLOWCTLD(connp)) {
7032 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
7033 		freemsg(first_mp);
7034 		return;
7035 	}
7036 
7037 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
7038 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
7039 		    NULL, mctl_present);
7040 		if (first_mp == NULL) {
7041 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7042 			return;	/* Freed by ipsec_check_inbound_policy(). */
7043 		}
7044 	}
7045 	if (mctl_present)
7046 		freeb(first_mp);
7047 
7048 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
7049 	if (connp->conn_udp->udp_nat_t_endpoint) {
7050 		if (mctl_present) {
7051 			/* mctl_present *shouldn't* happen. */
7052 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
7053 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
7054 			    &ipss->ipsec_dropper);
7055 			return;
7056 		}
7057 
7058 		if (!zero_spi_check(ill->ill_rq, mp, NULL, recv_ill, ipss))
7059 			return;
7060 	}
7061 
7062 	/* Handle options. */
7063 	if (connp->conn_recvif)
7064 		in_flags = IPF_RECVIF;
7065 	/*
7066 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7067 	 * passed to ip_add_info is based on IP version of connp.
7068 	 */
7069 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7070 		if (connp->conn_af_isv6) {
7071 			/*
7072 			 * V6 only needs index
7073 			 */
7074 			in_flags |= IPF_RECVIF;
7075 		} else {
7076 			/*
7077 			 * V4 needs index + matching address.
7078 			 */
7079 			in_flags |= IPF_RECVADDR;
7080 		}
7081 	}
7082 
7083 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7084 		in_flags |= IPF_RECVSLLA;
7085 
7086 	/*
7087 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7088 	 * freed if the packet is dropped. The caller will do so.
7089 	 */
7090 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7091 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7092 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7093 		if (mp == NULL) {
7094 			return;
7095 		}
7096 	}
7097 	if ((in_flags != 0) &&
7098 	    (mp->b_datap->db_type != M_CTL)) {
7099 		/*
7100 		 * The actual data will be contained in b_cont
7101 		 * upon successful return of the following call
7102 		 * else original mblk is returned
7103 		 */
7104 		ASSERT(recv_ill != NULL);
7105 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7106 		    ipst);
7107 	}
7108 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7109 	/* Send it upstream */
7110 	(connp->conn_recv)(connp, mp, NULL);
7111 }
7112 
7113 /*
7114  * Fanout for UDP packets.
7115  * The caller puts <fport, lport> in the ports parameter.
7116  *
7117  * If SO_REUSEADDR is set all multicast and broadcast packets
7118  * will be delivered to all streams bound to the same port.
7119  *
7120  * Zones notes:
7121  * Multicast and broadcast packets will be distributed to streams in all zones.
7122  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7123  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7124  * packets. To maintain this behavior with multiple zones, the conns are grouped
7125  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7126  * each zone. If unset, all the following conns in the same zone are skipped.
7127  */
7128 static void
7129 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7130     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7131     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7132 {
7133 	uint32_t	dstport, srcport;
7134 	ipaddr_t	dst;
7135 	mblk_t		*first_mp;
7136 	boolean_t	secure;
7137 	in6_addr_t	v6src;
7138 	conn_t		*connp;
7139 	connf_t		*connfp;
7140 	conn_t		*first_connp;
7141 	conn_t		*next_connp;
7142 	mblk_t		*mp1, *first_mp1;
7143 	ipaddr_t	src;
7144 	zoneid_t	last_zoneid;
7145 	boolean_t	reuseaddr;
7146 	boolean_t	shared_addr;
7147 	ip_stack_t	*ipst;
7148 
7149 	ASSERT(recv_ill != NULL);
7150 	ipst = recv_ill->ill_ipst;
7151 
7152 	first_mp = mp;
7153 	if (mctl_present) {
7154 		mp = first_mp->b_cont;
7155 		first_mp->b_cont = NULL;
7156 		secure = ipsec_in_is_secure(first_mp);
7157 		ASSERT(mp != NULL);
7158 	} else {
7159 		first_mp = NULL;
7160 		secure = B_FALSE;
7161 	}
7162 
7163 	/* Extract ports in net byte order */
7164 	dstport = htons(ntohl(ports) & 0xFFFF);
7165 	srcport = htons(ntohl(ports) >> 16);
7166 	dst = ipha->ipha_dst;
7167 	src = ipha->ipha_src;
7168 
7169 	shared_addr = (zoneid == ALL_ZONES);
7170 	if (shared_addr) {
7171 		/*
7172 		 * No need to handle exclusive-stack zones since ALL_ZONES
7173 		 * only applies to the shared stack.
7174 		 */
7175 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7176 		if (zoneid == ALL_ZONES)
7177 			zoneid = tsol_packet_to_zoneid(mp);
7178 	}
7179 
7180 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7181 	mutex_enter(&connfp->connf_lock);
7182 	connp = connfp->connf_head;
7183 	if (!broadcast && !CLASSD(dst)) {
7184 		/*
7185 		 * Not broadcast or multicast. Send to the one (first)
7186 		 * client we find. No need to check conn_wantpacket()
7187 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7188 		 * IPv4 unicast packets.
7189 		 */
7190 		while ((connp != NULL) &&
7191 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7192 		    !IPCL_ZONE_MATCH(connp, zoneid))) {
7193 			connp = connp->conn_next;
7194 		}
7195 
7196 		if (connp == NULL || connp->conn_upq == NULL)
7197 			goto notfound;
7198 
7199 		if (is_system_labeled() &&
7200 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7201 		    connp))
7202 			goto notfound;
7203 
7204 		CONN_INC_REF(connp);
7205 		mutex_exit(&connfp->connf_lock);
7206 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7207 		    flags, recv_ill, ip_policy);
7208 		IP_STAT(ipst, ip_udp_fannorm);
7209 		CONN_DEC_REF(connp);
7210 		return;
7211 	}
7212 
7213 	/*
7214 	 * Broadcast and multicast case
7215 	 *
7216 	 * Need to check conn_wantpacket().
7217 	 * If SO_REUSEADDR has been set on the first we send the
7218 	 * packet to all clients that have joined the group and
7219 	 * match the port.
7220 	 */
7221 
7222 	while (connp != NULL) {
7223 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7224 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7225 		    (!is_system_labeled() ||
7226 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7227 		    connp)))
7228 			break;
7229 		connp = connp->conn_next;
7230 	}
7231 
7232 	if (connp == NULL || connp->conn_upq == NULL)
7233 		goto notfound;
7234 
7235 	first_connp = connp;
7236 	/*
7237 	 * When SO_REUSEADDR is not set, send the packet only to the first
7238 	 * matching connection in its zone by keeping track of the zoneid.
7239 	 */
7240 	reuseaddr = first_connp->conn_reuseaddr;
7241 	last_zoneid = first_connp->conn_zoneid;
7242 
7243 	CONN_INC_REF(connp);
7244 	connp = connp->conn_next;
7245 	for (;;) {
7246 		while (connp != NULL) {
7247 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7248 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7249 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7250 			    (!is_system_labeled() ||
7251 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7252 			    shared_addr, connp)))
7253 				break;
7254 			connp = connp->conn_next;
7255 		}
7256 		/*
7257 		 * Just copy the data part alone. The mctl part is
7258 		 * needed just for verifying policy and it is never
7259 		 * sent up.
7260 		 */
7261 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7262 		    ((mp1 = copymsg(mp)) == NULL))) {
7263 			/*
7264 			 * No more interested clients or memory
7265 			 * allocation failed
7266 			 */
7267 			connp = first_connp;
7268 			break;
7269 		}
7270 		if (connp->conn_zoneid != last_zoneid) {
7271 			/*
7272 			 * Update the zoneid so that the packet isn't sent to
7273 			 * any more conns in the same zone unless SO_REUSEADDR
7274 			 * is set.
7275 			 */
7276 			reuseaddr = connp->conn_reuseaddr;
7277 			last_zoneid = connp->conn_zoneid;
7278 		}
7279 		if (first_mp != NULL) {
7280 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7281 			    ipsec_info_type == IPSEC_IN);
7282 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7283 			    ipst->ips_netstack);
7284 			if (first_mp1 == NULL) {
7285 				freemsg(mp1);
7286 				connp = first_connp;
7287 				break;
7288 			}
7289 		} else {
7290 			first_mp1 = NULL;
7291 		}
7292 		CONN_INC_REF(connp);
7293 		mutex_exit(&connfp->connf_lock);
7294 		/*
7295 		 * IPQoS notes: We don't send the packet for policy
7296 		 * processing here, will do it for the last one (below).
7297 		 * i.e. we do it per-packet now, but if we do policy
7298 		 * processing per-conn, then we would need to do it
7299 		 * here too.
7300 		 */
7301 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7302 		    ipha, flags, recv_ill, B_FALSE);
7303 		mutex_enter(&connfp->connf_lock);
7304 		/* Follow the next pointer before releasing the conn. */
7305 		next_connp = connp->conn_next;
7306 		IP_STAT(ipst, ip_udp_fanmb);
7307 		CONN_DEC_REF(connp);
7308 		connp = next_connp;
7309 	}
7310 
7311 	/* Last one.  Send it upstream. */
7312 	mutex_exit(&connfp->connf_lock);
7313 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7314 	    recv_ill, ip_policy);
7315 	IP_STAT(ipst, ip_udp_fanmb);
7316 	CONN_DEC_REF(connp);
7317 	return;
7318 
7319 notfound:
7320 
7321 	mutex_exit(&connfp->connf_lock);
7322 	IP_STAT(ipst, ip_udp_fanothers);
7323 	/*
7324 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7325 	 * have already been matched above, since they live in the IPv4
7326 	 * fanout tables. This implies we only need to
7327 	 * check for IPv6 in6addr_any endpoints here.
7328 	 * Thus we compare using ipv6_all_zeros instead of the destination
7329 	 * address, except for the multicast group membership lookup which
7330 	 * uses the IPv4 destination.
7331 	 */
7332 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7333 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7334 	mutex_enter(&connfp->connf_lock);
7335 	connp = connfp->connf_head;
7336 	if (!broadcast && !CLASSD(dst)) {
7337 		while (connp != NULL) {
7338 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7339 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7340 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7341 			    !connp->conn_ipv6_v6only)
7342 				break;
7343 			connp = connp->conn_next;
7344 		}
7345 
7346 		if (connp != NULL && is_system_labeled() &&
7347 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7348 		    connp))
7349 			connp = NULL;
7350 
7351 		if (connp == NULL || connp->conn_upq == NULL) {
7352 			/*
7353 			 * No one bound to this port.  Is
7354 			 * there a client that wants all
7355 			 * unclaimed datagrams?
7356 			 */
7357 			mutex_exit(&connfp->connf_lock);
7358 
7359 			if (mctl_present)
7360 				first_mp->b_cont = mp;
7361 			else
7362 				first_mp = mp;
7363 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7364 			    connf_head != NULL) {
7365 				ip_fanout_proto(q, first_mp, ill, ipha,
7366 				    flags | IP_FF_RAWIP, mctl_present,
7367 				    ip_policy, recv_ill, zoneid);
7368 			} else {
7369 				if (ip_fanout_send_icmp(q, first_mp, flags,
7370 				    ICMP_DEST_UNREACHABLE,
7371 				    ICMP_PORT_UNREACHABLE,
7372 				    mctl_present, zoneid, ipst)) {
7373 					BUMP_MIB(ill->ill_ip_mib,
7374 					    udpIfStatsNoPorts);
7375 				}
7376 			}
7377 			return;
7378 		}
7379 
7380 		CONN_INC_REF(connp);
7381 		mutex_exit(&connfp->connf_lock);
7382 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7383 		    flags, recv_ill, ip_policy);
7384 		CONN_DEC_REF(connp);
7385 		return;
7386 	}
7387 	/*
7388 	 * IPv4 multicast packet being delivered to an AF_INET6
7389 	 * in6addr_any endpoint.
7390 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7391 	 * and not conn_wantpacket_v6() since any multicast membership is
7392 	 * for an IPv4-mapped multicast address.
7393 	 * The packet is sent to all clients in all zones that have joined the
7394 	 * group and match the port.
7395 	 */
7396 	while (connp != NULL) {
7397 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7398 		    srcport, v6src) &&
7399 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7400 		    (!is_system_labeled() ||
7401 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7402 		    connp)))
7403 			break;
7404 		connp = connp->conn_next;
7405 	}
7406 
7407 	if (connp == NULL || connp->conn_upq == NULL) {
7408 		/*
7409 		 * No one bound to this port.  Is
7410 		 * there a client that wants all
7411 		 * unclaimed datagrams?
7412 		 */
7413 		mutex_exit(&connfp->connf_lock);
7414 
7415 		if (mctl_present)
7416 			first_mp->b_cont = mp;
7417 		else
7418 			first_mp = mp;
7419 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7420 		    NULL) {
7421 			ip_fanout_proto(q, first_mp, ill, ipha,
7422 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7423 			    recv_ill, zoneid);
7424 		} else {
7425 			/*
7426 			 * We used to attempt to send an icmp error here, but
7427 			 * since this is known to be a multicast packet
7428 			 * and we don't send icmp errors in response to
7429 			 * multicast, just drop the packet and give up sooner.
7430 			 */
7431 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7432 			freemsg(first_mp);
7433 		}
7434 		return;
7435 	}
7436 
7437 	first_connp = connp;
7438 
7439 	CONN_INC_REF(connp);
7440 	connp = connp->conn_next;
7441 	for (;;) {
7442 		while (connp != NULL) {
7443 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7444 			    ipv6_all_zeros, srcport, v6src) &&
7445 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7446 			    (!is_system_labeled() ||
7447 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7448 			    shared_addr, connp)))
7449 				break;
7450 			connp = connp->conn_next;
7451 		}
7452 		/*
7453 		 * Just copy the data part alone. The mctl part is
7454 		 * needed just for verifying policy and it is never
7455 		 * sent up.
7456 		 */
7457 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7458 		    ((mp1 = copymsg(mp)) == NULL))) {
7459 			/*
7460 			 * No more intested clients or memory
7461 			 * allocation failed
7462 			 */
7463 			connp = first_connp;
7464 			break;
7465 		}
7466 		if (first_mp != NULL) {
7467 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7468 			    ipsec_info_type == IPSEC_IN);
7469 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7470 			    ipst->ips_netstack);
7471 			if (first_mp1 == NULL) {
7472 				freemsg(mp1);
7473 				connp = first_connp;
7474 				break;
7475 			}
7476 		} else {
7477 			first_mp1 = NULL;
7478 		}
7479 		CONN_INC_REF(connp);
7480 		mutex_exit(&connfp->connf_lock);
7481 		/*
7482 		 * IPQoS notes: We don't send the packet for policy
7483 		 * processing here, will do it for the last one (below).
7484 		 * i.e. we do it per-packet now, but if we do policy
7485 		 * processing per-conn, then we would need to do it
7486 		 * here too.
7487 		 */
7488 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7489 		    ipha, flags, recv_ill, B_FALSE);
7490 		mutex_enter(&connfp->connf_lock);
7491 		/* Follow the next pointer before releasing the conn. */
7492 		next_connp = connp->conn_next;
7493 		CONN_DEC_REF(connp);
7494 		connp = next_connp;
7495 	}
7496 
7497 	/* Last one.  Send it upstream. */
7498 	mutex_exit(&connfp->connf_lock);
7499 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7500 	    recv_ill, ip_policy);
7501 	CONN_DEC_REF(connp);
7502 }
7503 
7504 /*
7505  * Complete the ip_wput header so that it
7506  * is possible to generate ICMP
7507  * errors.
7508  */
7509 int
7510 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7511 {
7512 	ire_t *ire;
7513 
7514 	if (ipha->ipha_src == INADDR_ANY) {
7515 		ire = ire_lookup_local(zoneid, ipst);
7516 		if (ire == NULL) {
7517 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7518 			return (1);
7519 		}
7520 		ipha->ipha_src = ire->ire_addr;
7521 		ire_refrele(ire);
7522 	}
7523 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7524 	ipha->ipha_hdr_checksum = 0;
7525 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7526 	return (0);
7527 }
7528 
7529 /*
7530  * Nobody should be sending
7531  * packets up this stream
7532  */
7533 static void
7534 ip_lrput(queue_t *q, mblk_t *mp)
7535 {
7536 	mblk_t *mp1;
7537 
7538 	switch (mp->b_datap->db_type) {
7539 	case M_FLUSH:
7540 		/* Turn around */
7541 		if (*mp->b_rptr & FLUSHW) {
7542 			*mp->b_rptr &= ~FLUSHR;
7543 			qreply(q, mp);
7544 			return;
7545 		}
7546 		break;
7547 	}
7548 	/* Could receive messages that passed through ar_rput */
7549 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7550 		mp1->b_prev = mp1->b_next = NULL;
7551 	freemsg(mp);
7552 }
7553 
7554 /* Nobody should be sending packets down this stream */
7555 /* ARGSUSED */
7556 void
7557 ip_lwput(queue_t *q, mblk_t *mp)
7558 {
7559 	freemsg(mp);
7560 }
7561 
7562 /*
7563  * Move the first hop in any source route to ipha_dst and remove that part of
7564  * the source route.  Called by other protocols.  Errors in option formatting
7565  * are ignored - will be handled by ip_wput_options Return the final
7566  * destination (either ipha_dst or the last entry in a source route.)
7567  */
7568 ipaddr_t
7569 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7570 {
7571 	ipoptp_t	opts;
7572 	uchar_t		*opt;
7573 	uint8_t		optval;
7574 	uint8_t		optlen;
7575 	ipaddr_t	dst;
7576 	int		i;
7577 	ire_t		*ire;
7578 	ip_stack_t	*ipst = ns->netstack_ip;
7579 
7580 	ip2dbg(("ip_massage_options\n"));
7581 	dst = ipha->ipha_dst;
7582 	for (optval = ipoptp_first(&opts, ipha);
7583 	    optval != IPOPT_EOL;
7584 	    optval = ipoptp_next(&opts)) {
7585 		opt = opts.ipoptp_cur;
7586 		switch (optval) {
7587 			uint8_t off;
7588 		case IPOPT_SSRR:
7589 		case IPOPT_LSRR:
7590 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7591 				ip1dbg(("ip_massage_options: bad src route\n"));
7592 				break;
7593 			}
7594 			optlen = opts.ipoptp_len;
7595 			off = opt[IPOPT_OFFSET];
7596 			off--;
7597 		redo_srr:
7598 			if (optlen < IP_ADDR_LEN ||
7599 			    off > optlen - IP_ADDR_LEN) {
7600 				/* End of source route */
7601 				ip1dbg(("ip_massage_options: end of SR\n"));
7602 				break;
7603 			}
7604 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7605 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7606 			    ntohl(dst)));
7607 			/*
7608 			 * Check if our address is present more than
7609 			 * once as consecutive hops in source route.
7610 			 * XXX verify per-interface ip_forwarding
7611 			 * for source route?
7612 			 */
7613 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7614 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7615 			if (ire != NULL) {
7616 				ire_refrele(ire);
7617 				off += IP_ADDR_LEN;
7618 				goto redo_srr;
7619 			}
7620 			if (dst == htonl(INADDR_LOOPBACK)) {
7621 				ip1dbg(("ip_massage_options: loopback addr in "
7622 				    "source route!\n"));
7623 				break;
7624 			}
7625 			/*
7626 			 * Update ipha_dst to be the first hop and remove the
7627 			 * first hop from the source route (by overwriting
7628 			 * part of the option with NOP options).
7629 			 */
7630 			ipha->ipha_dst = dst;
7631 			/* Put the last entry in dst */
7632 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7633 			    3;
7634 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7635 
7636 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7637 			    ntohl(dst)));
7638 			/* Move down and overwrite */
7639 			opt[IP_ADDR_LEN] = opt[0];
7640 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7641 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7642 			for (i = 0; i < IP_ADDR_LEN; i++)
7643 				opt[i] = IPOPT_NOP;
7644 			break;
7645 		}
7646 	}
7647 	return (dst);
7648 }
7649 
7650 /*
7651  * Return the network mask
7652  * associated with the specified address.
7653  */
7654 ipaddr_t
7655 ip_net_mask(ipaddr_t addr)
7656 {
7657 	uchar_t	*up = (uchar_t *)&addr;
7658 	ipaddr_t mask = 0;
7659 	uchar_t	*maskp = (uchar_t *)&mask;
7660 
7661 #if defined(__i386) || defined(__amd64)
7662 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7663 #endif
7664 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7665 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7666 #endif
7667 	if (CLASSD(addr)) {
7668 		maskp[0] = 0xF0;
7669 		return (mask);
7670 	}
7671 
7672 	/* We assume Class E default netmask to be 32 */
7673 	if (CLASSE(addr))
7674 		return (0xffffffffU);
7675 
7676 	if (addr == 0)
7677 		return (0);
7678 	maskp[0] = 0xFF;
7679 	if ((up[0] & 0x80) == 0)
7680 		return (mask);
7681 
7682 	maskp[1] = 0xFF;
7683 	if ((up[0] & 0xC0) == 0x80)
7684 		return (mask);
7685 
7686 	maskp[2] = 0xFF;
7687 	if ((up[0] & 0xE0) == 0xC0)
7688 		return (mask);
7689 
7690 	/* Otherwise return no mask */
7691 	return ((ipaddr_t)0);
7692 }
7693 
7694 /*
7695  * Select an ill for the packet by considering load spreading across
7696  * a different ill in the group if dst_ill is part of some group.
7697  */
7698 ill_t *
7699 ip_newroute_get_dst_ill(ill_t *dst_ill)
7700 {
7701 	ill_t *ill;
7702 
7703 	/*
7704 	 * We schedule irrespective of whether the source address is
7705 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7706 	 */
7707 	ill = illgrp_scheduler(dst_ill);
7708 	if (ill == NULL)
7709 		return (NULL);
7710 
7711 	/*
7712 	 * For groups with names ip_sioctl_groupname ensures that all
7713 	 * ills are of same type. For groups without names, ifgrp_insert
7714 	 * ensures this.
7715 	 */
7716 	ASSERT(dst_ill->ill_type == ill->ill_type);
7717 
7718 	return (ill);
7719 }
7720 
7721 /*
7722  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7723  */
7724 ill_t *
7725 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6,
7726     ip_stack_t *ipst)
7727 {
7728 	ill_t *ret_ill;
7729 
7730 	ASSERT(ifindex != 0);
7731 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7732 	    ipst);
7733 	if (ret_ill == NULL ||
7734 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7735 		if (isv6) {
7736 			if (ill != NULL) {
7737 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7738 			} else {
7739 				BUMP_MIB(&ipst->ips_ip6_mib,
7740 				    ipIfStatsOutDiscards);
7741 			}
7742 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7743 			    "bad ifindex %d.\n", ifindex));
7744 		} else {
7745 			if (ill != NULL) {
7746 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7747 			} else {
7748 				BUMP_MIB(&ipst->ips_ip_mib,
7749 				    ipIfStatsOutDiscards);
7750 			}
7751 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7752 			    "bad ifindex %d.\n", ifindex));
7753 		}
7754 		if (ret_ill != NULL)
7755 			ill_refrele(ret_ill);
7756 		freemsg(first_mp);
7757 		return (NULL);
7758 	}
7759 
7760 	return (ret_ill);
7761 }
7762 
7763 /*
7764  * IPv4 -
7765  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7766  * out a packet to a destination address for which we do not have specific
7767  * (or sufficient) routing information.
7768  *
7769  * NOTE : These are the scopes of some of the variables that point at IRE,
7770  *	  which needs to be followed while making any future modifications
7771  *	  to avoid memory leaks.
7772  *
7773  *	- ire and sire are the entries looked up initially by
7774  *	  ire_ftable_lookup.
7775  *	- ipif_ire is used to hold the interface ire associated with
7776  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7777  *	  it before branching out to error paths.
7778  *	- save_ire is initialized before ire_create, so that ire returned
7779  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7780  *	  before breaking out of the switch.
7781  *
7782  *	Thus on failures, we have to REFRELE only ire and sire, if they
7783  *	are not NULL.
7784  */
7785 void
7786 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7787     zoneid_t zoneid, ip_stack_t *ipst)
7788 {
7789 	areq_t	*areq;
7790 	ipaddr_t gw = 0;
7791 	ire_t	*ire = NULL;
7792 	mblk_t	*res_mp;
7793 	ipaddr_t *addrp;
7794 	ipaddr_t nexthop_addr;
7795 	ipif_t  *src_ipif = NULL;
7796 	ill_t	*dst_ill = NULL;
7797 	ipha_t  *ipha;
7798 	ire_t	*sire = NULL;
7799 	mblk_t	*first_mp;
7800 	ire_t	*save_ire;
7801 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7802 	ushort_t ire_marks = 0;
7803 	boolean_t mctl_present;
7804 	ipsec_out_t *io;
7805 	mblk_t	*saved_mp;
7806 	ire_t	*first_sire = NULL;
7807 	mblk_t	*copy_mp = NULL;
7808 	mblk_t	*xmit_mp = NULL;
7809 	ipaddr_t save_dst;
7810 	uint32_t multirt_flags =
7811 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7812 	boolean_t multirt_is_resolvable;
7813 	boolean_t multirt_resolve_next;
7814 	boolean_t unspec_src;
7815 	boolean_t do_attach_ill = B_FALSE;
7816 	boolean_t ip_nexthop = B_FALSE;
7817 	tsol_ire_gw_secattr_t *attrp = NULL;
7818 	tsol_gcgrp_t *gcgrp = NULL;
7819 	tsol_gcgrp_addr_t ga;
7820 
7821 	if (ip_debug > 2) {
7822 		/* ip1dbg */
7823 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7824 	}
7825 
7826 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7827 	if (mctl_present) {
7828 		io = (ipsec_out_t *)first_mp->b_rptr;
7829 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7830 		ASSERT(zoneid == io->ipsec_out_zoneid);
7831 		ASSERT(zoneid != ALL_ZONES);
7832 	}
7833 
7834 	ipha = (ipha_t *)mp->b_rptr;
7835 
7836 	/* All multicast lookups come through ip_newroute_ipif() */
7837 	if (CLASSD(dst)) {
7838 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7839 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7840 		freemsg(first_mp);
7841 		return;
7842 	}
7843 
7844 	if (mctl_present && io->ipsec_out_attach_if) {
7845 		/* ip_grab_attach_ill returns a held ill */
7846 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7847 		    io->ipsec_out_ill_index, B_FALSE, ipst);
7848 
7849 		/* Failure case frees things for us. */
7850 		if (attach_ill == NULL)
7851 			return;
7852 
7853 		/*
7854 		 * Check if we need an ire that will not be
7855 		 * looked up by anybody else i.e. HIDDEN.
7856 		 */
7857 		if (ill_is_probeonly(attach_ill))
7858 			ire_marks = IRE_MARK_HIDDEN;
7859 	}
7860 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7861 		ip_nexthop = B_TRUE;
7862 		nexthop_addr = io->ipsec_out_nexthop_addr;
7863 	}
7864 	/*
7865 	 * If this IRE is created for forwarding or it is not for
7866 	 * traffic for congestion controlled protocols, mark it as temporary.
7867 	 */
7868 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7869 		ire_marks |= IRE_MARK_TEMPORARY;
7870 
7871 	/*
7872 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7873 	 * chain until it gets the most specific information available.
7874 	 * For example, we know that there is no IRE_CACHE for this dest,
7875 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7876 	 * ire_ftable_lookup will look up the gateway, etc.
7877 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7878 	 * to the destination, of equal netmask length in the forward table,
7879 	 * will be recursively explored. If no information is available
7880 	 * for the final gateway of that route, we force the returned ire
7881 	 * to be equal to sire using MATCH_IRE_PARENT.
7882 	 * At least, in this case we have a starting point (in the buckets)
7883 	 * to look for other routes to the destination in the forward table.
7884 	 * This is actually used only for multirouting, where a list
7885 	 * of routes has to be processed in sequence.
7886 	 *
7887 	 * In the process of coming up with the most specific information,
7888 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7889 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7890 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7891 	 * Two caveats when handling incomplete ire's in ip_newroute:
7892 	 * - we should be careful when accessing its ire_nce (specifically
7893 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7894 	 * - not all legacy code path callers are prepared to handle
7895 	 *   incomplete ire's, so we should not create/add incomplete
7896 	 *   ire_cache entries here. (See discussion about temporary solution
7897 	 *   further below).
7898 	 *
7899 	 * In order to minimize packet dropping, and to preserve existing
7900 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7901 	 * gateway, and instead use the IF_RESOLVER ire to send out
7902 	 * another request to ARP (this is achieved by passing the
7903 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7904 	 * arp response comes back in ip_wput_nondata, we will create
7905 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7906 	 *
7907 	 * Note that this is a temporary solution; the correct solution is
7908 	 * to create an incomplete  per-dst ire_cache entry, and send the
7909 	 * packet out when the gw's nce is resolved. In order to achieve this,
7910 	 * all packet processing must have been completed prior to calling
7911 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7912 	 * to be modified to accomodate this solution.
7913 	 */
7914 	if (ip_nexthop) {
7915 		/*
7916 		 * The first time we come here, we look for an IRE_INTERFACE
7917 		 * entry for the specified nexthop, set the dst to be the
7918 		 * nexthop address and create an IRE_CACHE entry for the
7919 		 * nexthop. The next time around, we are able to find an
7920 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7921 		 * nexthop address and create an IRE_CACHE entry for the
7922 		 * destination address via the specified nexthop.
7923 		 */
7924 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7925 		    MBLK_GETLABEL(mp), ipst);
7926 		if (ire != NULL) {
7927 			gw = nexthop_addr;
7928 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7929 		} else {
7930 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7931 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7932 			    MBLK_GETLABEL(mp),
7933 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
7934 			    ipst);
7935 			if (ire != NULL) {
7936 				dst = nexthop_addr;
7937 			}
7938 		}
7939 	} else if (attach_ill == NULL) {
7940 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7941 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
7942 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7943 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7944 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
7945 		    ipst);
7946 	} else {
7947 		/*
7948 		 * attach_ill is set only for communicating with
7949 		 * on-link hosts. So, don't look for DEFAULT.
7950 		 */
7951 		ipif_t	*attach_ipif;
7952 
7953 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
7954 		if (attach_ipif == NULL) {
7955 			ill_refrele(attach_ill);
7956 			goto icmp_err_ret;
7957 		}
7958 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
7959 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
7960 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
7961 		    MATCH_IRE_SECATTR, ipst);
7962 		ipif_refrele(attach_ipif);
7963 	}
7964 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7965 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7966 
7967 	/*
7968 	 * This loop is run only once in most cases.
7969 	 * We loop to resolve further routes only when the destination
7970 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7971 	 */
7972 	do {
7973 		/* Clear the previous iteration's values */
7974 		if (src_ipif != NULL) {
7975 			ipif_refrele(src_ipif);
7976 			src_ipif = NULL;
7977 		}
7978 		if (dst_ill != NULL) {
7979 			ill_refrele(dst_ill);
7980 			dst_ill = NULL;
7981 		}
7982 
7983 		multirt_resolve_next = B_FALSE;
7984 		/*
7985 		 * We check if packets have to be multirouted.
7986 		 * In this case, given the current <ire, sire> couple,
7987 		 * we look for the next suitable <ire, sire>.
7988 		 * This check is done in ire_multirt_lookup(),
7989 		 * which applies various criteria to find the next route
7990 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7991 		 * unchanged if it detects it has not been tried yet.
7992 		 */
7993 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7994 			ip3dbg(("ip_newroute: starting next_resolution "
7995 			    "with first_mp %p, tag %d\n",
7996 			    (void *)first_mp,
7997 			    MULTIRT_DEBUG_TAGGED(first_mp)));
7998 
7999 			ASSERT(sire != NULL);
8000 			multirt_is_resolvable =
8001 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
8002 			    MBLK_GETLABEL(mp), ipst);
8003 
8004 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
8005 			    "ire %p, sire %p\n",
8006 			    multirt_is_resolvable,
8007 			    (void *)ire, (void *)sire));
8008 
8009 			if (!multirt_is_resolvable) {
8010 				/*
8011 				 * No more multirt route to resolve; give up
8012 				 * (all routes resolved or no more
8013 				 * resolvable routes).
8014 				 */
8015 				if (ire != NULL) {
8016 					ire_refrele(ire);
8017 					ire = NULL;
8018 				}
8019 			} else {
8020 				ASSERT(sire != NULL);
8021 				ASSERT(ire != NULL);
8022 				/*
8023 				 * We simply use first_sire as a flag that
8024 				 * indicates if a resolvable multirt route
8025 				 * has already been found.
8026 				 * If it is not the case, we may have to send
8027 				 * an ICMP error to report that the
8028 				 * destination is unreachable.
8029 				 * We do not IRE_REFHOLD first_sire.
8030 				 */
8031 				if (first_sire == NULL) {
8032 					first_sire = sire;
8033 				}
8034 			}
8035 		}
8036 		if (ire == NULL) {
8037 			if (ip_debug > 3) {
8038 				/* ip2dbg */
8039 				pr_addr_dbg("ip_newroute: "
8040 				    "can't resolve %s\n", AF_INET, &dst);
8041 			}
8042 			ip3dbg(("ip_newroute: "
8043 			    "ire %p, sire %p, first_sire %p\n",
8044 			    (void *)ire, (void *)sire, (void *)first_sire));
8045 
8046 			if (sire != NULL) {
8047 				ire_refrele(sire);
8048 				sire = NULL;
8049 			}
8050 
8051 			if (first_sire != NULL) {
8052 				/*
8053 				 * At least one multirt route has been found
8054 				 * in the same call to ip_newroute();
8055 				 * there is no need to report an ICMP error.
8056 				 * first_sire was not IRE_REFHOLDed.
8057 				 */
8058 				MULTIRT_DEBUG_UNTAG(first_mp);
8059 				freemsg(first_mp);
8060 				return;
8061 			}
8062 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8063 			    RTA_DST, ipst);
8064 			if (attach_ill != NULL)
8065 				ill_refrele(attach_ill);
8066 			goto icmp_err_ret;
8067 		}
8068 
8069 		/*
8070 		 * Verify that the returned IRE does not have either
8071 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8072 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8073 		 */
8074 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8075 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8076 			if (attach_ill != NULL)
8077 				ill_refrele(attach_ill);
8078 			goto icmp_err_ret;
8079 		}
8080 		/*
8081 		 * Increment the ire_ob_pkt_count field for ire if it is an
8082 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8083 		 * increment the same for the parent IRE, sire, if it is some
8084 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8085 		 */
8086 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8087 			UPDATE_OB_PKT_COUNT(ire);
8088 			ire->ire_last_used_time = lbolt;
8089 		}
8090 
8091 		if (sire != NULL) {
8092 			gw = sire->ire_gateway_addr;
8093 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8094 			    IRE_INTERFACE)) == 0);
8095 			UPDATE_OB_PKT_COUNT(sire);
8096 			sire->ire_last_used_time = lbolt;
8097 		}
8098 		/*
8099 		 * We have a route to reach the destination.
8100 		 *
8101 		 * 1) If the interface is part of ill group, try to get a new
8102 		 *    ill taking load spreading into account.
8103 		 *
8104 		 * 2) After selecting the ill, get a source address that
8105 		 *    might create good inbound load spreading.
8106 		 *    ipif_select_source does this for us.
8107 		 *
8108 		 * If the application specified the ill (ifindex), we still
8109 		 * load spread. Only if the packets needs to go out
8110 		 * specifically on a given ill e.g. binding to
8111 		 * IPIF_NOFAILOVER address, then we don't try to use a
8112 		 * different ill for load spreading.
8113 		 */
8114 		if (attach_ill == NULL) {
8115 			/*
8116 			 * Don't perform outbound load spreading in the
8117 			 * case of an RTF_MULTIRT route, as we actually
8118 			 * typically want to replicate outgoing packets
8119 			 * through particular interfaces.
8120 			 */
8121 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8122 				dst_ill = ire->ire_ipif->ipif_ill;
8123 				/* for uniformity */
8124 				ill_refhold(dst_ill);
8125 			} else {
8126 				/*
8127 				 * If we are here trying to create an IRE_CACHE
8128 				 * for an offlink destination and have the
8129 				 * IRE_CACHE for the next hop and the latter is
8130 				 * using virtual IP source address selection i.e
8131 				 * it's ire->ire_ipif is pointing to a virtual
8132 				 * network interface (vni) then
8133 				 * ip_newroute_get_dst_ll() will return the vni
8134 				 * interface as the dst_ill. Since the vni is
8135 				 * virtual i.e not associated with any physical
8136 				 * interface, it cannot be the dst_ill, hence
8137 				 * in such a case call ip_newroute_get_dst_ll()
8138 				 * with the stq_ill instead of the ire_ipif ILL.
8139 				 * The function returns a refheld ill.
8140 				 */
8141 				if ((ire->ire_type == IRE_CACHE) &&
8142 				    IS_VNI(ire->ire_ipif->ipif_ill))
8143 					dst_ill = ip_newroute_get_dst_ill(
8144 					    ire->ire_stq->q_ptr);
8145 				else
8146 					dst_ill = ip_newroute_get_dst_ill(
8147 					    ire->ire_ipif->ipif_ill);
8148 			}
8149 			if (dst_ill == NULL) {
8150 				if (ip_debug > 2) {
8151 					pr_addr_dbg("ip_newroute: "
8152 					    "no dst ill for dst"
8153 					    " %s\n", AF_INET, &dst);
8154 				}
8155 				goto icmp_err_ret;
8156 			}
8157 		} else {
8158 			dst_ill = ire->ire_ipif->ipif_ill;
8159 			/* for uniformity */
8160 			ill_refhold(dst_ill);
8161 			/*
8162 			 * We should have found a route matching ill as we
8163 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
8164 			 * Rather than asserting, when there is a mismatch,
8165 			 * we just drop the packet.
8166 			 */
8167 			if (dst_ill != attach_ill) {
8168 				ip0dbg(("ip_newroute: Packet dropped as "
8169 				    "IPIF_NOFAILOVER ill is %s, "
8170 				    "ire->ire_ipif->ipif_ill is %s\n",
8171 				    attach_ill->ill_name,
8172 				    dst_ill->ill_name));
8173 				ill_refrele(attach_ill);
8174 				goto icmp_err_ret;
8175 			}
8176 		}
8177 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
8178 		if (attach_ill != NULL) {
8179 			ill_refrele(attach_ill);
8180 			attach_ill = NULL;
8181 			do_attach_ill = B_TRUE;
8182 		}
8183 		ASSERT(dst_ill != NULL);
8184 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8185 
8186 		/*
8187 		 * Pick the best source address from dst_ill.
8188 		 *
8189 		 * 1) If it is part of a multipathing group, we would
8190 		 *    like to spread the inbound packets across different
8191 		 *    interfaces. ipif_select_source picks a random source
8192 		 *    across the different ills in the group.
8193 		 *
8194 		 * 2) If it is not part of a multipathing group, we try
8195 		 *    to pick the source address from the destination
8196 		 *    route. Clustering assumes that when we have multiple
8197 		 *    prefixes hosted on an interface, the prefix of the
8198 		 *    source address matches the prefix of the destination
8199 		 *    route. We do this only if the address is not
8200 		 *    DEPRECATED.
8201 		 *
8202 		 * 3) If the conn is in a different zone than the ire, we
8203 		 *    need to pick a source address from the right zone.
8204 		 *
8205 		 * NOTE : If we hit case (1) above, the prefix of the source
8206 		 *	  address picked may not match the prefix of the
8207 		 *	  destination routes prefix as ipif_select_source
8208 		 *	  does not look at "dst" while picking a source
8209 		 *	  address.
8210 		 *	  If we want the same behavior as (2), we will need
8211 		 *	  to change the behavior of ipif_select_source.
8212 		 */
8213 		ASSERT(src_ipif == NULL);
8214 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8215 			/*
8216 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8217 			 * Check that the ipif matching the requested source
8218 			 * address still exists.
8219 			 */
8220 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8221 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8222 		}
8223 
8224 		unspec_src = (connp != NULL && connp->conn_unspec_src);
8225 
8226 		if (src_ipif == NULL &&
8227 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
8228 			ire_marks |= IRE_MARK_USESRC_CHECK;
8229 			if ((dst_ill->ill_group != NULL) ||
8230 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8231 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8232 			    ire->ire_zoneid != ALL_ZONES) ||
8233 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8234 				/*
8235 				 * If the destination is reachable via a
8236 				 * given gateway, the selected source address
8237 				 * should be in the same subnet as the gateway.
8238 				 * Otherwise, the destination is not reachable.
8239 				 *
8240 				 * If there are no interfaces on the same subnet
8241 				 * as the destination, ipif_select_source gives
8242 				 * first non-deprecated interface which might be
8243 				 * on a different subnet than the gateway.
8244 				 * This is not desirable. Hence pass the dst_ire
8245 				 * source address to ipif_select_source.
8246 				 * It is sure that the destination is reachable
8247 				 * with the dst_ire source address subnet.
8248 				 * So passing dst_ire source address to
8249 				 * ipif_select_source will make sure that the
8250 				 * selected source will be on the same subnet
8251 				 * as dst_ire source address.
8252 				 */
8253 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8254 				src_ipif = ipif_select_source(dst_ill, saddr,
8255 				    zoneid);
8256 				if (src_ipif == NULL) {
8257 					if (ip_debug > 2) {
8258 						pr_addr_dbg("ip_newroute: "
8259 						    "no src for dst %s ",
8260 						    AF_INET, &dst);
8261 						printf("through interface %s\n",
8262 						    dst_ill->ill_name);
8263 					}
8264 					goto icmp_err_ret;
8265 				}
8266 			} else {
8267 				src_ipif = ire->ire_ipif;
8268 				ASSERT(src_ipif != NULL);
8269 				/* hold src_ipif for uniformity */
8270 				ipif_refhold(src_ipif);
8271 			}
8272 		}
8273 
8274 		/*
8275 		 * Assign a source address while we have the conn.
8276 		 * We can't have ip_wput_ire pick a source address when the
8277 		 * packet returns from arp since we need to look at
8278 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8279 		 * going through arp.
8280 		 *
8281 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8282 		 *	  it uses ip6i to store this information.
8283 		 */
8284 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
8285 			ipha->ipha_src = src_ipif->ipif_src_addr;
8286 
8287 		if (ip_debug > 3) {
8288 			/* ip2dbg */
8289 			pr_addr_dbg("ip_newroute: first hop %s\n",
8290 			    AF_INET, &gw);
8291 		}
8292 		ip2dbg(("\tire type %s (%d)\n",
8293 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8294 
8295 		/*
8296 		 * The TTL of multirouted packets is bounded by the
8297 		 * ip_multirt_ttl ndd variable.
8298 		 */
8299 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8300 			/* Force TTL of multirouted packets */
8301 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8302 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8303 				ip2dbg(("ip_newroute: forcing multirt TTL "
8304 				    "to %d (was %d), dst 0x%08x\n",
8305 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8306 				    ntohl(sire->ire_addr)));
8307 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8308 			}
8309 		}
8310 		/*
8311 		 * At this point in ip_newroute(), ire is either the
8312 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8313 		 * destination or an IRE_INTERFACE type that should be used
8314 		 * to resolve an on-subnet destination or an on-subnet
8315 		 * next-hop gateway.
8316 		 *
8317 		 * In the IRE_CACHE case, we have the following :
8318 		 *
8319 		 * 1) src_ipif - used for getting a source address.
8320 		 *
8321 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8322 		 *    means packets using this IRE_CACHE will go out on
8323 		 *    dst_ill.
8324 		 *
8325 		 * 3) The IRE sire will point to the prefix that is the
8326 		 *    longest  matching route for the destination. These
8327 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8328 		 *
8329 		 *    The newly created IRE_CACHE entry for the off-subnet
8330 		 *    destination is tied to both the prefix route and the
8331 		 *    interface route used to resolve the next-hop gateway
8332 		 *    via the ire_phandle and ire_ihandle fields,
8333 		 *    respectively.
8334 		 *
8335 		 * In the IRE_INTERFACE case, we have the following :
8336 		 *
8337 		 * 1) src_ipif - used for getting a source address.
8338 		 *
8339 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8340 		 *    means packets using the IRE_CACHE that we will build
8341 		 *    here will go out on dst_ill.
8342 		 *
8343 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8344 		 *    to be created will only be tied to the IRE_INTERFACE
8345 		 *    that was derived from the ire_ihandle field.
8346 		 *
8347 		 *    If sire is non-NULL, it means the destination is
8348 		 *    off-link and we will first create the IRE_CACHE for the
8349 		 *    gateway. Next time through ip_newroute, we will create
8350 		 *    the IRE_CACHE for the final destination as described
8351 		 *    above.
8352 		 *
8353 		 * In both cases, after the current resolution has been
8354 		 * completed (or possibly initialised, in the IRE_INTERFACE
8355 		 * case), the loop may be re-entered to attempt the resolution
8356 		 * of another RTF_MULTIRT route.
8357 		 *
8358 		 * When an IRE_CACHE entry for the off-subnet destination is
8359 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8360 		 * for further processing in emission loops.
8361 		 */
8362 		save_ire = ire;
8363 		switch (ire->ire_type) {
8364 		case IRE_CACHE: {
8365 			ire_t	*ipif_ire;
8366 
8367 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8368 			if (gw == 0)
8369 				gw = ire->ire_gateway_addr;
8370 			/*
8371 			 * We need 3 ire's to create a new cache ire for an
8372 			 * off-link destination from the cache ire of the
8373 			 * gateway.
8374 			 *
8375 			 *	1. The prefix ire 'sire' (Note that this does
8376 			 *	   not apply to the conn_nexthop_set case)
8377 			 *	2. The cache ire of the gateway 'ire'
8378 			 *	3. The interface ire 'ipif_ire'
8379 			 *
8380 			 * We have (1) and (2). We lookup (3) below.
8381 			 *
8382 			 * If there is no interface route to the gateway,
8383 			 * it is a race condition, where we found the cache
8384 			 * but the interface route has been deleted.
8385 			 */
8386 			if (ip_nexthop) {
8387 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8388 			} else {
8389 				ipif_ire =
8390 				    ire_ihandle_lookup_offlink(ire, sire);
8391 			}
8392 			if (ipif_ire == NULL) {
8393 				ip1dbg(("ip_newroute: "
8394 				    "ire_ihandle_lookup_offlink failed\n"));
8395 				goto icmp_err_ret;
8396 			}
8397 
8398 			/*
8399 			 * Check cached gateway IRE for any security
8400 			 * attributes; if found, associate the gateway
8401 			 * credentials group to the destination IRE.
8402 			 */
8403 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8404 				mutex_enter(&attrp->igsa_lock);
8405 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8406 					GCGRP_REFHOLD(gcgrp);
8407 				mutex_exit(&attrp->igsa_lock);
8408 			}
8409 
8410 			/*
8411 			 * XXX For the source of the resolver mp,
8412 			 * we are using the same DL_UNITDATA_REQ
8413 			 * (from save_ire->ire_nce->nce_res_mp)
8414 			 * though the save_ire is not pointing at the same ill.
8415 			 * This is incorrect. We need to send it up to the
8416 			 * resolver to get the right res_mp. For ethernets
8417 			 * this may be okay (ill_type == DL_ETHER).
8418 			 */
8419 
8420 			ire = ire_create(
8421 			    (uchar_t *)&dst,		/* dest address */
8422 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8423 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8424 			    (uchar_t *)&gw,		/* gateway address */
8425 			    &save_ire->ire_max_frag,
8426 			    save_ire->ire_nce,		/* src nce */
8427 			    dst_ill->ill_rq,		/* recv-from queue */
8428 			    dst_ill->ill_wq,		/* send-to queue */
8429 			    IRE_CACHE,			/* IRE type */
8430 			    src_ipif,
8431 			    (sire != NULL) ?
8432 			    sire->ire_mask : 0, 	/* Parent mask */
8433 			    (sire != NULL) ?
8434 			    sire->ire_phandle : 0,	/* Parent handle */
8435 			    ipif_ire->ire_ihandle,	/* Interface handle */
8436 			    (sire != NULL) ? (sire->ire_flags &
8437 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8438 			    (sire != NULL) ?
8439 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8440 			    NULL,
8441 			    gcgrp,
8442 			    ipst);
8443 
8444 			if (ire == NULL) {
8445 				if (gcgrp != NULL) {
8446 					GCGRP_REFRELE(gcgrp);
8447 					gcgrp = NULL;
8448 				}
8449 				ire_refrele(ipif_ire);
8450 				ire_refrele(save_ire);
8451 				break;
8452 			}
8453 
8454 			/* reference now held by IRE */
8455 			gcgrp = NULL;
8456 
8457 			ire->ire_marks |= ire_marks;
8458 
8459 			/*
8460 			 * Prevent sire and ipif_ire from getting deleted.
8461 			 * The newly created ire is tied to both of them via
8462 			 * the phandle and ihandle respectively.
8463 			 */
8464 			if (sire != NULL) {
8465 				IRB_REFHOLD(sire->ire_bucket);
8466 				/* Has it been removed already ? */
8467 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8468 					IRB_REFRELE(sire->ire_bucket);
8469 					ire_refrele(ipif_ire);
8470 					ire_refrele(save_ire);
8471 					break;
8472 				}
8473 			}
8474 
8475 			IRB_REFHOLD(ipif_ire->ire_bucket);
8476 			/* Has it been removed already ? */
8477 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8478 				IRB_REFRELE(ipif_ire->ire_bucket);
8479 				if (sire != NULL)
8480 					IRB_REFRELE(sire->ire_bucket);
8481 				ire_refrele(ipif_ire);
8482 				ire_refrele(save_ire);
8483 				break;
8484 			}
8485 
8486 			xmit_mp = first_mp;
8487 			/*
8488 			 * In the case of multirouting, a copy
8489 			 * of the packet is done before its sending.
8490 			 * The copy is used to attempt another
8491 			 * route resolution, in a next loop.
8492 			 */
8493 			if (ire->ire_flags & RTF_MULTIRT) {
8494 				copy_mp = copymsg(first_mp);
8495 				if (copy_mp != NULL) {
8496 					xmit_mp = copy_mp;
8497 					MULTIRT_DEBUG_TAG(first_mp);
8498 				}
8499 			}
8500 			ire_add_then_send(q, ire, xmit_mp);
8501 			ire_refrele(save_ire);
8502 
8503 			/* Assert that sire is not deleted yet. */
8504 			if (sire != NULL) {
8505 				ASSERT(sire->ire_ptpn != NULL);
8506 				IRB_REFRELE(sire->ire_bucket);
8507 			}
8508 
8509 			/* Assert that ipif_ire is not deleted yet. */
8510 			ASSERT(ipif_ire->ire_ptpn != NULL);
8511 			IRB_REFRELE(ipif_ire->ire_bucket);
8512 			ire_refrele(ipif_ire);
8513 
8514 			/*
8515 			 * If copy_mp is not NULL, multirouting was
8516 			 * requested. We loop to initiate a next
8517 			 * route resolution attempt, starting from sire.
8518 			 */
8519 			if (copy_mp != NULL) {
8520 				/*
8521 				 * Search for the next unresolved
8522 				 * multirt route.
8523 				 */
8524 				copy_mp = NULL;
8525 				ipif_ire = NULL;
8526 				ire = NULL;
8527 				multirt_resolve_next = B_TRUE;
8528 				continue;
8529 			}
8530 			if (sire != NULL)
8531 				ire_refrele(sire);
8532 			ipif_refrele(src_ipif);
8533 			ill_refrele(dst_ill);
8534 			return;
8535 		}
8536 		case IRE_IF_NORESOLVER: {
8537 
8538 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8539 			    dst_ill->ill_resolver_mp == NULL) {
8540 				ip1dbg(("ip_newroute: dst_ill %p "
8541 				    "for IRE_IF_NORESOLVER ire %p has "
8542 				    "no ill_resolver_mp\n",
8543 				    (void *)dst_ill, (void *)ire));
8544 				break;
8545 			}
8546 
8547 			/*
8548 			 * TSol note: We are creating the ire cache for the
8549 			 * destination 'dst'. If 'dst' is offlink, going
8550 			 * through the first hop 'gw', the security attributes
8551 			 * of 'dst' must be set to point to the gateway
8552 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8553 			 * is possible that 'dst' is a potential gateway that is
8554 			 * referenced by some route that has some security
8555 			 * attributes. Thus in the former case, we need to do a
8556 			 * gcgrp_lookup of 'gw' while in the latter case we
8557 			 * need to do gcgrp_lookup of 'dst' itself.
8558 			 */
8559 			ga.ga_af = AF_INET;
8560 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8561 			    &ga.ga_addr);
8562 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8563 
8564 			ire = ire_create(
8565 			    (uchar_t *)&dst,		/* dest address */
8566 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8567 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8568 			    (uchar_t *)&gw,		/* gateway address */
8569 			    &save_ire->ire_max_frag,
8570 			    NULL,			/* no src nce */
8571 			    dst_ill->ill_rq,		/* recv-from queue */
8572 			    dst_ill->ill_wq,		/* send-to queue */
8573 			    IRE_CACHE,
8574 			    src_ipif,
8575 			    save_ire->ire_mask,		/* Parent mask */
8576 			    (sire != NULL) ?		/* Parent handle */
8577 			    sire->ire_phandle : 0,
8578 			    save_ire->ire_ihandle,	/* Interface handle */
8579 			    (sire != NULL) ? sire->ire_flags &
8580 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8581 			    &(save_ire->ire_uinfo),
8582 			    NULL,
8583 			    gcgrp,
8584 			    ipst);
8585 
8586 			if (ire == NULL) {
8587 				if (gcgrp != NULL) {
8588 					GCGRP_REFRELE(gcgrp);
8589 					gcgrp = NULL;
8590 				}
8591 				ire_refrele(save_ire);
8592 				break;
8593 			}
8594 
8595 			/* reference now held by IRE */
8596 			gcgrp = NULL;
8597 
8598 			ire->ire_marks |= ire_marks;
8599 
8600 			/* Prevent save_ire from getting deleted */
8601 			IRB_REFHOLD(save_ire->ire_bucket);
8602 			/* Has it been removed already ? */
8603 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8604 				IRB_REFRELE(save_ire->ire_bucket);
8605 				ire_refrele(save_ire);
8606 				break;
8607 			}
8608 
8609 			/*
8610 			 * In the case of multirouting, a copy
8611 			 * of the packet is made before it is sent.
8612 			 * The copy is used in the next
8613 			 * loop to attempt another resolution.
8614 			 */
8615 			xmit_mp = first_mp;
8616 			if ((sire != NULL) &&
8617 			    (sire->ire_flags & RTF_MULTIRT)) {
8618 				copy_mp = copymsg(first_mp);
8619 				if (copy_mp != NULL) {
8620 					xmit_mp = copy_mp;
8621 					MULTIRT_DEBUG_TAG(first_mp);
8622 				}
8623 			}
8624 			ire_add_then_send(q, ire, xmit_mp);
8625 
8626 			/* Assert that it is not deleted yet. */
8627 			ASSERT(save_ire->ire_ptpn != NULL);
8628 			IRB_REFRELE(save_ire->ire_bucket);
8629 			ire_refrele(save_ire);
8630 
8631 			if (copy_mp != NULL) {
8632 				/*
8633 				 * If we found a (no)resolver, we ignore any
8634 				 * trailing top priority IRE_CACHE in further
8635 				 * loops. This ensures that we do not omit any
8636 				 * (no)resolver.
8637 				 * This IRE_CACHE, if any, will be processed
8638 				 * by another thread entering ip_newroute().
8639 				 * IRE_CACHE entries, if any, will be processed
8640 				 * by another thread entering ip_newroute(),
8641 				 * (upon resolver response, for instance).
8642 				 * This aims to force parallel multirt
8643 				 * resolutions as soon as a packet must be sent.
8644 				 * In the best case, after the tx of only one
8645 				 * packet, all reachable routes are resolved.
8646 				 * Otherwise, the resolution of all RTF_MULTIRT
8647 				 * routes would require several emissions.
8648 				 */
8649 				multirt_flags &= ~MULTIRT_CACHEGW;
8650 
8651 				/*
8652 				 * Search for the next unresolved multirt
8653 				 * route.
8654 				 */
8655 				copy_mp = NULL;
8656 				save_ire = NULL;
8657 				ire = NULL;
8658 				multirt_resolve_next = B_TRUE;
8659 				continue;
8660 			}
8661 
8662 			/*
8663 			 * Don't need sire anymore
8664 			 */
8665 			if (sire != NULL)
8666 				ire_refrele(sire);
8667 
8668 			ipif_refrele(src_ipif);
8669 			ill_refrele(dst_ill);
8670 			return;
8671 		}
8672 		case IRE_IF_RESOLVER:
8673 			/*
8674 			 * We can't build an IRE_CACHE yet, but at least we
8675 			 * found a resolver that can help.
8676 			 */
8677 			res_mp = dst_ill->ill_resolver_mp;
8678 			if (!OK_RESOLVER_MP(res_mp))
8679 				break;
8680 
8681 			/*
8682 			 * To be at this point in the code with a non-zero gw
8683 			 * means that dst is reachable through a gateway that
8684 			 * we have never resolved.  By changing dst to the gw
8685 			 * addr we resolve the gateway first.
8686 			 * When ire_add_then_send() tries to put the IP dg
8687 			 * to dst, it will reenter ip_newroute() at which
8688 			 * time we will find the IRE_CACHE for the gw and
8689 			 * create another IRE_CACHE in case IRE_CACHE above.
8690 			 */
8691 			if (gw != INADDR_ANY) {
8692 				/*
8693 				 * The source ipif that was determined above was
8694 				 * relative to the destination address, not the
8695 				 * gateway's. If src_ipif was not taken out of
8696 				 * the IRE_IF_RESOLVER entry, we'll need to call
8697 				 * ipif_select_source() again.
8698 				 */
8699 				if (src_ipif != ire->ire_ipif) {
8700 					ipif_refrele(src_ipif);
8701 					src_ipif = ipif_select_source(dst_ill,
8702 					    gw, zoneid);
8703 					if (src_ipif == NULL) {
8704 						if (ip_debug > 2) {
8705 							pr_addr_dbg(
8706 							    "ip_newroute: no "
8707 							    "src for gw %s ",
8708 							    AF_INET, &gw);
8709 							printf("through "
8710 							    "interface %s\n",
8711 							    dst_ill->ill_name);
8712 						}
8713 						goto icmp_err_ret;
8714 					}
8715 				}
8716 				save_dst = dst;
8717 				dst = gw;
8718 				gw = INADDR_ANY;
8719 			}
8720 
8721 			/*
8722 			 * We obtain a partial IRE_CACHE which we will pass
8723 			 * along with the resolver query.  When the response
8724 			 * comes back it will be there ready for us to add.
8725 			 * The ire_max_frag is atomically set under the
8726 			 * irebucket lock in ire_add_v[46].
8727 			 */
8728 
8729 			ire = ire_create_mp(
8730 			    (uchar_t *)&dst,		/* dest address */
8731 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8732 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8733 			    (uchar_t *)&gw,		/* gateway address */
8734 			    NULL,			/* ire_max_frag */
8735 			    NULL,			/* no src nce */
8736 			    dst_ill->ill_rq,		/* recv-from queue */
8737 			    dst_ill->ill_wq,		/* send-to queue */
8738 			    IRE_CACHE,
8739 			    src_ipif,			/* Interface ipif */
8740 			    save_ire->ire_mask,		/* Parent mask */
8741 			    0,
8742 			    save_ire->ire_ihandle,	/* Interface handle */
8743 			    0,				/* flags if any */
8744 			    &(save_ire->ire_uinfo),
8745 			    NULL,
8746 			    NULL,
8747 			    ipst);
8748 
8749 			if (ire == NULL) {
8750 				ire_refrele(save_ire);
8751 				break;
8752 			}
8753 
8754 			if ((sire != NULL) &&
8755 			    (sire->ire_flags & RTF_MULTIRT)) {
8756 				copy_mp = copymsg(first_mp);
8757 				if (copy_mp != NULL)
8758 					MULTIRT_DEBUG_TAG(copy_mp);
8759 			}
8760 
8761 			ire->ire_marks |= ire_marks;
8762 
8763 			/*
8764 			 * Construct message chain for the resolver
8765 			 * of the form:
8766 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8767 			 * Packet could contain a IPSEC_OUT mp.
8768 			 *
8769 			 * NOTE : ire will be added later when the response
8770 			 * comes back from ARP. If the response does not
8771 			 * come back, ARP frees the packet. For this reason,
8772 			 * we can't REFHOLD the bucket of save_ire to prevent
8773 			 * deletions. We may not be able to REFRELE the bucket
8774 			 * if the response never comes back. Thus, before
8775 			 * adding the ire, ire_add_v4 will make sure that the
8776 			 * interface route does not get deleted. This is the
8777 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8778 			 * where we can always prevent deletions because of
8779 			 * the synchronous nature of adding IRES i.e
8780 			 * ire_add_then_send is called after creating the IRE.
8781 			 */
8782 			ASSERT(ire->ire_mp != NULL);
8783 			ire->ire_mp->b_cont = first_mp;
8784 			/* Have saved_mp handy, for cleanup if canput fails */
8785 			saved_mp = mp;
8786 			mp = copyb(res_mp);
8787 			if (mp == NULL) {
8788 				/* Prepare for cleanup */
8789 				mp = saved_mp; /* pkt */
8790 				ire_delete(ire); /* ire_mp */
8791 				ire = NULL;
8792 				ire_refrele(save_ire);
8793 				if (copy_mp != NULL) {
8794 					MULTIRT_DEBUG_UNTAG(copy_mp);
8795 					freemsg(copy_mp);
8796 					copy_mp = NULL;
8797 				}
8798 				break;
8799 			}
8800 			linkb(mp, ire->ire_mp);
8801 
8802 			/*
8803 			 * Fill in the source and dest addrs for the resolver.
8804 			 * NOTE: this depends on memory layouts imposed by
8805 			 * ill_init().
8806 			 */
8807 			areq = (areq_t *)mp->b_rptr;
8808 			addrp = (ipaddr_t *)((char *)areq +
8809 			    areq->areq_sender_addr_offset);
8810 			if (do_attach_ill) {
8811 				/*
8812 				 * This is bind to no failover case.
8813 				 * arp packet also must go out on attach_ill.
8814 				 */
8815 				ASSERT(ipha->ipha_src != NULL);
8816 				*addrp = ipha->ipha_src;
8817 			} else {
8818 				*addrp = save_ire->ire_src_addr;
8819 			}
8820 
8821 			ire_refrele(save_ire);
8822 			addrp = (ipaddr_t *)((char *)areq +
8823 			    areq->areq_target_addr_offset);
8824 			*addrp = dst;
8825 			/* Up to the resolver. */
8826 			if (canputnext(dst_ill->ill_rq) &&
8827 			    !(dst_ill->ill_arp_closing)) {
8828 				putnext(dst_ill->ill_rq, mp);
8829 				ire = NULL;
8830 				if (copy_mp != NULL) {
8831 					/*
8832 					 * If we found a resolver, we ignore
8833 					 * any trailing top priority IRE_CACHE
8834 					 * in the further loops. This ensures
8835 					 * that we do not omit any resolver.
8836 					 * IRE_CACHE entries, if any, will be
8837 					 * processed next time we enter
8838 					 * ip_newroute().
8839 					 */
8840 					multirt_flags &= ~MULTIRT_CACHEGW;
8841 					/*
8842 					 * Search for the next unresolved
8843 					 * multirt route.
8844 					 */
8845 					first_mp = copy_mp;
8846 					copy_mp = NULL;
8847 					/* Prepare the next resolution loop. */
8848 					mp = first_mp;
8849 					EXTRACT_PKT_MP(mp, first_mp,
8850 					    mctl_present);
8851 					if (mctl_present)
8852 						io = (ipsec_out_t *)
8853 						    first_mp->b_rptr;
8854 					ipha = (ipha_t *)mp->b_rptr;
8855 
8856 					ASSERT(sire != NULL);
8857 
8858 					dst = save_dst;
8859 					multirt_resolve_next = B_TRUE;
8860 					continue;
8861 				}
8862 
8863 				if (sire != NULL)
8864 					ire_refrele(sire);
8865 
8866 				/*
8867 				 * The response will come back in ip_wput
8868 				 * with db_type IRE_DB_TYPE.
8869 				 */
8870 				ipif_refrele(src_ipif);
8871 				ill_refrele(dst_ill);
8872 				return;
8873 			} else {
8874 				/* Prepare for cleanup */
8875 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8876 				    mp);
8877 				mp->b_cont = NULL;
8878 				freeb(mp); /* areq */
8879 				/*
8880 				 * this is an ire that is not added to the
8881 				 * cache. ire_freemblk will handle the release
8882 				 * of any resources associated with the ire.
8883 				 */
8884 				ire_delete(ire); /* ire_mp */
8885 				mp = saved_mp; /* pkt */
8886 				ire = NULL;
8887 				if (copy_mp != NULL) {
8888 					MULTIRT_DEBUG_UNTAG(copy_mp);
8889 					freemsg(copy_mp);
8890 					copy_mp = NULL;
8891 				}
8892 				break;
8893 			}
8894 		default:
8895 			break;
8896 		}
8897 	} while (multirt_resolve_next);
8898 
8899 	ip1dbg(("ip_newroute: dropped\n"));
8900 	/* Did this packet originate externally? */
8901 	if (mp->b_prev) {
8902 		mp->b_next = NULL;
8903 		mp->b_prev = NULL;
8904 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8905 	} else {
8906 		if (dst_ill != NULL) {
8907 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8908 		} else {
8909 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8910 		}
8911 	}
8912 	ASSERT(copy_mp == NULL);
8913 	MULTIRT_DEBUG_UNTAG(first_mp);
8914 	freemsg(first_mp);
8915 	if (ire != NULL)
8916 		ire_refrele(ire);
8917 	if (sire != NULL)
8918 		ire_refrele(sire);
8919 	if (src_ipif != NULL)
8920 		ipif_refrele(src_ipif);
8921 	if (dst_ill != NULL)
8922 		ill_refrele(dst_ill);
8923 	return;
8924 
8925 icmp_err_ret:
8926 	ip1dbg(("ip_newroute: no route\n"));
8927 	if (src_ipif != NULL)
8928 		ipif_refrele(src_ipif);
8929 	if (dst_ill != NULL)
8930 		ill_refrele(dst_ill);
8931 	if (sire != NULL)
8932 		ire_refrele(sire);
8933 	/* Did this packet originate externally? */
8934 	if (mp->b_prev) {
8935 		mp->b_next = NULL;
8936 		mp->b_prev = NULL;
8937 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8938 		q = WR(q);
8939 	} else {
8940 		/*
8941 		 * There is no outgoing ill, so just increment the
8942 		 * system MIB.
8943 		 */
8944 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
8945 		/*
8946 		 * Since ip_wput() isn't close to finished, we fill
8947 		 * in enough of the header for credible error reporting.
8948 		 */
8949 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
8950 			/* Failed */
8951 			MULTIRT_DEBUG_UNTAG(first_mp);
8952 			freemsg(first_mp);
8953 			if (ire != NULL)
8954 				ire_refrele(ire);
8955 			return;
8956 		}
8957 	}
8958 
8959 	/*
8960 	 * At this point we will have ire only if RTF_BLACKHOLE
8961 	 * or RTF_REJECT flags are set on the IRE. It will not
8962 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8963 	 */
8964 	if (ire != NULL) {
8965 		if (ire->ire_flags & RTF_BLACKHOLE) {
8966 			ire_refrele(ire);
8967 			MULTIRT_DEBUG_UNTAG(first_mp);
8968 			freemsg(first_mp);
8969 			return;
8970 		}
8971 		ire_refrele(ire);
8972 	}
8973 	if (ip_source_routed(ipha, ipst)) {
8974 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8975 		    zoneid, ipst);
8976 		return;
8977 	}
8978 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
8979 }
8980 
8981 ip_opt_info_t zero_info;
8982 
8983 /*
8984  * IPv4 -
8985  * ip_newroute_ipif is called by ip_wput_multicast and
8986  * ip_rput_forward_multicast whenever we need to send
8987  * out a packet to a destination address for which we do not have specific
8988  * routing information. It is used when the packet will be sent out
8989  * on a specific interface. It is also called by ip_wput() when IP_BOUND_IF
8990  * socket option is set or icmp error message wants to go out on a particular
8991  * interface for a unicast packet.
8992  *
8993  * In most cases, the destination address is resolved thanks to the ipif
8994  * intrinsic resolver. However, there are some cases where the call to
8995  * ip_newroute_ipif must take into account the potential presence of
8996  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8997  * that uses the interface. This is specified through flags,
8998  * which can be a combination of:
8999  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
9000  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
9001  *   and flags. Additionally, the packet source address has to be set to
9002  *   the specified address. The caller is thus expected to set this flag
9003  *   if the packet has no specific source address yet.
9004  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
9005  *   flag, the resulting ire will inherit the flag. All unresolved routes
9006  *   to the destination must be explored in the same call to
9007  *   ip_newroute_ipif().
9008  */
9009 static void
9010 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
9011     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
9012 {
9013 	areq_t	*areq;
9014 	ire_t	*ire = NULL;
9015 	mblk_t	*res_mp;
9016 	ipaddr_t *addrp;
9017 	mblk_t *first_mp;
9018 	ire_t	*save_ire = NULL;
9019 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
9020 	ipif_t	*src_ipif = NULL;
9021 	ushort_t ire_marks = 0;
9022 	ill_t	*dst_ill = NULL;
9023 	boolean_t mctl_present;
9024 	ipsec_out_t *io;
9025 	ipha_t *ipha;
9026 	int	ihandle = 0;
9027 	mblk_t	*saved_mp;
9028 	ire_t   *fire = NULL;
9029 	mblk_t  *copy_mp = NULL;
9030 	boolean_t multirt_resolve_next;
9031 	boolean_t unspec_src;
9032 	ipaddr_t ipha_dst;
9033 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
9034 
9035 	/*
9036 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9037 	 * here for uniformity
9038 	 */
9039 	ipif_refhold(ipif);
9040 
9041 	/*
9042 	 * This loop is run only once in most cases.
9043 	 * We loop to resolve further routes only when the destination
9044 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9045 	 */
9046 	do {
9047 		if (dst_ill != NULL) {
9048 			ill_refrele(dst_ill);
9049 			dst_ill = NULL;
9050 		}
9051 		if (src_ipif != NULL) {
9052 			ipif_refrele(src_ipif);
9053 			src_ipif = NULL;
9054 		}
9055 		multirt_resolve_next = B_FALSE;
9056 
9057 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9058 		    ipif->ipif_ill->ill_name));
9059 
9060 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
9061 		if (mctl_present)
9062 			io = (ipsec_out_t *)first_mp->b_rptr;
9063 
9064 		ipha = (ipha_t *)mp->b_rptr;
9065 
9066 		/*
9067 		 * Save the packet destination address, we may need it after
9068 		 * the packet has been consumed.
9069 		 */
9070 		ipha_dst = ipha->ipha_dst;
9071 
9072 		/*
9073 		 * If the interface is a pt-pt interface we look for an
9074 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9075 		 * local_address and the pt-pt destination address. Otherwise
9076 		 * we just match the local address.
9077 		 * NOTE: dst could be different than ipha->ipha_dst in case
9078 		 * of sending igmp multicast packets over a point-to-point
9079 		 * connection.
9080 		 * Thus we must be careful enough to check ipha_dst to be a
9081 		 * multicast address, otherwise it will take xmit_if path for
9082 		 * multicast packets resulting into kernel stack overflow by
9083 		 * repeated calls to ip_newroute_ipif from ire_send().
9084 		 */
9085 		if (CLASSD(ipha_dst) &&
9086 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9087 			goto err_ret;
9088 		}
9089 
9090 		/*
9091 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9092 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9093 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9094 		 * propagate its flags to the new ire.
9095 		 */
9096 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9097 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9098 			ip2dbg(("ip_newroute_ipif: "
9099 			    "ipif_lookup_multi_ire("
9100 			    "ipif %p, dst %08x) = fire %p\n",
9101 			    (void *)ipif, ntohl(dst), (void *)fire));
9102 		}
9103 
9104 		if (mctl_present && io->ipsec_out_attach_if) {
9105 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
9106 			    io->ipsec_out_ill_index, B_FALSE, ipst);
9107 
9108 			/* Failure case frees things for us. */
9109 			if (attach_ill == NULL) {
9110 				ipif_refrele(ipif);
9111 				if (fire != NULL)
9112 					ire_refrele(fire);
9113 				return;
9114 			}
9115 
9116 			/*
9117 			 * Check if we need an ire that will not be
9118 			 * looked up by anybody else i.e. HIDDEN.
9119 			 */
9120 			if (ill_is_probeonly(attach_ill)) {
9121 				ire_marks = IRE_MARK_HIDDEN;
9122 			}
9123 			/*
9124 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
9125 			 * case.
9126 			 */
9127 			dst_ill = ipif->ipif_ill;
9128 			/* attach_ill has been refheld by ip_grab_attach_ill */
9129 			ASSERT(dst_ill == attach_ill);
9130 		} else {
9131 			/*
9132 			 * If the interface belongs to an interface group,
9133 			 * make sure the next possible interface in the group
9134 			 * is used.  This encourages load spreading among
9135 			 * peers in an interface group.
9136 			 * Note: load spreading is disabled for RTF_MULTIRT
9137 			 * routes.
9138 			 */
9139 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9140 			    (fire->ire_flags & RTF_MULTIRT)) {
9141 				/*
9142 				 * Don't perform outbound load spreading
9143 				 * in the case of an RTF_MULTIRT issued route,
9144 				 * we actually typically want to replicate
9145 				 * outgoing packets through particular
9146 				 * interfaces.
9147 				 */
9148 				dst_ill = ipif->ipif_ill;
9149 				ill_refhold(dst_ill);
9150 			} else {
9151 				dst_ill = ip_newroute_get_dst_ill(
9152 				    ipif->ipif_ill);
9153 			}
9154 			if (dst_ill == NULL) {
9155 				if (ip_debug > 2) {
9156 					pr_addr_dbg("ip_newroute_ipif: "
9157 					    "no dst ill for dst %s\n",
9158 					    AF_INET, &dst);
9159 				}
9160 				goto err_ret;
9161 			}
9162 		}
9163 
9164 		/*
9165 		 * Pick a source address preferring non-deprecated ones.
9166 		 * Unlike ip_newroute, we don't do any source address
9167 		 * selection here since for multicast it really does not help
9168 		 * in inbound load spreading as in the unicast case.
9169 		 */
9170 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9171 		    (fire->ire_flags & RTF_SETSRC)) {
9172 			/*
9173 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9174 			 * on that interface. This ire has RTF_SETSRC flag, so
9175 			 * the source address of the packet must be changed.
9176 			 * Check that the ipif matching the requested source
9177 			 * address still exists.
9178 			 */
9179 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9180 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9181 		}
9182 
9183 		unspec_src = (connp != NULL && connp->conn_unspec_src);
9184 
9185 		if (((!ipif->ipif_isv6 && ipif->ipif_lcl_addr == INADDR_ANY) ||
9186 		    (ipif->ipif_flags & (IPIF_DEPRECATED|IPIF_UP)) != IPIF_UP ||
9187 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9188 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9189 		    (src_ipif == NULL) &&
9190 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
9191 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9192 			if (src_ipif == NULL) {
9193 				if (ip_debug > 2) {
9194 					/* ip1dbg */
9195 					pr_addr_dbg("ip_newroute_ipif: "
9196 					    "no src for dst %s",
9197 					    AF_INET, &dst);
9198 				}
9199 				ip1dbg((" through interface %s\n",
9200 				    dst_ill->ill_name));
9201 				goto err_ret;
9202 			}
9203 			ipif_refrele(ipif);
9204 			ipif = src_ipif;
9205 			ipif_refhold(ipif);
9206 		}
9207 		if (src_ipif == NULL) {
9208 			src_ipif = ipif;
9209 			ipif_refhold(src_ipif);
9210 		}
9211 
9212 		/*
9213 		 * Assign a source address while we have the conn.
9214 		 * We can't have ip_wput_ire pick a source address when the
9215 		 * packet returns from arp since conn_unspec_src might be set
9216 		 * and we lose the conn when going through arp.
9217 		 */
9218 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
9219 			ipha->ipha_src = src_ipif->ipif_src_addr;
9220 
9221 		/*
9222 		 * In the case of IP_BOUND_IF and IP_PKTINFO, it is possible
9223 		 * that the outgoing interface does not have an interface ire.
9224 		 */
9225 		if (CLASSD(ipha_dst) && (connp == NULL ||
9226 		    connp->conn_outgoing_ill == NULL) &&
9227 		    infop->ip_opt_ill_index == 0) {
9228 			/* ipif_to_ire returns an held ire */
9229 			ire = ipif_to_ire(ipif);
9230 			if (ire == NULL)
9231 				goto err_ret;
9232 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9233 				goto err_ret;
9234 			/*
9235 			 * ihandle is needed when the ire is added to
9236 			 * cache table.
9237 			 */
9238 			save_ire = ire;
9239 			ihandle = save_ire->ire_ihandle;
9240 
9241 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9242 			    "flags %04x\n",
9243 			    (void *)ire, (void *)ipif, flags));
9244 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9245 			    (fire->ire_flags & RTF_MULTIRT)) {
9246 				/*
9247 				 * As requested by flags, an IRE_OFFSUBNET was
9248 				 * looked up on that interface. This ire has
9249 				 * RTF_MULTIRT flag, so the resolution loop will
9250 				 * be re-entered to resolve additional routes on
9251 				 * other interfaces. For that purpose, a copy of
9252 				 * the packet is performed at this point.
9253 				 */
9254 				fire->ire_last_used_time = lbolt;
9255 				copy_mp = copymsg(first_mp);
9256 				if (copy_mp) {
9257 					MULTIRT_DEBUG_TAG(copy_mp);
9258 				}
9259 			}
9260 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9261 			    (fire->ire_flags & RTF_SETSRC)) {
9262 				/*
9263 				 * As requested by flags, an IRE_OFFSUBET was
9264 				 * looked up on that interface. This ire has
9265 				 * RTF_SETSRC flag, so the source address of the
9266 				 * packet must be changed.
9267 				 */
9268 				ipha->ipha_src = fire->ire_src_addr;
9269 			}
9270 		} else {
9271 			ASSERT((connp == NULL) ||
9272 			    (connp->conn_outgoing_ill != NULL) ||
9273 			    (connp->conn_dontroute) ||
9274 			    infop->ip_opt_ill_index != 0);
9275 			/*
9276 			 * The only ways we can come here are:
9277 			 * 1) IP_BOUND_IF socket option is set
9278 			 * 2) SO_DONTROUTE socket option is set
9279 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9280 			 * In all cases, the new ire will not be added
9281 			 * into cache table.
9282 			 */
9283 			ire_marks |= IRE_MARK_NOADD;
9284 		}
9285 
9286 		switch (ipif->ipif_net_type) {
9287 		case IRE_IF_NORESOLVER: {
9288 			/* We have what we need to build an IRE_CACHE. */
9289 
9290 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9291 			    (dst_ill->ill_resolver_mp == NULL)) {
9292 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9293 				    "for IRE_IF_NORESOLVER ire %p has "
9294 				    "no ill_resolver_mp\n",
9295 				    (void *)dst_ill, (void *)ire));
9296 				break;
9297 			}
9298 
9299 			/*
9300 			 * The new ire inherits the IRE_OFFSUBNET flags
9301 			 * and source address, if this was requested.
9302 			 */
9303 			ire = ire_create(
9304 			    (uchar_t *)&dst,		/* dest address */
9305 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9306 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9307 			    NULL,			/* gateway address */
9308 			    &ipif->ipif_mtu,
9309 			    NULL,			/* no src nce */
9310 			    dst_ill->ill_rq,		/* recv-from queue */
9311 			    dst_ill->ill_wq,		/* send-to queue */
9312 			    IRE_CACHE,
9313 			    src_ipif,
9314 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9315 			    (fire != NULL) ?		/* Parent handle */
9316 			    fire->ire_phandle : 0,
9317 			    ihandle,			/* Interface handle */
9318 			    (fire != NULL) ?
9319 			    (fire->ire_flags &
9320 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9321 			    (save_ire == NULL ? &ire_uinfo_null :
9322 			    &save_ire->ire_uinfo),
9323 			    NULL,
9324 			    NULL,
9325 			    ipst);
9326 
9327 			if (ire == NULL) {
9328 				if (save_ire != NULL)
9329 					ire_refrele(save_ire);
9330 				break;
9331 			}
9332 
9333 			ire->ire_marks |= ire_marks;
9334 
9335 			/*
9336 			 * If IRE_MARK_NOADD is set then we need to convert
9337 			 * the max_fragp to a useable value now. This is
9338 			 * normally done in ire_add_v[46]. We also need to
9339 			 * associate the ire with an nce (normally would be
9340 			 * done in ip_wput_nondata()).
9341 			 *
9342 			 * Note that IRE_MARK_NOADD packets created here
9343 			 * do not have a non-null ire_mp pointer. The null
9344 			 * value of ire_bucket indicates that they were
9345 			 * never added.
9346 			 */
9347 			if (ire->ire_marks & IRE_MARK_NOADD) {
9348 				uint_t  max_frag;
9349 
9350 				max_frag = *ire->ire_max_fragp;
9351 				ire->ire_max_fragp = NULL;
9352 				ire->ire_max_frag = max_frag;
9353 
9354 				if ((ire->ire_nce = ndp_lookup_v4(
9355 				    ire_to_ill(ire),
9356 				    (ire->ire_gateway_addr != INADDR_ANY ?
9357 				    &ire->ire_gateway_addr : &ire->ire_addr),
9358 				    B_FALSE)) == NULL) {
9359 					if (save_ire != NULL)
9360 						ire_refrele(save_ire);
9361 					break;
9362 				}
9363 				ASSERT(ire->ire_nce->nce_state ==
9364 				    ND_REACHABLE);
9365 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9366 			}
9367 
9368 			/* Prevent save_ire from getting deleted */
9369 			if (save_ire != NULL) {
9370 				IRB_REFHOLD(save_ire->ire_bucket);
9371 				/* Has it been removed already ? */
9372 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9373 					IRB_REFRELE(save_ire->ire_bucket);
9374 					ire_refrele(save_ire);
9375 					break;
9376 				}
9377 			}
9378 
9379 			ire_add_then_send(q, ire, first_mp);
9380 
9381 			/* Assert that save_ire is not deleted yet. */
9382 			if (save_ire != NULL) {
9383 				ASSERT(save_ire->ire_ptpn != NULL);
9384 				IRB_REFRELE(save_ire->ire_bucket);
9385 				ire_refrele(save_ire);
9386 				save_ire = NULL;
9387 			}
9388 			if (fire != NULL) {
9389 				ire_refrele(fire);
9390 				fire = NULL;
9391 			}
9392 
9393 			/*
9394 			 * the resolution loop is re-entered if this
9395 			 * was requested through flags and if we
9396 			 * actually are in a multirouting case.
9397 			 */
9398 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9399 				boolean_t need_resolve =
9400 				    ire_multirt_need_resolve(ipha_dst,
9401 				    MBLK_GETLABEL(copy_mp), ipst);
9402 				if (!need_resolve) {
9403 					MULTIRT_DEBUG_UNTAG(copy_mp);
9404 					freemsg(copy_mp);
9405 					copy_mp = NULL;
9406 				} else {
9407 					/*
9408 					 * ipif_lookup_group() calls
9409 					 * ire_lookup_multi() that uses
9410 					 * ire_ftable_lookup() to find
9411 					 * an IRE_INTERFACE for the group.
9412 					 * In the multirt case,
9413 					 * ire_lookup_multi() then invokes
9414 					 * ire_multirt_lookup() to find
9415 					 * the next resolvable ire.
9416 					 * As a result, we obtain an new
9417 					 * interface, derived from the
9418 					 * next ire.
9419 					 */
9420 					ipif_refrele(ipif);
9421 					ipif = ipif_lookup_group(ipha_dst,
9422 					    zoneid, ipst);
9423 					ip2dbg(("ip_newroute_ipif: "
9424 					    "multirt dst %08x, ipif %p\n",
9425 					    htonl(dst), (void *)ipif));
9426 					if (ipif != NULL) {
9427 						mp = copy_mp;
9428 						copy_mp = NULL;
9429 						multirt_resolve_next = B_TRUE;
9430 						continue;
9431 					} else {
9432 						freemsg(copy_mp);
9433 					}
9434 				}
9435 			}
9436 			if (ipif != NULL)
9437 				ipif_refrele(ipif);
9438 			ill_refrele(dst_ill);
9439 			ipif_refrele(src_ipif);
9440 			return;
9441 		}
9442 		case IRE_IF_RESOLVER:
9443 			/*
9444 			 * We can't build an IRE_CACHE yet, but at least
9445 			 * we found a resolver that can help.
9446 			 */
9447 			res_mp = dst_ill->ill_resolver_mp;
9448 			if (!OK_RESOLVER_MP(res_mp))
9449 				break;
9450 
9451 			/*
9452 			 * We obtain a partial IRE_CACHE which we will pass
9453 			 * along with the resolver query.  When the response
9454 			 * comes back it will be there ready for us to add.
9455 			 * The new ire inherits the IRE_OFFSUBNET flags
9456 			 * and source address, if this was requested.
9457 			 * The ire_max_frag is atomically set under the
9458 			 * irebucket lock in ire_add_v[46]. Only in the
9459 			 * case of IRE_MARK_NOADD, we set it here itself.
9460 			 */
9461 			ire = ire_create_mp(
9462 			    (uchar_t *)&dst,		/* dest address */
9463 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9464 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9465 			    NULL,			/* gateway address */
9466 			    (ire_marks & IRE_MARK_NOADD) ?
9467 			    ipif->ipif_mtu : 0,		/* max_frag */
9468 			    NULL,			/* no src nce */
9469 			    dst_ill->ill_rq,		/* recv-from queue */
9470 			    dst_ill->ill_wq,		/* send-to queue */
9471 			    IRE_CACHE,
9472 			    src_ipif,
9473 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9474 			    (fire != NULL) ?		/* Parent handle */
9475 			    fire->ire_phandle : 0,
9476 			    ihandle,			/* Interface handle */
9477 			    (fire != NULL) ?		/* flags if any */
9478 			    (fire->ire_flags &
9479 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9480 			    (save_ire == NULL ? &ire_uinfo_null :
9481 			    &save_ire->ire_uinfo),
9482 			    NULL,
9483 			    NULL,
9484 			    ipst);
9485 
9486 			if (save_ire != NULL) {
9487 				ire_refrele(save_ire);
9488 				save_ire = NULL;
9489 			}
9490 			if (ire == NULL)
9491 				break;
9492 
9493 			ire->ire_marks |= ire_marks;
9494 			/*
9495 			 * Construct message chain for the resolver of the
9496 			 * form:
9497 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9498 			 *
9499 			 * NOTE : ire will be added later when the response
9500 			 * comes back from ARP. If the response does not
9501 			 * come back, ARP frees the packet. For this reason,
9502 			 * we can't REFHOLD the bucket of save_ire to prevent
9503 			 * deletions. We may not be able to REFRELE the
9504 			 * bucket if the response never comes back.
9505 			 * Thus, before adding the ire, ire_add_v4 will make
9506 			 * sure that the interface route does not get deleted.
9507 			 * This is the only case unlike ip_newroute_v6,
9508 			 * ip_newroute_ipif_v6 where we can always prevent
9509 			 * deletions because ire_add_then_send is called after
9510 			 * creating the IRE.
9511 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9512 			 * does not add this IRE into the IRE CACHE.
9513 			 */
9514 			ASSERT(ire->ire_mp != NULL);
9515 			ire->ire_mp->b_cont = first_mp;
9516 			/* Have saved_mp handy, for cleanup if canput fails */
9517 			saved_mp = mp;
9518 			mp = copyb(res_mp);
9519 			if (mp == NULL) {
9520 				/* Prepare for cleanup */
9521 				mp = saved_mp; /* pkt */
9522 				ire_delete(ire); /* ire_mp */
9523 				ire = NULL;
9524 				if (copy_mp != NULL) {
9525 					MULTIRT_DEBUG_UNTAG(copy_mp);
9526 					freemsg(copy_mp);
9527 					copy_mp = NULL;
9528 				}
9529 				break;
9530 			}
9531 			linkb(mp, ire->ire_mp);
9532 
9533 			/*
9534 			 * Fill in the source and dest addrs for the resolver.
9535 			 * NOTE: this depends on memory layouts imposed by
9536 			 * ill_init().
9537 			 */
9538 			areq = (areq_t *)mp->b_rptr;
9539 			addrp = (ipaddr_t *)((char *)areq +
9540 			    areq->areq_sender_addr_offset);
9541 			*addrp = ire->ire_src_addr;
9542 			addrp = (ipaddr_t *)((char *)areq +
9543 			    areq->areq_target_addr_offset);
9544 			*addrp = dst;
9545 			/* Up to the resolver. */
9546 			if (canputnext(dst_ill->ill_rq) &&
9547 			    !(dst_ill->ill_arp_closing)) {
9548 				putnext(dst_ill->ill_rq, mp);
9549 				/*
9550 				 * The response will come back in ip_wput
9551 				 * with db_type IRE_DB_TYPE.
9552 				 */
9553 			} else {
9554 				mp->b_cont = NULL;
9555 				freeb(mp); /* areq */
9556 				ire_delete(ire); /* ire_mp */
9557 				saved_mp->b_next = NULL;
9558 				saved_mp->b_prev = NULL;
9559 				freemsg(first_mp); /* pkt */
9560 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9561 			}
9562 
9563 			if (fire != NULL) {
9564 				ire_refrele(fire);
9565 				fire = NULL;
9566 			}
9567 
9568 
9569 			/*
9570 			 * The resolution loop is re-entered if this was
9571 			 * requested through flags and we actually are
9572 			 * in a multirouting case.
9573 			 */
9574 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9575 				boolean_t need_resolve =
9576 				    ire_multirt_need_resolve(ipha_dst,
9577 				    MBLK_GETLABEL(copy_mp), ipst);
9578 				if (!need_resolve) {
9579 					MULTIRT_DEBUG_UNTAG(copy_mp);
9580 					freemsg(copy_mp);
9581 					copy_mp = NULL;
9582 				} else {
9583 					/*
9584 					 * ipif_lookup_group() calls
9585 					 * ire_lookup_multi() that uses
9586 					 * ire_ftable_lookup() to find
9587 					 * an IRE_INTERFACE for the group.
9588 					 * In the multirt case,
9589 					 * ire_lookup_multi() then invokes
9590 					 * ire_multirt_lookup() to find
9591 					 * the next resolvable ire.
9592 					 * As a result, we obtain an new
9593 					 * interface, derived from the
9594 					 * next ire.
9595 					 */
9596 					ipif_refrele(ipif);
9597 					ipif = ipif_lookup_group(ipha_dst,
9598 					    zoneid, ipst);
9599 					if (ipif != NULL) {
9600 						mp = copy_mp;
9601 						copy_mp = NULL;
9602 						multirt_resolve_next = B_TRUE;
9603 						continue;
9604 					} else {
9605 						freemsg(copy_mp);
9606 					}
9607 				}
9608 			}
9609 			if (ipif != NULL)
9610 				ipif_refrele(ipif);
9611 			ill_refrele(dst_ill);
9612 			ipif_refrele(src_ipif);
9613 			return;
9614 		default:
9615 			break;
9616 		}
9617 	} while (multirt_resolve_next);
9618 
9619 err_ret:
9620 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9621 	if (fire != NULL)
9622 		ire_refrele(fire);
9623 	ipif_refrele(ipif);
9624 	/* Did this packet originate externally? */
9625 	if (dst_ill != NULL)
9626 		ill_refrele(dst_ill);
9627 	if (src_ipif != NULL)
9628 		ipif_refrele(src_ipif);
9629 	if (mp->b_prev || mp->b_next) {
9630 		mp->b_next = NULL;
9631 		mp->b_prev = NULL;
9632 	} else {
9633 		/*
9634 		 * Since ip_wput() isn't close to finished, we fill
9635 		 * in enough of the header for credible error reporting.
9636 		 */
9637 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9638 			/* Failed */
9639 			freemsg(first_mp);
9640 			if (ire != NULL)
9641 				ire_refrele(ire);
9642 			return;
9643 		}
9644 	}
9645 	/*
9646 	 * At this point we will have ire only if RTF_BLACKHOLE
9647 	 * or RTF_REJECT flags are set on the IRE. It will not
9648 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9649 	 */
9650 	if (ire != NULL) {
9651 		if (ire->ire_flags & RTF_BLACKHOLE) {
9652 			ire_refrele(ire);
9653 			freemsg(first_mp);
9654 			return;
9655 		}
9656 		ire_refrele(ire);
9657 	}
9658 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9659 }
9660 
9661 /* Name/Value Table Lookup Routine */
9662 char *
9663 ip_nv_lookup(nv_t *nv, int value)
9664 {
9665 	if (!nv)
9666 		return (NULL);
9667 	for (; nv->nv_name; nv++) {
9668 		if (nv->nv_value == value)
9669 			return (nv->nv_name);
9670 	}
9671 	return ("unknown");
9672 }
9673 
9674 /*
9675  * This is a module open, i.e. this is a control stream for access
9676  * to a DLPI device.  We allocate an ill_t as the instance data in
9677  * this case.
9678  */
9679 int
9680 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9681 {
9682 	ill_t	*ill;
9683 	int	err;
9684 	zoneid_t zoneid;
9685 	netstack_t *ns;
9686 	ip_stack_t *ipst;
9687 
9688 	/*
9689 	 * Prevent unprivileged processes from pushing IP so that
9690 	 * they can't send raw IP.
9691 	 */
9692 	if (secpolicy_net_rawaccess(credp) != 0)
9693 		return (EPERM);
9694 
9695 	ns = netstack_find_by_cred(credp);
9696 	ASSERT(ns != NULL);
9697 	ipst = ns->netstack_ip;
9698 	ASSERT(ipst != NULL);
9699 
9700 	/*
9701 	 * For exclusive stacks we set the zoneid to zero
9702 	 * to make IP operate as if in the global zone.
9703 	 */
9704 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9705 		zoneid = GLOBAL_ZONEID;
9706 	else
9707 		zoneid = crgetzoneid(credp);
9708 
9709 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9710 	q->q_ptr = WR(q)->q_ptr = ill;
9711 	ill->ill_ipst = ipst;
9712 	ill->ill_zoneid = zoneid;
9713 
9714 	/*
9715 	 * ill_init initializes the ill fields and then sends down
9716 	 * down a DL_INFO_REQ after calling qprocson.
9717 	 */
9718 	err = ill_init(q, ill);
9719 	if (err != 0) {
9720 		mi_free(ill);
9721 		netstack_rele(ipst->ips_netstack);
9722 		q->q_ptr = NULL;
9723 		WR(q)->q_ptr = NULL;
9724 		return (err);
9725 	}
9726 
9727 	/* ill_init initializes the ipsq marking this thread as writer */
9728 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9729 	/* Wait for the DL_INFO_ACK */
9730 	mutex_enter(&ill->ill_lock);
9731 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9732 		/*
9733 		 * Return value of 0 indicates a pending signal.
9734 		 */
9735 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9736 		if (err == 0) {
9737 			mutex_exit(&ill->ill_lock);
9738 			(void) ip_close(q, 0);
9739 			return (EINTR);
9740 		}
9741 	}
9742 	mutex_exit(&ill->ill_lock);
9743 
9744 	/*
9745 	 * ip_rput_other could have set an error  in ill_error on
9746 	 * receipt of M_ERROR.
9747 	 */
9748 
9749 	err = ill->ill_error;
9750 	if (err != 0) {
9751 		(void) ip_close(q, 0);
9752 		return (err);
9753 	}
9754 
9755 	ill->ill_credp = credp;
9756 	crhold(credp);
9757 
9758 	mutex_enter(&ipst->ips_ip_mi_lock);
9759 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9760 	    credp);
9761 	mutex_exit(&ipst->ips_ip_mi_lock);
9762 	if (err) {
9763 		(void) ip_close(q, 0);
9764 		return (err);
9765 	}
9766 	return (0);
9767 }
9768 
9769 /* For /dev/ip aka AF_INET open */
9770 int
9771 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9772 {
9773 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
9774 }
9775 
9776 /* For /dev/ip6 aka AF_INET6 open */
9777 int
9778 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9779 {
9780 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
9781 }
9782 
9783 /* IP open routine. */
9784 int
9785 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9786     boolean_t isv6)
9787 {
9788 	conn_t 		*connp;
9789 	major_t		maj;
9790 	zoneid_t	zoneid;
9791 	netstack_t	*ns;
9792 	ip_stack_t	*ipst;
9793 
9794 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9795 
9796 	/* Allow reopen. */
9797 	if (q->q_ptr != NULL)
9798 		return (0);
9799 
9800 	if (sflag & MODOPEN) {
9801 		/* This is a module open */
9802 		return (ip_modopen(q, devp, flag, sflag, credp));
9803 	}
9804 
9805 	ns = netstack_find_by_cred(credp);
9806 	ASSERT(ns != NULL);
9807 	ipst = ns->netstack_ip;
9808 	ASSERT(ipst != NULL);
9809 
9810 	/*
9811 	 * For exclusive stacks we set the zoneid to zero
9812 	 * to make IP operate as if in the global zone.
9813 	 */
9814 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9815 		zoneid = GLOBAL_ZONEID;
9816 	else
9817 		zoneid = crgetzoneid(credp);
9818 
9819 	/*
9820 	 * We are opening as a device. This is an IP client stream, and we
9821 	 * allocate an conn_t as the instance data.
9822 	 */
9823 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9824 
9825 	/*
9826 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9827 	 * done by netstack_find_by_cred()
9828 	 */
9829 	netstack_rele(ipst->ips_netstack);
9830 
9831 	connp->conn_zoneid = zoneid;
9832 
9833 	connp->conn_upq = q;
9834 	q->q_ptr = WR(q)->q_ptr = connp;
9835 
9836 	if (flag & SO_SOCKSTR)
9837 		connp->conn_flags |= IPCL_SOCKET;
9838 
9839 	/* Minor tells us which /dev entry was opened */
9840 	if (isv6) {
9841 		connp->conn_flags |= IPCL_ISV6;
9842 		connp->conn_af_isv6 = B_TRUE;
9843 		ip_setpktversion(connp, isv6, B_FALSE, ipst);
9844 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9845 	} else {
9846 		connp->conn_af_isv6 = B_FALSE;
9847 		connp->conn_pkt_isv6 = B_FALSE;
9848 	}
9849 
9850 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
9851 		/* CONN_DEC_REF takes care of netstack_rele() */
9852 		q->q_ptr = WR(q)->q_ptr = NULL;
9853 		CONN_DEC_REF(connp);
9854 		return (EBUSY);
9855 	}
9856 
9857 	maj = getemajor(*devp);
9858 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9859 
9860 	/*
9861 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9862 	 */
9863 	connp->conn_cred = credp;
9864 
9865 	/*
9866 	 * Handle IP_RTS_REQUEST and other ioctls which use conn_recv
9867 	 */
9868 	connp->conn_recv = ip_conn_input;
9869 
9870 	crhold(connp->conn_cred);
9871 
9872 	/*
9873 	 * If the caller has the process-wide flag set, then default to MAC
9874 	 * exempt mode.  This allows read-down to unlabeled hosts.
9875 	 */
9876 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9877 		connp->conn_mac_exempt = B_TRUE;
9878 
9879 	connp->conn_rq = q;
9880 	connp->conn_wq = WR(q);
9881 
9882 	/* Non-zero default values */
9883 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9884 
9885 	/*
9886 	 * Make the conn globally visible to walkers
9887 	 */
9888 	ASSERT(connp->conn_ref == 1);
9889 	mutex_enter(&connp->conn_lock);
9890 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9891 	mutex_exit(&connp->conn_lock);
9892 
9893 	qprocson(q);
9894 
9895 	return (0);
9896 }
9897 
9898 /*
9899  * Change the output format (IPv4 vs. IPv6) for a conn_t.
9900  * Note that there is no race since either ip_output function works - it
9901  * is just an optimization to enter the best ip_output routine directly.
9902  */
9903 void
9904 ip_setpktversion(conn_t *connp, boolean_t isv6, boolean_t bump_mib,
9905     ip_stack_t *ipst)
9906 {
9907 	if (isv6)  {
9908 		if (bump_mib) {
9909 			BUMP_MIB(&ipst->ips_ip6_mib,
9910 			    ipIfStatsOutSwitchIPVersion);
9911 		}
9912 		connp->conn_send = ip_output_v6;
9913 		connp->conn_pkt_isv6 = B_TRUE;
9914 	} else {
9915 		if (bump_mib) {
9916 			BUMP_MIB(&ipst->ips_ip_mib,
9917 			    ipIfStatsOutSwitchIPVersion);
9918 		}
9919 		connp->conn_send = ip_output;
9920 		connp->conn_pkt_isv6 = B_FALSE;
9921 	}
9922 
9923 }
9924 
9925 /*
9926  * See if IPsec needs loading because of the options in mp.
9927  */
9928 static boolean_t
9929 ipsec_opt_present(mblk_t *mp)
9930 {
9931 	uint8_t *optcp, *next_optcp, *opt_endcp;
9932 	struct opthdr *opt;
9933 	struct T_opthdr *topt;
9934 	int opthdr_len;
9935 	t_uscalar_t optname, optlevel;
9936 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9937 	ipsec_req_t *ipsr;
9938 
9939 	/*
9940 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9941 	 * return TRUE.
9942 	 */
9943 
9944 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9945 	opt_endcp = optcp + tor->OPT_length;
9946 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9947 		opthdr_len = sizeof (struct T_opthdr);
9948 	} else {		/* O_OPTMGMT_REQ */
9949 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9950 		opthdr_len = sizeof (struct opthdr);
9951 	}
9952 	for (; optcp < opt_endcp; optcp = next_optcp) {
9953 		if (optcp + opthdr_len > opt_endcp)
9954 			return (B_FALSE);	/* Not enough option header. */
9955 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9956 			topt = (struct T_opthdr *)optcp;
9957 			optlevel = topt->level;
9958 			optname = topt->name;
9959 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9960 		} else {
9961 			opt = (struct opthdr *)optcp;
9962 			optlevel = opt->level;
9963 			optname = opt->name;
9964 			next_optcp = optcp + opthdr_len +
9965 			    _TPI_ALIGN_OPT(opt->len);
9966 		}
9967 		if ((next_optcp < optcp) || /* wraparound pointer space */
9968 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9969 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9970 			return (B_FALSE); /* bad option buffer */
9971 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9972 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9973 			/*
9974 			 * Check to see if it's an all-bypass or all-zeroes
9975 			 * IPsec request.  Don't bother loading IPsec if
9976 			 * the socket doesn't want to use it.  (A good example
9977 			 * is a bypass request.)
9978 			 *
9979 			 * Basically, if any of the non-NEVER bits are set,
9980 			 * load IPsec.
9981 			 */
9982 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9983 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9984 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9985 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9986 			    != 0)
9987 				return (B_TRUE);
9988 		}
9989 	}
9990 	return (B_FALSE);
9991 }
9992 
9993 /*
9994  * If conn is is waiting for ipsec to finish loading, kick it.
9995  */
9996 /* ARGSUSED */
9997 static void
9998 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9999 {
10000 	t_scalar_t	optreq_prim;
10001 	mblk_t		*mp;
10002 	cred_t		*cr;
10003 	int		err = 0;
10004 
10005 	/*
10006 	 * This function is called, after ipsec loading is complete.
10007 	 * Since IP checks exclusively and atomically (i.e it prevents
10008 	 * ipsec load from completing until ip_optcom_req completes)
10009 	 * whether ipsec load is complete, there cannot be a race with IP
10010 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
10011 	 */
10012 	mutex_enter(&connp->conn_lock);
10013 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
10014 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
10015 		mp = connp->conn_ipsec_opt_mp;
10016 		connp->conn_ipsec_opt_mp = NULL;
10017 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
10018 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
10019 		mutex_exit(&connp->conn_lock);
10020 
10021 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
10022 
10023 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
10024 		if (optreq_prim == T_OPTMGMT_REQ) {
10025 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10026 			    &ip_opt_obj, B_FALSE);
10027 		} else {
10028 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10029 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10030 			    &ip_opt_obj, B_FALSE);
10031 		}
10032 		if (err != EINPROGRESS)
10033 			CONN_OPER_PENDING_DONE(connp);
10034 		return;
10035 	}
10036 	mutex_exit(&connp->conn_lock);
10037 }
10038 
10039 /*
10040  * Called from the ipsec_loader thread, outside any perimeter, to tell
10041  * ip qenable any of the queues waiting for the ipsec loader to
10042  * complete.
10043  */
10044 void
10045 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10046 {
10047 	netstack_t *ns = ipss->ipsec_netstack;
10048 
10049 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10050 }
10051 
10052 /*
10053  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10054  * determines the grp on which it has to become exclusive, queues the mp
10055  * and sq draining restarts the optmgmt
10056  */
10057 static boolean_t
10058 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10059 {
10060 	conn_t *connp = Q_TO_CONN(q);
10061 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10062 
10063 	/*
10064 	 * Take IPsec requests and treat them special.
10065 	 */
10066 	if (ipsec_opt_present(mp)) {
10067 		/* First check if IPsec is loaded. */
10068 		mutex_enter(&ipss->ipsec_loader_lock);
10069 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10070 			mutex_exit(&ipss->ipsec_loader_lock);
10071 			return (B_FALSE);
10072 		}
10073 		mutex_enter(&connp->conn_lock);
10074 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10075 
10076 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10077 		connp->conn_ipsec_opt_mp = mp;
10078 		mutex_exit(&connp->conn_lock);
10079 		mutex_exit(&ipss->ipsec_loader_lock);
10080 
10081 		ipsec_loader_loadnow(ipss);
10082 		return (B_TRUE);
10083 	}
10084 	return (B_FALSE);
10085 }
10086 
10087 /*
10088  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10089  * all of them are copied to the conn_t. If the req is "zero", the policy is
10090  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10091  * fields.
10092  * We keep only the latest setting of the policy and thus policy setting
10093  * is not incremental/cumulative.
10094  *
10095  * Requests to set policies with multiple alternative actions will
10096  * go through a different API.
10097  */
10098 int
10099 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10100 {
10101 	uint_t ah_req = 0;
10102 	uint_t esp_req = 0;
10103 	uint_t se_req = 0;
10104 	ipsec_selkey_t sel;
10105 	ipsec_act_t *actp = NULL;
10106 	uint_t nact;
10107 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10108 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10109 	ipsec_policy_root_t *pr;
10110 	ipsec_policy_head_t *ph;
10111 	int fam;
10112 	boolean_t is_pol_reset;
10113 	int error = 0;
10114 	netstack_t	*ns = connp->conn_netstack;
10115 	ip_stack_t	*ipst = ns->netstack_ip;
10116 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10117 
10118 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10119 
10120 	/*
10121 	 * The IP_SEC_OPT option does not allow variable length parameters,
10122 	 * hence a request cannot be NULL.
10123 	 */
10124 	if (req == NULL)
10125 		return (EINVAL);
10126 
10127 	ah_req = req->ipsr_ah_req;
10128 	esp_req = req->ipsr_esp_req;
10129 	se_req = req->ipsr_self_encap_req;
10130 
10131 	/*
10132 	 * Are we dealing with a request to reset the policy (i.e.
10133 	 * zero requests).
10134 	 */
10135 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10136 	    (esp_req & REQ_MASK) == 0 &&
10137 	    (se_req & REQ_MASK) == 0);
10138 
10139 	if (!is_pol_reset) {
10140 		/*
10141 		 * If we couldn't load IPsec, fail with "protocol
10142 		 * not supported".
10143 		 * IPsec may not have been loaded for a request with zero
10144 		 * policies, so we don't fail in this case.
10145 		 */
10146 		mutex_enter(&ipss->ipsec_loader_lock);
10147 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10148 			mutex_exit(&ipss->ipsec_loader_lock);
10149 			return (EPROTONOSUPPORT);
10150 		}
10151 		mutex_exit(&ipss->ipsec_loader_lock);
10152 
10153 		/*
10154 		 * Test for valid requests. Invalid algorithms
10155 		 * need to be tested by IPsec code because new
10156 		 * algorithms can be added dynamically.
10157 		 */
10158 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10159 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10160 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10161 			return (EINVAL);
10162 		}
10163 
10164 		/*
10165 		 * Only privileged users can issue these
10166 		 * requests.
10167 		 */
10168 		if (((ah_req & IPSEC_PREF_NEVER) ||
10169 		    (esp_req & IPSEC_PREF_NEVER) ||
10170 		    (se_req & IPSEC_PREF_NEVER)) &&
10171 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10172 			return (EPERM);
10173 		}
10174 
10175 		/*
10176 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10177 		 * are mutually exclusive.
10178 		 */
10179 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10180 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10181 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10182 			/* Both of them are set */
10183 			return (EINVAL);
10184 		}
10185 	}
10186 
10187 	mutex_enter(&connp->conn_lock);
10188 
10189 	/*
10190 	 * If we have already cached policies in ip_bind_connected*(), don't
10191 	 * let them change now. We cache policies for connections
10192 	 * whose src,dst [addr, port] is known.
10193 	 */
10194 	if (connp->conn_policy_cached) {
10195 		mutex_exit(&connp->conn_lock);
10196 		return (EINVAL);
10197 	}
10198 
10199 	/*
10200 	 * We have a zero policies, reset the connection policy if already
10201 	 * set. This will cause the connection to inherit the
10202 	 * global policy, if any.
10203 	 */
10204 	if (is_pol_reset) {
10205 		if (connp->conn_policy != NULL) {
10206 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10207 			connp->conn_policy = NULL;
10208 		}
10209 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10210 		connp->conn_in_enforce_policy = B_FALSE;
10211 		connp->conn_out_enforce_policy = B_FALSE;
10212 		mutex_exit(&connp->conn_lock);
10213 		return (0);
10214 	}
10215 
10216 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10217 	    ipst->ips_netstack);
10218 	if (ph == NULL)
10219 		goto enomem;
10220 
10221 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10222 	if (actp == NULL)
10223 		goto enomem;
10224 
10225 	/*
10226 	 * Always allocate IPv4 policy entries, since they can also
10227 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10228 	 */
10229 	bzero(&sel, sizeof (sel));
10230 	sel.ipsl_valid = IPSL_IPV4;
10231 
10232 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10233 	    ipst->ips_netstack);
10234 	if (pin4 == NULL)
10235 		goto enomem;
10236 
10237 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10238 	    ipst->ips_netstack);
10239 	if (pout4 == NULL)
10240 		goto enomem;
10241 
10242 	if (connp->conn_af_isv6) {
10243 		/*
10244 		 * We're looking at a v6 socket, also allocate the
10245 		 * v6-specific entries...
10246 		 */
10247 		sel.ipsl_valid = IPSL_IPV6;
10248 		pin6 = ipsec_policy_create(&sel, actp, nact,
10249 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10250 		if (pin6 == NULL)
10251 			goto enomem;
10252 
10253 		pout6 = ipsec_policy_create(&sel, actp, nact,
10254 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10255 		if (pout6 == NULL)
10256 			goto enomem;
10257 
10258 		/*
10259 		 * .. and file them away in the right place.
10260 		 */
10261 		fam = IPSEC_AF_V6;
10262 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10263 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10264 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10265 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10266 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10267 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10268 	}
10269 
10270 	ipsec_actvec_free(actp, nact);
10271 
10272 	/*
10273 	 * File the v4 policies.
10274 	 */
10275 	fam = IPSEC_AF_V4;
10276 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10277 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10278 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10279 
10280 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10281 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10282 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10283 
10284 	/*
10285 	 * If the requests need security, set enforce_policy.
10286 	 * If the requests are IPSEC_PREF_NEVER, one should
10287 	 * still set conn_out_enforce_policy so that an ipsec_out
10288 	 * gets attached in ip_wput. This is needed so that
10289 	 * for connections that we don't cache policy in ip_bind,
10290 	 * if global policy matches in ip_wput_attach_policy, we
10291 	 * don't wrongly inherit global policy. Similarly, we need
10292 	 * to set conn_in_enforce_policy also so that we don't verify
10293 	 * policy wrongly.
10294 	 */
10295 	if ((ah_req & REQ_MASK) != 0 ||
10296 	    (esp_req & REQ_MASK) != 0 ||
10297 	    (se_req & REQ_MASK) != 0) {
10298 		connp->conn_in_enforce_policy = B_TRUE;
10299 		connp->conn_out_enforce_policy = B_TRUE;
10300 		connp->conn_flags |= IPCL_CHECK_POLICY;
10301 	}
10302 
10303 	mutex_exit(&connp->conn_lock);
10304 	return (error);
10305 #undef REQ_MASK
10306 
10307 	/*
10308 	 * Common memory-allocation-failure exit path.
10309 	 */
10310 enomem:
10311 	mutex_exit(&connp->conn_lock);
10312 	if (actp != NULL)
10313 		ipsec_actvec_free(actp, nact);
10314 	if (pin4 != NULL)
10315 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10316 	if (pout4 != NULL)
10317 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10318 	if (pin6 != NULL)
10319 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10320 	if (pout6 != NULL)
10321 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10322 	return (ENOMEM);
10323 }
10324 
10325 /*
10326  * Only for options that pass in an IP addr. Currently only V4 options
10327  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10328  * So this function assumes level is IPPROTO_IP
10329  */
10330 int
10331 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10332     mblk_t *first_mp)
10333 {
10334 	ipif_t *ipif = NULL;
10335 	int error;
10336 	ill_t *ill;
10337 	int zoneid;
10338 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10339 
10340 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10341 
10342 	if (addr != INADDR_ANY || checkonly) {
10343 		ASSERT(connp != NULL);
10344 		zoneid = IPCL_ZONEID(connp);
10345 		if (option == IP_NEXTHOP) {
10346 			ipif = ipif_lookup_onlink_addr(addr,
10347 			    connp->conn_zoneid, ipst);
10348 		} else {
10349 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10350 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10351 			    &error, ipst);
10352 		}
10353 		if (ipif == NULL) {
10354 			if (error == EINPROGRESS)
10355 				return (error);
10356 			else if ((option == IP_MULTICAST_IF) ||
10357 			    (option == IP_NEXTHOP))
10358 				return (EHOSTUNREACH);
10359 			else
10360 				return (EINVAL);
10361 		} else if (checkonly) {
10362 			if (option == IP_MULTICAST_IF) {
10363 				ill = ipif->ipif_ill;
10364 				/* not supported by the virtual network iface */
10365 				if (IS_VNI(ill)) {
10366 					ipif_refrele(ipif);
10367 					return (EINVAL);
10368 				}
10369 			}
10370 			ipif_refrele(ipif);
10371 			return (0);
10372 		}
10373 		ill = ipif->ipif_ill;
10374 		mutex_enter(&connp->conn_lock);
10375 		mutex_enter(&ill->ill_lock);
10376 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10377 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10378 			mutex_exit(&ill->ill_lock);
10379 			mutex_exit(&connp->conn_lock);
10380 			ipif_refrele(ipif);
10381 			return (option == IP_MULTICAST_IF ?
10382 			    EHOSTUNREACH : EINVAL);
10383 		}
10384 	} else {
10385 		mutex_enter(&connp->conn_lock);
10386 	}
10387 
10388 	/* None of the options below are supported on the VNI */
10389 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10390 		mutex_exit(&ill->ill_lock);
10391 		mutex_exit(&connp->conn_lock);
10392 		ipif_refrele(ipif);
10393 		return (EINVAL);
10394 	}
10395 
10396 	switch (option) {
10397 	case IP_DONTFAILOVER_IF:
10398 		/*
10399 		 * This option is used by in.mpathd to ensure
10400 		 * that IPMP probe packets only go out on the
10401 		 * test interfaces. in.mpathd sets this option
10402 		 * on the non-failover interfaces.
10403 		 * For backward compatibility, this option
10404 		 * implicitly sets IP_MULTICAST_IF, as used
10405 		 * be done in bind(), so that ip_wput gets
10406 		 * this ipif to send mcast packets.
10407 		 */
10408 		if (ipif != NULL) {
10409 			ASSERT(addr != INADDR_ANY);
10410 			connp->conn_nofailover_ill = ipif->ipif_ill;
10411 			connp->conn_multicast_ipif = ipif;
10412 		} else {
10413 			ASSERT(addr == INADDR_ANY);
10414 			connp->conn_nofailover_ill = NULL;
10415 			connp->conn_multicast_ipif = NULL;
10416 		}
10417 		break;
10418 
10419 	case IP_MULTICAST_IF:
10420 		connp->conn_multicast_ipif = ipif;
10421 		break;
10422 	case IP_NEXTHOP:
10423 		connp->conn_nexthop_v4 = addr;
10424 		connp->conn_nexthop_set = B_TRUE;
10425 		break;
10426 	}
10427 
10428 	if (ipif != NULL) {
10429 		mutex_exit(&ill->ill_lock);
10430 		mutex_exit(&connp->conn_lock);
10431 		ipif_refrele(ipif);
10432 		return (0);
10433 	}
10434 	mutex_exit(&connp->conn_lock);
10435 	/* We succeded in cleared the option */
10436 	return (0);
10437 }
10438 
10439 /*
10440  * For options that pass in an ifindex specifying the ill. V6 options always
10441  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10442  */
10443 int
10444 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10445     int level, int option, mblk_t *first_mp)
10446 {
10447 	ill_t *ill = NULL;
10448 	int error = 0;
10449 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10450 
10451 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10452 	if (ifindex != 0) {
10453 		ASSERT(connp != NULL);
10454 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10455 		    first_mp, ip_restart_optmgmt, &error, ipst);
10456 		if (ill != NULL) {
10457 			if (checkonly) {
10458 				/* not supported by the virtual network iface */
10459 				if (IS_VNI(ill)) {
10460 					ill_refrele(ill);
10461 					return (EINVAL);
10462 				}
10463 				ill_refrele(ill);
10464 				return (0);
10465 			}
10466 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10467 			    0, NULL)) {
10468 				ill_refrele(ill);
10469 				ill = NULL;
10470 				mutex_enter(&connp->conn_lock);
10471 				goto setit;
10472 			}
10473 			mutex_enter(&connp->conn_lock);
10474 			mutex_enter(&ill->ill_lock);
10475 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10476 				mutex_exit(&ill->ill_lock);
10477 				mutex_exit(&connp->conn_lock);
10478 				ill_refrele(ill);
10479 				ill = NULL;
10480 				mutex_enter(&connp->conn_lock);
10481 			}
10482 			goto setit;
10483 		} else if (error == EINPROGRESS) {
10484 			return (error);
10485 		} else {
10486 			error = 0;
10487 		}
10488 	}
10489 	mutex_enter(&connp->conn_lock);
10490 setit:
10491 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10492 
10493 	/*
10494 	 * The options below assume that the ILL (if any) transmits and/or
10495 	 * receives traffic. Neither of which is true for the virtual network
10496 	 * interface, so fail setting these on a VNI.
10497 	 */
10498 	if (IS_VNI(ill)) {
10499 		ASSERT(ill != NULL);
10500 		mutex_exit(&ill->ill_lock);
10501 		mutex_exit(&connp->conn_lock);
10502 		ill_refrele(ill);
10503 		return (EINVAL);
10504 	}
10505 
10506 	if (level == IPPROTO_IP) {
10507 		switch (option) {
10508 		case IP_BOUND_IF:
10509 			connp->conn_incoming_ill = ill;
10510 			connp->conn_outgoing_ill = ill;
10511 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10512 			    0 : ifindex;
10513 			break;
10514 
10515 		case IP_MULTICAST_IF:
10516 			/*
10517 			 * This option is an internal special. The socket
10518 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10519 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10520 			 * specifies an ifindex and we try first on V6 ill's.
10521 			 * If we don't find one, we they try using on v4 ill's
10522 			 * intenally and we come here.
10523 			 */
10524 			if (!checkonly && ill != NULL) {
10525 				ipif_t	*ipif;
10526 				ipif = ill->ill_ipif;
10527 
10528 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10529 					mutex_exit(&ill->ill_lock);
10530 					mutex_exit(&connp->conn_lock);
10531 					ill_refrele(ill);
10532 					ill = NULL;
10533 					mutex_enter(&connp->conn_lock);
10534 				} else {
10535 					connp->conn_multicast_ipif = ipif;
10536 				}
10537 			}
10538 			break;
10539 
10540 		case IP_DHCPINIT_IF:
10541 			if (connp->conn_dhcpinit_ill != NULL) {
10542 				/*
10543 				 * We've locked the conn so conn_cleanup_ill()
10544 				 * cannot clear conn_dhcpinit_ill -- so it's
10545 				 * safe to access the ill.
10546 				 */
10547 				ill_t *oill = connp->conn_dhcpinit_ill;
10548 
10549 				ASSERT(oill->ill_dhcpinit != 0);
10550 				atomic_dec_32(&oill->ill_dhcpinit);
10551 				connp->conn_dhcpinit_ill = NULL;
10552 			}
10553 
10554 			if (ill != NULL) {
10555 				connp->conn_dhcpinit_ill = ill;
10556 				atomic_inc_32(&ill->ill_dhcpinit);
10557 			}
10558 			break;
10559 		}
10560 	} else {
10561 		switch (option) {
10562 		case IPV6_BOUND_IF:
10563 			connp->conn_incoming_ill = ill;
10564 			connp->conn_outgoing_ill = ill;
10565 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10566 			    0 : ifindex;
10567 			break;
10568 
10569 		case IPV6_BOUND_PIF:
10570 			/*
10571 			 * Limit all transmit to this ill.
10572 			 * Unlike IPV6_BOUND_IF, using this option
10573 			 * prevents load spreading and failover from
10574 			 * happening when the interface is part of the
10575 			 * group. That's why we don't need to remember
10576 			 * the ifindex in orig_bound_ifindex as in
10577 			 * IPV6_BOUND_IF.
10578 			 */
10579 			connp->conn_outgoing_pill = ill;
10580 			break;
10581 
10582 		case IPV6_DONTFAILOVER_IF:
10583 			/*
10584 			 * This option is used by in.mpathd to ensure
10585 			 * that IPMP probe packets only go out on the
10586 			 * test interfaces. in.mpathd sets this option
10587 			 * on the non-failover interfaces.
10588 			 */
10589 			connp->conn_nofailover_ill = ill;
10590 			/*
10591 			 * For backward compatibility, this option
10592 			 * implicitly sets ip_multicast_ill as used in
10593 			 * IPV6_MULTICAST_IF so that ip_wput gets
10594 			 * this ill to send mcast packets.
10595 			 */
10596 			connp->conn_multicast_ill = ill;
10597 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10598 			    0 : ifindex;
10599 			break;
10600 
10601 		case IPV6_MULTICAST_IF:
10602 			/*
10603 			 * Set conn_multicast_ill to be the IPv6 ill.
10604 			 * Set conn_multicast_ipif to be an IPv4 ipif
10605 			 * for ifindex to make IPv4 mapped addresses
10606 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10607 			 * Even if no IPv6 ill exists for the ifindex
10608 			 * we need to check for an IPv4 ifindex in order
10609 			 * for this to work with mapped addresses. In that
10610 			 * case only set conn_multicast_ipif.
10611 			 */
10612 			if (!checkonly) {
10613 				if (ifindex == 0) {
10614 					connp->conn_multicast_ill = NULL;
10615 					connp->conn_orig_multicast_ifindex = 0;
10616 					connp->conn_multicast_ipif = NULL;
10617 				} else if (ill != NULL) {
10618 					connp->conn_multicast_ill = ill;
10619 					connp->conn_orig_multicast_ifindex =
10620 					    ifindex;
10621 				}
10622 			}
10623 			break;
10624 		}
10625 	}
10626 
10627 	if (ill != NULL) {
10628 		mutex_exit(&ill->ill_lock);
10629 		mutex_exit(&connp->conn_lock);
10630 		ill_refrele(ill);
10631 		return (0);
10632 	}
10633 	mutex_exit(&connp->conn_lock);
10634 	/*
10635 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10636 	 * locate the ill and could not set the option (ifindex != 0)
10637 	 */
10638 	return (ifindex == 0 ? 0 : EINVAL);
10639 }
10640 
10641 /* This routine sets socket options. */
10642 /* ARGSUSED */
10643 int
10644 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10645     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10646     void *dummy, cred_t *cr, mblk_t *first_mp)
10647 {
10648 	int		*i1 = (int *)invalp;
10649 	conn_t		*connp = Q_TO_CONN(q);
10650 	int		error = 0;
10651 	boolean_t	checkonly;
10652 	ire_t		*ire;
10653 	boolean_t	found;
10654 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10655 
10656 	switch (optset_context) {
10657 
10658 	case SETFN_OPTCOM_CHECKONLY:
10659 		checkonly = B_TRUE;
10660 		/*
10661 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10662 		 * inlen != 0 implies value supplied and
10663 		 * 	we have to "pretend" to set it.
10664 		 * inlen == 0 implies that there is no
10665 		 * 	value part in T_CHECK request and just validation
10666 		 * done elsewhere should be enough, we just return here.
10667 		 */
10668 		if (inlen == 0) {
10669 			*outlenp = 0;
10670 			return (0);
10671 		}
10672 		break;
10673 	case SETFN_OPTCOM_NEGOTIATE:
10674 	case SETFN_UD_NEGOTIATE:
10675 	case SETFN_CONN_NEGOTIATE:
10676 		checkonly = B_FALSE;
10677 		break;
10678 	default:
10679 		/*
10680 		 * We should never get here
10681 		 */
10682 		*outlenp = 0;
10683 		return (EINVAL);
10684 	}
10685 
10686 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10687 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10688 
10689 	/*
10690 	 * For fixed length options, no sanity check
10691 	 * of passed in length is done. It is assumed *_optcom_req()
10692 	 * routines do the right thing.
10693 	 */
10694 
10695 	switch (level) {
10696 	case SOL_SOCKET:
10697 		/*
10698 		 * conn_lock protects the bitfields, and is used to
10699 		 * set the fields atomically.
10700 		 */
10701 		switch (name) {
10702 		case SO_BROADCAST:
10703 			if (!checkonly) {
10704 				/* TODO: use value someplace? */
10705 				mutex_enter(&connp->conn_lock);
10706 				connp->conn_broadcast = *i1 ? 1 : 0;
10707 				mutex_exit(&connp->conn_lock);
10708 			}
10709 			break;	/* goto sizeof (int) option return */
10710 		case SO_USELOOPBACK:
10711 			if (!checkonly) {
10712 				/* TODO: use value someplace? */
10713 				mutex_enter(&connp->conn_lock);
10714 				connp->conn_loopback = *i1 ? 1 : 0;
10715 				mutex_exit(&connp->conn_lock);
10716 			}
10717 			break;	/* goto sizeof (int) option return */
10718 		case SO_DONTROUTE:
10719 			if (!checkonly) {
10720 				mutex_enter(&connp->conn_lock);
10721 				connp->conn_dontroute = *i1 ? 1 : 0;
10722 				mutex_exit(&connp->conn_lock);
10723 			}
10724 			break;	/* goto sizeof (int) option return */
10725 		case SO_REUSEADDR:
10726 			if (!checkonly) {
10727 				mutex_enter(&connp->conn_lock);
10728 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10729 				mutex_exit(&connp->conn_lock);
10730 			}
10731 			break;	/* goto sizeof (int) option return */
10732 		case SO_PROTOTYPE:
10733 			if (!checkonly) {
10734 				mutex_enter(&connp->conn_lock);
10735 				connp->conn_proto = *i1;
10736 				mutex_exit(&connp->conn_lock);
10737 			}
10738 			break;	/* goto sizeof (int) option return */
10739 		case SO_ALLZONES:
10740 			if (!checkonly) {
10741 				mutex_enter(&connp->conn_lock);
10742 				if (IPCL_IS_BOUND(connp)) {
10743 					mutex_exit(&connp->conn_lock);
10744 					return (EINVAL);
10745 				}
10746 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10747 				mutex_exit(&connp->conn_lock);
10748 			}
10749 			break;	/* goto sizeof (int) option return */
10750 		case SO_ANON_MLP:
10751 			if (!checkonly) {
10752 				mutex_enter(&connp->conn_lock);
10753 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10754 				mutex_exit(&connp->conn_lock);
10755 			}
10756 			break;	/* goto sizeof (int) option return */
10757 		case SO_MAC_EXEMPT:
10758 			if (secpolicy_net_mac_aware(cr) != 0 ||
10759 			    IPCL_IS_BOUND(connp))
10760 				return (EACCES);
10761 			if (!checkonly) {
10762 				mutex_enter(&connp->conn_lock);
10763 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10764 				mutex_exit(&connp->conn_lock);
10765 			}
10766 			break;	/* goto sizeof (int) option return */
10767 		default:
10768 			/*
10769 			 * "soft" error (negative)
10770 			 * option not handled at this level
10771 			 * Note: Do not modify *outlenp
10772 			 */
10773 			return (-EINVAL);
10774 		}
10775 		break;
10776 	case IPPROTO_IP:
10777 		switch (name) {
10778 		case IP_NEXTHOP:
10779 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10780 				return (EPERM);
10781 			/* FALLTHRU */
10782 		case IP_MULTICAST_IF:
10783 		case IP_DONTFAILOVER_IF: {
10784 			ipaddr_t addr = *i1;
10785 
10786 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10787 			    first_mp);
10788 			if (error != 0)
10789 				return (error);
10790 			break;	/* goto sizeof (int) option return */
10791 		}
10792 
10793 		case IP_MULTICAST_TTL:
10794 			/* Recorded in transport above IP */
10795 			*outvalp = *invalp;
10796 			*outlenp = sizeof (uchar_t);
10797 			return (0);
10798 		case IP_MULTICAST_LOOP:
10799 			if (!checkonly) {
10800 				mutex_enter(&connp->conn_lock);
10801 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10802 				mutex_exit(&connp->conn_lock);
10803 			}
10804 			*outvalp = *invalp;
10805 			*outlenp = sizeof (uchar_t);
10806 			return (0);
10807 		case IP_ADD_MEMBERSHIP:
10808 		case MCAST_JOIN_GROUP:
10809 		case IP_DROP_MEMBERSHIP:
10810 		case MCAST_LEAVE_GROUP: {
10811 			struct ip_mreq *mreqp;
10812 			struct group_req *greqp;
10813 			ire_t *ire;
10814 			boolean_t done = B_FALSE;
10815 			ipaddr_t group, ifaddr;
10816 			struct sockaddr_in *sin;
10817 			uint32_t *ifindexp;
10818 			boolean_t mcast_opt = B_TRUE;
10819 			mcast_record_t fmode;
10820 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10821 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10822 
10823 			switch (name) {
10824 			case IP_ADD_MEMBERSHIP:
10825 				mcast_opt = B_FALSE;
10826 				/* FALLTHRU */
10827 			case MCAST_JOIN_GROUP:
10828 				fmode = MODE_IS_EXCLUDE;
10829 				optfn = ip_opt_add_group;
10830 				break;
10831 
10832 			case IP_DROP_MEMBERSHIP:
10833 				mcast_opt = B_FALSE;
10834 				/* FALLTHRU */
10835 			case MCAST_LEAVE_GROUP:
10836 				fmode = MODE_IS_INCLUDE;
10837 				optfn = ip_opt_delete_group;
10838 				break;
10839 			}
10840 
10841 			if (mcast_opt) {
10842 				greqp = (struct group_req *)i1;
10843 				sin = (struct sockaddr_in *)&greqp->gr_group;
10844 				if (sin->sin_family != AF_INET) {
10845 					*outlenp = 0;
10846 					return (ENOPROTOOPT);
10847 				}
10848 				group = (ipaddr_t)sin->sin_addr.s_addr;
10849 				ifaddr = INADDR_ANY;
10850 				ifindexp = &greqp->gr_interface;
10851 			} else {
10852 				mreqp = (struct ip_mreq *)i1;
10853 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10854 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10855 				ifindexp = NULL;
10856 			}
10857 
10858 			/*
10859 			 * In the multirouting case, we need to replicate
10860 			 * the request on all interfaces that will take part
10861 			 * in replication.  We do so because multirouting is
10862 			 * reflective, thus we will probably receive multi-
10863 			 * casts on those interfaces.
10864 			 * The ip_multirt_apply_membership() succeeds if the
10865 			 * operation succeeds on at least one interface.
10866 			 */
10867 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10868 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10869 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10870 			if (ire != NULL) {
10871 				if (ire->ire_flags & RTF_MULTIRT) {
10872 					error = ip_multirt_apply_membership(
10873 					    optfn, ire, connp, checkonly, group,
10874 					    fmode, INADDR_ANY, first_mp);
10875 					done = B_TRUE;
10876 				}
10877 				ire_refrele(ire);
10878 			}
10879 			if (!done) {
10880 				error = optfn(connp, checkonly, group, ifaddr,
10881 				    ifindexp, fmode, INADDR_ANY, first_mp);
10882 			}
10883 			if (error) {
10884 				/*
10885 				 * EINPROGRESS is a soft error, needs retry
10886 				 * so don't make *outlenp zero.
10887 				 */
10888 				if (error != EINPROGRESS)
10889 					*outlenp = 0;
10890 				return (error);
10891 			}
10892 			/* OK return - copy input buffer into output buffer */
10893 			if (invalp != outvalp) {
10894 				/* don't trust bcopy for identical src/dst */
10895 				bcopy(invalp, outvalp, inlen);
10896 			}
10897 			*outlenp = inlen;
10898 			return (0);
10899 		}
10900 		case IP_BLOCK_SOURCE:
10901 		case IP_UNBLOCK_SOURCE:
10902 		case IP_ADD_SOURCE_MEMBERSHIP:
10903 		case IP_DROP_SOURCE_MEMBERSHIP:
10904 		case MCAST_BLOCK_SOURCE:
10905 		case MCAST_UNBLOCK_SOURCE:
10906 		case MCAST_JOIN_SOURCE_GROUP:
10907 		case MCAST_LEAVE_SOURCE_GROUP: {
10908 			struct ip_mreq_source *imreqp;
10909 			struct group_source_req *gsreqp;
10910 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10911 			uint32_t ifindex = 0;
10912 			mcast_record_t fmode;
10913 			struct sockaddr_in *sin;
10914 			ire_t *ire;
10915 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10916 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10917 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10918 
10919 			switch (name) {
10920 			case IP_BLOCK_SOURCE:
10921 				mcast_opt = B_FALSE;
10922 				/* FALLTHRU */
10923 			case MCAST_BLOCK_SOURCE:
10924 				fmode = MODE_IS_EXCLUDE;
10925 				optfn = ip_opt_add_group;
10926 				break;
10927 
10928 			case IP_UNBLOCK_SOURCE:
10929 				mcast_opt = B_FALSE;
10930 				/* FALLTHRU */
10931 			case MCAST_UNBLOCK_SOURCE:
10932 				fmode = MODE_IS_EXCLUDE;
10933 				optfn = ip_opt_delete_group;
10934 				break;
10935 
10936 			case IP_ADD_SOURCE_MEMBERSHIP:
10937 				mcast_opt = B_FALSE;
10938 				/* FALLTHRU */
10939 			case MCAST_JOIN_SOURCE_GROUP:
10940 				fmode = MODE_IS_INCLUDE;
10941 				optfn = ip_opt_add_group;
10942 				break;
10943 
10944 			case IP_DROP_SOURCE_MEMBERSHIP:
10945 				mcast_opt = B_FALSE;
10946 				/* FALLTHRU */
10947 			case MCAST_LEAVE_SOURCE_GROUP:
10948 				fmode = MODE_IS_INCLUDE;
10949 				optfn = ip_opt_delete_group;
10950 				break;
10951 			}
10952 
10953 			if (mcast_opt) {
10954 				gsreqp = (struct group_source_req *)i1;
10955 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10956 					*outlenp = 0;
10957 					return (ENOPROTOOPT);
10958 				}
10959 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10960 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10961 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10962 				src = (ipaddr_t)sin->sin_addr.s_addr;
10963 				ifindex = gsreqp->gsr_interface;
10964 			} else {
10965 				imreqp = (struct ip_mreq_source *)i1;
10966 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10967 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10968 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10969 			}
10970 
10971 			/*
10972 			 * In the multirouting case, we need to replicate
10973 			 * the request as noted in the mcast cases above.
10974 			 */
10975 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10976 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10977 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10978 			if (ire != NULL) {
10979 				if (ire->ire_flags & RTF_MULTIRT) {
10980 					error = ip_multirt_apply_membership(
10981 					    optfn, ire, connp, checkonly, grp,
10982 					    fmode, src, first_mp);
10983 					done = B_TRUE;
10984 				}
10985 				ire_refrele(ire);
10986 			}
10987 			if (!done) {
10988 				error = optfn(connp, checkonly, grp, ifaddr,
10989 				    &ifindex, fmode, src, first_mp);
10990 			}
10991 			if (error != 0) {
10992 				/*
10993 				 * EINPROGRESS is a soft error, needs retry
10994 				 * so don't make *outlenp zero.
10995 				 */
10996 				if (error != EINPROGRESS)
10997 					*outlenp = 0;
10998 				return (error);
10999 			}
11000 			/* OK return - copy input buffer into output buffer */
11001 			if (invalp != outvalp) {
11002 				bcopy(invalp, outvalp, inlen);
11003 			}
11004 			*outlenp = inlen;
11005 			return (0);
11006 		}
11007 		case IP_SEC_OPT:
11008 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11009 			if (error != 0) {
11010 				*outlenp = 0;
11011 				return (error);
11012 			}
11013 			break;
11014 		case IP_HDRINCL:
11015 		case IP_OPTIONS:
11016 		case T_IP_OPTIONS:
11017 		case IP_TOS:
11018 		case T_IP_TOS:
11019 		case IP_TTL:
11020 		case IP_RECVDSTADDR:
11021 		case IP_RECVOPTS:
11022 			/* OK return - copy input buffer into output buffer */
11023 			if (invalp != outvalp) {
11024 				/* don't trust bcopy for identical src/dst */
11025 				bcopy(invalp, outvalp, inlen);
11026 			}
11027 			*outlenp = inlen;
11028 			return (0);
11029 		case IP_RECVIF:
11030 			/* Retrieve the inbound interface index */
11031 			if (!checkonly) {
11032 				mutex_enter(&connp->conn_lock);
11033 				connp->conn_recvif = *i1 ? 1 : 0;
11034 				mutex_exit(&connp->conn_lock);
11035 			}
11036 			break;	/* goto sizeof (int) option return */
11037 		case IP_RECVPKTINFO:
11038 			if (!checkonly) {
11039 				mutex_enter(&connp->conn_lock);
11040 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11041 				mutex_exit(&connp->conn_lock);
11042 			}
11043 			break;	/* goto sizeof (int) option return */
11044 		case IP_RECVSLLA:
11045 			/* Retrieve the source link layer address */
11046 			if (!checkonly) {
11047 				mutex_enter(&connp->conn_lock);
11048 				connp->conn_recvslla = *i1 ? 1 : 0;
11049 				mutex_exit(&connp->conn_lock);
11050 			}
11051 			break;	/* goto sizeof (int) option return */
11052 		case MRT_INIT:
11053 		case MRT_DONE:
11054 		case MRT_ADD_VIF:
11055 		case MRT_DEL_VIF:
11056 		case MRT_ADD_MFC:
11057 		case MRT_DEL_MFC:
11058 		case MRT_ASSERT:
11059 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11060 				*outlenp = 0;
11061 				return (error);
11062 			}
11063 			error = ip_mrouter_set((int)name, q, checkonly,
11064 			    (uchar_t *)invalp, inlen, first_mp);
11065 			if (error) {
11066 				*outlenp = 0;
11067 				return (error);
11068 			}
11069 			/* OK return - copy input buffer into output buffer */
11070 			if (invalp != outvalp) {
11071 				/* don't trust bcopy for identical src/dst */
11072 				bcopy(invalp, outvalp, inlen);
11073 			}
11074 			*outlenp = inlen;
11075 			return (0);
11076 		case IP_BOUND_IF:
11077 		case IP_DHCPINIT_IF:
11078 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11079 			    level, name, first_mp);
11080 			if (error != 0)
11081 				return (error);
11082 			break; 		/* goto sizeof (int) option return */
11083 
11084 		case IP_UNSPEC_SRC:
11085 			/* Allow sending with a zero source address */
11086 			if (!checkonly) {
11087 				mutex_enter(&connp->conn_lock);
11088 				connp->conn_unspec_src = *i1 ? 1 : 0;
11089 				mutex_exit(&connp->conn_lock);
11090 			}
11091 			break;	/* goto sizeof (int) option return */
11092 		default:
11093 			/*
11094 			 * "soft" error (negative)
11095 			 * option not handled at this level
11096 			 * Note: Do not modify *outlenp
11097 			 */
11098 			return (-EINVAL);
11099 		}
11100 		break;
11101 	case IPPROTO_IPV6:
11102 		switch (name) {
11103 		case IPV6_BOUND_IF:
11104 		case IPV6_BOUND_PIF:
11105 		case IPV6_DONTFAILOVER_IF:
11106 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11107 			    level, name, first_mp);
11108 			if (error != 0)
11109 				return (error);
11110 			break; 		/* goto sizeof (int) option return */
11111 
11112 		case IPV6_MULTICAST_IF:
11113 			/*
11114 			 * The only possible errors are EINPROGRESS and
11115 			 * EINVAL. EINPROGRESS will be restarted and is not
11116 			 * a hard error. We call this option on both V4 and V6
11117 			 * If both return EINVAL, then this call returns
11118 			 * EINVAL. If at least one of them succeeds we
11119 			 * return success.
11120 			 */
11121 			found = B_FALSE;
11122 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11123 			    level, name, first_mp);
11124 			if (error == EINPROGRESS)
11125 				return (error);
11126 			if (error == 0)
11127 				found = B_TRUE;
11128 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11129 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11130 			if (error == 0)
11131 				found = B_TRUE;
11132 			if (!found)
11133 				return (error);
11134 			break; 		/* goto sizeof (int) option return */
11135 
11136 		case IPV6_MULTICAST_HOPS:
11137 			/* Recorded in transport above IP */
11138 			break;	/* goto sizeof (int) option return */
11139 		case IPV6_MULTICAST_LOOP:
11140 			if (!checkonly) {
11141 				mutex_enter(&connp->conn_lock);
11142 				connp->conn_multicast_loop = *i1;
11143 				mutex_exit(&connp->conn_lock);
11144 			}
11145 			break;	/* goto sizeof (int) option return */
11146 		case IPV6_JOIN_GROUP:
11147 		case MCAST_JOIN_GROUP:
11148 		case IPV6_LEAVE_GROUP:
11149 		case MCAST_LEAVE_GROUP: {
11150 			struct ipv6_mreq *ip_mreqp;
11151 			struct group_req *greqp;
11152 			ire_t *ire;
11153 			boolean_t done = B_FALSE;
11154 			in6_addr_t groupv6;
11155 			uint32_t ifindex;
11156 			boolean_t mcast_opt = B_TRUE;
11157 			mcast_record_t fmode;
11158 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11159 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11160 
11161 			switch (name) {
11162 			case IPV6_JOIN_GROUP:
11163 				mcast_opt = B_FALSE;
11164 				/* FALLTHRU */
11165 			case MCAST_JOIN_GROUP:
11166 				fmode = MODE_IS_EXCLUDE;
11167 				optfn = ip_opt_add_group_v6;
11168 				break;
11169 
11170 			case IPV6_LEAVE_GROUP:
11171 				mcast_opt = B_FALSE;
11172 				/* FALLTHRU */
11173 			case MCAST_LEAVE_GROUP:
11174 				fmode = MODE_IS_INCLUDE;
11175 				optfn = ip_opt_delete_group_v6;
11176 				break;
11177 			}
11178 
11179 			if (mcast_opt) {
11180 				struct sockaddr_in *sin;
11181 				struct sockaddr_in6 *sin6;
11182 				greqp = (struct group_req *)i1;
11183 				if (greqp->gr_group.ss_family == AF_INET) {
11184 					sin = (struct sockaddr_in *)
11185 					    &(greqp->gr_group);
11186 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11187 					    &groupv6);
11188 				} else {
11189 					sin6 = (struct sockaddr_in6 *)
11190 					    &(greqp->gr_group);
11191 					groupv6 = sin6->sin6_addr;
11192 				}
11193 				ifindex = greqp->gr_interface;
11194 			} else {
11195 				ip_mreqp = (struct ipv6_mreq *)i1;
11196 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11197 				ifindex = ip_mreqp->ipv6mr_interface;
11198 			}
11199 			/*
11200 			 * In the multirouting case, we need to replicate
11201 			 * the request on all interfaces that will take part
11202 			 * in replication.  We do so because multirouting is
11203 			 * reflective, thus we will probably receive multi-
11204 			 * casts on those interfaces.
11205 			 * The ip_multirt_apply_membership_v6() succeeds if
11206 			 * the operation succeeds on at least one interface.
11207 			 */
11208 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11209 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11210 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11211 			if (ire != NULL) {
11212 				if (ire->ire_flags & RTF_MULTIRT) {
11213 					error = ip_multirt_apply_membership_v6(
11214 					    optfn, ire, connp, checkonly,
11215 					    &groupv6, fmode, &ipv6_all_zeros,
11216 					    first_mp);
11217 					done = B_TRUE;
11218 				}
11219 				ire_refrele(ire);
11220 			}
11221 			if (!done) {
11222 				error = optfn(connp, checkonly, &groupv6,
11223 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11224 			}
11225 			if (error) {
11226 				/*
11227 				 * EINPROGRESS is a soft error, needs retry
11228 				 * so don't make *outlenp zero.
11229 				 */
11230 				if (error != EINPROGRESS)
11231 					*outlenp = 0;
11232 				return (error);
11233 			}
11234 			/* OK return - copy input buffer into output buffer */
11235 			if (invalp != outvalp) {
11236 				/* don't trust bcopy for identical src/dst */
11237 				bcopy(invalp, outvalp, inlen);
11238 			}
11239 			*outlenp = inlen;
11240 			return (0);
11241 		}
11242 		case MCAST_BLOCK_SOURCE:
11243 		case MCAST_UNBLOCK_SOURCE:
11244 		case MCAST_JOIN_SOURCE_GROUP:
11245 		case MCAST_LEAVE_SOURCE_GROUP: {
11246 			struct group_source_req *gsreqp;
11247 			in6_addr_t v6grp, v6src;
11248 			uint32_t ifindex;
11249 			mcast_record_t fmode;
11250 			ire_t *ire;
11251 			boolean_t done = B_FALSE;
11252 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11253 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11254 
11255 			switch (name) {
11256 			case MCAST_BLOCK_SOURCE:
11257 				fmode = MODE_IS_EXCLUDE;
11258 				optfn = ip_opt_add_group_v6;
11259 				break;
11260 			case MCAST_UNBLOCK_SOURCE:
11261 				fmode = MODE_IS_EXCLUDE;
11262 				optfn = ip_opt_delete_group_v6;
11263 				break;
11264 			case MCAST_JOIN_SOURCE_GROUP:
11265 				fmode = MODE_IS_INCLUDE;
11266 				optfn = ip_opt_add_group_v6;
11267 				break;
11268 			case MCAST_LEAVE_SOURCE_GROUP:
11269 				fmode = MODE_IS_INCLUDE;
11270 				optfn = ip_opt_delete_group_v6;
11271 				break;
11272 			}
11273 
11274 			gsreqp = (struct group_source_req *)i1;
11275 			ifindex = gsreqp->gsr_interface;
11276 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11277 				struct sockaddr_in *s;
11278 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11279 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11280 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11281 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11282 			} else {
11283 				struct sockaddr_in6 *s6;
11284 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11285 				v6grp = s6->sin6_addr;
11286 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11287 				v6src = s6->sin6_addr;
11288 			}
11289 
11290 			/*
11291 			 * In the multirouting case, we need to replicate
11292 			 * the request as noted in the mcast cases above.
11293 			 */
11294 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11295 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11296 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11297 			if (ire != NULL) {
11298 				if (ire->ire_flags & RTF_MULTIRT) {
11299 					error = ip_multirt_apply_membership_v6(
11300 					    optfn, ire, connp, checkonly,
11301 					    &v6grp, fmode, &v6src, first_mp);
11302 					done = B_TRUE;
11303 				}
11304 				ire_refrele(ire);
11305 			}
11306 			if (!done) {
11307 				error = optfn(connp, checkonly, &v6grp,
11308 				    ifindex, fmode, &v6src, first_mp);
11309 			}
11310 			if (error != 0) {
11311 				/*
11312 				 * EINPROGRESS is a soft error, needs retry
11313 				 * so don't make *outlenp zero.
11314 				 */
11315 				if (error != EINPROGRESS)
11316 					*outlenp = 0;
11317 				return (error);
11318 			}
11319 			/* OK return - copy input buffer into output buffer */
11320 			if (invalp != outvalp) {
11321 				bcopy(invalp, outvalp, inlen);
11322 			}
11323 			*outlenp = inlen;
11324 			return (0);
11325 		}
11326 		case IPV6_UNICAST_HOPS:
11327 			/* Recorded in transport above IP */
11328 			break;	/* goto sizeof (int) option return */
11329 		case IPV6_UNSPEC_SRC:
11330 			/* Allow sending with a zero source address */
11331 			if (!checkonly) {
11332 				mutex_enter(&connp->conn_lock);
11333 				connp->conn_unspec_src = *i1 ? 1 : 0;
11334 				mutex_exit(&connp->conn_lock);
11335 			}
11336 			break;	/* goto sizeof (int) option return */
11337 		case IPV6_RECVPKTINFO:
11338 			if (!checkonly) {
11339 				mutex_enter(&connp->conn_lock);
11340 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11341 				mutex_exit(&connp->conn_lock);
11342 			}
11343 			break;	/* goto sizeof (int) option return */
11344 		case IPV6_RECVTCLASS:
11345 			if (!checkonly) {
11346 				if (*i1 < 0 || *i1 > 1) {
11347 					return (EINVAL);
11348 				}
11349 				mutex_enter(&connp->conn_lock);
11350 				connp->conn_ipv6_recvtclass = *i1;
11351 				mutex_exit(&connp->conn_lock);
11352 			}
11353 			break;
11354 		case IPV6_RECVPATHMTU:
11355 			if (!checkonly) {
11356 				if (*i1 < 0 || *i1 > 1) {
11357 					return (EINVAL);
11358 				}
11359 				mutex_enter(&connp->conn_lock);
11360 				connp->conn_ipv6_recvpathmtu = *i1;
11361 				mutex_exit(&connp->conn_lock);
11362 			}
11363 			break;
11364 		case IPV6_RECVHOPLIMIT:
11365 			if (!checkonly) {
11366 				mutex_enter(&connp->conn_lock);
11367 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11368 				mutex_exit(&connp->conn_lock);
11369 			}
11370 			break;	/* goto sizeof (int) option return */
11371 		case IPV6_RECVHOPOPTS:
11372 			if (!checkonly) {
11373 				mutex_enter(&connp->conn_lock);
11374 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11375 				mutex_exit(&connp->conn_lock);
11376 			}
11377 			break;	/* goto sizeof (int) option return */
11378 		case IPV6_RECVDSTOPTS:
11379 			if (!checkonly) {
11380 				mutex_enter(&connp->conn_lock);
11381 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11382 				mutex_exit(&connp->conn_lock);
11383 			}
11384 			break;	/* goto sizeof (int) option return */
11385 		case IPV6_RECVRTHDR:
11386 			if (!checkonly) {
11387 				mutex_enter(&connp->conn_lock);
11388 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11389 				mutex_exit(&connp->conn_lock);
11390 			}
11391 			break;	/* goto sizeof (int) option return */
11392 		case IPV6_RECVRTHDRDSTOPTS:
11393 			if (!checkonly) {
11394 				mutex_enter(&connp->conn_lock);
11395 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11396 				mutex_exit(&connp->conn_lock);
11397 			}
11398 			break;	/* goto sizeof (int) option return */
11399 		case IPV6_PKTINFO:
11400 			if (inlen == 0)
11401 				return (-EINVAL);	/* clearing option */
11402 			error = ip6_set_pktinfo(cr, connp,
11403 			    (struct in6_pktinfo *)invalp, first_mp);
11404 			if (error != 0)
11405 				*outlenp = 0;
11406 			else
11407 				*outlenp = inlen;
11408 			return (error);
11409 		case IPV6_NEXTHOP: {
11410 			struct sockaddr_in6 *sin6;
11411 
11412 			/* Verify that the nexthop is reachable */
11413 			if (inlen == 0)
11414 				return (-EINVAL);	/* clearing option */
11415 
11416 			sin6 = (struct sockaddr_in6 *)invalp;
11417 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11418 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11419 			    NULL, MATCH_IRE_DEFAULT, ipst);
11420 
11421 			if (ire == NULL) {
11422 				*outlenp = 0;
11423 				return (EHOSTUNREACH);
11424 			}
11425 			ire_refrele(ire);
11426 			return (-EINVAL);
11427 		}
11428 		case IPV6_SEC_OPT:
11429 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11430 			if (error != 0) {
11431 				*outlenp = 0;
11432 				return (error);
11433 			}
11434 			break;
11435 		case IPV6_SRC_PREFERENCES: {
11436 			/*
11437 			 * This is implemented strictly in the ip module
11438 			 * (here and in tcp_opt_*() to accomodate tcp
11439 			 * sockets).  Modules above ip pass this option
11440 			 * down here since ip is the only one that needs to
11441 			 * be aware of source address preferences.
11442 			 *
11443 			 * This socket option only affects connected
11444 			 * sockets that haven't already bound to a specific
11445 			 * IPv6 address.  In other words, sockets that
11446 			 * don't call bind() with an address other than the
11447 			 * unspecified address and that call connect().
11448 			 * ip_bind_connected_v6() passes these preferences
11449 			 * to the ipif_select_source_v6() function.
11450 			 */
11451 			if (inlen != sizeof (uint32_t))
11452 				return (EINVAL);
11453 			error = ip6_set_src_preferences(connp,
11454 			    *(uint32_t *)invalp);
11455 			if (error != 0) {
11456 				*outlenp = 0;
11457 				return (error);
11458 			} else {
11459 				*outlenp = sizeof (uint32_t);
11460 			}
11461 			break;
11462 		}
11463 		case IPV6_V6ONLY:
11464 			if (*i1 < 0 || *i1 > 1) {
11465 				return (EINVAL);
11466 			}
11467 			mutex_enter(&connp->conn_lock);
11468 			connp->conn_ipv6_v6only = *i1;
11469 			mutex_exit(&connp->conn_lock);
11470 			break;
11471 		default:
11472 			return (-EINVAL);
11473 		}
11474 		break;
11475 	default:
11476 		/*
11477 		 * "soft" error (negative)
11478 		 * option not handled at this level
11479 		 * Note: Do not modify *outlenp
11480 		 */
11481 		return (-EINVAL);
11482 	}
11483 	/*
11484 	 * Common case of return from an option that is sizeof (int)
11485 	 */
11486 	*(int *)outvalp = *i1;
11487 	*outlenp = sizeof (int);
11488 	return (0);
11489 }
11490 
11491 /*
11492  * This routine gets default values of certain options whose default
11493  * values are maintained by protocol specific code
11494  */
11495 /* ARGSUSED */
11496 int
11497 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11498 {
11499 	int *i1 = (int *)ptr;
11500 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11501 
11502 	switch (level) {
11503 	case IPPROTO_IP:
11504 		switch (name) {
11505 		case IP_MULTICAST_TTL:
11506 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11507 			return (sizeof (uchar_t));
11508 		case IP_MULTICAST_LOOP:
11509 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11510 			return (sizeof (uchar_t));
11511 		default:
11512 			return (-1);
11513 		}
11514 	case IPPROTO_IPV6:
11515 		switch (name) {
11516 		case IPV6_UNICAST_HOPS:
11517 			*i1 = ipst->ips_ipv6_def_hops;
11518 			return (sizeof (int));
11519 		case IPV6_MULTICAST_HOPS:
11520 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11521 			return (sizeof (int));
11522 		case IPV6_MULTICAST_LOOP:
11523 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11524 			return (sizeof (int));
11525 		case IPV6_V6ONLY:
11526 			*i1 = 1;
11527 			return (sizeof (int));
11528 		default:
11529 			return (-1);
11530 		}
11531 	default:
11532 		return (-1);
11533 	}
11534 	/* NOTREACHED */
11535 }
11536 
11537 /*
11538  * Given a destination address and a pointer to where to put the information
11539  * this routine fills in the mtuinfo.
11540  */
11541 int
11542 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11543     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11544 {
11545 	ire_t *ire;
11546 	ip_stack_t	*ipst = ns->netstack_ip;
11547 
11548 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11549 		return (-1);
11550 
11551 	bzero(mtuinfo, sizeof (*mtuinfo));
11552 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11553 	mtuinfo->ip6m_addr.sin6_port = port;
11554 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11555 
11556 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11557 	if (ire != NULL) {
11558 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11559 		ire_refrele(ire);
11560 	} else {
11561 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11562 	}
11563 	return (sizeof (struct ip6_mtuinfo));
11564 }
11565 
11566 /*
11567  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11568  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11569  * isn't.  This doesn't matter as the error checking is done properly for the
11570  * other MRT options coming in through ip_opt_set.
11571  */
11572 int
11573 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11574 {
11575 	conn_t		*connp = Q_TO_CONN(q);
11576 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11577 
11578 	switch (level) {
11579 	case IPPROTO_IP:
11580 		switch (name) {
11581 		case MRT_VERSION:
11582 		case MRT_ASSERT:
11583 			(void) ip_mrouter_get(name, q, ptr);
11584 			return (sizeof (int));
11585 		case IP_SEC_OPT:
11586 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11587 		case IP_NEXTHOP:
11588 			if (connp->conn_nexthop_set) {
11589 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11590 				return (sizeof (ipaddr_t));
11591 			} else
11592 				return (0);
11593 		case IP_RECVPKTINFO:
11594 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11595 			return (sizeof (int));
11596 		default:
11597 			break;
11598 		}
11599 		break;
11600 	case IPPROTO_IPV6:
11601 		switch (name) {
11602 		case IPV6_SEC_OPT:
11603 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11604 		case IPV6_SRC_PREFERENCES: {
11605 			return (ip6_get_src_preferences(connp,
11606 			    (uint32_t *)ptr));
11607 		}
11608 		case IPV6_V6ONLY:
11609 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11610 			return (sizeof (int));
11611 		case IPV6_PATHMTU:
11612 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11613 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11614 		default:
11615 			break;
11616 		}
11617 		break;
11618 	default:
11619 		break;
11620 	}
11621 	return (-1);
11622 }
11623 
11624 /* Named Dispatch routine to get a current value out of our parameter table. */
11625 /* ARGSUSED */
11626 static int
11627 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11628 {
11629 	ipparam_t *ippa = (ipparam_t *)cp;
11630 
11631 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11632 	return (0);
11633 }
11634 
11635 /* ARGSUSED */
11636 static int
11637 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11638 {
11639 
11640 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11641 	return (0);
11642 }
11643 
11644 /*
11645  * Set ip{,6}_forwarding values.  This means walking through all of the
11646  * ill's and toggling their forwarding values.
11647  */
11648 /* ARGSUSED */
11649 static int
11650 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11651 {
11652 	long new_value;
11653 	int *forwarding_value = (int *)cp;
11654 	ill_t *ill;
11655 	boolean_t isv6;
11656 	ill_walk_context_t ctx;
11657 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11658 
11659 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11660 
11661 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11662 	    new_value < 0 || new_value > 1) {
11663 		return (EINVAL);
11664 	}
11665 
11666 	*forwarding_value = new_value;
11667 
11668 	/*
11669 	 * Regardless of the current value of ip_forwarding, set all per-ill
11670 	 * values of ip_forwarding to the value being set.
11671 	 *
11672 	 * Bring all the ill's up to date with the new global value.
11673 	 */
11674 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11675 
11676 	if (isv6)
11677 		ill = ILL_START_WALK_V6(&ctx, ipst);
11678 	else
11679 		ill = ILL_START_WALK_V4(&ctx, ipst);
11680 
11681 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11682 		(void) ill_forward_set(ill, new_value != 0);
11683 
11684 	rw_exit(&ipst->ips_ill_g_lock);
11685 	return (0);
11686 }
11687 
11688 /*
11689  * Walk through the param array specified registering each element with the
11690  * Named Dispatch handler. This is called only during init. So it is ok
11691  * not to acquire any locks
11692  */
11693 static boolean_t
11694 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11695     ipndp_t *ipnd, size_t ipnd_cnt)
11696 {
11697 	for (; ippa_cnt-- > 0; ippa++) {
11698 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11699 			if (!nd_load(ndp, ippa->ip_param_name,
11700 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11701 				nd_free(ndp);
11702 				return (B_FALSE);
11703 			}
11704 		}
11705 	}
11706 
11707 	for (; ipnd_cnt-- > 0; ipnd++) {
11708 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11709 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11710 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11711 			    ipnd->ip_ndp_data)) {
11712 				nd_free(ndp);
11713 				return (B_FALSE);
11714 			}
11715 		}
11716 	}
11717 
11718 	return (B_TRUE);
11719 }
11720 
11721 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11722 /* ARGSUSED */
11723 static int
11724 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11725 {
11726 	long		new_value;
11727 	ipparam_t	*ippa = (ipparam_t *)cp;
11728 
11729 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11730 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11731 		return (EINVAL);
11732 	}
11733 	ippa->ip_param_value = new_value;
11734 	return (0);
11735 }
11736 
11737 /*
11738  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11739  * When an ipf is passed here for the first time, if
11740  * we already have in-order fragments on the queue, we convert from the fast-
11741  * path reassembly scheme to the hard-case scheme.  From then on, additional
11742  * fragments are reassembled here.  We keep track of the start and end offsets
11743  * of each piece, and the number of holes in the chain.  When the hole count
11744  * goes to zero, we are done!
11745  *
11746  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11747  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11748  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11749  * after the call to ip_reassemble().
11750  */
11751 int
11752 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11753     size_t msg_len)
11754 {
11755 	uint_t	end;
11756 	mblk_t	*next_mp;
11757 	mblk_t	*mp1;
11758 	uint_t	offset;
11759 	boolean_t incr_dups = B_TRUE;
11760 	boolean_t offset_zero_seen = B_FALSE;
11761 	boolean_t pkt_boundary_checked = B_FALSE;
11762 
11763 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11764 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11765 
11766 	/* Add in byte count */
11767 	ipf->ipf_count += msg_len;
11768 	if (ipf->ipf_end) {
11769 		/*
11770 		 * We were part way through in-order reassembly, but now there
11771 		 * is a hole.  We walk through messages already queued, and
11772 		 * mark them for hard case reassembly.  We know that up till
11773 		 * now they were in order starting from offset zero.
11774 		 */
11775 		offset = 0;
11776 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11777 			IP_REASS_SET_START(mp1, offset);
11778 			if (offset == 0) {
11779 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11780 				offset = -ipf->ipf_nf_hdr_len;
11781 			}
11782 			offset += mp1->b_wptr - mp1->b_rptr;
11783 			IP_REASS_SET_END(mp1, offset);
11784 		}
11785 		/* One hole at the end. */
11786 		ipf->ipf_hole_cnt = 1;
11787 		/* Brand it as a hard case, forever. */
11788 		ipf->ipf_end = 0;
11789 	}
11790 	/* Walk through all the new pieces. */
11791 	do {
11792 		end = start + (mp->b_wptr - mp->b_rptr);
11793 		/*
11794 		 * If start is 0, decrease 'end' only for the first mblk of
11795 		 * the fragment. Otherwise 'end' can get wrong value in the
11796 		 * second pass of the loop if first mblk is exactly the
11797 		 * size of ipf_nf_hdr_len.
11798 		 */
11799 		if (start == 0 && !offset_zero_seen) {
11800 			/* First segment */
11801 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11802 			end -= ipf->ipf_nf_hdr_len;
11803 			offset_zero_seen = B_TRUE;
11804 		}
11805 		next_mp = mp->b_cont;
11806 		/*
11807 		 * We are checking to see if there is any interesing data
11808 		 * to process.  If there isn't and the mblk isn't the
11809 		 * one which carries the unfragmentable header then we
11810 		 * drop it.  It's possible to have just the unfragmentable
11811 		 * header come through without any data.  That needs to be
11812 		 * saved.
11813 		 *
11814 		 * If the assert at the top of this function holds then the
11815 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11816 		 * is infrequently traveled enough that the test is left in
11817 		 * to protect against future code changes which break that
11818 		 * invariant.
11819 		 */
11820 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11821 			/* Empty.  Blast it. */
11822 			IP_REASS_SET_START(mp, 0);
11823 			IP_REASS_SET_END(mp, 0);
11824 			/*
11825 			 * If the ipf points to the mblk we are about to free,
11826 			 * update ipf to point to the next mblk (or NULL
11827 			 * if none).
11828 			 */
11829 			if (ipf->ipf_mp->b_cont == mp)
11830 				ipf->ipf_mp->b_cont = next_mp;
11831 			freeb(mp);
11832 			continue;
11833 		}
11834 		mp->b_cont = NULL;
11835 		IP_REASS_SET_START(mp, start);
11836 		IP_REASS_SET_END(mp, end);
11837 		if (!ipf->ipf_tail_mp) {
11838 			ipf->ipf_tail_mp = mp;
11839 			ipf->ipf_mp->b_cont = mp;
11840 			if (start == 0 || !more) {
11841 				ipf->ipf_hole_cnt = 1;
11842 				/*
11843 				 * if the first fragment comes in more than one
11844 				 * mblk, this loop will be executed for each
11845 				 * mblk. Need to adjust hole count so exiting
11846 				 * this routine will leave hole count at 1.
11847 				 */
11848 				if (next_mp)
11849 					ipf->ipf_hole_cnt++;
11850 			} else
11851 				ipf->ipf_hole_cnt = 2;
11852 			continue;
11853 		} else if (ipf->ipf_last_frag_seen && !more &&
11854 		    !pkt_boundary_checked) {
11855 			/*
11856 			 * We check datagram boundary only if this fragment
11857 			 * claims to be the last fragment and we have seen a
11858 			 * last fragment in the past too. We do this only
11859 			 * once for a given fragment.
11860 			 *
11861 			 * start cannot be 0 here as fragments with start=0
11862 			 * and MF=0 gets handled as a complete packet. These
11863 			 * fragments should not reach here.
11864 			 */
11865 
11866 			if (start + msgdsize(mp) !=
11867 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11868 				/*
11869 				 * We have two fragments both of which claim
11870 				 * to be the last fragment but gives conflicting
11871 				 * information about the whole datagram size.
11872 				 * Something fishy is going on. Drop the
11873 				 * fragment and free up the reassembly list.
11874 				 */
11875 				return (IP_REASS_FAILED);
11876 			}
11877 
11878 			/*
11879 			 * We shouldn't come to this code block again for this
11880 			 * particular fragment.
11881 			 */
11882 			pkt_boundary_checked = B_TRUE;
11883 		}
11884 
11885 		/* New stuff at or beyond tail? */
11886 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11887 		if (start >= offset) {
11888 			if (ipf->ipf_last_frag_seen) {
11889 				/* current fragment is beyond last fragment */
11890 				return (IP_REASS_FAILED);
11891 			}
11892 			/* Link it on end. */
11893 			ipf->ipf_tail_mp->b_cont = mp;
11894 			ipf->ipf_tail_mp = mp;
11895 			if (more) {
11896 				if (start != offset)
11897 					ipf->ipf_hole_cnt++;
11898 			} else if (start == offset && next_mp == NULL)
11899 					ipf->ipf_hole_cnt--;
11900 			continue;
11901 		}
11902 		mp1 = ipf->ipf_mp->b_cont;
11903 		offset = IP_REASS_START(mp1);
11904 		/* New stuff at the front? */
11905 		if (start < offset) {
11906 			if (start == 0) {
11907 				if (end >= offset) {
11908 					/* Nailed the hole at the begining. */
11909 					ipf->ipf_hole_cnt--;
11910 				}
11911 			} else if (end < offset) {
11912 				/*
11913 				 * A hole, stuff, and a hole where there used
11914 				 * to be just a hole.
11915 				 */
11916 				ipf->ipf_hole_cnt++;
11917 			}
11918 			mp->b_cont = mp1;
11919 			/* Check for overlap. */
11920 			while (end > offset) {
11921 				if (end < IP_REASS_END(mp1)) {
11922 					mp->b_wptr -= end - offset;
11923 					IP_REASS_SET_END(mp, offset);
11924 					BUMP_MIB(ill->ill_ip_mib,
11925 					    ipIfStatsReasmPartDups);
11926 					break;
11927 				}
11928 				/* Did we cover another hole? */
11929 				if ((mp1->b_cont &&
11930 				    IP_REASS_END(mp1) !=
11931 				    IP_REASS_START(mp1->b_cont) &&
11932 				    end >= IP_REASS_START(mp1->b_cont)) ||
11933 				    (!ipf->ipf_last_frag_seen && !more)) {
11934 					ipf->ipf_hole_cnt--;
11935 				}
11936 				/* Clip out mp1. */
11937 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11938 					/*
11939 					 * After clipping out mp1, this guy
11940 					 * is now hanging off the end.
11941 					 */
11942 					ipf->ipf_tail_mp = mp;
11943 				}
11944 				IP_REASS_SET_START(mp1, 0);
11945 				IP_REASS_SET_END(mp1, 0);
11946 				/* Subtract byte count */
11947 				ipf->ipf_count -= mp1->b_datap->db_lim -
11948 				    mp1->b_datap->db_base;
11949 				freeb(mp1);
11950 				BUMP_MIB(ill->ill_ip_mib,
11951 				    ipIfStatsReasmPartDups);
11952 				mp1 = mp->b_cont;
11953 				if (!mp1)
11954 					break;
11955 				offset = IP_REASS_START(mp1);
11956 			}
11957 			ipf->ipf_mp->b_cont = mp;
11958 			continue;
11959 		}
11960 		/*
11961 		 * The new piece starts somewhere between the start of the head
11962 		 * and before the end of the tail.
11963 		 */
11964 		for (; mp1; mp1 = mp1->b_cont) {
11965 			offset = IP_REASS_END(mp1);
11966 			if (start < offset) {
11967 				if (end <= offset) {
11968 					/* Nothing new. */
11969 					IP_REASS_SET_START(mp, 0);
11970 					IP_REASS_SET_END(mp, 0);
11971 					/* Subtract byte count */
11972 					ipf->ipf_count -= mp->b_datap->db_lim -
11973 					    mp->b_datap->db_base;
11974 					if (incr_dups) {
11975 						ipf->ipf_num_dups++;
11976 						incr_dups = B_FALSE;
11977 					}
11978 					freeb(mp);
11979 					BUMP_MIB(ill->ill_ip_mib,
11980 					    ipIfStatsReasmDuplicates);
11981 					break;
11982 				}
11983 				/*
11984 				 * Trim redundant stuff off beginning of new
11985 				 * piece.
11986 				 */
11987 				IP_REASS_SET_START(mp, offset);
11988 				mp->b_rptr += offset - start;
11989 				BUMP_MIB(ill->ill_ip_mib,
11990 				    ipIfStatsReasmPartDups);
11991 				start = offset;
11992 				if (!mp1->b_cont) {
11993 					/*
11994 					 * After trimming, this guy is now
11995 					 * hanging off the end.
11996 					 */
11997 					mp1->b_cont = mp;
11998 					ipf->ipf_tail_mp = mp;
11999 					if (!more) {
12000 						ipf->ipf_hole_cnt--;
12001 					}
12002 					break;
12003 				}
12004 			}
12005 			if (start >= IP_REASS_START(mp1->b_cont))
12006 				continue;
12007 			/* Fill a hole */
12008 			if (start > offset)
12009 				ipf->ipf_hole_cnt++;
12010 			mp->b_cont = mp1->b_cont;
12011 			mp1->b_cont = mp;
12012 			mp1 = mp->b_cont;
12013 			offset = IP_REASS_START(mp1);
12014 			if (end >= offset) {
12015 				ipf->ipf_hole_cnt--;
12016 				/* Check for overlap. */
12017 				while (end > offset) {
12018 					if (end < IP_REASS_END(mp1)) {
12019 						mp->b_wptr -= end - offset;
12020 						IP_REASS_SET_END(mp, offset);
12021 						/*
12022 						 * TODO we might bump
12023 						 * this up twice if there is
12024 						 * overlap at both ends.
12025 						 */
12026 						BUMP_MIB(ill->ill_ip_mib,
12027 						    ipIfStatsReasmPartDups);
12028 						break;
12029 					}
12030 					/* Did we cover another hole? */
12031 					if ((mp1->b_cont &&
12032 					    IP_REASS_END(mp1)
12033 					    != IP_REASS_START(mp1->b_cont) &&
12034 					    end >=
12035 					    IP_REASS_START(mp1->b_cont)) ||
12036 					    (!ipf->ipf_last_frag_seen &&
12037 					    !more)) {
12038 						ipf->ipf_hole_cnt--;
12039 					}
12040 					/* Clip out mp1. */
12041 					if ((mp->b_cont = mp1->b_cont) ==
12042 					    NULL) {
12043 						/*
12044 						 * After clipping out mp1,
12045 						 * this guy is now hanging
12046 						 * off the end.
12047 						 */
12048 						ipf->ipf_tail_mp = mp;
12049 					}
12050 					IP_REASS_SET_START(mp1, 0);
12051 					IP_REASS_SET_END(mp1, 0);
12052 					/* Subtract byte count */
12053 					ipf->ipf_count -=
12054 					    mp1->b_datap->db_lim -
12055 					    mp1->b_datap->db_base;
12056 					freeb(mp1);
12057 					BUMP_MIB(ill->ill_ip_mib,
12058 					    ipIfStatsReasmPartDups);
12059 					mp1 = mp->b_cont;
12060 					if (!mp1)
12061 						break;
12062 					offset = IP_REASS_START(mp1);
12063 				}
12064 			}
12065 			break;
12066 		}
12067 	} while (start = end, mp = next_mp);
12068 
12069 	/* Fragment just processed could be the last one. Remember this fact */
12070 	if (!more)
12071 		ipf->ipf_last_frag_seen = B_TRUE;
12072 
12073 	/* Still got holes? */
12074 	if (ipf->ipf_hole_cnt)
12075 		return (IP_REASS_PARTIAL);
12076 	/* Clean up overloaded fields to avoid upstream disasters. */
12077 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12078 		IP_REASS_SET_START(mp1, 0);
12079 		IP_REASS_SET_END(mp1, 0);
12080 	}
12081 	return (IP_REASS_COMPLETE);
12082 }
12083 
12084 /*
12085  * ipsec processing for the fast path, used for input UDP Packets
12086  * Returns true if ready for passup to UDP.
12087  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
12088  * was an ESP-in-UDP packet, etc.).
12089  */
12090 static boolean_t
12091 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12092     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
12093 {
12094 	uint32_t	ill_index;
12095 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12096 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12097 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12098 	udp_t		*udp = connp->conn_udp;
12099 
12100 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12101 	/* The ill_index of the incoming ILL */
12102 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12103 
12104 	/* pass packet up to the transport */
12105 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12106 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12107 		    NULL, mctl_present);
12108 		if (*first_mpp == NULL) {
12109 			return (B_FALSE);
12110 		}
12111 	}
12112 
12113 	/* Initiate IPPF processing for fastpath UDP */
12114 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12115 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12116 		if (*mpp == NULL) {
12117 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12118 			    "deferred/dropped during IPPF processing\n"));
12119 			return (B_FALSE);
12120 		}
12121 	}
12122 	/*
12123 	 * Remove 0-spi if it's 0, or move everything behind
12124 	 * the UDP header over it and forward to ESP via
12125 	 * ip_proto_input().
12126 	 */
12127 	if (udp->udp_nat_t_endpoint) {
12128 		if (mctl_present) {
12129 			/* mctl_present *shouldn't* happen. */
12130 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
12131 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
12132 			    &ipss->ipsec_dropper);
12133 			*first_mpp = NULL;
12134 			return (B_FALSE);
12135 		}
12136 
12137 		/* "ill" is "recv_ill" in actuality. */
12138 		if (!zero_spi_check(q, *mpp, ire, ill, ipss))
12139 			return (B_FALSE);
12140 
12141 		/* Else continue like a normal UDP packet. */
12142 	}
12143 
12144 	/*
12145 	 * We make the checks as below since we are in the fast path
12146 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12147 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12148 	 */
12149 	if (connp->conn_recvif || connp->conn_recvslla ||
12150 	    connp->conn_ip_recvpktinfo) {
12151 		if (connp->conn_recvif) {
12152 			in_flags = IPF_RECVIF;
12153 		}
12154 		/*
12155 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12156 		 * so the flag passed to ip_add_info is based on IP version
12157 		 * of connp.
12158 		 */
12159 		if (connp->conn_ip_recvpktinfo) {
12160 			if (connp->conn_af_isv6) {
12161 				/*
12162 				 * V6 only needs index
12163 				 */
12164 				in_flags |= IPF_RECVIF;
12165 			} else {
12166 				/*
12167 				 * V4 needs index + matching address.
12168 				 */
12169 				in_flags |= IPF_RECVADDR;
12170 			}
12171 		}
12172 		if (connp->conn_recvslla) {
12173 			in_flags |= IPF_RECVSLLA;
12174 		}
12175 		/*
12176 		 * since in_flags are being set ill will be
12177 		 * referenced in ip_add_info, so it better not
12178 		 * be NULL.
12179 		 */
12180 		/*
12181 		 * the actual data will be contained in b_cont
12182 		 * upon successful return of the following call.
12183 		 * If the call fails then the original mblk is
12184 		 * returned.
12185 		 */
12186 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12187 		    ipst);
12188 	}
12189 
12190 	return (B_TRUE);
12191 }
12192 
12193 /*
12194  * Fragmentation reassembly.  Each ILL has a hash table for
12195  * queuing packets undergoing reassembly for all IPIFs
12196  * associated with the ILL.  The hash is based on the packet
12197  * IP ident field.  The ILL frag hash table was allocated
12198  * as a timer block at the time the ILL was created.  Whenever
12199  * there is anything on the reassembly queue, the timer will
12200  * be running.  Returns B_TRUE if successful else B_FALSE;
12201  * frees mp on failure.
12202  */
12203 static boolean_t
12204 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12205     uint32_t *cksum_val, uint16_t *cksum_flags)
12206 {
12207 	uint32_t	frag_offset_flags;
12208 	ill_t		*ill = (ill_t *)q->q_ptr;
12209 	mblk_t		*mp = *mpp;
12210 	mblk_t		*t_mp;
12211 	ipaddr_t	dst;
12212 	uint8_t		proto = ipha->ipha_protocol;
12213 	uint32_t	sum_val;
12214 	uint16_t	sum_flags;
12215 	ipf_t		*ipf;
12216 	ipf_t		**ipfp;
12217 	ipfb_t		*ipfb;
12218 	uint16_t	ident;
12219 	uint32_t	offset;
12220 	ipaddr_t	src;
12221 	uint_t		hdr_length;
12222 	uint32_t	end;
12223 	mblk_t		*mp1;
12224 	mblk_t		*tail_mp;
12225 	size_t		count;
12226 	size_t		msg_len;
12227 	uint8_t		ecn_info = 0;
12228 	uint32_t	packet_size;
12229 	boolean_t	pruned = B_FALSE;
12230 	ip_stack_t *ipst = ill->ill_ipst;
12231 
12232 	if (cksum_val != NULL)
12233 		*cksum_val = 0;
12234 	if (cksum_flags != NULL)
12235 		*cksum_flags = 0;
12236 
12237 	/*
12238 	 * Drop the fragmented as early as possible, if
12239 	 * we don't have resource(s) to re-assemble.
12240 	 */
12241 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12242 		freemsg(mp);
12243 		return (B_FALSE);
12244 	}
12245 
12246 	/* Check for fragmentation offset; return if there's none */
12247 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12248 	    (IPH_MF | IPH_OFFSET)) == 0)
12249 		return (B_TRUE);
12250 
12251 	/*
12252 	 * We utilize hardware computed checksum info only for UDP since
12253 	 * IP fragmentation is a normal occurence for the protocol.  In
12254 	 * addition, checksum offload support for IP fragments carrying
12255 	 * UDP payload is commonly implemented across network adapters.
12256 	 */
12257 	ASSERT(ill != NULL);
12258 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12259 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12260 		mblk_t *mp1 = mp->b_cont;
12261 		int32_t len;
12262 
12263 		/* Record checksum information from the packet */
12264 		sum_val = (uint32_t)DB_CKSUM16(mp);
12265 		sum_flags = DB_CKSUMFLAGS(mp);
12266 
12267 		/* IP payload offset from beginning of mblk */
12268 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12269 
12270 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12271 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12272 		    offset >= DB_CKSUMSTART(mp) &&
12273 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12274 			uint32_t adj;
12275 			/*
12276 			 * Partial checksum has been calculated by hardware
12277 			 * and attached to the packet; in addition, any
12278 			 * prepended extraneous data is even byte aligned.
12279 			 * If any such data exists, we adjust the checksum;
12280 			 * this would also handle any postpended data.
12281 			 */
12282 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12283 			    mp, mp1, len, adj);
12284 
12285 			/* One's complement subtract extraneous checksum */
12286 			if (adj >= sum_val)
12287 				sum_val = ~(adj - sum_val) & 0xFFFF;
12288 			else
12289 				sum_val -= adj;
12290 		}
12291 	} else {
12292 		sum_val = 0;
12293 		sum_flags = 0;
12294 	}
12295 
12296 	/* Clear hardware checksumming flag */
12297 	DB_CKSUMFLAGS(mp) = 0;
12298 
12299 	ident = ipha->ipha_ident;
12300 	offset = (frag_offset_flags << 3) & 0xFFFF;
12301 	src = ipha->ipha_src;
12302 	dst = ipha->ipha_dst;
12303 	hdr_length = IPH_HDR_LENGTH(ipha);
12304 	end = ntohs(ipha->ipha_length) - hdr_length;
12305 
12306 	/* If end == 0 then we have a packet with no data, so just free it */
12307 	if (end == 0) {
12308 		freemsg(mp);
12309 		return (B_FALSE);
12310 	}
12311 
12312 	/* Record the ECN field info. */
12313 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12314 	if (offset != 0) {
12315 		/*
12316 		 * If this isn't the first piece, strip the header, and
12317 		 * add the offset to the end value.
12318 		 */
12319 		mp->b_rptr += hdr_length;
12320 		end += offset;
12321 	}
12322 
12323 	msg_len = MBLKSIZE(mp);
12324 	tail_mp = mp;
12325 	while (tail_mp->b_cont != NULL) {
12326 		tail_mp = tail_mp->b_cont;
12327 		msg_len += MBLKSIZE(tail_mp);
12328 	}
12329 
12330 	/* If the reassembly list for this ILL will get too big, prune it */
12331 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12332 	    ipst->ips_ip_reass_queue_bytes) {
12333 		ill_frag_prune(ill,
12334 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12335 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12336 		pruned = B_TRUE;
12337 	}
12338 
12339 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12340 	mutex_enter(&ipfb->ipfb_lock);
12341 
12342 	ipfp = &ipfb->ipfb_ipf;
12343 	/* Try to find an existing fragment queue for this packet. */
12344 	for (;;) {
12345 		ipf = ipfp[0];
12346 		if (ipf != NULL) {
12347 			/*
12348 			 * It has to match on ident and src/dst address.
12349 			 */
12350 			if (ipf->ipf_ident == ident &&
12351 			    ipf->ipf_src == src &&
12352 			    ipf->ipf_dst == dst &&
12353 			    ipf->ipf_protocol == proto) {
12354 				/*
12355 				 * If we have received too many
12356 				 * duplicate fragments for this packet
12357 				 * free it.
12358 				 */
12359 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12360 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12361 					freemsg(mp);
12362 					mutex_exit(&ipfb->ipfb_lock);
12363 					return (B_FALSE);
12364 				}
12365 				/* Found it. */
12366 				break;
12367 			}
12368 			ipfp = &ipf->ipf_hash_next;
12369 			continue;
12370 		}
12371 
12372 		/*
12373 		 * If we pruned the list, do we want to store this new
12374 		 * fragment?. We apply an optimization here based on the
12375 		 * fact that most fragments will be received in order.
12376 		 * So if the offset of this incoming fragment is zero,
12377 		 * it is the first fragment of a new packet. We will
12378 		 * keep it.  Otherwise drop the fragment, as we have
12379 		 * probably pruned the packet already (since the
12380 		 * packet cannot be found).
12381 		 */
12382 		if (pruned && offset != 0) {
12383 			mutex_exit(&ipfb->ipfb_lock);
12384 			freemsg(mp);
12385 			return (B_FALSE);
12386 		}
12387 
12388 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12389 			/*
12390 			 * Too many fragmented packets in this hash
12391 			 * bucket. Free the oldest.
12392 			 */
12393 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12394 		}
12395 
12396 		/* New guy.  Allocate a frag message. */
12397 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12398 		if (mp1 == NULL) {
12399 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12400 			freemsg(mp);
12401 reass_done:
12402 			mutex_exit(&ipfb->ipfb_lock);
12403 			return (B_FALSE);
12404 		}
12405 
12406 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12407 		mp1->b_cont = mp;
12408 
12409 		/* Initialize the fragment header. */
12410 		ipf = (ipf_t *)mp1->b_rptr;
12411 		ipf->ipf_mp = mp1;
12412 		ipf->ipf_ptphn = ipfp;
12413 		ipfp[0] = ipf;
12414 		ipf->ipf_hash_next = NULL;
12415 		ipf->ipf_ident = ident;
12416 		ipf->ipf_protocol = proto;
12417 		ipf->ipf_src = src;
12418 		ipf->ipf_dst = dst;
12419 		ipf->ipf_nf_hdr_len = 0;
12420 		/* Record reassembly start time. */
12421 		ipf->ipf_timestamp = gethrestime_sec();
12422 		/* Record ipf generation and account for frag header */
12423 		ipf->ipf_gen = ill->ill_ipf_gen++;
12424 		ipf->ipf_count = MBLKSIZE(mp1);
12425 		ipf->ipf_last_frag_seen = B_FALSE;
12426 		ipf->ipf_ecn = ecn_info;
12427 		ipf->ipf_num_dups = 0;
12428 		ipfb->ipfb_frag_pkts++;
12429 		ipf->ipf_checksum = 0;
12430 		ipf->ipf_checksum_flags = 0;
12431 
12432 		/* Store checksum value in fragment header */
12433 		if (sum_flags != 0) {
12434 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12435 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12436 			ipf->ipf_checksum = sum_val;
12437 			ipf->ipf_checksum_flags = sum_flags;
12438 		}
12439 
12440 		/*
12441 		 * We handle reassembly two ways.  In the easy case,
12442 		 * where all the fragments show up in order, we do
12443 		 * minimal bookkeeping, and just clip new pieces on
12444 		 * the end.  If we ever see a hole, then we go off
12445 		 * to ip_reassemble which has to mark the pieces and
12446 		 * keep track of the number of holes, etc.  Obviously,
12447 		 * the point of having both mechanisms is so we can
12448 		 * handle the easy case as efficiently as possible.
12449 		 */
12450 		if (offset == 0) {
12451 			/* Easy case, in-order reassembly so far. */
12452 			ipf->ipf_count += msg_len;
12453 			ipf->ipf_tail_mp = tail_mp;
12454 			/*
12455 			 * Keep track of next expected offset in
12456 			 * ipf_end.
12457 			 */
12458 			ipf->ipf_end = end;
12459 			ipf->ipf_nf_hdr_len = hdr_length;
12460 		} else {
12461 			/* Hard case, hole at the beginning. */
12462 			ipf->ipf_tail_mp = NULL;
12463 			/*
12464 			 * ipf_end == 0 means that we have given up
12465 			 * on easy reassembly.
12466 			 */
12467 			ipf->ipf_end = 0;
12468 
12469 			/* Forget checksum offload from now on */
12470 			ipf->ipf_checksum_flags = 0;
12471 
12472 			/*
12473 			 * ipf_hole_cnt is set by ip_reassemble.
12474 			 * ipf_count is updated by ip_reassemble.
12475 			 * No need to check for return value here
12476 			 * as we don't expect reassembly to complete
12477 			 * or fail for the first fragment itself.
12478 			 */
12479 			(void) ip_reassemble(mp, ipf,
12480 			    (frag_offset_flags & IPH_OFFSET) << 3,
12481 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12482 		}
12483 		/* Update per ipfb and ill byte counts */
12484 		ipfb->ipfb_count += ipf->ipf_count;
12485 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12486 		ill->ill_frag_count += ipf->ipf_count;
12487 		/* If the frag timer wasn't already going, start it. */
12488 		mutex_enter(&ill->ill_lock);
12489 		ill_frag_timer_start(ill);
12490 		mutex_exit(&ill->ill_lock);
12491 		goto reass_done;
12492 	}
12493 
12494 	/*
12495 	 * If the packet's flag has changed (it could be coming up
12496 	 * from an interface different than the previous, therefore
12497 	 * possibly different checksum capability), then forget about
12498 	 * any stored checksum states.  Otherwise add the value to
12499 	 * the existing one stored in the fragment header.
12500 	 */
12501 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12502 		sum_val += ipf->ipf_checksum;
12503 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12504 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12505 		ipf->ipf_checksum = sum_val;
12506 	} else if (ipf->ipf_checksum_flags != 0) {
12507 		/* Forget checksum offload from now on */
12508 		ipf->ipf_checksum_flags = 0;
12509 	}
12510 
12511 	/*
12512 	 * We have a new piece of a datagram which is already being
12513 	 * reassembled.  Update the ECN info if all IP fragments
12514 	 * are ECN capable.  If there is one which is not, clear
12515 	 * all the info.  If there is at least one which has CE
12516 	 * code point, IP needs to report that up to transport.
12517 	 */
12518 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12519 		if (ecn_info == IPH_ECN_CE)
12520 			ipf->ipf_ecn = IPH_ECN_CE;
12521 	} else {
12522 		ipf->ipf_ecn = IPH_ECN_NECT;
12523 	}
12524 	if (offset && ipf->ipf_end == offset) {
12525 		/* The new fragment fits at the end */
12526 		ipf->ipf_tail_mp->b_cont = mp;
12527 		/* Update the byte count */
12528 		ipf->ipf_count += msg_len;
12529 		/* Update per ipfb and ill byte counts */
12530 		ipfb->ipfb_count += msg_len;
12531 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12532 		ill->ill_frag_count += msg_len;
12533 		if (frag_offset_flags & IPH_MF) {
12534 			/* More to come. */
12535 			ipf->ipf_end = end;
12536 			ipf->ipf_tail_mp = tail_mp;
12537 			goto reass_done;
12538 		}
12539 	} else {
12540 		/* Go do the hard cases. */
12541 		int ret;
12542 
12543 		if (offset == 0)
12544 			ipf->ipf_nf_hdr_len = hdr_length;
12545 
12546 		/* Save current byte count */
12547 		count = ipf->ipf_count;
12548 		ret = ip_reassemble(mp, ipf,
12549 		    (frag_offset_flags & IPH_OFFSET) << 3,
12550 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12551 		/* Count of bytes added and subtracted (freeb()ed) */
12552 		count = ipf->ipf_count - count;
12553 		if (count) {
12554 			/* Update per ipfb and ill byte counts */
12555 			ipfb->ipfb_count += count;
12556 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12557 			ill->ill_frag_count += count;
12558 		}
12559 		if (ret == IP_REASS_PARTIAL) {
12560 			goto reass_done;
12561 		} else if (ret == IP_REASS_FAILED) {
12562 			/* Reassembly failed. Free up all resources */
12563 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12564 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12565 				IP_REASS_SET_START(t_mp, 0);
12566 				IP_REASS_SET_END(t_mp, 0);
12567 			}
12568 			freemsg(mp);
12569 			goto reass_done;
12570 		}
12571 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12572 	}
12573 	/*
12574 	 * We have completed reassembly.  Unhook the frag header from
12575 	 * the reassembly list.
12576 	 *
12577 	 * Before we free the frag header, record the ECN info
12578 	 * to report back to the transport.
12579 	 */
12580 	ecn_info = ipf->ipf_ecn;
12581 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12582 	ipfp = ipf->ipf_ptphn;
12583 
12584 	/* We need to supply these to caller */
12585 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12586 		sum_val = ipf->ipf_checksum;
12587 	else
12588 		sum_val = 0;
12589 
12590 	mp1 = ipf->ipf_mp;
12591 	count = ipf->ipf_count;
12592 	ipf = ipf->ipf_hash_next;
12593 	if (ipf != NULL)
12594 		ipf->ipf_ptphn = ipfp;
12595 	ipfp[0] = ipf;
12596 	ill->ill_frag_count -= count;
12597 	ASSERT(ipfb->ipfb_count >= count);
12598 	ipfb->ipfb_count -= count;
12599 	ipfb->ipfb_frag_pkts--;
12600 	mutex_exit(&ipfb->ipfb_lock);
12601 	/* Ditch the frag header. */
12602 	mp = mp1->b_cont;
12603 
12604 	freeb(mp1);
12605 
12606 	/* Restore original IP length in header. */
12607 	packet_size = (uint32_t)msgdsize(mp);
12608 	if (packet_size > IP_MAXPACKET) {
12609 		freemsg(mp);
12610 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12611 		return (B_FALSE);
12612 	}
12613 
12614 	if (DB_REF(mp) > 1) {
12615 		mblk_t *mp2 = copymsg(mp);
12616 
12617 		freemsg(mp);
12618 		if (mp2 == NULL) {
12619 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12620 			return (B_FALSE);
12621 		}
12622 		mp = mp2;
12623 	}
12624 	ipha = (ipha_t *)mp->b_rptr;
12625 
12626 	ipha->ipha_length = htons((uint16_t)packet_size);
12627 	/* We're now complete, zip the frag state */
12628 	ipha->ipha_fragment_offset_and_flags = 0;
12629 	/* Record the ECN info. */
12630 	ipha->ipha_type_of_service &= 0xFC;
12631 	ipha->ipha_type_of_service |= ecn_info;
12632 	*mpp = mp;
12633 
12634 	/* Reassembly is successful; return checksum information if needed */
12635 	if (cksum_val != NULL)
12636 		*cksum_val = sum_val;
12637 	if (cksum_flags != NULL)
12638 		*cksum_flags = sum_flags;
12639 
12640 	return (B_TRUE);
12641 }
12642 
12643 /*
12644  * Perform ip header check sum update local options.
12645  * return B_TRUE if all is well, else return B_FALSE and release
12646  * the mp. caller is responsible for decrementing ire ref cnt.
12647  */
12648 static boolean_t
12649 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12650     ip_stack_t *ipst)
12651 {
12652 	mblk_t		*first_mp;
12653 	boolean_t	mctl_present;
12654 	uint16_t	sum;
12655 
12656 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12657 	/*
12658 	 * Don't do the checksum if it has gone through AH/ESP
12659 	 * processing.
12660 	 */
12661 	if (!mctl_present) {
12662 		sum = ip_csum_hdr(ipha);
12663 		if (sum != 0) {
12664 			if (ill != NULL) {
12665 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12666 			} else {
12667 				BUMP_MIB(&ipst->ips_ip_mib,
12668 				    ipIfStatsInCksumErrs);
12669 			}
12670 			freemsg(first_mp);
12671 			return (B_FALSE);
12672 		}
12673 	}
12674 
12675 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12676 		if (mctl_present)
12677 			freeb(first_mp);
12678 		return (B_FALSE);
12679 	}
12680 
12681 	return (B_TRUE);
12682 }
12683 
12684 /*
12685  * All udp packet are delivered to the local host via this routine.
12686  */
12687 void
12688 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12689     ill_t *recv_ill)
12690 {
12691 	uint32_t	sum;
12692 	uint32_t	u1;
12693 	boolean_t	mctl_present;
12694 	conn_t		*connp;
12695 	mblk_t		*first_mp;
12696 	uint16_t	*up;
12697 	ill_t		*ill = (ill_t *)q->q_ptr;
12698 	uint16_t	reass_hck_flags = 0;
12699 	ip_stack_t	*ipst;
12700 
12701 	ASSERT(recv_ill != NULL);
12702 	ipst = recv_ill->ill_ipst;
12703 
12704 #define	rptr    ((uchar_t *)ipha)
12705 
12706 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12707 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12708 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12709 	ASSERT(ill != NULL);
12710 
12711 	/*
12712 	 * FAST PATH for udp packets
12713 	 */
12714 
12715 	/* u1 is # words of IP options */
12716 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12717 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12718 
12719 	/* IP options present */
12720 	if (u1 != 0)
12721 		goto ipoptions;
12722 
12723 	/* Check the IP header checksum.  */
12724 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12725 		/* Clear the IP header h/w cksum flag */
12726 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12727 	} else if (!mctl_present) {
12728 		/*
12729 		 * Don't verify header checksum if this packet is coming
12730 		 * back from AH/ESP as we already did it.
12731 		 */
12732 #define	uph	((uint16_t *)ipha)
12733 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12734 		    uph[6] + uph[7] + uph[8] + uph[9];
12735 #undef	uph
12736 		/* finish doing IP checksum */
12737 		sum = (sum & 0xFFFF) + (sum >> 16);
12738 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12739 		if (sum != 0 && sum != 0xFFFF) {
12740 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12741 			freemsg(first_mp);
12742 			return;
12743 		}
12744 	}
12745 
12746 	/*
12747 	 * Count for SNMP of inbound packets for ire.
12748 	 * if mctl is present this might be a secure packet and
12749 	 * has already been counted for in ip_proto_input().
12750 	 */
12751 	if (!mctl_present) {
12752 		UPDATE_IB_PKT_COUNT(ire);
12753 		ire->ire_last_used_time = lbolt;
12754 	}
12755 
12756 	/* packet part of fragmented IP packet? */
12757 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12758 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12759 		goto fragmented;
12760 	}
12761 
12762 	/* u1 = IP header length (20 bytes) */
12763 	u1 = IP_SIMPLE_HDR_LENGTH;
12764 
12765 	/* packet does not contain complete IP & UDP headers */
12766 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12767 		goto udppullup;
12768 
12769 	/* up points to UDP header */
12770 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12771 #define	iphs    ((uint16_t *)ipha)
12772 
12773 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12774 	if (up[3] != 0) {
12775 		mblk_t *mp1 = mp->b_cont;
12776 		boolean_t cksum_err;
12777 		uint16_t hck_flags = 0;
12778 
12779 		/* Pseudo-header checksum */
12780 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12781 		    iphs[9] + up[2];
12782 
12783 		/*
12784 		 * Revert to software checksum calculation if the interface
12785 		 * isn't capable of checksum offload or if IPsec is present.
12786 		 */
12787 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12788 			hck_flags = DB_CKSUMFLAGS(mp);
12789 
12790 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12791 			IP_STAT(ipst, ip_in_sw_cksum);
12792 
12793 		IP_CKSUM_RECV(hck_flags, u1,
12794 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12795 		    (int32_t)((uchar_t *)up - rptr),
12796 		    mp, mp1, cksum_err);
12797 
12798 		if (cksum_err) {
12799 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12800 			if (hck_flags & HCK_FULLCKSUM)
12801 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12802 			else if (hck_flags & HCK_PARTIALCKSUM)
12803 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12804 			else
12805 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12806 
12807 			freemsg(first_mp);
12808 			return;
12809 		}
12810 	}
12811 
12812 	/* Non-fragmented broadcast or multicast packet? */
12813 	if (ire->ire_type == IRE_BROADCAST)
12814 		goto udpslowpath;
12815 
12816 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12817 	    ire->ire_zoneid, ipst)) != NULL) {
12818 		ASSERT(connp->conn_upq != NULL);
12819 		IP_STAT(ipst, ip_udp_fast_path);
12820 
12821 		if (CONN_UDP_FLOWCTLD(connp)) {
12822 			freemsg(mp);
12823 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12824 		} else {
12825 			if (!mctl_present) {
12826 				BUMP_MIB(ill->ill_ip_mib,
12827 				    ipIfStatsHCInDelivers);
12828 			}
12829 			/*
12830 			 * mp and first_mp can change.
12831 			 */
12832 			if (ip_udp_check(q, connp, recv_ill,
12833 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12834 				/* Send it upstream */
12835 				(connp->conn_recv)(connp, mp, NULL);
12836 			}
12837 		}
12838 		/*
12839 		 * freeb() cannot deal with null mblk being passed
12840 		 * in and first_mp can be set to null in the call
12841 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12842 		 */
12843 		if (mctl_present && first_mp != NULL) {
12844 			freeb(first_mp);
12845 		}
12846 		CONN_DEC_REF(connp);
12847 		return;
12848 	}
12849 
12850 	/*
12851 	 * if we got here we know the packet is not fragmented and
12852 	 * has no options. The classifier could not find a conn_t and
12853 	 * most likely its an icmp packet so send it through slow path.
12854 	 */
12855 
12856 	goto udpslowpath;
12857 
12858 ipoptions:
12859 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12860 		goto slow_done;
12861 	}
12862 
12863 	UPDATE_IB_PKT_COUNT(ire);
12864 	ire->ire_last_used_time = lbolt;
12865 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12866 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12867 fragmented:
12868 		/*
12869 		 * "sum" and "reass_hck_flags" are non-zero if the
12870 		 * reassembled packet has a valid hardware computed
12871 		 * checksum information associated with it.
12872 		 */
12873 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12874 			goto slow_done;
12875 		/*
12876 		 * Make sure that first_mp points back to mp as
12877 		 * the mp we came in with could have changed in
12878 		 * ip_rput_fragment().
12879 		 */
12880 		ASSERT(!mctl_present);
12881 		ipha = (ipha_t *)mp->b_rptr;
12882 		first_mp = mp;
12883 	}
12884 
12885 	/* Now we have a complete datagram, destined for this machine. */
12886 	u1 = IPH_HDR_LENGTH(ipha);
12887 	/* Pull up the UDP header, if necessary. */
12888 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12889 udppullup:
12890 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12891 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12892 			freemsg(first_mp);
12893 			goto slow_done;
12894 		}
12895 		ipha = (ipha_t *)mp->b_rptr;
12896 	}
12897 
12898 	/*
12899 	 * Validate the checksum for the reassembled packet; for the
12900 	 * pullup case we calculate the payload checksum in software.
12901 	 */
12902 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12903 	if (up[3] != 0) {
12904 		boolean_t cksum_err;
12905 
12906 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12907 			IP_STAT(ipst, ip_in_sw_cksum);
12908 
12909 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12910 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12911 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12912 		    iphs[9] + up[2], sum, cksum_err);
12913 
12914 		if (cksum_err) {
12915 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12916 
12917 			if (reass_hck_flags & HCK_FULLCKSUM)
12918 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12919 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12920 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12921 			else
12922 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12923 
12924 			freemsg(first_mp);
12925 			goto slow_done;
12926 		}
12927 	}
12928 udpslowpath:
12929 
12930 	/* Clear hardware checksum flag to be safe */
12931 	DB_CKSUMFLAGS(mp) = 0;
12932 
12933 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12934 	    (ire->ire_type == IRE_BROADCAST),
12935 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12936 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12937 
12938 slow_done:
12939 	IP_STAT(ipst, ip_udp_slow_path);
12940 	return;
12941 
12942 #undef  iphs
12943 #undef  rptr
12944 }
12945 
12946 /* ARGSUSED */
12947 static mblk_t *
12948 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12949     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12950     ill_rx_ring_t *ill_ring)
12951 {
12952 	conn_t		*connp;
12953 	uint32_t	sum;
12954 	uint32_t	u1;
12955 	uint16_t	*up;
12956 	int		offset;
12957 	ssize_t		len;
12958 	mblk_t		*mp1;
12959 	boolean_t	syn_present = B_FALSE;
12960 	tcph_t		*tcph;
12961 	uint_t		ip_hdr_len;
12962 	ill_t		*ill = (ill_t *)q->q_ptr;
12963 	zoneid_t	zoneid = ire->ire_zoneid;
12964 	boolean_t	cksum_err;
12965 	uint16_t	hck_flags = 0;
12966 	ip_stack_t	*ipst = recv_ill->ill_ipst;
12967 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12968 
12969 #define	rptr	((uchar_t *)ipha)
12970 
12971 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12972 	ASSERT(ill != NULL);
12973 
12974 	/*
12975 	 * FAST PATH for tcp packets
12976 	 */
12977 
12978 	/* u1 is # words of IP options */
12979 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12980 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12981 
12982 	/* IP options present */
12983 	if (u1) {
12984 		goto ipoptions;
12985 	} else if (!mctl_present) {
12986 		/* Check the IP header checksum.  */
12987 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12988 			/* Clear the IP header h/w cksum flag */
12989 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12990 		} else if (!mctl_present) {
12991 			/*
12992 			 * Don't verify header checksum if this packet
12993 			 * is coming back from AH/ESP as we already did it.
12994 			 */
12995 #define	uph	((uint16_t *)ipha)
12996 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12997 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12998 #undef	uph
12999 			/* finish doing IP checksum */
13000 			sum = (sum & 0xFFFF) + (sum >> 16);
13001 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13002 			if (sum != 0 && sum != 0xFFFF) {
13003 				BUMP_MIB(ill->ill_ip_mib,
13004 				    ipIfStatsInCksumErrs);
13005 				goto error;
13006 			}
13007 		}
13008 	}
13009 
13010 	if (!mctl_present) {
13011 		UPDATE_IB_PKT_COUNT(ire);
13012 		ire->ire_last_used_time = lbolt;
13013 	}
13014 
13015 	/* packet part of fragmented IP packet? */
13016 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13017 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13018 		goto fragmented;
13019 	}
13020 
13021 	/* u1 = IP header length (20 bytes) */
13022 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
13023 
13024 	/* does packet contain IP+TCP headers? */
13025 	len = mp->b_wptr - rptr;
13026 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
13027 		IP_STAT(ipst, ip_tcppullup);
13028 		goto tcppullup;
13029 	}
13030 
13031 	/* TCP options present? */
13032 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
13033 
13034 	/*
13035 	 * If options need to be pulled up, then goto tcpoptions.
13036 	 * otherwise we are still in the fast path
13037 	 */
13038 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
13039 		IP_STAT(ipst, ip_tcpoptions);
13040 		goto tcpoptions;
13041 	}
13042 
13043 	/* multiple mblks of tcp data? */
13044 	if ((mp1 = mp->b_cont) != NULL) {
13045 		/* more then two? */
13046 		if (mp1->b_cont != NULL) {
13047 			IP_STAT(ipst, ip_multipkttcp);
13048 			goto multipkttcp;
13049 		}
13050 		len += mp1->b_wptr - mp1->b_rptr;
13051 	}
13052 
13053 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13054 
13055 	/* part of pseudo checksum */
13056 
13057 	/* TCP datagram length */
13058 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13059 
13060 #define	iphs    ((uint16_t *)ipha)
13061 
13062 #ifdef	_BIG_ENDIAN
13063 	u1 += IPPROTO_TCP;
13064 #else
13065 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13066 #endif
13067 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13068 
13069 	/*
13070 	 * Revert to software checksum calculation if the interface
13071 	 * isn't capable of checksum offload or if IPsec is present.
13072 	 */
13073 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
13074 		hck_flags = DB_CKSUMFLAGS(mp);
13075 
13076 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13077 		IP_STAT(ipst, ip_in_sw_cksum);
13078 
13079 	IP_CKSUM_RECV(hck_flags, u1,
13080 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13081 	    (int32_t)((uchar_t *)up - rptr),
13082 	    mp, mp1, cksum_err);
13083 
13084 	if (cksum_err) {
13085 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13086 
13087 		if (hck_flags & HCK_FULLCKSUM)
13088 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13089 		else if (hck_flags & HCK_PARTIALCKSUM)
13090 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13091 		else
13092 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13093 
13094 		goto error;
13095 	}
13096 
13097 try_again:
13098 
13099 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13100 	    zoneid, ipst)) == NULL) {
13101 		/* Send the TH_RST */
13102 		goto no_conn;
13103 	}
13104 
13105 	/*
13106 	 * TCP FAST PATH for AF_INET socket.
13107 	 *
13108 	 * TCP fast path to avoid extra work. An AF_INET socket type
13109 	 * does not have facility to receive extra information via
13110 	 * ip_process or ip_add_info. Also, when the connection was
13111 	 * established, we made a check if this connection is impacted
13112 	 * by any global IPsec policy or per connection policy (a
13113 	 * policy that comes in effect later will not apply to this
13114 	 * connection). Since all this can be determined at the
13115 	 * connection establishment time, a quick check of flags
13116 	 * can avoid extra work.
13117 	 */
13118 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13119 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13120 		ASSERT(first_mp == mp);
13121 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13122 		SET_SQUEUE(mp, tcp_rput_data, connp);
13123 		return (mp);
13124 	}
13125 
13126 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13127 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
13128 		if (IPCL_IS_TCP(connp)) {
13129 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13130 			DB_CKSUMSTART(mp) =
13131 			    (intptr_t)ip_squeue_get(ill_ring);
13132 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13133 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13134 				BUMP_MIB(ill->ill_ip_mib,
13135 				    ipIfStatsHCInDelivers);
13136 				SET_SQUEUE(mp, connp->conn_recv, connp);
13137 				return (mp);
13138 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13139 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13140 				BUMP_MIB(ill->ill_ip_mib,
13141 				    ipIfStatsHCInDelivers);
13142 				ip_squeue_enter_unbound++;
13143 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13144 				    connp);
13145 				return (mp);
13146 			}
13147 			syn_present = B_TRUE;
13148 		}
13149 
13150 	}
13151 
13152 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13153 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13154 
13155 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13156 		/* No need to send this packet to TCP */
13157 		if ((flags & TH_RST) || (flags & TH_URG)) {
13158 			CONN_DEC_REF(connp);
13159 			freemsg(first_mp);
13160 			return (NULL);
13161 		}
13162 		if (flags & TH_ACK) {
13163 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
13164 			    ipst->ips_netstack->netstack_tcp, connp);
13165 			CONN_DEC_REF(connp);
13166 			return (NULL);
13167 		}
13168 
13169 		CONN_DEC_REF(connp);
13170 		freemsg(first_mp);
13171 		return (NULL);
13172 	}
13173 
13174 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13175 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13176 		    ipha, NULL, mctl_present);
13177 		if (first_mp == NULL) {
13178 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13179 			CONN_DEC_REF(connp);
13180 			return (NULL);
13181 		}
13182 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13183 			ASSERT(syn_present);
13184 			if (mctl_present) {
13185 				ASSERT(first_mp != mp);
13186 				first_mp->b_datap->db_struioflag |=
13187 				    STRUIO_POLICY;
13188 			} else {
13189 				ASSERT(first_mp == mp);
13190 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13191 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13192 			}
13193 		} else {
13194 			/*
13195 			 * Discard first_mp early since we're dealing with a
13196 			 * fully-connected conn_t and tcp doesn't do policy in
13197 			 * this case.
13198 			 */
13199 			if (mctl_present) {
13200 				freeb(first_mp);
13201 				mctl_present = B_FALSE;
13202 			}
13203 			first_mp = mp;
13204 		}
13205 	}
13206 
13207 	/* Initiate IPPF processing for fastpath */
13208 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13209 		uint32_t	ill_index;
13210 
13211 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13212 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13213 		if (mp == NULL) {
13214 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13215 			    "deferred/dropped during IPPF processing\n"));
13216 			CONN_DEC_REF(connp);
13217 			if (mctl_present)
13218 				freeb(first_mp);
13219 			return (NULL);
13220 		} else if (mctl_present) {
13221 			/*
13222 			 * ip_process might return a new mp.
13223 			 */
13224 			ASSERT(first_mp != mp);
13225 			first_mp->b_cont = mp;
13226 		} else {
13227 			first_mp = mp;
13228 		}
13229 
13230 	}
13231 
13232 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13233 		/*
13234 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13235 		 * make sure IPF_RECVIF is passed to ip_add_info.
13236 		 */
13237 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13238 		    IPCL_ZONEID(connp), ipst);
13239 		if (mp == NULL) {
13240 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13241 			CONN_DEC_REF(connp);
13242 			if (mctl_present)
13243 				freeb(first_mp);
13244 			return (NULL);
13245 		} else if (mctl_present) {
13246 			/*
13247 			 * ip_add_info might return a new mp.
13248 			 */
13249 			ASSERT(first_mp != mp);
13250 			first_mp->b_cont = mp;
13251 		} else {
13252 			first_mp = mp;
13253 		}
13254 	}
13255 
13256 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13257 	if (IPCL_IS_TCP(connp)) {
13258 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13259 		return (first_mp);
13260 	} else {
13261 		/* SOCK_RAW, IPPROTO_TCP case */
13262 		(connp->conn_recv)(connp, first_mp, NULL);
13263 		CONN_DEC_REF(connp);
13264 		return (NULL);
13265 	}
13266 
13267 no_conn:
13268 	/* Initiate IPPf processing, if needed. */
13269 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13270 		uint32_t ill_index;
13271 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13272 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13273 		if (first_mp == NULL) {
13274 			return (NULL);
13275 		}
13276 	}
13277 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13278 
13279 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13280 	    ipst->ips_netstack->netstack_tcp, NULL);
13281 	return (NULL);
13282 ipoptions:
13283 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13284 		goto slow_done;
13285 	}
13286 
13287 	UPDATE_IB_PKT_COUNT(ire);
13288 	ire->ire_last_used_time = lbolt;
13289 
13290 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13291 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13292 fragmented:
13293 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13294 			if (mctl_present)
13295 				freeb(first_mp);
13296 			goto slow_done;
13297 		}
13298 		/*
13299 		 * Make sure that first_mp points back to mp as
13300 		 * the mp we came in with could have changed in
13301 		 * ip_rput_fragment().
13302 		 */
13303 		ASSERT(!mctl_present);
13304 		ipha = (ipha_t *)mp->b_rptr;
13305 		first_mp = mp;
13306 	}
13307 
13308 	/* Now we have a complete datagram, destined for this machine. */
13309 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13310 
13311 	len = mp->b_wptr - mp->b_rptr;
13312 	/* Pull up a minimal TCP header, if necessary. */
13313 	if (len < (u1 + 20)) {
13314 tcppullup:
13315 		if (!pullupmsg(mp, u1 + 20)) {
13316 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13317 			goto error;
13318 		}
13319 		ipha = (ipha_t *)mp->b_rptr;
13320 		len = mp->b_wptr - mp->b_rptr;
13321 	}
13322 
13323 	/*
13324 	 * Extract the offset field from the TCP header.  As usual, we
13325 	 * try to help the compiler more than the reader.
13326 	 */
13327 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13328 	if (offset != 5) {
13329 tcpoptions:
13330 		if (offset < 5) {
13331 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13332 			goto error;
13333 		}
13334 		/*
13335 		 * There must be TCP options.
13336 		 * Make sure we can grab them.
13337 		 */
13338 		offset <<= 2;
13339 		offset += u1;
13340 		if (len < offset) {
13341 			if (!pullupmsg(mp, offset)) {
13342 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13343 				goto error;
13344 			}
13345 			ipha = (ipha_t *)mp->b_rptr;
13346 			len = mp->b_wptr - rptr;
13347 		}
13348 	}
13349 
13350 	/* Get the total packet length in len, including headers. */
13351 	if (mp->b_cont) {
13352 multipkttcp:
13353 		len = msgdsize(mp);
13354 	}
13355 
13356 	/*
13357 	 * Check the TCP checksum by pulling together the pseudo-
13358 	 * header checksum, and passing it to ip_csum to be added in
13359 	 * with the TCP datagram.
13360 	 *
13361 	 * Since we are not using the hwcksum if available we must
13362 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13363 	 * If either of these fails along the way the mblk is freed.
13364 	 * If this logic ever changes and mblk is reused to say send
13365 	 * ICMP's back, then this flag may need to be cleared in
13366 	 * other places as well.
13367 	 */
13368 	DB_CKSUMFLAGS(mp) = 0;
13369 
13370 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13371 
13372 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13373 #ifdef	_BIG_ENDIAN
13374 	u1 += IPPROTO_TCP;
13375 #else
13376 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13377 #endif
13378 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13379 	/*
13380 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13381 	 */
13382 	IP_STAT(ipst, ip_in_sw_cksum);
13383 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13384 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13385 		goto error;
13386 	}
13387 
13388 	IP_STAT(ipst, ip_tcp_slow_path);
13389 	goto try_again;
13390 #undef  iphs
13391 #undef  rptr
13392 
13393 error:
13394 	freemsg(first_mp);
13395 slow_done:
13396 	return (NULL);
13397 }
13398 
13399 /* ARGSUSED */
13400 static void
13401 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13402     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13403 {
13404 	conn_t		*connp;
13405 	uint32_t	sum;
13406 	uint32_t	u1;
13407 	ssize_t		len;
13408 	sctp_hdr_t	*sctph;
13409 	zoneid_t	zoneid = ire->ire_zoneid;
13410 	uint32_t	pktsum;
13411 	uint32_t	calcsum;
13412 	uint32_t	ports;
13413 	in6_addr_t	map_src, map_dst;
13414 	ill_t		*ill = (ill_t *)q->q_ptr;
13415 	ip_stack_t	*ipst;
13416 	sctp_stack_t	*sctps;
13417 	boolean_t	sctp_csum_err = B_FALSE;
13418 
13419 	ASSERT(recv_ill != NULL);
13420 	ipst = recv_ill->ill_ipst;
13421 	sctps = ipst->ips_netstack->netstack_sctp;
13422 
13423 #define	rptr	((uchar_t *)ipha)
13424 
13425 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13426 	ASSERT(ill != NULL);
13427 
13428 	/* u1 is # words of IP options */
13429 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13430 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13431 
13432 	/* IP options present */
13433 	if (u1 > 0) {
13434 		goto ipoptions;
13435 	} else {
13436 		/* Check the IP header checksum.  */
13437 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill) &&
13438 		    !mctl_present) {
13439 #define	uph	((uint16_t *)ipha)
13440 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13441 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13442 #undef	uph
13443 			/* finish doing IP checksum */
13444 			sum = (sum & 0xFFFF) + (sum >> 16);
13445 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13446 			/*
13447 			 * Don't verify header checksum if this packet
13448 			 * is coming back from AH/ESP as we already did it.
13449 			 */
13450 			if (sum != 0 && sum != 0xFFFF) {
13451 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13452 				goto error;
13453 			}
13454 		}
13455 		/*
13456 		 * Since there is no SCTP h/w cksum support yet, just
13457 		 * clear the flag.
13458 		 */
13459 		DB_CKSUMFLAGS(mp) = 0;
13460 	}
13461 
13462 	/*
13463 	 * Don't verify header checksum if this packet is coming
13464 	 * back from AH/ESP as we already did it.
13465 	 */
13466 	if (!mctl_present) {
13467 		UPDATE_IB_PKT_COUNT(ire);
13468 		ire->ire_last_used_time = lbolt;
13469 	}
13470 
13471 	/* packet part of fragmented IP packet? */
13472 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13473 	if (u1 & (IPH_MF | IPH_OFFSET))
13474 		goto fragmented;
13475 
13476 	/* u1 = IP header length (20 bytes) */
13477 	u1 = IP_SIMPLE_HDR_LENGTH;
13478 
13479 find_sctp_client:
13480 	/* Pullup if we don't have the sctp common header. */
13481 	len = MBLKL(mp);
13482 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13483 		if (mp->b_cont == NULL ||
13484 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13485 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13486 			goto error;
13487 		}
13488 		ipha = (ipha_t *)mp->b_rptr;
13489 		len = MBLKL(mp);
13490 	}
13491 
13492 	sctph = (sctp_hdr_t *)(rptr + u1);
13493 #ifdef	DEBUG
13494 	if (!skip_sctp_cksum) {
13495 #endif
13496 		pktsum = sctph->sh_chksum;
13497 		sctph->sh_chksum = 0;
13498 		calcsum = sctp_cksum(mp, u1);
13499 		sctph->sh_chksum = pktsum;
13500 		if (calcsum != pktsum)
13501 			sctp_csum_err = B_TRUE;
13502 #ifdef	DEBUG	/* skip_sctp_cksum */
13503 	}
13504 #endif
13505 	/* get the ports */
13506 	ports = *(uint32_t *)&sctph->sh_sport;
13507 
13508 	IRE_REFRELE(ire);
13509 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13510 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13511 	if (sctp_csum_err) {
13512 		/*
13513 		 * No potential sctp checksum errors go to the Sun
13514 		 * sctp stack however they might be Adler-32 summed
13515 		 * packets a userland stack bound to a raw IP socket
13516 		 * could reasonably use. Note though that Adler-32 is
13517 		 * a long deprecated algorithm and customer sctp
13518 		 * networks should eventually migrate to CRC-32 at
13519 		 * which time this facility should be removed.
13520 		 */
13521 		flags |= IP_FF_SCTP_CSUM_ERR;
13522 		goto no_conn;
13523 	}
13524 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13525 	    sctps)) == NULL) {
13526 		/* Check for raw socket or OOTB handling */
13527 		goto no_conn;
13528 	}
13529 
13530 	/* Found a client; up it goes */
13531 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13532 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13533 	return;
13534 
13535 no_conn:
13536 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13537 	    ports, mctl_present, flags, B_TRUE, zoneid);
13538 	return;
13539 
13540 ipoptions:
13541 	DB_CKSUMFLAGS(mp) = 0;
13542 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13543 		goto slow_done;
13544 
13545 	UPDATE_IB_PKT_COUNT(ire);
13546 	ire->ire_last_used_time = lbolt;
13547 
13548 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13549 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13550 fragmented:
13551 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13552 			goto slow_done;
13553 		/*
13554 		 * Make sure that first_mp points back to mp as
13555 		 * the mp we came in with could have changed in
13556 		 * ip_rput_fragment().
13557 		 */
13558 		ASSERT(!mctl_present);
13559 		ipha = (ipha_t *)mp->b_rptr;
13560 		first_mp = mp;
13561 	}
13562 
13563 	/* Now we have a complete datagram, destined for this machine. */
13564 	u1 = IPH_HDR_LENGTH(ipha);
13565 	goto find_sctp_client;
13566 #undef  iphs
13567 #undef  rptr
13568 
13569 error:
13570 	freemsg(first_mp);
13571 slow_done:
13572 	IRE_REFRELE(ire);
13573 }
13574 
13575 #define	VER_BITS	0xF0
13576 #define	VERSION_6	0x60
13577 
13578 static boolean_t
13579 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13580     ipaddr_t *dstp, ip_stack_t *ipst)
13581 {
13582 	uint_t	opt_len;
13583 	ipha_t *ipha;
13584 	ssize_t len;
13585 	uint_t	pkt_len;
13586 
13587 	ASSERT(ill != NULL);
13588 	IP_STAT(ipst, ip_ipoptions);
13589 	ipha = *iphapp;
13590 
13591 #define	rptr    ((uchar_t *)ipha)
13592 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13593 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13594 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13595 		freemsg(mp);
13596 		return (B_FALSE);
13597 	}
13598 
13599 	/* multiple mblk or too short */
13600 	pkt_len = ntohs(ipha->ipha_length);
13601 
13602 	/* Get the number of words of IP options in the IP header. */
13603 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13604 	if (opt_len) {
13605 		/* IP Options present!  Validate and process. */
13606 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13607 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13608 			goto done;
13609 		}
13610 		/*
13611 		 * Recompute complete header length and make sure we
13612 		 * have access to all of it.
13613 		 */
13614 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13615 		if (len > (mp->b_wptr - rptr)) {
13616 			if (len > pkt_len) {
13617 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13618 				goto done;
13619 			}
13620 			if (!pullupmsg(mp, len)) {
13621 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13622 				goto done;
13623 			}
13624 			ipha = (ipha_t *)mp->b_rptr;
13625 		}
13626 		/*
13627 		 * Go off to ip_rput_options which returns the next hop
13628 		 * destination address, which may have been affected
13629 		 * by source routing.
13630 		 */
13631 		IP_STAT(ipst, ip_opt);
13632 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13633 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13634 			return (B_FALSE);
13635 		}
13636 	}
13637 	*iphapp = ipha;
13638 	return (B_TRUE);
13639 done:
13640 	/* clear b_prev - used by ip_mroute_decap */
13641 	mp->b_prev = NULL;
13642 	freemsg(mp);
13643 	return (B_FALSE);
13644 #undef  rptr
13645 }
13646 
13647 /*
13648  * Deal with the fact that there is no ire for the destination.
13649  */
13650 static ire_t *
13651 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13652 {
13653 	ipha_t	*ipha;
13654 	ill_t	*ill;
13655 	ire_t	*ire;
13656 	boolean_t	check_multirt = B_FALSE;
13657 	ip_stack_t *ipst;
13658 
13659 	ipha = (ipha_t *)mp->b_rptr;
13660 	ill = (ill_t *)q->q_ptr;
13661 
13662 	ASSERT(ill != NULL);
13663 	ipst = ill->ill_ipst;
13664 
13665 	/*
13666 	 * No IRE for this destination, so it can't be for us.
13667 	 * Unless we are forwarding, drop the packet.
13668 	 * We have to let source routed packets through
13669 	 * since we don't yet know if they are 'ping -l'
13670 	 * packets i.e. if they will go out over the
13671 	 * same interface as they came in on.
13672 	 */
13673 	if (ll_multicast) {
13674 		freemsg(mp);
13675 		return (NULL);
13676 	}
13677 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13678 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13679 		freemsg(mp);
13680 		return (NULL);
13681 	}
13682 
13683 	/*
13684 	 * Mark this packet as having originated externally.
13685 	 *
13686 	 * For non-forwarding code path, ire_send later double
13687 	 * checks this interface to see if it is still exists
13688 	 * post-ARP resolution.
13689 	 *
13690 	 * Also, IPQOS uses this to differentiate between
13691 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13692 	 * QOS packet processing in ip_wput_attach_llhdr().
13693 	 * The QoS module can mark the b_band for a fastpath message
13694 	 * or the dl_priority field in a unitdata_req header for
13695 	 * CoS marking. This info can only be found in
13696 	 * ip_wput_attach_llhdr().
13697 	 */
13698 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13699 	/*
13700 	 * Clear the indication that this may have a hardware checksum
13701 	 * as we are not using it
13702 	 */
13703 	DB_CKSUMFLAGS(mp) = 0;
13704 
13705 	ire = ire_forward(dst, &check_multirt, NULL, NULL,
13706 	    MBLK_GETLABEL(mp), ipst);
13707 
13708 	if (ire == NULL && check_multirt) {
13709 		/* Let ip_newroute handle CGTP  */
13710 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13711 		return (NULL);
13712 	}
13713 
13714 	if (ire != NULL)
13715 		return (ire);
13716 
13717 	mp->b_prev = mp->b_next = 0;
13718 	/* send icmp unreachable */
13719 	q = WR(q);
13720 	/* Sent by forwarding path, and router is global zone */
13721 	if (ip_source_routed(ipha, ipst)) {
13722 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13723 		    GLOBAL_ZONEID, ipst);
13724 	} else {
13725 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13726 		    ipst);
13727 	}
13728 
13729 	return (NULL);
13730 
13731 }
13732 
13733 /*
13734  * check ip header length and align it.
13735  */
13736 static boolean_t
13737 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13738 {
13739 	ssize_t len;
13740 	ill_t *ill;
13741 	ipha_t	*ipha;
13742 
13743 	len = MBLKL(mp);
13744 
13745 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13746 		ill = (ill_t *)q->q_ptr;
13747 
13748 		if (!OK_32PTR(mp->b_rptr))
13749 			IP_STAT(ipst, ip_notaligned1);
13750 		else
13751 			IP_STAT(ipst, ip_notaligned2);
13752 		/* Guard against bogus device drivers */
13753 		if (len < 0) {
13754 			/* clear b_prev - used by ip_mroute_decap */
13755 			mp->b_prev = NULL;
13756 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13757 			freemsg(mp);
13758 			return (B_FALSE);
13759 		}
13760 
13761 		if (ip_rput_pullups++ == 0) {
13762 			ipha = (ipha_t *)mp->b_rptr;
13763 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13764 			    "ip_check_and_align_header: %s forced us to "
13765 			    " pullup pkt, hdr len %ld, hdr addr %p",
13766 			    ill->ill_name, len, ipha);
13767 		}
13768 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13769 			/* clear b_prev - used by ip_mroute_decap */
13770 			mp->b_prev = NULL;
13771 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13772 			freemsg(mp);
13773 			return (B_FALSE);
13774 		}
13775 	}
13776 	return (B_TRUE);
13777 }
13778 
13779 ire_t *
13780 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13781 {
13782 	ire_t		*new_ire;
13783 	ill_t		*ire_ill;
13784 	uint_t		ifindex;
13785 	ip_stack_t	*ipst = ill->ill_ipst;
13786 	boolean_t	strict_check = B_FALSE;
13787 
13788 	/*
13789 	 * This packet came in on an interface other than the one associated
13790 	 * with the first ire we found for the destination address. We do
13791 	 * another ire lookup here, using the ingress ill, to see if the
13792 	 * interface is in an interface group.
13793 	 * As long as the ills belong to the same group, we don't consider
13794 	 * them to be arriving on the wrong interface. Thus, if the switch
13795 	 * is doing inbound load spreading, we won't drop packets when the
13796 	 * ip*_strict_dst_multihoming switch is on. Note, the same holds true
13797 	 * for 'usesrc groups' where the destination address may belong to
13798 	 * another interface to allow multipathing to happen.
13799 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13800 	 * where the local address may not be unique. In this case we were
13801 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13802 	 * actually returned. The new lookup, which is more specific, should
13803 	 * only find the IRE_LOCAL associated with the ingress ill if one
13804 	 * exists.
13805 	 */
13806 
13807 	if (ire->ire_ipversion == IPV4_VERSION) {
13808 		if (ipst->ips_ip_strict_dst_multihoming)
13809 			strict_check = B_TRUE;
13810 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13811 		    ill->ill_ipif, ALL_ZONES, NULL,
13812 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13813 	} else {
13814 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13815 		if (ipst->ips_ipv6_strict_dst_multihoming)
13816 			strict_check = B_TRUE;
13817 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13818 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13819 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13820 	}
13821 	/*
13822 	 * If the same ire that was returned in ip_input() is found then this
13823 	 * is an indication that interface groups are in use. The packet
13824 	 * arrived on a different ill in the group than the one associated with
13825 	 * the destination address.  If a different ire was found then the same
13826 	 * IP address must be hosted on multiple ills. This is possible with
13827 	 * unnumbered point2point interfaces. We switch to use this new ire in
13828 	 * order to have accurate interface statistics.
13829 	 */
13830 	if (new_ire != NULL) {
13831 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13832 			ire_refrele(ire);
13833 			ire = new_ire;
13834 		} else {
13835 			ire_refrele(new_ire);
13836 		}
13837 		return (ire);
13838 	} else if ((ire->ire_rfq == NULL) &&
13839 	    (ire->ire_ipversion == IPV4_VERSION)) {
13840 		/*
13841 		 * The best match could have been the original ire which
13842 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13843 		 * the strict multihoming checks are irrelevant as we consider
13844 		 * local addresses hosted on lo0 to be interface agnostic. We
13845 		 * only expect a null ire_rfq on IREs which are associated with
13846 		 * lo0 hence we can return now.
13847 		 */
13848 		return (ire);
13849 	}
13850 
13851 	/*
13852 	 * Chase pointers once and store locally.
13853 	 */
13854 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13855 	    (ill_t *)(ire->ire_rfq->q_ptr);
13856 	ifindex = ill->ill_usesrc_ifindex;
13857 
13858 	/*
13859 	 * Check if it's a legal address on the 'usesrc' interface.
13860 	 */
13861 	if ((ifindex != 0) && (ire_ill != NULL) &&
13862 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13863 		return (ire);
13864 	}
13865 
13866 	/*
13867 	 * If the ip*_strict_dst_multihoming switch is on then we can
13868 	 * only accept this packet if the interface is marked as routing.
13869 	 */
13870 	if (!(strict_check))
13871 		return (ire);
13872 
13873 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13874 	    ILLF_ROUTER) != 0) {
13875 		return (ire);
13876 	}
13877 
13878 	ire_refrele(ire);
13879 	return (NULL);
13880 }
13881 
13882 ire_t *
13883 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13884 {
13885 	ipha_t	*ipha;
13886 	ire_t	*src_ire;
13887 	ill_t	*stq_ill;
13888 	uint_t	hlen;
13889 	uint_t	pkt_len;
13890 	uint32_t sum;
13891 	queue_t	*dev_q;
13892 	ip_stack_t *ipst = ill->ill_ipst;
13893 	mblk_t *fpmp;
13894 
13895 	ipha = (ipha_t *)mp->b_rptr;
13896 
13897 	/*
13898 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13899 	 * The loopback address check for both src and dst has already
13900 	 * been checked in ip_input
13901 	 */
13902 
13903 	if (dst == INADDR_ANY || CLASSD(ipha->ipha_src)) {
13904 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13905 		goto drop;
13906 	}
13907 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13908 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13909 
13910 	if (src_ire != NULL) {
13911 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13912 		ire_refrele(src_ire);
13913 		goto drop;
13914 	}
13915 
13916 
13917 	/* No ire cache of nexthop. So first create one  */
13918 	if (ire == NULL) {
13919 		boolean_t check_multirt;
13920 
13921 		ire = ire_forward(dst, &check_multirt, NULL, NULL, NULL, ipst);
13922 		/*
13923 		 * We only come to ip_fast_forward if ip_cgtp_filter is
13924 		 * is not set. So upon return from ire_forward
13925 		 * check_multirt should remain as false.
13926 		 */
13927 		if (ire == NULL) {
13928 			/* An attempt was made to forward the packet */
13929 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13930 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13931 			mp->b_prev = mp->b_next = 0;
13932 			/* send icmp unreachable */
13933 			/* Sent by forwarding path, and router is global zone */
13934 			if (ip_source_routed(ipha, ipst)) {
13935 				icmp_unreachable(ill->ill_wq, mp,
13936 				    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID,
13937 				    ipst);
13938 			} else {
13939 				icmp_unreachable(ill->ill_wq, mp,
13940 				    ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13941 				    ipst);
13942 			}
13943 			return (ire);
13944 		}
13945 	}
13946 
13947 	/*
13948 	 * Forwarding fastpath exception case:
13949 	 * If either of the follwoing case is true, we take
13950 	 * the slowpath
13951 	 *	o forwarding is not enabled
13952 	 *	o incoming and outgoing interface are the same, or the same
13953 	 *	  IPMP group
13954 	 *	o corresponding ire is in incomplete state
13955 	 *	o packet needs fragmentation
13956 	 *	o ARP cache is not resolved
13957 	 *
13958 	 * The codeflow from here on is thus:
13959 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13960 	 */
13961 	pkt_len = ntohs(ipha->ipha_length);
13962 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13963 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13964 	    !(ill->ill_flags & ILLF_ROUTER) ||
13965 	    (ill == stq_ill) ||
13966 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
13967 	    (ire->ire_nce == NULL) ||
13968 	    (pkt_len > ire->ire_max_frag) ||
13969 	    ((fpmp = ire->ire_nce->nce_fp_mp) == NULL) ||
13970 	    ((hlen = MBLKL(fpmp)) > MBLKHEAD(mp)) ||
13971 	    ipha->ipha_ttl <= 1) {
13972 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13973 		    ipha, ill, B_FALSE);
13974 		return (ire);
13975 	}
13976 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13977 
13978 	DTRACE_PROBE4(ip4__forwarding__start,
13979 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13980 
13981 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
13982 	    ipst->ips_ipv4firewall_forwarding,
13983 	    ill, stq_ill, ipha, mp, mp, ipst);
13984 
13985 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13986 
13987 	if (mp == NULL)
13988 		goto drop;
13989 
13990 	mp->b_datap->db_struioun.cksum.flags = 0;
13991 	/* Adjust the checksum to reflect the ttl decrement. */
13992 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13993 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
13994 	ipha->ipha_ttl--;
13995 
13996 	/*
13997 	 * Write the link layer header.  We can do this safely here,
13998 	 * because we have already tested to make sure that the IP
13999 	 * policy is not set, and that we have a fast path destination
14000 	 * header.
14001 	 */
14002 	mp->b_rptr -= hlen;
14003 	bcopy(fpmp->b_rptr, mp->b_rptr, hlen);
14004 
14005 	UPDATE_IB_PKT_COUNT(ire);
14006 	ire->ire_last_used_time = lbolt;
14007 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
14008 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14009 	UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets, pkt_len);
14010 
14011 	dev_q = ire->ire_stq->q_next;
14012 	if ((dev_q->q_next != NULL || dev_q->q_first != NULL) &&
14013 	    !canputnext(ire->ire_stq)) {
14014 		goto indiscard;
14015 	}
14016 	if (ILL_DLS_CAPABLE(stq_ill)) {
14017 		/*
14018 		 * Send the packet directly to DLD, where it
14019 		 * may be queued depending on the availability
14020 		 * of transmit resources at the media layer.
14021 		 */
14022 		IP_DLS_ILL_TX(stq_ill, ipha, mp, ipst);
14023 	} else {
14024 		DTRACE_PROBE4(ip4__physical__out__start,
14025 		    ill_t *, NULL, ill_t *, stq_ill,
14026 		    ipha_t *, ipha, mblk_t *, mp);
14027 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
14028 		    ipst->ips_ipv4firewall_physical_out,
14029 		    NULL, stq_ill, ipha, mp, mp, ipst);
14030 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
14031 		if (mp == NULL)
14032 			goto drop;
14033 		putnext(ire->ire_stq, mp);
14034 	}
14035 	return (ire);
14036 
14037 indiscard:
14038 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14039 drop:
14040 	if (mp != NULL)
14041 		freemsg(mp);
14042 	return (ire);
14043 
14044 }
14045 
14046 /*
14047  * This function is called in the forwarding slowpath, when
14048  * either the ire lacks the link-layer address, or the packet needs
14049  * further processing(eg. fragmentation), before transmission.
14050  */
14051 
14052 static void
14053 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14054     ill_t *ill, boolean_t ll_multicast)
14055 {
14056 	ill_group_t	*ill_group;
14057 	ill_group_t	*ire_group;
14058 	queue_t		*dev_q;
14059 	ire_t		*src_ire;
14060 	ip_stack_t	*ipst = ill->ill_ipst;
14061 
14062 	ASSERT(ire->ire_stq != NULL);
14063 
14064 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14065 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14066 
14067 	if (ll_multicast != 0) {
14068 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14069 		goto drop_pkt;
14070 	}
14071 
14072 	/*
14073 	 * check if ipha_src is a broadcast address. Note that this
14074 	 * check is redundant when we get here from ip_fast_forward()
14075 	 * which has already done this check. However, since we can
14076 	 * also get here from ip_rput_process_broadcast() or, for
14077 	 * for the slow path through ip_fast_forward(), we perform
14078 	 * the check again for code-reusability
14079 	 */
14080 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14081 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14082 	if (src_ire != NULL || ipha->ipha_dst == INADDR_ANY) {
14083 		if (src_ire != NULL)
14084 			ire_refrele(src_ire);
14085 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14086 		ip2dbg(("ip_rput_process_forward: Received packet with"
14087 		    " bad src/dst address on %s\n", ill->ill_name));
14088 		goto drop_pkt;
14089 	}
14090 
14091 	ill_group = ill->ill_group;
14092 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
14093 	/*
14094 	 * Check if we want to forward this one at this time.
14095 	 * We allow source routed packets on a host provided that
14096 	 * they go out the same interface or same interface group
14097 	 * as they came in on.
14098 	 *
14099 	 * XXX To be quicker, we may wish to not chase pointers to
14100 	 * get the ILLF_ROUTER flag and instead store the
14101 	 * forwarding policy in the ire.  An unfortunate
14102 	 * side-effect of that would be requiring an ire flush
14103 	 * whenever the ILLF_ROUTER flag changes.
14104 	 */
14105 	if (((ill->ill_flags &
14106 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
14107 	    ILLF_ROUTER) == 0) &&
14108 	    !(ip_source_routed(ipha, ipst) && (ire->ire_rfq == q ||
14109 	    (ill_group != NULL && ill_group == ire_group)))) {
14110 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14111 		if (ip_source_routed(ipha, ipst)) {
14112 			q = WR(q);
14113 			/*
14114 			 * Clear the indication that this may have
14115 			 * hardware checksum as we are not using it.
14116 			 */
14117 			DB_CKSUMFLAGS(mp) = 0;
14118 			/* Sent by forwarding path, and router is global zone */
14119 			icmp_unreachable(q, mp,
14120 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14121 			return;
14122 		}
14123 		goto drop_pkt;
14124 	}
14125 
14126 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14127 
14128 	/* Packet is being forwarded. Turning off hwcksum flag. */
14129 	DB_CKSUMFLAGS(mp) = 0;
14130 	if (ipst->ips_ip_g_send_redirects) {
14131 		/*
14132 		 * Check whether the incoming interface and outgoing
14133 		 * interface is part of the same group. If so,
14134 		 * send redirects.
14135 		 *
14136 		 * Check the source address to see if it originated
14137 		 * on the same logical subnet it is going back out on.
14138 		 * If so, we should be able to send it a redirect.
14139 		 * Avoid sending a redirect if the destination
14140 		 * is directly connected (i.e., ipha_dst is the same
14141 		 * as ire_gateway_addr or the ire_addr of the
14142 		 * nexthop IRE_CACHE ), or if the packet was source
14143 		 * routed out this interface.
14144 		 */
14145 		ipaddr_t src, nhop;
14146 		mblk_t	*mp1;
14147 		ire_t	*nhop_ire = NULL;
14148 
14149 		/*
14150 		 * Check whether ire_rfq and q are from the same ill
14151 		 * or if they are not same, they at least belong
14152 		 * to the same group. If so, send redirects.
14153 		 */
14154 		if ((ire->ire_rfq == q ||
14155 		    (ill_group != NULL && ill_group == ire_group)) &&
14156 		    !ip_source_routed(ipha, ipst)) {
14157 
14158 			nhop = (ire->ire_gateway_addr != 0 ?
14159 			    ire->ire_gateway_addr : ire->ire_addr);
14160 
14161 			if (ipha->ipha_dst == nhop) {
14162 				/*
14163 				 * We avoid sending a redirect if the
14164 				 * destination is directly connected
14165 				 * because it is possible that multiple
14166 				 * IP subnets may have been configured on
14167 				 * the link, and the source may not
14168 				 * be on the same subnet as ip destination,
14169 				 * even though they are on the same
14170 				 * physical link.
14171 				 */
14172 				goto sendit;
14173 			}
14174 
14175 			src = ipha->ipha_src;
14176 
14177 			/*
14178 			 * We look up the interface ire for the nexthop,
14179 			 * to see if ipha_src is in the same subnet
14180 			 * as the nexthop.
14181 			 *
14182 			 * Note that, if, in the future, IRE_CACHE entries
14183 			 * are obsoleted,  this lookup will not be needed,
14184 			 * as the ire passed to this function will be the
14185 			 * same as the nhop_ire computed below.
14186 			 */
14187 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14188 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14189 			    0, NULL, MATCH_IRE_TYPE, ipst);
14190 
14191 			if (nhop_ire != NULL) {
14192 				if ((src & nhop_ire->ire_mask) ==
14193 				    (nhop & nhop_ire->ire_mask)) {
14194 					/*
14195 					 * The source is directly connected.
14196 					 * Just copy the ip header (which is
14197 					 * in the first mblk)
14198 					 */
14199 					mp1 = copyb(mp);
14200 					if (mp1 != NULL) {
14201 						icmp_send_redirect(WR(q), mp1,
14202 						    nhop, ipst);
14203 					}
14204 				}
14205 				ire_refrele(nhop_ire);
14206 			}
14207 		}
14208 	}
14209 sendit:
14210 	dev_q = ire->ire_stq->q_next;
14211 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
14212 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14213 		freemsg(mp);
14214 		return;
14215 	}
14216 
14217 	ip_rput_forward(ire, ipha, mp, ill);
14218 	return;
14219 
14220 drop_pkt:
14221 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14222 	freemsg(mp);
14223 }
14224 
14225 ire_t *
14226 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14227     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14228 {
14229 	queue_t		*q;
14230 	uint16_t	hcksumflags;
14231 	ip_stack_t	*ipst = ill->ill_ipst;
14232 
14233 	q = *qp;
14234 
14235 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14236 
14237 	/*
14238 	 * Clear the indication that this may have hardware
14239 	 * checksum as we are not using it for forwarding.
14240 	 */
14241 	hcksumflags = DB_CKSUMFLAGS(mp);
14242 	DB_CKSUMFLAGS(mp) = 0;
14243 
14244 	/*
14245 	 * Directed broadcast forwarding: if the packet came in over a
14246 	 * different interface then it is routed out over we can forward it.
14247 	 */
14248 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14249 		ire_refrele(ire);
14250 		freemsg(mp);
14251 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14252 		return (NULL);
14253 	}
14254 	/*
14255 	 * For multicast we have set dst to be INADDR_BROADCAST
14256 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
14257 	 * only for broadcast packets.
14258 	 */
14259 	if (!CLASSD(ipha->ipha_dst)) {
14260 		ire_t *new_ire;
14261 		ipif_t *ipif;
14262 		/*
14263 		 * For ill groups, as the switch duplicates broadcasts
14264 		 * across all the ports, we need to filter out and
14265 		 * send up only one copy. There is one copy for every
14266 		 * broadcast address on each ill. Thus, we look for a
14267 		 * specific IRE on this ill and look at IRE_MARK_NORECV
14268 		 * later to see whether this ill is eligible to receive
14269 		 * them or not. ill_nominate_bcast_rcv() nominates only
14270 		 * one set of IREs for receiving.
14271 		 */
14272 
14273 		ipif = ipif_get_next_ipif(NULL, ill);
14274 		if (ipif == NULL) {
14275 			ire_refrele(ire);
14276 			freemsg(mp);
14277 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14278 			return (NULL);
14279 		}
14280 		new_ire = ire_ctable_lookup(dst, 0, 0,
14281 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14282 		ipif_refrele(ipif);
14283 
14284 		if (new_ire != NULL) {
14285 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
14286 				ire_refrele(ire);
14287 				ire_refrele(new_ire);
14288 				freemsg(mp);
14289 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14290 				return (NULL);
14291 			}
14292 			/*
14293 			 * In the special case of multirouted broadcast
14294 			 * packets, we unconditionally need to "gateway"
14295 			 * them to the appropriate interface here.
14296 			 * In the normal case, this cannot happen, because
14297 			 * there is no broadcast IRE tagged with the
14298 			 * RTF_MULTIRT flag.
14299 			 */
14300 			if (new_ire->ire_flags & RTF_MULTIRT) {
14301 				ire_refrele(new_ire);
14302 				if (ire->ire_rfq != NULL) {
14303 					q = ire->ire_rfq;
14304 					*qp = q;
14305 				}
14306 			} else {
14307 				ire_refrele(ire);
14308 				ire = new_ire;
14309 			}
14310 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14311 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14312 				/*
14313 				 * Free the message if
14314 				 * ip_g_forward_directed_bcast is turned
14315 				 * off for non-local broadcast.
14316 				 */
14317 				ire_refrele(ire);
14318 				freemsg(mp);
14319 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14320 				return (NULL);
14321 			}
14322 		} else {
14323 			/*
14324 			 * This CGTP packet successfully passed the
14325 			 * CGTP filter, but the related CGTP
14326 			 * broadcast IRE has not been found,
14327 			 * meaning that the redundant ipif is
14328 			 * probably down. However, if we discarded
14329 			 * this packet, its duplicate would be
14330 			 * filtered out by the CGTP filter so none
14331 			 * of them would get through. So we keep
14332 			 * going with this one.
14333 			 */
14334 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14335 			if (ire->ire_rfq != NULL) {
14336 				q = ire->ire_rfq;
14337 				*qp = q;
14338 			}
14339 		}
14340 	}
14341 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14342 		/*
14343 		 * Verify that there are not more then one
14344 		 * IRE_BROADCAST with this broadcast address which
14345 		 * has ire_stq set.
14346 		 * TODO: simplify, loop over all IRE's
14347 		 */
14348 		ire_t	*ire1;
14349 		int	num_stq = 0;
14350 		mblk_t	*mp1;
14351 
14352 		/* Find the first one with ire_stq set */
14353 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14354 		for (ire1 = ire; ire1 &&
14355 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14356 		    ire1 = ire1->ire_next)
14357 			;
14358 		if (ire1) {
14359 			ire_refrele(ire);
14360 			ire = ire1;
14361 			IRE_REFHOLD(ire);
14362 		}
14363 
14364 		/* Check if there are additional ones with stq set */
14365 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14366 			if (ire->ire_addr != ire1->ire_addr)
14367 				break;
14368 			if (ire1->ire_stq) {
14369 				num_stq++;
14370 				break;
14371 			}
14372 		}
14373 		rw_exit(&ire->ire_bucket->irb_lock);
14374 		if (num_stq == 1 && ire->ire_stq != NULL) {
14375 			ip1dbg(("ip_rput_process_broadcast: directed "
14376 			    "broadcast to 0x%x\n",
14377 			    ntohl(ire->ire_addr)));
14378 			mp1 = copymsg(mp);
14379 			if (mp1) {
14380 				switch (ipha->ipha_protocol) {
14381 				case IPPROTO_UDP:
14382 					ip_udp_input(q, mp1, ipha, ire, ill);
14383 					break;
14384 				default:
14385 					ip_proto_input(q, mp1, ipha, ire, ill,
14386 					    B_FALSE);
14387 					break;
14388 				}
14389 			}
14390 			/*
14391 			 * Adjust ttl to 2 (1+1 - the forward engine
14392 			 * will decrement it by one.
14393 			 */
14394 			if (ip_csum_hdr(ipha)) {
14395 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14396 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14397 				freemsg(mp);
14398 				ire_refrele(ire);
14399 				return (NULL);
14400 			}
14401 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14402 			ipha->ipha_hdr_checksum = 0;
14403 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14404 			ip_rput_process_forward(q, mp, ire, ipha,
14405 			    ill, ll_multicast);
14406 			ire_refrele(ire);
14407 			return (NULL);
14408 		}
14409 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14410 		    ntohl(ire->ire_addr)));
14411 	}
14412 
14413 
14414 	/* Restore any hardware checksum flags */
14415 	DB_CKSUMFLAGS(mp) = hcksumflags;
14416 	return (ire);
14417 }
14418 
14419 /* ARGSUSED */
14420 static boolean_t
14421 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14422     int *ll_multicast, ipaddr_t *dstp)
14423 {
14424 	ip_stack_t	*ipst = ill->ill_ipst;
14425 
14426 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14427 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14428 	    ntohs(ipha->ipha_length));
14429 
14430 	/*
14431 	 * Forward packets only if we have joined the allmulti
14432 	 * group on this interface.
14433 	 */
14434 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14435 		int retval;
14436 
14437 		/*
14438 		 * Clear the indication that this may have hardware
14439 		 * checksum as we are not using it.
14440 		 */
14441 		DB_CKSUMFLAGS(mp) = 0;
14442 		retval = ip_mforward(ill, ipha, mp);
14443 		/* ip_mforward updates mib variables if needed */
14444 		/* clear b_prev - used by ip_mroute_decap */
14445 		mp->b_prev = NULL;
14446 
14447 		switch (retval) {
14448 		case 0:
14449 			/*
14450 			 * pkt is okay and arrived on phyint.
14451 			 *
14452 			 * If we are running as a multicast router
14453 			 * we need to see all IGMP and/or PIM packets.
14454 			 */
14455 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14456 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14457 				goto done;
14458 			}
14459 			break;
14460 		case -1:
14461 			/* pkt is mal-formed, toss it */
14462 			goto drop_pkt;
14463 		case 1:
14464 			/* pkt is okay and arrived on a tunnel */
14465 			/*
14466 			 * If we are running a multicast router
14467 			 *  we need to see all igmp packets.
14468 			 */
14469 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14470 				*dstp = INADDR_BROADCAST;
14471 				*ll_multicast = 1;
14472 				return (B_FALSE);
14473 			}
14474 
14475 			goto drop_pkt;
14476 		}
14477 	}
14478 
14479 	ILM_WALKER_HOLD(ill);
14480 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14481 		/*
14482 		 * This might just be caused by the fact that
14483 		 * multiple IP Multicast addresses map to the same
14484 		 * link layer multicast - no need to increment counter!
14485 		 */
14486 		ILM_WALKER_RELE(ill);
14487 		freemsg(mp);
14488 		return (B_TRUE);
14489 	}
14490 	ILM_WALKER_RELE(ill);
14491 done:
14492 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14493 	/*
14494 	 * This assumes the we deliver to all streams for multicast
14495 	 * and broadcast packets.
14496 	 */
14497 	*dstp = INADDR_BROADCAST;
14498 	*ll_multicast = 1;
14499 	return (B_FALSE);
14500 drop_pkt:
14501 	ip2dbg(("ip_rput: drop pkt\n"));
14502 	freemsg(mp);
14503 	return (B_TRUE);
14504 }
14505 
14506 static boolean_t
14507 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14508     int *ll_multicast, mblk_t **mpp)
14509 {
14510 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14511 	boolean_t must_copy = B_FALSE;
14512 	struct iocblk   *iocp;
14513 	ipha_t		*ipha;
14514 	ip_stack_t	*ipst = ill->ill_ipst;
14515 
14516 #define	rptr    ((uchar_t *)ipha)
14517 
14518 	first_mp = *first_mpp;
14519 	mp = *mpp;
14520 
14521 	ASSERT(first_mp == mp);
14522 
14523 	/*
14524 	 * if db_ref > 1 then copymsg and free original. Packet may be
14525 	 * changed and do not want other entity who has a reference to this
14526 	 * message to trip over the changes. This is a blind change because
14527 	 * trying to catch all places that might change packet is too
14528 	 * difficult (since it may be a module above this one)
14529 	 *
14530 	 * This corresponds to the non-fast path case. We walk down the full
14531 	 * chain in this case, and check the db_ref count of all the dblks,
14532 	 * and do a copymsg if required. It is possible that the db_ref counts
14533 	 * of the data blocks in the mblk chain can be different.
14534 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14535 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14536 	 * 'snoop' is running.
14537 	 */
14538 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14539 		if (mp1->b_datap->db_ref > 1) {
14540 			must_copy = B_TRUE;
14541 			break;
14542 		}
14543 	}
14544 
14545 	if (must_copy) {
14546 		mp1 = copymsg(mp);
14547 		if (mp1 == NULL) {
14548 			for (mp1 = mp; mp1 != NULL;
14549 			    mp1 = mp1->b_cont) {
14550 				mp1->b_next = NULL;
14551 				mp1->b_prev = NULL;
14552 			}
14553 			freemsg(mp);
14554 			if (ill != NULL) {
14555 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14556 			} else {
14557 				BUMP_MIB(&ipst->ips_ip_mib,
14558 				    ipIfStatsInDiscards);
14559 			}
14560 			return (B_TRUE);
14561 		}
14562 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14563 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14564 			/* Copy b_prev - used by ip_mroute_decap */
14565 			to_mp->b_prev = from_mp->b_prev;
14566 			from_mp->b_prev = NULL;
14567 		}
14568 		*first_mpp = first_mp = mp1;
14569 		freemsg(mp);
14570 		mp = mp1;
14571 		*mpp = mp1;
14572 	}
14573 
14574 	ipha = (ipha_t *)mp->b_rptr;
14575 
14576 	/*
14577 	 * previous code has a case for M_DATA.
14578 	 * We want to check how that happens.
14579 	 */
14580 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14581 	switch (first_mp->b_datap->db_type) {
14582 	case M_PROTO:
14583 	case M_PCPROTO:
14584 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14585 		    DL_UNITDATA_IND) {
14586 			/* Go handle anything other than data elsewhere. */
14587 			ip_rput_dlpi(q, mp);
14588 			return (B_TRUE);
14589 		}
14590 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
14591 		/* Ditch the DLPI header. */
14592 		mp1 = mp->b_cont;
14593 		ASSERT(first_mp == mp);
14594 		*first_mpp = mp1;
14595 		freeb(mp);
14596 		*mpp = mp1;
14597 		return (B_FALSE);
14598 	case M_IOCACK:
14599 		ip1dbg(("got iocack "));
14600 		iocp = (struct iocblk *)mp->b_rptr;
14601 		switch (iocp->ioc_cmd) {
14602 		case DL_IOC_HDR_INFO:
14603 			ill = (ill_t *)q->q_ptr;
14604 			ill_fastpath_ack(ill, mp);
14605 			return (B_TRUE);
14606 		case SIOCSTUNPARAM:
14607 		case OSIOCSTUNPARAM:
14608 			/* Go through qwriter_ip */
14609 			break;
14610 		case SIOCGTUNPARAM:
14611 		case OSIOCGTUNPARAM:
14612 			ip_rput_other(NULL, q, mp, NULL);
14613 			return (B_TRUE);
14614 		default:
14615 			putnext(q, mp);
14616 			return (B_TRUE);
14617 		}
14618 		/* FALLTHRU */
14619 	case M_ERROR:
14620 	case M_HANGUP:
14621 		/*
14622 		 * Since this is on the ill stream we unconditionally
14623 		 * bump up the refcount
14624 		 */
14625 		ill_refhold(ill);
14626 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14627 		return (B_TRUE);
14628 	case M_CTL:
14629 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14630 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14631 		    IPHADA_M_CTL)) {
14632 			/*
14633 			 * It's an IPsec accelerated packet.
14634 			 * Make sure that the ill from which we received the
14635 			 * packet has enabled IPsec hardware acceleration.
14636 			 */
14637 			if (!(ill->ill_capabilities &
14638 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14639 				/* IPsec kstats: bean counter */
14640 				freemsg(mp);
14641 				return (B_TRUE);
14642 			}
14643 
14644 			/*
14645 			 * Make mp point to the mblk following the M_CTL,
14646 			 * then process according to type of mp.
14647 			 * After this processing, first_mp will point to
14648 			 * the data-attributes and mp to the pkt following
14649 			 * the M_CTL.
14650 			 */
14651 			mp = first_mp->b_cont;
14652 			if (mp == NULL) {
14653 				freemsg(first_mp);
14654 				return (B_TRUE);
14655 			}
14656 			/*
14657 			 * A Hardware Accelerated packet can only be M_DATA
14658 			 * ESP or AH packet.
14659 			 */
14660 			if (mp->b_datap->db_type != M_DATA) {
14661 				/* non-M_DATA IPsec accelerated packet */
14662 				IPSECHW_DEBUG(IPSECHW_PKT,
14663 				    ("non-M_DATA IPsec accelerated pkt\n"));
14664 				freemsg(first_mp);
14665 				return (B_TRUE);
14666 			}
14667 			ipha = (ipha_t *)mp->b_rptr;
14668 			if (ipha->ipha_protocol != IPPROTO_AH &&
14669 			    ipha->ipha_protocol != IPPROTO_ESP) {
14670 				IPSECHW_DEBUG(IPSECHW_PKT,
14671 				    ("non-M_DATA IPsec accelerated pkt\n"));
14672 				freemsg(first_mp);
14673 				return (B_TRUE);
14674 			}
14675 			*mpp = mp;
14676 			return (B_FALSE);
14677 		}
14678 		putnext(q, mp);
14679 		return (B_TRUE);
14680 	case M_IOCNAK:
14681 		ip1dbg(("got iocnak "));
14682 		iocp = (struct iocblk *)mp->b_rptr;
14683 		switch (iocp->ioc_cmd) {
14684 		case SIOCSTUNPARAM:
14685 		case OSIOCSTUNPARAM:
14686 			/*
14687 			 * Since this is on the ill stream we unconditionally
14688 			 * bump up the refcount
14689 			 */
14690 			ill_refhold(ill);
14691 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14692 			return (B_TRUE);
14693 		case DL_IOC_HDR_INFO:
14694 		case SIOCGTUNPARAM:
14695 		case OSIOCGTUNPARAM:
14696 			ip_rput_other(NULL, q, mp, NULL);
14697 			return (B_TRUE);
14698 		default:
14699 			break;
14700 		}
14701 		/* FALLTHRU */
14702 	default:
14703 		putnext(q, mp);
14704 		return (B_TRUE);
14705 	}
14706 }
14707 
14708 /* Read side put procedure.  Packets coming from the wire arrive here. */
14709 void
14710 ip_rput(queue_t *q, mblk_t *mp)
14711 {
14712 	ill_t	*ill;
14713 	union DL_primitives *dl;
14714 
14715 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14716 
14717 	ill = (ill_t *)q->q_ptr;
14718 
14719 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14720 		/*
14721 		 * If things are opening or closing, only accept high-priority
14722 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14723 		 * created; on close, things hanging off the ill may have been
14724 		 * freed already.)
14725 		 */
14726 		dl = (union DL_primitives *)mp->b_rptr;
14727 		if (DB_TYPE(mp) != M_PCPROTO ||
14728 		    dl->dl_primitive == DL_UNITDATA_IND) {
14729 			/*
14730 			 * SIOC[GS]TUNPARAM ioctls can come here.
14731 			 */
14732 			inet_freemsg(mp);
14733 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14734 			    "ip_rput_end: q %p (%S)", q, "uninit");
14735 			return;
14736 		}
14737 	}
14738 
14739 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14740 	    "ip_rput_end: q %p (%S)", q, "end");
14741 
14742 	ip_input(ill, NULL, mp, NULL);
14743 }
14744 
14745 static mblk_t *
14746 ip_fix_dbref(ill_t *ill, mblk_t *mp)
14747 {
14748 	mblk_t *mp1;
14749 	boolean_t adjusted = B_FALSE;
14750 	ip_stack_t *ipst = ill->ill_ipst;
14751 
14752 	IP_STAT(ipst, ip_db_ref);
14753 	/*
14754 	 * The IP_RECVSLLA option depends on having the
14755 	 * link layer header. First check that:
14756 	 * a> the underlying device is of type ether,
14757 	 * since this option is currently supported only
14758 	 * over ethernet.
14759 	 * b> there is enough room to copy over the link
14760 	 * layer header.
14761 	 *
14762 	 * Once the checks are done, adjust rptr so that
14763 	 * the link layer header will be copied via
14764 	 * copymsg. Note that, IFT_ETHER may be returned
14765 	 * by some non-ethernet drivers but in this case
14766 	 * the second check will fail.
14767 	 */
14768 	if (ill->ill_type == IFT_ETHER &&
14769 	    (mp->b_rptr - mp->b_datap->db_base) >=
14770 	    sizeof (struct ether_header)) {
14771 		mp->b_rptr -= sizeof (struct ether_header);
14772 		adjusted = B_TRUE;
14773 	}
14774 	mp1 = copymsg(mp);
14775 
14776 	if (mp1 == NULL) {
14777 		mp->b_next = NULL;
14778 		/* clear b_prev - used by ip_mroute_decap */
14779 		mp->b_prev = NULL;
14780 		freemsg(mp);
14781 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14782 		return (NULL);
14783 	}
14784 
14785 	if (adjusted) {
14786 		/*
14787 		 * Copy is done. Restore the pointer in
14788 		 * the _new_ mblk
14789 		 */
14790 		mp1->b_rptr += sizeof (struct ether_header);
14791 	}
14792 
14793 	/* Copy b_prev - used by ip_mroute_decap */
14794 	mp1->b_prev = mp->b_prev;
14795 	mp->b_prev = NULL;
14796 
14797 	/* preserve the hardware checksum flags and data, if present */
14798 	if (DB_CKSUMFLAGS(mp) != 0) {
14799 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
14800 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
14801 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
14802 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
14803 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
14804 	}
14805 
14806 	freemsg(mp);
14807 	return (mp1);
14808 }
14809 
14810 /*
14811  * Direct read side procedure capable of dealing with chains. GLDv3 based
14812  * drivers call this function directly with mblk chains while STREAMS
14813  * read side procedure ip_rput() calls this for single packet with ip_ring
14814  * set to NULL to process one packet at a time.
14815  *
14816  * The ill will always be valid if this function is called directly from
14817  * the driver.
14818  *
14819  * If ip_input() is called from GLDv3:
14820  *
14821  *   - This must be a non-VLAN IP stream.
14822  *   - 'mp' is either an untagged or a special priority-tagged packet.
14823  *   - Any VLAN tag that was in the MAC header has been stripped.
14824  *
14825  * If the IP header in packet is not 32-bit aligned, every message in the
14826  * chain will be aligned before further operations. This is required on SPARC
14827  * platform.
14828  */
14829 /* ARGSUSED */
14830 void
14831 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14832     struct mac_header_info_s *mhip)
14833 {
14834 	ipaddr_t		dst = NULL;
14835 	ipaddr_t		prev_dst;
14836 	ire_t			*ire = NULL;
14837 	ipha_t			*ipha;
14838 	uint_t			pkt_len;
14839 	ssize_t			len;
14840 	uint_t			opt_len;
14841 	int			ll_multicast;
14842 	int			cgtp_flt_pkt;
14843 	queue_t			*q = ill->ill_rq;
14844 	squeue_t		*curr_sqp = NULL;
14845 	mblk_t 			*head = NULL;
14846 	mblk_t			*tail = NULL;
14847 	mblk_t			*first_mp;
14848 	mblk_t 			*mp;
14849 	mblk_t			*dmp;
14850 	int			cnt = 0;
14851 	ip_stack_t		*ipst = ill->ill_ipst;
14852 
14853 	ASSERT(mp_chain != NULL);
14854 	ASSERT(ill != NULL);
14855 
14856 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14857 
14858 #define	rptr	((uchar_t *)ipha)
14859 
14860 	while (mp_chain != NULL) {
14861 		first_mp = mp = mp_chain;
14862 		mp_chain = mp_chain->b_next;
14863 		mp->b_next = NULL;
14864 		ll_multicast = 0;
14865 
14866 		/*
14867 		 * We do ire caching from one iteration to
14868 		 * another. In the event the packet chain contains
14869 		 * all packets from the same dst, this caching saves
14870 		 * an ire_cache_lookup for each of the succeeding
14871 		 * packets in a packet chain.
14872 		 */
14873 		prev_dst = dst;
14874 
14875 		/*
14876 		 * if db_ref > 1 then copymsg and free original. Packet
14877 		 * may be changed and we do not want the other entity
14878 		 * who has a reference to this message to trip over the
14879 		 * changes. This is a blind change because trying to
14880 		 * catch all places that might change the packet is too
14881 		 * difficult.
14882 		 *
14883 		 * This corresponds to the fast path case, where we have
14884 		 * a chain of M_DATA mblks.  We check the db_ref count
14885 		 * of only the 1st data block in the mblk chain. There
14886 		 * doesn't seem to be a reason why a device driver would
14887 		 * send up data with varying db_ref counts in the mblk
14888 		 * chain. In any case the Fast path is a private
14889 		 * interface, and our drivers don't do such a thing.
14890 		 * Given the above assumption, there is no need to walk
14891 		 * down the entire mblk chain (which could have a
14892 		 * potential performance problem)
14893 		 */
14894 
14895 		if (DB_REF(mp) > 1) {
14896 			if ((mp = ip_fix_dbref(ill, mp)) == NULL)
14897 				continue;
14898 		}
14899 
14900 		/*
14901 		 * Check and align the IP header.
14902 		 */
14903 		first_mp = mp;
14904 		if (DB_TYPE(mp) == M_DATA) {
14905 			dmp = mp;
14906 		} else if (DB_TYPE(mp) == M_PROTO &&
14907 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14908 			dmp = mp->b_cont;
14909 		} else {
14910 			dmp = NULL;
14911 		}
14912 		if (dmp != NULL) {
14913 			/*
14914 			 * IP header ptr not aligned?
14915 			 * OR IP header not complete in first mblk
14916 			 */
14917 			if (!OK_32PTR(dmp->b_rptr) ||
14918 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
14919 				if (!ip_check_and_align_header(q, dmp, ipst))
14920 					continue;
14921 			}
14922 		}
14923 
14924 		/*
14925 		 * ip_input fast path
14926 		 */
14927 
14928 		/* mblk type is not M_DATA */
14929 		if (DB_TYPE(mp) != M_DATA) {
14930 			if (ip_rput_process_notdata(q, &first_mp, ill,
14931 			    &ll_multicast, &mp))
14932 				continue;
14933 
14934 			/*
14935 			 * The only way we can get here is if we had a
14936 			 * packet that was either a DL_UNITDATA_IND or
14937 			 * an M_CTL for an IPsec accelerated packet.
14938 			 *
14939 			 * In either case, the first_mp will point to
14940 			 * the leading M_PROTO or M_CTL.
14941 			 */
14942 			ASSERT(first_mp != NULL);
14943 		}
14944 
14945 		/* Make sure its an M_DATA and that its aligned */
14946 		ASSERT(DB_TYPE(mp) == M_DATA);
14947 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
14948 
14949 		ipha = (ipha_t *)mp->b_rptr;
14950 		len = mp->b_wptr - rptr;
14951 		pkt_len = ntohs(ipha->ipha_length);
14952 
14953 		/*
14954 		 * We must count all incoming packets, even if they end
14955 		 * up being dropped later on.
14956 		 */
14957 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
14958 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
14959 
14960 		/* multiple mblk or too short */
14961 		len -= pkt_len;
14962 		if (len != 0) {
14963 			/*
14964 			 * Make sure we have data length consistent
14965 			 * with the IP header.
14966 			 */
14967 			if (mp->b_cont == NULL) {
14968 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14969 					BUMP_MIB(ill->ill_ip_mib,
14970 					    ipIfStatsInHdrErrors);
14971 					ip2dbg(("ip_input: drop pkt\n"));
14972 					freemsg(mp);
14973 					continue;
14974 				}
14975 				mp->b_wptr = rptr + pkt_len;
14976 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
14977 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14978 					BUMP_MIB(ill->ill_ip_mib,
14979 					    ipIfStatsInHdrErrors);
14980 					ip2dbg(("ip_input: drop pkt\n"));
14981 					freemsg(mp);
14982 					continue;
14983 				}
14984 				(void) adjmsg(mp, -len);
14985 				IP_STAT(ipst, ip_multimblk3);
14986 			}
14987 		}
14988 
14989 		/* Obtain the dst of the current packet */
14990 		dst = ipha->ipha_dst;
14991 
14992 		/*
14993 		 * The following test for loopback is faster than
14994 		 * IP_LOOPBACK_ADDR(), because it avoids any bitwise
14995 		 * operations.
14996 		 * Note that these addresses are always in network byte order
14997 		 */
14998 		if (((*(uchar_t *)&ipha->ipha_dst) == 127) ||
14999 		    ((*(uchar_t *)&ipha->ipha_src) == 127)) {
15000 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
15001 			freemsg(mp);
15002 			continue;
15003 		}
15004 
15005 		/*
15006 		 * The event for packets being received from a 'physical'
15007 		 * interface is placed after validation of the source and/or
15008 		 * destination address as being local so that packets can be
15009 		 * redirected to loopback addresses using ipnat.
15010 		 */
15011 		DTRACE_PROBE4(ip4__physical__in__start,
15012 		    ill_t *, ill, ill_t *, NULL,
15013 		    ipha_t *, ipha, mblk_t *, first_mp);
15014 
15015 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15016 		    ipst->ips_ipv4firewall_physical_in,
15017 		    ill, NULL, ipha, first_mp, mp, ipst);
15018 
15019 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15020 
15021 		if (first_mp == NULL) {
15022 			continue;
15023 		}
15024 		dst = ipha->ipha_dst;
15025 
15026 		/*
15027 		 * Attach any necessary label information to
15028 		 * this packet
15029 		 */
15030 		if (is_system_labeled() &&
15031 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15032 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15033 			freemsg(mp);
15034 			continue;
15035 		}
15036 
15037 		/*
15038 		 * Reuse the cached ire only if the ipha_dst of the previous
15039 		 * packet is the same as the current packet AND it is not
15040 		 * INADDR_ANY.
15041 		 */
15042 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15043 		    (ire != NULL)) {
15044 			ire_refrele(ire);
15045 			ire = NULL;
15046 		}
15047 		opt_len = ipha->ipha_version_and_hdr_length -
15048 		    IP_SIMPLE_HDR_VERSION;
15049 
15050 		/*
15051 		 * Check to see if we can take the fastpath.
15052 		 * That is possible if the following conditions are met
15053 		 *	o Tsol disabled
15054 		 *	o CGTP disabled
15055 		 *	o ipp_action_count is 0
15056 		 *	o no options in the packet
15057 		 *	o not a RSVP packet
15058 		 * 	o not a multicast packet
15059 		 *	o ill not in IP_DHCPINIT_IF mode
15060 		 */
15061 		if (!is_system_labeled() &&
15062 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
15063 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15064 		    !ll_multicast && !CLASSD(dst) && ill->ill_dhcpinit == 0) {
15065 			if (ire == NULL)
15066 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL,
15067 				    ipst);
15068 
15069 			/* incoming packet is for forwarding */
15070 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
15071 				ire = ip_fast_forward(ire, dst, ill, mp);
15072 				continue;
15073 			}
15074 			/* incoming packet is for local consumption */
15075 			if (ire->ire_type & IRE_LOCAL)
15076 				goto local;
15077 		}
15078 
15079 		/*
15080 		 * Disable ire caching for anything more complex
15081 		 * than the simple fast path case we checked for above.
15082 		 */
15083 		if (ire != NULL) {
15084 			ire_refrele(ire);
15085 			ire = NULL;
15086 		}
15087 
15088 		/*
15089 		 * Brutal hack for DHCPv4 unicast: RFC2131 allows a DHCP
15090 		 * server to unicast DHCP packets to a DHCP client using the
15091 		 * IP address it is offering to the client.  This can be
15092 		 * disabled through the "broadcast bit", but not all DHCP
15093 		 * servers honor that bit.  Therefore, to interoperate with as
15094 		 * many DHCP servers as possible, the DHCP client allows the
15095 		 * server to unicast, but we treat those packets as broadcast
15096 		 * here.  Note that we don't rewrite the packet itself since
15097 		 * (a) that would mess up the checksums and (b) the DHCP
15098 		 * client conn is bound to INADDR_ANY so ip_fanout_udp() will
15099 		 * hand it the packet regardless.
15100 		 */
15101 		if (ill->ill_dhcpinit != 0 &&
15102 		    IS_SIMPLE_IPH(ipha) && ipha->ipha_protocol == IPPROTO_UDP &&
15103 		    pullupmsg(mp, sizeof (ipha_t) + sizeof (udpha_t)) == 1) {
15104 			udpha_t *udpha;
15105 
15106 			/*
15107 			 * Reload ipha since pullupmsg() can change b_rptr.
15108 			 */
15109 			ipha = (ipha_t *)mp->b_rptr;
15110 			udpha = (udpha_t *)&ipha[1];
15111 
15112 			if (ntohs(udpha->uha_dst_port) == IPPORT_BOOTPC) {
15113 				DTRACE_PROBE2(ip4__dhcpinit__pkt, ill_t *, ill,
15114 				    mblk_t *, mp);
15115 				dst = INADDR_BROADCAST;
15116 			}
15117 		}
15118 
15119 		/* Full-blown slow path */
15120 		if (opt_len != 0) {
15121 			if (len != 0)
15122 				IP_STAT(ipst, ip_multimblk4);
15123 			else
15124 				IP_STAT(ipst, ip_ipoptions);
15125 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15126 			    &dst, ipst))
15127 				continue;
15128 		}
15129 
15130 		/*
15131 		 * Invoke the CGTP (multirouting) filtering module to process
15132 		 * the incoming packet. Packets identified as duplicates
15133 		 * must be discarded. Filtering is active only if the
15134 		 * the ip_cgtp_filter ndd variable is non-zero.
15135 		 */
15136 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15137 		if (ipst->ips_ip_cgtp_filter &&
15138 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15139 			netstackid_t stackid;
15140 
15141 			stackid = ipst->ips_netstack->netstack_stackid;
15142 			cgtp_flt_pkt =
15143 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15144 			    ill->ill_phyint->phyint_ifindex, mp);
15145 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15146 				freemsg(first_mp);
15147 				continue;
15148 			}
15149 		}
15150 
15151 		/*
15152 		 * If rsvpd is running, let RSVP daemon handle its processing
15153 		 * and forwarding of RSVP multicast/unicast packets.
15154 		 * If rsvpd is not running but mrouted is running, RSVP
15155 		 * multicast packets are forwarded as multicast traffic
15156 		 * and RSVP unicast packets are forwarded by unicast router.
15157 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15158 		 * packets are not forwarded, but the unicast packets are
15159 		 * forwarded like unicast traffic.
15160 		 */
15161 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15162 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15163 		    NULL) {
15164 			/* RSVP packet and rsvpd running. Treat as ours */
15165 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15166 			/*
15167 			 * This assumes that we deliver to all streams for
15168 			 * multicast and broadcast packets.
15169 			 * We have to force ll_multicast to 1 to handle the
15170 			 * M_DATA messages passed in from ip_mroute_decap.
15171 			 */
15172 			dst = INADDR_BROADCAST;
15173 			ll_multicast = 1;
15174 		} else if (CLASSD(dst)) {
15175 			/* packet is multicast */
15176 			mp->b_next = NULL;
15177 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15178 			    &ll_multicast, &dst))
15179 				continue;
15180 		}
15181 
15182 		if (ire == NULL) {
15183 			ire = ire_cache_lookup(dst, ALL_ZONES,
15184 			    MBLK_GETLABEL(mp), ipst);
15185 		}
15186 
15187 		if (ire == NULL) {
15188 			/*
15189 			 * No IRE for this destination, so it can't be for us.
15190 			 * Unless we are forwarding, drop the packet.
15191 			 * We have to let source routed packets through
15192 			 * since we don't yet know if they are 'ping -l'
15193 			 * packets i.e. if they will go out over the
15194 			 * same interface as they came in on.
15195 			 */
15196 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15197 			if (ire == NULL)
15198 				continue;
15199 		}
15200 
15201 		/*
15202 		 * Broadcast IRE may indicate either broadcast or
15203 		 * multicast packet
15204 		 */
15205 		if (ire->ire_type == IRE_BROADCAST) {
15206 			/*
15207 			 * Skip broadcast checks if packet is UDP multicast;
15208 			 * we'd rather not enter ip_rput_process_broadcast()
15209 			 * unless the packet is broadcast for real, since
15210 			 * that routine is a no-op for multicast.
15211 			 */
15212 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15213 			    !CLASSD(ipha->ipha_dst)) {
15214 				ire = ip_rput_process_broadcast(&q, mp,
15215 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15216 				    ll_multicast);
15217 				if (ire == NULL)
15218 					continue;
15219 			}
15220 		} else if (ire->ire_stq != NULL) {
15221 			/* fowarding? */
15222 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15223 			    ll_multicast);
15224 			/* ip_rput_process_forward consumed the packet */
15225 			continue;
15226 		}
15227 
15228 local:
15229 		/*
15230 		 * If the queue in the ire is different to the ingress queue
15231 		 * then we need to check to see if we can accept the packet.
15232 		 * Note that for multicast packets and broadcast packets sent
15233 		 * to a broadcast address which is shared between multiple
15234 		 * interfaces we should not do this since we just got a random
15235 		 * broadcast ire.
15236 		 */
15237 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15238 			if ((ire = ip_check_multihome(&ipha->ipha_dst, ire,
15239 			    ill)) == NULL) {
15240 				/* Drop packet */
15241 				BUMP_MIB(ill->ill_ip_mib,
15242 				    ipIfStatsForwProhibits);
15243 				freemsg(mp);
15244 				continue;
15245 			}
15246 			if (ire->ire_rfq != NULL)
15247 				q = ire->ire_rfq;
15248 		}
15249 
15250 		switch (ipha->ipha_protocol) {
15251 		case IPPROTO_TCP:
15252 			ASSERT(first_mp == mp);
15253 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15254 			    mp, 0, q, ip_ring)) != NULL) {
15255 				if (curr_sqp == NULL) {
15256 					curr_sqp = GET_SQUEUE(mp);
15257 					ASSERT(cnt == 0);
15258 					cnt++;
15259 					head = tail = mp;
15260 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15261 					ASSERT(tail != NULL);
15262 					cnt++;
15263 					tail->b_next = mp;
15264 					tail = mp;
15265 				} else {
15266 					/*
15267 					 * A different squeue. Send the
15268 					 * chain for the previous squeue on
15269 					 * its way. This shouldn't happen
15270 					 * often unless interrupt binding
15271 					 * changes.
15272 					 */
15273 					IP_STAT(ipst, ip_input_multi_squeue);
15274 					squeue_enter_chain(curr_sqp, head,
15275 					    tail, cnt, SQTAG_IP_INPUT);
15276 					curr_sqp = GET_SQUEUE(mp);
15277 					head = mp;
15278 					tail = mp;
15279 					cnt = 1;
15280 				}
15281 			}
15282 			continue;
15283 		case IPPROTO_UDP:
15284 			ASSERT(first_mp == mp);
15285 			ip_udp_input(q, mp, ipha, ire, ill);
15286 			continue;
15287 		case IPPROTO_SCTP:
15288 			ASSERT(first_mp == mp);
15289 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15290 			    q, dst);
15291 			/* ire has been released by ip_sctp_input */
15292 			ire = NULL;
15293 			continue;
15294 		default:
15295 			ip_proto_input(q, first_mp, ipha, ire, ill, B_FALSE);
15296 			continue;
15297 		}
15298 	}
15299 
15300 	if (ire != NULL)
15301 		ire_refrele(ire);
15302 
15303 	if (head != NULL)
15304 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
15305 
15306 	/*
15307 	 * This code is there just to make netperf/ttcp look good.
15308 	 *
15309 	 * Its possible that after being in polling mode (and having cleared
15310 	 * the backlog), squeues have turned the interrupt frequency higher
15311 	 * to improve latency at the expense of more CPU utilization (less
15312 	 * packets per interrupts or more number of interrupts). Workloads
15313 	 * like ttcp/netperf do manage to tickle polling once in a while
15314 	 * but for the remaining time, stay in higher interrupt mode since
15315 	 * their packet arrival rate is pretty uniform and this shows up
15316 	 * as higher CPU utilization. Since people care about CPU utilization
15317 	 * while running netperf/ttcp, turn the interrupt frequency back to
15318 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
15319 	 */
15320 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
15321 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
15322 			ip_ring->rr_poll_state &= ~ILL_POLLING;
15323 			ip_ring->rr_blank(ip_ring->rr_handle,
15324 			    ip_ring->rr_normal_blank_time,
15325 			    ip_ring->rr_normal_pkt_cnt);
15326 		}
15327 		}
15328 
15329 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15330 	    "ip_input_end: q %p (%S)", q, "end");
15331 #undef  rptr
15332 }
15333 
15334 static void
15335 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15336     t_uscalar_t err)
15337 {
15338 	if (dl_err == DL_SYSERR) {
15339 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15340 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15341 		    ill->ill_name, dlpi_prim_str(prim), err);
15342 		return;
15343 	}
15344 
15345 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15346 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
15347 	    dlpi_err_str(dl_err));
15348 }
15349 
15350 /*
15351  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15352  * than DL_UNITDATA_IND messages. If we need to process this message
15353  * exclusively, we call qwriter_ip, in which case we also need to call
15354  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15355  */
15356 void
15357 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15358 {
15359 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15360 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15361 	ill_t		*ill = (ill_t *)q->q_ptr;
15362 	boolean_t	pending;
15363 
15364 	ip1dbg(("ip_rput_dlpi"));
15365 	if (dloa->dl_primitive == DL_ERROR_ACK) {
15366 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
15367 		    "%s (0x%x), unix %u\n", ill->ill_name,
15368 		    dlpi_prim_str(dlea->dl_error_primitive),
15369 		    dlea->dl_error_primitive,
15370 		    dlpi_err_str(dlea->dl_errno),
15371 		    dlea->dl_errno,
15372 		    dlea->dl_unix_errno));
15373 	}
15374 
15375 	/*
15376 	 * If we received an ACK but didn't send a request for it, then it
15377 	 * can't be part of any pending operation; discard up-front.
15378 	 */
15379 	switch (dloa->dl_primitive) {
15380 	case DL_NOTIFY_IND:
15381 		pending = B_TRUE;
15382 		break;
15383 	case DL_ERROR_ACK:
15384 		pending = ill_dlpi_pending(ill, dlea->dl_error_primitive);
15385 		break;
15386 	case DL_OK_ACK:
15387 		pending = ill_dlpi_pending(ill, dloa->dl_correct_primitive);
15388 		break;
15389 	case DL_INFO_ACK:
15390 		pending = ill_dlpi_pending(ill, DL_INFO_REQ);
15391 		break;
15392 	case DL_BIND_ACK:
15393 		pending = ill_dlpi_pending(ill, DL_BIND_REQ);
15394 		break;
15395 	case DL_PHYS_ADDR_ACK:
15396 		pending = ill_dlpi_pending(ill, DL_PHYS_ADDR_REQ);
15397 		break;
15398 	case DL_NOTIFY_ACK:
15399 		pending = ill_dlpi_pending(ill, DL_NOTIFY_REQ);
15400 		break;
15401 	case DL_CONTROL_ACK:
15402 		pending = ill_dlpi_pending(ill, DL_CONTROL_REQ);
15403 		break;
15404 	case DL_CAPABILITY_ACK:
15405 		pending = ill_dlpi_pending(ill, DL_CAPABILITY_REQ);
15406 		break;
15407 	default:
15408 		/* Not a DLPI message we support or were expecting */
15409 		freemsg(mp);
15410 		return;
15411 	}
15412 
15413 	if (!pending) {
15414 		freemsg(mp);
15415 		return;
15416 	}
15417 
15418 	switch (dloa->dl_primitive) {
15419 	case DL_ERROR_ACK:
15420 		if (dlea->dl_error_primitive == DL_UNBIND_REQ) {
15421 			mutex_enter(&ill->ill_lock);
15422 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15423 			cv_signal(&ill->ill_cv);
15424 			mutex_exit(&ill->ill_lock);
15425 		}
15426 		break;
15427 
15428 	case DL_OK_ACK:
15429 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
15430 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
15431 		switch (dloa->dl_correct_primitive) {
15432 		case DL_UNBIND_REQ:
15433 			mutex_enter(&ill->ill_lock);
15434 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15435 			cv_signal(&ill->ill_cv);
15436 			mutex_exit(&ill->ill_lock);
15437 			break;
15438 
15439 		case DL_ENABMULTI_REQ:
15440 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15441 				ill->ill_dlpi_multicast_state = IDS_OK;
15442 			break;
15443 		}
15444 		break;
15445 	default:
15446 		break;
15447 	}
15448 
15449 	/*
15450 	 * We know the message is one we're waiting for (or DL_NOTIFY_IND),
15451 	 * and we need to become writer to continue to process it. If it's not
15452 	 * a DL_NOTIFY_IND, we assume we're in the middle of an exclusive
15453 	 * operation and pass CUR_OP.  If this isn't true, we'll end up doing
15454 	 * some work as part of the current exclusive operation that actually
15455 	 * is not part of it -- which is wrong, but better than the
15456 	 * alternative of deadlock (if NEW_OP is always used).  Someday, we
15457 	 * should track which DLPI requests have ACKs that we wait on
15458 	 * synchronously so we can know whether to use CUR_OP or NEW_OP.
15459 	 *
15460 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15461 	 * Since this is on the ill stream we unconditionally bump up the
15462 	 * refcount without doing ILL_CAN_LOOKUP().
15463 	 */
15464 	ill_refhold(ill);
15465 	if (dloa->dl_primitive == DL_NOTIFY_IND)
15466 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15467 	else
15468 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15469 }
15470 
15471 /*
15472  * Handling of DLPI messages that require exclusive access to the ipsq.
15473  *
15474  * Need to do ill_pending_mp_release on ioctl completion, which could
15475  * happen here. (along with mi_copy_done)
15476  */
15477 /* ARGSUSED */
15478 static void
15479 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15480 {
15481 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15482 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15483 	int		err = 0;
15484 	ill_t		*ill;
15485 	ipif_t		*ipif = NULL;
15486 	mblk_t		*mp1 = NULL;
15487 	conn_t		*connp = NULL;
15488 	t_uscalar_t	paddrreq;
15489 	mblk_t		*mp_hw;
15490 	boolean_t	success;
15491 	boolean_t	ioctl_aborted = B_FALSE;
15492 	boolean_t	log = B_TRUE;
15493 	hook_nic_event_t	*info;
15494 	ip_stack_t		*ipst;
15495 
15496 	ip1dbg(("ip_rput_dlpi_writer .."));
15497 	ill = (ill_t *)q->q_ptr;
15498 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15499 
15500 	ASSERT(IAM_WRITER_ILL(ill));
15501 
15502 	ipst = ill->ill_ipst;
15503 
15504 	/*
15505 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15506 	 * both are null or non-null. However we can assert that only
15507 	 * after grabbing the ipsq_lock. So we don't make any assertion
15508 	 * here and in other places in the code.
15509 	 */
15510 	ipif = ipsq->ipsq_pending_ipif;
15511 	/*
15512 	 * The current ioctl could have been aborted by the user and a new
15513 	 * ioctl to bring up another ill could have started. We could still
15514 	 * get a response from the driver later.
15515 	 */
15516 	if (ipif != NULL && ipif->ipif_ill != ill)
15517 		ioctl_aborted = B_TRUE;
15518 
15519 	switch (dloa->dl_primitive) {
15520 	case DL_ERROR_ACK:
15521 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15522 		    dlpi_prim_str(dlea->dl_error_primitive)));
15523 
15524 		switch (dlea->dl_error_primitive) {
15525 		case DL_PROMISCON_REQ:
15526 		case DL_PROMISCOFF_REQ:
15527 		case DL_DISABMULTI_REQ:
15528 		case DL_UNBIND_REQ:
15529 		case DL_ATTACH_REQ:
15530 		case DL_INFO_REQ:
15531 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15532 			break;
15533 		case DL_NOTIFY_REQ:
15534 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15535 			log = B_FALSE;
15536 			break;
15537 		case DL_PHYS_ADDR_REQ:
15538 			/*
15539 			 * For IPv6 only, there are two additional
15540 			 * phys_addr_req's sent to the driver to get the
15541 			 * IPv6 token and lla. This allows IP to acquire
15542 			 * the hardware address format for a given interface
15543 			 * without having built in knowledge of the hardware
15544 			 * address. ill_phys_addr_pend keeps track of the last
15545 			 * DL_PAR sent so we know which response we are
15546 			 * dealing with. ill_dlpi_done will update
15547 			 * ill_phys_addr_pend when it sends the next req.
15548 			 * We don't complete the IOCTL until all three DL_PARs
15549 			 * have been attempted, so set *_len to 0 and break.
15550 			 */
15551 			paddrreq = ill->ill_phys_addr_pend;
15552 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15553 			if (paddrreq == DL_IPV6_TOKEN) {
15554 				ill->ill_token_length = 0;
15555 				log = B_FALSE;
15556 				break;
15557 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15558 				ill->ill_nd_lla_len = 0;
15559 				log = B_FALSE;
15560 				break;
15561 			}
15562 			/*
15563 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15564 			 * We presumably have an IOCTL hanging out waiting
15565 			 * for completion. Find it and complete the IOCTL
15566 			 * with the error noted.
15567 			 * However, ill_dl_phys was called on an ill queue
15568 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15569 			 * set. But the ioctl is known to be pending on ill_wq.
15570 			 */
15571 			if (!ill->ill_ifname_pending)
15572 				break;
15573 			ill->ill_ifname_pending = 0;
15574 			if (!ioctl_aborted)
15575 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15576 			if (mp1 != NULL) {
15577 				/*
15578 				 * This operation (SIOCSLIFNAME) must have
15579 				 * happened on the ill. Assert there is no conn
15580 				 */
15581 				ASSERT(connp == NULL);
15582 				q = ill->ill_wq;
15583 			}
15584 			break;
15585 		case DL_BIND_REQ:
15586 			ill_dlpi_done(ill, DL_BIND_REQ);
15587 			if (ill->ill_ifname_pending)
15588 				break;
15589 			/*
15590 			 * Something went wrong with the bind.  We presumably
15591 			 * have an IOCTL hanging out waiting for completion.
15592 			 * Find it, take down the interface that was coming
15593 			 * up, and complete the IOCTL with the error noted.
15594 			 */
15595 			if (!ioctl_aborted)
15596 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15597 			if (mp1 != NULL) {
15598 				/*
15599 				 * This operation (SIOCSLIFFLAGS) must have
15600 				 * happened from a conn.
15601 				 */
15602 				ASSERT(connp != NULL);
15603 				q = CONNP_TO_WQ(connp);
15604 				if (ill->ill_move_in_progress) {
15605 					ILL_CLEAR_MOVE(ill);
15606 				}
15607 				(void) ipif_down(ipif, NULL, NULL);
15608 				/* error is set below the switch */
15609 			}
15610 			break;
15611 		case DL_ENABMULTI_REQ:
15612 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15613 
15614 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15615 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15616 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15617 				ipif_t *ipif;
15618 
15619 				printf("ip: joining multicasts failed (%d)"
15620 				    " on %s - will use link layer "
15621 				    "broadcasts for multicast\n",
15622 				    dlea->dl_errno, ill->ill_name);
15623 
15624 				/*
15625 				 * Set up the multicast mapping alone.
15626 				 * writer, so ok to access ill->ill_ipif
15627 				 * without any lock.
15628 				 */
15629 				ipif = ill->ill_ipif;
15630 				mutex_enter(&ill->ill_phyint->phyint_lock);
15631 				ill->ill_phyint->phyint_flags |=
15632 				    PHYI_MULTI_BCAST;
15633 				mutex_exit(&ill->ill_phyint->phyint_lock);
15634 
15635 				if (!ill->ill_isv6) {
15636 					(void) ipif_arp_setup_multicast(ipif,
15637 					    NULL);
15638 				} else {
15639 					(void) ipif_ndp_setup_multicast(ipif,
15640 					    NULL);
15641 				}
15642 			}
15643 			freemsg(mp);	/* Don't want to pass this up */
15644 			return;
15645 
15646 		case DL_CAPABILITY_REQ:
15647 		case DL_CONTROL_REQ:
15648 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15649 			ill->ill_dlpi_capab_state = IDS_FAILED;
15650 			freemsg(mp);
15651 			return;
15652 		}
15653 		/*
15654 		 * Note the error for IOCTL completion (mp1 is set when
15655 		 * ready to complete ioctl). If ill_ifname_pending_err is
15656 		 * set, an error occured during plumbing (ill_ifname_pending),
15657 		 * so we want to report that error.
15658 		 *
15659 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15660 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15661 		 * expected to get errack'd if the driver doesn't support
15662 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15663 		 * if these error conditions are encountered.
15664 		 */
15665 		if (mp1 != NULL) {
15666 			if (ill->ill_ifname_pending_err != 0)  {
15667 				err = ill->ill_ifname_pending_err;
15668 				ill->ill_ifname_pending_err = 0;
15669 			} else {
15670 				err = dlea->dl_unix_errno ?
15671 				    dlea->dl_unix_errno : ENXIO;
15672 			}
15673 		/*
15674 		 * If we're plumbing an interface and an error hasn't already
15675 		 * been saved, set ill_ifname_pending_err to the error passed
15676 		 * up. Ignore the error if log is B_FALSE (see comment above).
15677 		 */
15678 		} else if (log && ill->ill_ifname_pending &&
15679 		    ill->ill_ifname_pending_err == 0) {
15680 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15681 			    dlea->dl_unix_errno : ENXIO;
15682 		}
15683 
15684 		if (log)
15685 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15686 			    dlea->dl_errno, dlea->dl_unix_errno);
15687 		break;
15688 	case DL_CAPABILITY_ACK:
15689 		/* Call a routine to handle this one. */
15690 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15691 		ill_capability_ack(ill, mp);
15692 
15693 		/*
15694 		 * If the ack is due to renegotiation, we will need to send
15695 		 * a new CAPABILITY_REQ to start the renegotiation.
15696 		 */
15697 		if (ill->ill_capab_reneg) {
15698 			ill->ill_capab_reneg = B_FALSE;
15699 			ill_capability_probe(ill);
15700 		}
15701 		break;
15702 	case DL_CONTROL_ACK:
15703 		/* We treat all of these as "fire and forget" */
15704 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15705 		break;
15706 	case DL_INFO_ACK:
15707 		/* Call a routine to handle this one. */
15708 		ill_dlpi_done(ill, DL_INFO_REQ);
15709 		ip_ll_subnet_defaults(ill, mp);
15710 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15711 		return;
15712 	case DL_BIND_ACK:
15713 		/*
15714 		 * We should have an IOCTL waiting on this unless
15715 		 * sent by ill_dl_phys, in which case just return
15716 		 */
15717 		ill_dlpi_done(ill, DL_BIND_REQ);
15718 		if (ill->ill_ifname_pending)
15719 			break;
15720 
15721 		if (!ioctl_aborted)
15722 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15723 		if (mp1 == NULL)
15724 			break;
15725 		/*
15726 		 * Because mp1 was added by ill_dl_up(), and it always
15727 		 * passes a valid connp, connp must be valid here.
15728 		 */
15729 		ASSERT(connp != NULL);
15730 		q = CONNP_TO_WQ(connp);
15731 
15732 		/*
15733 		 * We are exclusive. So nothing can change even after
15734 		 * we get the pending mp. If need be we can put it back
15735 		 * and restart, as in calling ipif_arp_up()  below.
15736 		 */
15737 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15738 
15739 		mutex_enter(&ill->ill_lock);
15740 
15741 		ill->ill_dl_up = 1;
15742 
15743 		if ((info = ill->ill_nic_event_info) != NULL) {
15744 			ip2dbg(("ip_rput_dlpi_writer: unexpected nic event %d "
15745 			    "attached for %s\n", info->hne_event,
15746 			    ill->ill_name));
15747 			if (info->hne_data != NULL)
15748 				kmem_free(info->hne_data, info->hne_datalen);
15749 			kmem_free(info, sizeof (hook_nic_event_t));
15750 		}
15751 
15752 		info = kmem_alloc(sizeof (hook_nic_event_t), KM_NOSLEEP);
15753 		if (info != NULL) {
15754 			info->hne_nic = ill->ill_phyint->phyint_hook_ifindex;
15755 			info->hne_lif = 0;
15756 			info->hne_event = NE_UP;
15757 			info->hne_data = NULL;
15758 			info->hne_datalen = 0;
15759 			info->hne_family = ill->ill_isv6 ?
15760 			    ipst->ips_ipv6_net_data : ipst->ips_ipv4_net_data;
15761 		} else
15762 			ip2dbg(("ip_rput_dlpi_writer: could not attach UP nic "
15763 			    "event information for %s (ENOMEM)\n",
15764 			    ill->ill_name));
15765 
15766 		ill->ill_nic_event_info = info;
15767 
15768 		mutex_exit(&ill->ill_lock);
15769 
15770 		/*
15771 		 * Now bring up the resolver; when that is complete, we'll
15772 		 * create IREs.  Note that we intentionally mirror what
15773 		 * ipif_up() would have done, because we got here by way of
15774 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15775 		 */
15776 		if (ill->ill_isv6) {
15777 			/*
15778 			 * v6 interfaces.
15779 			 * Unlike ARP which has to do another bind
15780 			 * and attach, once we get here we are
15781 			 * done with NDP. Except in the case of
15782 			 * ILLF_XRESOLV, in which case we send an
15783 			 * AR_INTERFACE_UP to the external resolver.
15784 			 * If all goes well, the ioctl will complete
15785 			 * in ip_rput(). If there's an error, we
15786 			 * complete it here.
15787 			 */
15788 			if ((err = ipif_ndp_up(ipif)) == 0) {
15789 				if (ill->ill_flags & ILLF_XRESOLV) {
15790 					mutex_enter(&connp->conn_lock);
15791 					mutex_enter(&ill->ill_lock);
15792 					success = ipsq_pending_mp_add(
15793 					    connp, ipif, q, mp1, 0);
15794 					mutex_exit(&ill->ill_lock);
15795 					mutex_exit(&connp->conn_lock);
15796 					if (success) {
15797 						err = ipif_resolver_up(ipif,
15798 						    Res_act_initial);
15799 						if (err == EINPROGRESS) {
15800 							freemsg(mp);
15801 							return;
15802 						}
15803 						ASSERT(err != 0);
15804 						mp1 = ipsq_pending_mp_get(ipsq,
15805 						    &connp);
15806 						ASSERT(mp1 != NULL);
15807 					} else {
15808 						/* conn has started closing */
15809 						err = EINTR;
15810 					}
15811 				} else { /* Non XRESOLV interface */
15812 					(void) ipif_resolver_up(ipif,
15813 					    Res_act_initial);
15814 					err = ipif_up_done_v6(ipif);
15815 				}
15816 			}
15817 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
15818 			/*
15819 			 * ARP and other v4 external resolvers.
15820 			 * Leave the pending mblk intact so that
15821 			 * the ioctl completes in ip_rput().
15822 			 */
15823 			mutex_enter(&connp->conn_lock);
15824 			mutex_enter(&ill->ill_lock);
15825 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
15826 			mutex_exit(&ill->ill_lock);
15827 			mutex_exit(&connp->conn_lock);
15828 			if (success) {
15829 				err = ipif_resolver_up(ipif, Res_act_initial);
15830 				if (err == EINPROGRESS) {
15831 					freemsg(mp);
15832 					return;
15833 				}
15834 				ASSERT(err != 0);
15835 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15836 			} else {
15837 				/* The conn has started closing */
15838 				err = EINTR;
15839 			}
15840 		} else {
15841 			/*
15842 			 * This one is complete. Reply to pending ioctl.
15843 			 */
15844 			(void) ipif_resolver_up(ipif, Res_act_initial);
15845 			err = ipif_up_done(ipif);
15846 		}
15847 
15848 		if ((err == 0) && (ill->ill_up_ipifs)) {
15849 			err = ill_up_ipifs(ill, q, mp1);
15850 			if (err == EINPROGRESS) {
15851 				freemsg(mp);
15852 				return;
15853 			}
15854 		}
15855 
15856 		if (ill->ill_up_ipifs) {
15857 			ill_group_cleanup(ill);
15858 		}
15859 
15860 		break;
15861 	case DL_NOTIFY_IND: {
15862 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
15863 		ire_t *ire;
15864 		boolean_t need_ire_walk_v4 = B_FALSE;
15865 		boolean_t need_ire_walk_v6 = B_FALSE;
15866 
15867 		switch (notify->dl_notification) {
15868 		case DL_NOTE_PHYS_ADDR:
15869 			err = ill_set_phys_addr(ill, mp);
15870 			break;
15871 
15872 		case DL_NOTE_FASTPATH_FLUSH:
15873 			ill_fastpath_flush(ill);
15874 			break;
15875 
15876 		case DL_NOTE_SDU_SIZE:
15877 			/*
15878 			 * Change the MTU size of the interface, of all
15879 			 * attached ipif's, and of all relevant ire's.  The
15880 			 * new value's a uint32_t at notify->dl_data.
15881 			 * Mtu change Vs. new ire creation - protocol below.
15882 			 *
15883 			 * a Mark the ipif as IPIF_CHANGING.
15884 			 * b Set the new mtu in the ipif.
15885 			 * c Change the ire_max_frag on all affected ires
15886 			 * d Unmark the IPIF_CHANGING
15887 			 *
15888 			 * To see how the protocol works, assume an interface
15889 			 * route is also being added simultaneously by
15890 			 * ip_rt_add and let 'ipif' be the ipif referenced by
15891 			 * the ire. If the ire is created before step a,
15892 			 * it will be cleaned up by step c. If the ire is
15893 			 * created after step d, it will see the new value of
15894 			 * ipif_mtu. Any attempt to create the ire between
15895 			 * steps a to d will fail because of the IPIF_CHANGING
15896 			 * flag. Note that ire_create() is passed a pointer to
15897 			 * the ipif_mtu, and not the value. During ire_add
15898 			 * under the bucket lock, the ire_max_frag of the
15899 			 * new ire being created is set from the ipif/ire from
15900 			 * which it is being derived.
15901 			 */
15902 			mutex_enter(&ill->ill_lock);
15903 			ill->ill_max_frag = (uint_t)notify->dl_data;
15904 
15905 			/*
15906 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
15907 			 * leave it alone
15908 			 */
15909 			if (ill->ill_mtu_userspecified) {
15910 				mutex_exit(&ill->ill_lock);
15911 				break;
15912 			}
15913 			ill->ill_max_mtu = ill->ill_max_frag;
15914 			if (ill->ill_isv6) {
15915 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
15916 					ill->ill_max_mtu = IPV6_MIN_MTU;
15917 			} else {
15918 				if (ill->ill_max_mtu < IP_MIN_MTU)
15919 					ill->ill_max_mtu = IP_MIN_MTU;
15920 			}
15921 			for (ipif = ill->ill_ipif; ipif != NULL;
15922 			    ipif = ipif->ipif_next) {
15923 				/*
15924 				 * Don't override the mtu if the user
15925 				 * has explicitly set it.
15926 				 */
15927 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
15928 					continue;
15929 				ipif->ipif_mtu = (uint_t)notify->dl_data;
15930 				if (ipif->ipif_isv6)
15931 					ire = ipif_to_ire_v6(ipif);
15932 				else
15933 					ire = ipif_to_ire(ipif);
15934 				if (ire != NULL) {
15935 					ire->ire_max_frag = ipif->ipif_mtu;
15936 					ire_refrele(ire);
15937 				}
15938 				if (ipif->ipif_flags & IPIF_UP) {
15939 					if (ill->ill_isv6)
15940 						need_ire_walk_v6 = B_TRUE;
15941 					else
15942 						need_ire_walk_v4 = B_TRUE;
15943 				}
15944 			}
15945 			mutex_exit(&ill->ill_lock);
15946 			if (need_ire_walk_v4)
15947 				ire_walk_v4(ill_mtu_change, (char *)ill,
15948 				    ALL_ZONES, ipst);
15949 			if (need_ire_walk_v6)
15950 				ire_walk_v6(ill_mtu_change, (char *)ill,
15951 				    ALL_ZONES, ipst);
15952 			break;
15953 		case DL_NOTE_LINK_UP:
15954 		case DL_NOTE_LINK_DOWN: {
15955 			/*
15956 			 * We are writer. ill / phyint / ipsq assocs stable.
15957 			 * The RUNNING flag reflects the state of the link.
15958 			 */
15959 			phyint_t *phyint = ill->ill_phyint;
15960 			uint64_t new_phyint_flags;
15961 			boolean_t changed = B_FALSE;
15962 			boolean_t went_up;
15963 
15964 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
15965 			mutex_enter(&phyint->phyint_lock);
15966 			new_phyint_flags = went_up ?
15967 			    phyint->phyint_flags | PHYI_RUNNING :
15968 			    phyint->phyint_flags & ~PHYI_RUNNING;
15969 			if (new_phyint_flags != phyint->phyint_flags) {
15970 				phyint->phyint_flags = new_phyint_flags;
15971 				changed = B_TRUE;
15972 			}
15973 			mutex_exit(&phyint->phyint_lock);
15974 			/*
15975 			 * ill_restart_dad handles the DAD restart and routing
15976 			 * socket notification logic.
15977 			 */
15978 			if (changed) {
15979 				ill_restart_dad(phyint->phyint_illv4, went_up);
15980 				ill_restart_dad(phyint->phyint_illv6, went_up);
15981 			}
15982 			break;
15983 		}
15984 		case DL_NOTE_PROMISC_ON_PHYS:
15985 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15986 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
15987 			mutex_enter(&ill->ill_lock);
15988 			ill->ill_promisc_on_phys = B_TRUE;
15989 			mutex_exit(&ill->ill_lock);
15990 			break;
15991 		case DL_NOTE_PROMISC_OFF_PHYS:
15992 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15993 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
15994 			mutex_enter(&ill->ill_lock);
15995 			ill->ill_promisc_on_phys = B_FALSE;
15996 			mutex_exit(&ill->ill_lock);
15997 			break;
15998 		case DL_NOTE_CAPAB_RENEG:
15999 			/*
16000 			 * Something changed on the driver side.
16001 			 * It wants us to renegotiate the capabilities
16002 			 * on this ill. One possible cause is the aggregation
16003 			 * interface under us where a port got added or
16004 			 * went away.
16005 			 *
16006 			 * If the capability negotiation is already done
16007 			 * or is in progress, reset the capabilities and
16008 			 * mark the ill's ill_capab_reneg to be B_TRUE,
16009 			 * so that when the ack comes back, we can start
16010 			 * the renegotiation process.
16011 			 *
16012 			 * Note that if ill_capab_reneg is already B_TRUE
16013 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
16014 			 * the capability resetting request has been sent
16015 			 * and the renegotiation has not been started yet;
16016 			 * nothing needs to be done in this case.
16017 			 */
16018 			if (ill->ill_dlpi_capab_state != IDS_UNKNOWN) {
16019 				ill_capability_reset(ill);
16020 				ill->ill_capab_reneg = B_TRUE;
16021 			}
16022 			break;
16023 		default:
16024 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16025 			    "type 0x%x for DL_NOTIFY_IND\n",
16026 			    notify->dl_notification));
16027 			break;
16028 		}
16029 
16030 		/*
16031 		 * As this is an asynchronous operation, we
16032 		 * should not call ill_dlpi_done
16033 		 */
16034 		break;
16035 	}
16036 	case DL_NOTIFY_ACK: {
16037 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16038 
16039 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16040 			ill->ill_note_link = 1;
16041 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16042 		break;
16043 	}
16044 	case DL_PHYS_ADDR_ACK: {
16045 		/*
16046 		 * As part of plumbing the interface via SIOCSLIFNAME,
16047 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16048 		 * whose answers we receive here.  As each answer is received,
16049 		 * we call ill_dlpi_done() to dispatch the next request as
16050 		 * we're processing the current one.  Once all answers have
16051 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16052 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16053 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16054 		 * available, but we know the ioctl is pending on ill_wq.)
16055 		 */
16056 		uint_t paddrlen, paddroff;
16057 
16058 		paddrreq = ill->ill_phys_addr_pend;
16059 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16060 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16061 
16062 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16063 		if (paddrreq == DL_IPV6_TOKEN) {
16064 			/*
16065 			 * bcopy to low-order bits of ill_token
16066 			 *
16067 			 * XXX Temporary hack - currently, all known tokens
16068 			 * are 64 bits, so I'll cheat for the moment.
16069 			 */
16070 			bcopy(mp->b_rptr + paddroff,
16071 			    &ill->ill_token.s6_addr32[2], paddrlen);
16072 			ill->ill_token_length = paddrlen;
16073 			break;
16074 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16075 			ASSERT(ill->ill_nd_lla_mp == NULL);
16076 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16077 			mp = NULL;
16078 			break;
16079 		}
16080 
16081 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16082 		ASSERT(ill->ill_phys_addr_mp == NULL);
16083 		if (!ill->ill_ifname_pending)
16084 			break;
16085 		ill->ill_ifname_pending = 0;
16086 		if (!ioctl_aborted)
16087 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16088 		if (mp1 != NULL) {
16089 			ASSERT(connp == NULL);
16090 			q = ill->ill_wq;
16091 		}
16092 		/*
16093 		 * If any error acks received during the plumbing sequence,
16094 		 * ill_ifname_pending_err will be set. Break out and send up
16095 		 * the error to the pending ioctl.
16096 		 */
16097 		if (ill->ill_ifname_pending_err != 0) {
16098 			err = ill->ill_ifname_pending_err;
16099 			ill->ill_ifname_pending_err = 0;
16100 			break;
16101 		}
16102 
16103 		ill->ill_phys_addr_mp = mp;
16104 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16105 		mp = NULL;
16106 
16107 		/*
16108 		 * If paddrlen is zero, the DLPI provider doesn't support
16109 		 * physical addresses.  The other two tests were historical
16110 		 * workarounds for bugs in our former PPP implementation, but
16111 		 * now other things have grown dependencies on them -- e.g.,
16112 		 * the tun module specifies a dl_addr_length of zero in its
16113 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16114 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16115 		 * but only after careful testing ensures that all dependent
16116 		 * broken DLPI providers have been fixed.
16117 		 */
16118 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16119 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16120 			ill->ill_phys_addr = NULL;
16121 		} else if (paddrlen != ill->ill_phys_addr_length) {
16122 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16123 			    paddrlen, ill->ill_phys_addr_length));
16124 			err = EINVAL;
16125 			break;
16126 		}
16127 
16128 		if (ill->ill_nd_lla_mp == NULL) {
16129 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16130 				err = ENOMEM;
16131 				break;
16132 			}
16133 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16134 		}
16135 
16136 		/*
16137 		 * Set the interface token.  If the zeroth interface address
16138 		 * is unspecified, then set it to the link local address.
16139 		 */
16140 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16141 			(void) ill_setdefaulttoken(ill);
16142 
16143 		ASSERT(ill->ill_ipif->ipif_id == 0);
16144 		if (ipif != NULL &&
16145 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16146 			(void) ipif_setlinklocal(ipif);
16147 		}
16148 		break;
16149 	}
16150 	case DL_OK_ACK:
16151 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16152 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
16153 		    dloa->dl_correct_primitive));
16154 		switch (dloa->dl_correct_primitive) {
16155 		case DL_PROMISCON_REQ:
16156 		case DL_PROMISCOFF_REQ:
16157 		case DL_ENABMULTI_REQ:
16158 		case DL_DISABMULTI_REQ:
16159 		case DL_UNBIND_REQ:
16160 		case DL_ATTACH_REQ:
16161 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16162 			break;
16163 		}
16164 		break;
16165 	default:
16166 		break;
16167 	}
16168 
16169 	freemsg(mp);
16170 	if (mp1 != NULL) {
16171 		/*
16172 		 * The operation must complete without EINPROGRESS
16173 		 * since ipsq_pending_mp_get() has removed the mblk
16174 		 * from ipsq_pending_mp.  Otherwise, the operation
16175 		 * will be stuck forever in the ipsq.
16176 		 */
16177 		ASSERT(err != EINPROGRESS);
16178 
16179 		switch (ipsq->ipsq_current_ioctl) {
16180 		case 0:
16181 			ipsq_current_finish(ipsq);
16182 			break;
16183 
16184 		case SIOCLIFADDIF:
16185 		case SIOCSLIFNAME:
16186 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16187 			break;
16188 
16189 		default:
16190 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16191 			break;
16192 		}
16193 	}
16194 }
16195 
16196 /*
16197  * ip_rput_other is called by ip_rput to handle messages modifying the global
16198  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16199  */
16200 /* ARGSUSED */
16201 void
16202 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16203 {
16204 	ill_t		*ill;
16205 	struct iocblk	*iocp;
16206 	mblk_t		*mp1;
16207 	conn_t		*connp = NULL;
16208 
16209 	ip1dbg(("ip_rput_other "));
16210 	ill = (ill_t *)q->q_ptr;
16211 	/*
16212 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16213 	 * in which case ipsq is NULL.
16214 	 */
16215 	if (ipsq != NULL) {
16216 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16217 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16218 	}
16219 
16220 	switch (mp->b_datap->db_type) {
16221 	case M_ERROR:
16222 	case M_HANGUP:
16223 		/*
16224 		 * The device has a problem.  We force the ILL down.  It can
16225 		 * be brought up again manually using SIOCSIFFLAGS (via
16226 		 * ifconfig or equivalent).
16227 		 */
16228 		ASSERT(ipsq != NULL);
16229 		if (mp->b_rptr < mp->b_wptr)
16230 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16231 		if (ill->ill_error == 0)
16232 			ill->ill_error = ENXIO;
16233 		if (!ill_down_start(q, mp))
16234 			return;
16235 		ipif_all_down_tail(ipsq, q, mp, NULL);
16236 		break;
16237 	case M_IOCACK:
16238 		iocp = (struct iocblk *)mp->b_rptr;
16239 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16240 		switch (iocp->ioc_cmd) {
16241 		case SIOCSTUNPARAM:
16242 		case OSIOCSTUNPARAM:
16243 			ASSERT(ipsq != NULL);
16244 			/*
16245 			 * Finish socket ioctl passed through to tun.
16246 			 * We should have an IOCTL waiting on this.
16247 			 */
16248 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16249 			if (ill->ill_isv6) {
16250 				struct iftun_req *ta;
16251 
16252 				/*
16253 				 * if a source or destination is
16254 				 * being set, try and set the link
16255 				 * local address for the tunnel
16256 				 */
16257 				ta = (struct iftun_req *)mp->b_cont->
16258 				    b_cont->b_rptr;
16259 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16260 					ipif_set_tun_llink(ill, ta);
16261 				}
16262 
16263 			}
16264 			if (mp1 != NULL) {
16265 				/*
16266 				 * Now copy back the b_next/b_prev used by
16267 				 * mi code for the mi_copy* functions.
16268 				 * See ip_sioctl_tunparam() for the reason.
16269 				 * Also protect against missing b_cont.
16270 				 */
16271 				if (mp->b_cont != NULL) {
16272 					mp->b_cont->b_next =
16273 					    mp1->b_cont->b_next;
16274 					mp->b_cont->b_prev =
16275 					    mp1->b_cont->b_prev;
16276 				}
16277 				inet_freemsg(mp1);
16278 				ASSERT(connp != NULL);
16279 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16280 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16281 			} else {
16282 				ASSERT(connp == NULL);
16283 				putnext(q, mp);
16284 			}
16285 			break;
16286 		case SIOCGTUNPARAM:
16287 		case OSIOCGTUNPARAM:
16288 			/*
16289 			 * This is really M_IOCDATA from the tunnel driver.
16290 			 * convert back and complete the ioctl.
16291 			 * We should have an IOCTL waiting on this.
16292 			 */
16293 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16294 			if (mp1) {
16295 				/*
16296 				 * Now copy back the b_next/b_prev used by
16297 				 * mi code for the mi_copy* functions.
16298 				 * See ip_sioctl_tunparam() for the reason.
16299 				 * Also protect against missing b_cont.
16300 				 */
16301 				if (mp->b_cont != NULL) {
16302 					mp->b_cont->b_next =
16303 					    mp1->b_cont->b_next;
16304 					mp->b_cont->b_prev =
16305 					    mp1->b_cont->b_prev;
16306 				}
16307 				inet_freemsg(mp1);
16308 				if (iocp->ioc_error == 0)
16309 					mp->b_datap->db_type = M_IOCDATA;
16310 				ASSERT(connp != NULL);
16311 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16312 				    iocp->ioc_error, COPYOUT, NULL);
16313 			} else {
16314 				ASSERT(connp == NULL);
16315 				putnext(q, mp);
16316 			}
16317 			break;
16318 		default:
16319 			break;
16320 		}
16321 		break;
16322 	case M_IOCNAK:
16323 		iocp = (struct iocblk *)mp->b_rptr;
16324 
16325 		switch (iocp->ioc_cmd) {
16326 		int mode;
16327 
16328 		case DL_IOC_HDR_INFO:
16329 			/*
16330 			 * If this was the first attempt turn of the
16331 			 * fastpath probing.
16332 			 */
16333 			mutex_enter(&ill->ill_lock);
16334 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16335 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16336 				mutex_exit(&ill->ill_lock);
16337 				ill_fastpath_nack(ill);
16338 				ip1dbg(("ip_rput: DLPI fastpath off on "
16339 				    "interface %s\n",
16340 				    ill->ill_name));
16341 			} else {
16342 				mutex_exit(&ill->ill_lock);
16343 			}
16344 			freemsg(mp);
16345 			break;
16346 		case SIOCSTUNPARAM:
16347 		case OSIOCSTUNPARAM:
16348 			ASSERT(ipsq != NULL);
16349 			/*
16350 			 * Finish socket ioctl passed through to tun
16351 			 * We should have an IOCTL waiting on this.
16352 			 */
16353 			/* FALLTHRU */
16354 		case SIOCGTUNPARAM:
16355 		case OSIOCGTUNPARAM:
16356 			/*
16357 			 * This is really M_IOCDATA from the tunnel driver.
16358 			 * convert back and complete the ioctl.
16359 			 * We should have an IOCTL waiting on this.
16360 			 */
16361 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16362 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16363 				mp1 = ill_pending_mp_get(ill, &connp,
16364 				    iocp->ioc_id);
16365 				mode = COPYOUT;
16366 				ipsq = NULL;
16367 			} else {
16368 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16369 				mode = NO_COPYOUT;
16370 			}
16371 			if (mp1 != NULL) {
16372 				/*
16373 				 * Now copy back the b_next/b_prev used by
16374 				 * mi code for the mi_copy* functions.
16375 				 * See ip_sioctl_tunparam() for the reason.
16376 				 * Also protect against missing b_cont.
16377 				 */
16378 				if (mp->b_cont != NULL) {
16379 					mp->b_cont->b_next =
16380 					    mp1->b_cont->b_next;
16381 					mp->b_cont->b_prev =
16382 					    mp1->b_cont->b_prev;
16383 				}
16384 				inet_freemsg(mp1);
16385 				if (iocp->ioc_error == 0)
16386 					iocp->ioc_error = EINVAL;
16387 				ASSERT(connp != NULL);
16388 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16389 				    iocp->ioc_error, mode, ipsq);
16390 			} else {
16391 				ASSERT(connp == NULL);
16392 				putnext(q, mp);
16393 			}
16394 			break;
16395 		default:
16396 			break;
16397 		}
16398 	default:
16399 		break;
16400 	}
16401 }
16402 
16403 /*
16404  * NOTE : This function does not ire_refrele the ire argument passed in.
16405  *
16406  * IPQoS notes
16407  * IP policy is invoked twice for a forwarded packet, once on the read side
16408  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16409  * enabled. An additional parameter, in_ill, has been added for this purpose.
16410  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16411  * because ip_mroute drops this information.
16412  *
16413  */
16414 void
16415 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16416 {
16417 	uint32_t	old_pkt_len;
16418 	uint32_t	pkt_len;
16419 	queue_t	*q;
16420 	uint32_t	sum;
16421 #define	rptr	((uchar_t *)ipha)
16422 	uint32_t	max_frag;
16423 	uint32_t	ill_index;
16424 	ill_t		*out_ill;
16425 	mib2_ipIfStatsEntry_t *mibptr;
16426 	ip_stack_t	*ipst = ((ill_t *)(ire->ire_stq->q_ptr))->ill_ipst;
16427 
16428 	/* Get the ill_index of the incoming ILL */
16429 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16430 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16431 
16432 	/* Initiate Read side IPPF processing */
16433 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16434 		ip_process(IPP_FWD_IN, &mp, ill_index);
16435 		if (mp == NULL) {
16436 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16437 			    "during IPPF processing\n"));
16438 			return;
16439 		}
16440 	}
16441 
16442 	/* Adjust the checksum to reflect the ttl decrement. */
16443 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16444 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16445 
16446 	if (ipha->ipha_ttl-- <= 1) {
16447 		if (ip_csum_hdr(ipha)) {
16448 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16449 			goto drop_pkt;
16450 		}
16451 		/*
16452 		 * Note: ire_stq this will be NULL for multicast
16453 		 * datagrams using the long path through arp (the IRE
16454 		 * is not an IRE_CACHE). This should not cause
16455 		 * problems since we don't generate ICMP errors for
16456 		 * multicast packets.
16457 		 */
16458 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16459 		q = ire->ire_stq;
16460 		if (q != NULL) {
16461 			/* Sent by forwarding path, and router is global zone */
16462 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16463 			    GLOBAL_ZONEID, ipst);
16464 		} else
16465 			freemsg(mp);
16466 		return;
16467 	}
16468 
16469 	/*
16470 	 * Don't forward if the interface is down
16471 	 */
16472 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16473 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16474 		ip2dbg(("ip_rput_forward:interface is down\n"));
16475 		goto drop_pkt;
16476 	}
16477 
16478 	/* Get the ill_index of the outgoing ILL */
16479 	out_ill = ire_to_ill(ire);
16480 	ill_index = out_ill->ill_phyint->phyint_ifindex;
16481 
16482 	DTRACE_PROBE4(ip4__forwarding__start,
16483 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16484 
16485 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16486 	    ipst->ips_ipv4firewall_forwarding,
16487 	    in_ill, out_ill, ipha, mp, mp, ipst);
16488 
16489 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16490 
16491 	if (mp == NULL)
16492 		return;
16493 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16494 
16495 	if (is_system_labeled()) {
16496 		mblk_t *mp1;
16497 
16498 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16499 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16500 			goto drop_pkt;
16501 		}
16502 		/* Size may have changed */
16503 		mp = mp1;
16504 		ipha = (ipha_t *)mp->b_rptr;
16505 		pkt_len = ntohs(ipha->ipha_length);
16506 	}
16507 
16508 	/* Check if there are options to update */
16509 	if (!IS_SIMPLE_IPH(ipha)) {
16510 		if (ip_csum_hdr(ipha)) {
16511 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16512 			goto drop_pkt;
16513 		}
16514 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16515 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16516 			return;
16517 		}
16518 
16519 		ipha->ipha_hdr_checksum = 0;
16520 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16521 	}
16522 	max_frag = ire->ire_max_frag;
16523 	if (pkt_len > max_frag) {
16524 		/*
16525 		 * It needs fragging on its way out.  We haven't
16526 		 * verified the header checksum yet.  Since we
16527 		 * are going to put a surely good checksum in the
16528 		 * outgoing header, we have to make sure that it
16529 		 * was good coming in.
16530 		 */
16531 		if (ip_csum_hdr(ipha)) {
16532 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16533 			goto drop_pkt;
16534 		}
16535 		/* Initiate Write side IPPF processing */
16536 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16537 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16538 			if (mp == NULL) {
16539 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16540 				    " during IPPF processing\n"));
16541 				return;
16542 			}
16543 		}
16544 		/*
16545 		 * Handle labeled packet resizing.
16546 		 *
16547 		 * If we have added a label, inform ip_wput_frag() of its
16548 		 * effect on the MTU for ICMP messages.
16549 		 */
16550 		if (pkt_len > old_pkt_len) {
16551 			uint32_t secopt_size;
16552 
16553 			secopt_size = pkt_len - old_pkt_len;
16554 			if (secopt_size < max_frag)
16555 				max_frag -= secopt_size;
16556 		}
16557 
16558 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
16559 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16560 		return;
16561 	}
16562 
16563 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16564 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16565 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16566 	    ipst->ips_ipv4firewall_physical_out,
16567 	    NULL, out_ill, ipha, mp, mp, ipst);
16568 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16569 	if (mp == NULL)
16570 		return;
16571 
16572 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16573 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16574 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16575 	/* ip_xmit_v4 always consumes the packet */
16576 	return;
16577 
16578 drop_pkt:;
16579 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16580 	freemsg(mp);
16581 #undef	rptr
16582 }
16583 
16584 void
16585 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16586 {
16587 	ire_t	*ire;
16588 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16589 
16590 	ASSERT(!ipif->ipif_isv6);
16591 	/*
16592 	 * Find an IRE which matches the destination and the outgoing
16593 	 * queue in the cache table. All we need is an IRE_CACHE which
16594 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16595 	 * then it is enough to have some IRE_CACHE in the group.
16596 	 */
16597 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16598 		dst = ipif->ipif_pp_dst_addr;
16599 
16600 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16601 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR, ipst);
16602 	if (ire == NULL) {
16603 		/*
16604 		 * Mark this packet to make it be delivered to
16605 		 * ip_rput_forward after the new ire has been
16606 		 * created.
16607 		 */
16608 		mp->b_prev = NULL;
16609 		mp->b_next = mp;
16610 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16611 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16612 	} else {
16613 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16614 		IRE_REFRELE(ire);
16615 	}
16616 }
16617 
16618 /* Update any source route, record route or timestamp options */
16619 static int
16620 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16621 {
16622 	ipoptp_t	opts;
16623 	uchar_t		*opt;
16624 	uint8_t		optval;
16625 	uint8_t		optlen;
16626 	ipaddr_t	dst;
16627 	uint32_t	ts;
16628 	ire_t		*dst_ire = NULL;
16629 	ire_t		*tmp_ire = NULL;
16630 	timestruc_t	now;
16631 
16632 	ip2dbg(("ip_rput_forward_options\n"));
16633 	dst = ipha->ipha_dst;
16634 	for (optval = ipoptp_first(&opts, ipha);
16635 	    optval != IPOPT_EOL;
16636 	    optval = ipoptp_next(&opts)) {
16637 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16638 		opt = opts.ipoptp_cur;
16639 		optlen = opts.ipoptp_len;
16640 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16641 		    optval, opts.ipoptp_len));
16642 		switch (optval) {
16643 			uint32_t off;
16644 		case IPOPT_SSRR:
16645 		case IPOPT_LSRR:
16646 			/* Check if adminstratively disabled */
16647 			if (!ipst->ips_ip_forward_src_routed) {
16648 				if (ire->ire_stq != NULL) {
16649 					/*
16650 					 * Sent by forwarding path, and router
16651 					 * is global zone
16652 					 */
16653 					icmp_unreachable(ire->ire_stq, mp,
16654 					    ICMP_SOURCE_ROUTE_FAILED,
16655 					    GLOBAL_ZONEID, ipst);
16656 				} else {
16657 					ip0dbg(("ip_rput_forward_options: "
16658 					    "unable to send unreach\n"));
16659 					freemsg(mp);
16660 				}
16661 				return (-1);
16662 			}
16663 
16664 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16665 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16666 			if (dst_ire == NULL) {
16667 				/*
16668 				 * Must be partial since ip_rput_options
16669 				 * checked for strict.
16670 				 */
16671 				break;
16672 			}
16673 			off = opt[IPOPT_OFFSET];
16674 			off--;
16675 		redo_srr:
16676 			if (optlen < IP_ADDR_LEN ||
16677 			    off > optlen - IP_ADDR_LEN) {
16678 				/* End of source route */
16679 				ip1dbg((
16680 				    "ip_rput_forward_options: end of SR\n"));
16681 				ire_refrele(dst_ire);
16682 				break;
16683 			}
16684 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16685 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16686 			    IP_ADDR_LEN);
16687 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16688 			    ntohl(dst)));
16689 
16690 			/*
16691 			 * Check if our address is present more than
16692 			 * once as consecutive hops in source route.
16693 			 */
16694 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16695 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16696 			if (tmp_ire != NULL) {
16697 				ire_refrele(tmp_ire);
16698 				off += IP_ADDR_LEN;
16699 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16700 				goto redo_srr;
16701 			}
16702 			ipha->ipha_dst = dst;
16703 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16704 			ire_refrele(dst_ire);
16705 			break;
16706 		case IPOPT_RR:
16707 			off = opt[IPOPT_OFFSET];
16708 			off--;
16709 			if (optlen < IP_ADDR_LEN ||
16710 			    off > optlen - IP_ADDR_LEN) {
16711 				/* No more room - ignore */
16712 				ip1dbg((
16713 				    "ip_rput_forward_options: end of RR\n"));
16714 				break;
16715 			}
16716 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16717 			    IP_ADDR_LEN);
16718 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16719 			break;
16720 		case IPOPT_TS:
16721 			/* Insert timestamp if there is room */
16722 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16723 			case IPOPT_TS_TSONLY:
16724 				off = IPOPT_TS_TIMELEN;
16725 				break;
16726 			case IPOPT_TS_PRESPEC:
16727 			case IPOPT_TS_PRESPEC_RFC791:
16728 				/* Verify that the address matched */
16729 				off = opt[IPOPT_OFFSET] - 1;
16730 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16731 				dst_ire = ire_ctable_lookup(dst, 0,
16732 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16733 				    MATCH_IRE_TYPE, ipst);
16734 				if (dst_ire == NULL) {
16735 					/* Not for us */
16736 					break;
16737 				}
16738 				ire_refrele(dst_ire);
16739 				/* FALLTHRU */
16740 			case IPOPT_TS_TSANDADDR:
16741 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16742 				break;
16743 			default:
16744 				/*
16745 				 * ip_*put_options should have already
16746 				 * dropped this packet.
16747 				 */
16748 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16749 				    "unknown IT - bug in ip_rput_options?\n");
16750 				return (0);	/* Keep "lint" happy */
16751 			}
16752 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16753 				/* Increase overflow counter */
16754 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16755 				opt[IPOPT_POS_OV_FLG] =
16756 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16757 				    (off << 4));
16758 				break;
16759 			}
16760 			off = opt[IPOPT_OFFSET] - 1;
16761 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16762 			case IPOPT_TS_PRESPEC:
16763 			case IPOPT_TS_PRESPEC_RFC791:
16764 			case IPOPT_TS_TSANDADDR:
16765 				bcopy(&ire->ire_src_addr,
16766 				    (char *)opt + off, IP_ADDR_LEN);
16767 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16768 				/* FALLTHRU */
16769 			case IPOPT_TS_TSONLY:
16770 				off = opt[IPOPT_OFFSET] - 1;
16771 				/* Compute # of milliseconds since midnight */
16772 				gethrestime(&now);
16773 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16774 				    now.tv_nsec / (NANOSEC / MILLISEC);
16775 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16776 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16777 				break;
16778 			}
16779 			break;
16780 		}
16781 	}
16782 	return (0);
16783 }
16784 
16785 /*
16786  * This is called after processing at least one of AH/ESP headers.
16787  *
16788  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16789  * the actual, physical interface on which the packet was received,
16790  * but, when ip_strict_dst_multihoming is set to 1, could be the
16791  * interface which had the ipha_dst configured when the packet went
16792  * through ip_rput. The ill_index corresponding to the recv_ill
16793  * is saved in ipsec_in_rill_index
16794  *
16795  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
16796  * cannot assume "ire" points to valid data for any IPv6 cases.
16797  */
16798 void
16799 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16800 {
16801 	mblk_t *mp;
16802 	ipaddr_t dst;
16803 	in6_addr_t *v6dstp;
16804 	ipha_t *ipha;
16805 	ip6_t *ip6h;
16806 	ipsec_in_t *ii;
16807 	boolean_t ill_need_rele = B_FALSE;
16808 	boolean_t rill_need_rele = B_FALSE;
16809 	boolean_t ire_need_rele = B_FALSE;
16810 	netstack_t	*ns;
16811 	ip_stack_t	*ipst;
16812 
16813 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16814 	ASSERT(ii->ipsec_in_ill_index != 0);
16815 	ns = ii->ipsec_in_ns;
16816 	ASSERT(ii->ipsec_in_ns != NULL);
16817 	ipst = ns->netstack_ip;
16818 
16819 	mp = ipsec_mp->b_cont;
16820 	ASSERT(mp != NULL);
16821 
16822 
16823 	if (ill == NULL) {
16824 		ASSERT(recv_ill == NULL);
16825 		/*
16826 		 * We need to get the original queue on which ip_rput_local
16827 		 * or ip_rput_data_v6 was called.
16828 		 */
16829 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16830 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
16831 		ill_need_rele = B_TRUE;
16832 
16833 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16834 			recv_ill = ill_lookup_on_ifindex(
16835 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16836 			    NULL, NULL, NULL, NULL, ipst);
16837 			rill_need_rele = B_TRUE;
16838 		} else {
16839 			recv_ill = ill;
16840 		}
16841 
16842 		if ((ill == NULL) || (recv_ill == NULL)) {
16843 			ip0dbg(("ip_fanout_proto_again: interface "
16844 			    "disappeared\n"));
16845 			if (ill != NULL)
16846 				ill_refrele(ill);
16847 			if (recv_ill != NULL)
16848 				ill_refrele(recv_ill);
16849 			freemsg(ipsec_mp);
16850 			return;
16851 		}
16852 	}
16853 
16854 	ASSERT(ill != NULL && recv_ill != NULL);
16855 
16856 	if (mp->b_datap->db_type == M_CTL) {
16857 		/*
16858 		 * AH/ESP is returning the ICMP message after
16859 		 * removing their headers. Fanout again till
16860 		 * it gets to the right protocol.
16861 		 */
16862 		if (ii->ipsec_in_v4) {
16863 			icmph_t *icmph;
16864 			int iph_hdr_length;
16865 			int hdr_length;
16866 
16867 			ipha = (ipha_t *)mp->b_rptr;
16868 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
16869 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
16870 			ipha = (ipha_t *)&icmph[1];
16871 			hdr_length = IPH_HDR_LENGTH(ipha);
16872 			/*
16873 			 * icmp_inbound_error_fanout may need to do pullupmsg.
16874 			 * Reset the type to M_DATA.
16875 			 */
16876 			mp->b_datap->db_type = M_DATA;
16877 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
16878 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
16879 			    B_FALSE, ill, ii->ipsec_in_zoneid);
16880 		} else {
16881 			icmp6_t *icmp6;
16882 			int hdr_length;
16883 
16884 			ip6h = (ip6_t *)mp->b_rptr;
16885 			/* Don't call hdr_length_v6() unless you have to. */
16886 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
16887 				hdr_length = ip_hdr_length_v6(mp, ip6h);
16888 			else
16889 				hdr_length = IPV6_HDR_LEN;
16890 
16891 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
16892 			/*
16893 			 * icmp_inbound_error_fanout_v6 may need to do
16894 			 * pullupmsg.  Reset the type to M_DATA.
16895 			 */
16896 			mp->b_datap->db_type = M_DATA;
16897 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
16898 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
16899 		}
16900 		if (ill_need_rele)
16901 			ill_refrele(ill);
16902 		if (rill_need_rele)
16903 			ill_refrele(recv_ill);
16904 		return;
16905 	}
16906 
16907 	if (ii->ipsec_in_v4) {
16908 		ipha = (ipha_t *)mp->b_rptr;
16909 		dst = ipha->ipha_dst;
16910 		if (CLASSD(dst)) {
16911 			/*
16912 			 * Multicast has to be delivered to all streams.
16913 			 */
16914 			dst = INADDR_BROADCAST;
16915 		}
16916 
16917 		if (ire == NULL) {
16918 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
16919 			    MBLK_GETLABEL(mp), ipst);
16920 			if (ire == NULL) {
16921 				if (ill_need_rele)
16922 					ill_refrele(ill);
16923 				if (rill_need_rele)
16924 					ill_refrele(recv_ill);
16925 				ip1dbg(("ip_fanout_proto_again: "
16926 				    "IRE not found"));
16927 				freemsg(ipsec_mp);
16928 				return;
16929 			}
16930 			ire_need_rele = B_TRUE;
16931 		}
16932 
16933 		switch (ipha->ipha_protocol) {
16934 			case IPPROTO_UDP:
16935 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
16936 				    recv_ill);
16937 				if (ire_need_rele)
16938 					ire_refrele(ire);
16939 				break;
16940 			case IPPROTO_TCP:
16941 				if (!ire_need_rele)
16942 					IRE_REFHOLD(ire);
16943 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
16944 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
16945 				IRE_REFRELE(ire);
16946 				if (mp != NULL)
16947 					squeue_enter_chain(GET_SQUEUE(mp), mp,
16948 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
16949 				break;
16950 			case IPPROTO_SCTP:
16951 				if (!ire_need_rele)
16952 					IRE_REFHOLD(ire);
16953 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
16954 				    ipsec_mp, 0, ill->ill_rq, dst);
16955 				break;
16956 			default:
16957 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
16958 				    recv_ill, B_FALSE);
16959 				if (ire_need_rele)
16960 					ire_refrele(ire);
16961 				break;
16962 		}
16963 	} else {
16964 		uint32_t rput_flags = 0;
16965 
16966 		ip6h = (ip6_t *)mp->b_rptr;
16967 		v6dstp = &ip6h->ip6_dst;
16968 		/*
16969 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
16970 		 * address.
16971 		 *
16972 		 * Currently, we don't store that state in the IPSEC_IN
16973 		 * message, and we may need to.
16974 		 */
16975 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
16976 		    IP6_IN_LLMCAST : 0);
16977 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
16978 		    NULL, NULL);
16979 	}
16980 	if (ill_need_rele)
16981 		ill_refrele(ill);
16982 	if (rill_need_rele)
16983 		ill_refrele(recv_ill);
16984 }
16985 
16986 /*
16987  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
16988  * returns 'true' if there are still fragments left on the queue, in
16989  * which case we restart the timer.
16990  */
16991 void
16992 ill_frag_timer(void *arg)
16993 {
16994 	ill_t	*ill = (ill_t *)arg;
16995 	boolean_t frag_pending;
16996 	ip_stack_t	*ipst = ill->ill_ipst;
16997 
16998 	mutex_enter(&ill->ill_lock);
16999 	ASSERT(!ill->ill_fragtimer_executing);
17000 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17001 		ill->ill_frag_timer_id = 0;
17002 		mutex_exit(&ill->ill_lock);
17003 		return;
17004 	}
17005 	ill->ill_fragtimer_executing = 1;
17006 	mutex_exit(&ill->ill_lock);
17007 
17008 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
17009 
17010 	/*
17011 	 * Restart the timer, if we have fragments pending or if someone
17012 	 * wanted us to be scheduled again.
17013 	 */
17014 	mutex_enter(&ill->ill_lock);
17015 	ill->ill_fragtimer_executing = 0;
17016 	ill->ill_frag_timer_id = 0;
17017 	if (frag_pending || ill->ill_fragtimer_needrestart)
17018 		ill_frag_timer_start(ill);
17019 	mutex_exit(&ill->ill_lock);
17020 }
17021 
17022 void
17023 ill_frag_timer_start(ill_t *ill)
17024 {
17025 	ip_stack_t	*ipst = ill->ill_ipst;
17026 
17027 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17028 
17029 	/* If the ill is closing or opening don't proceed */
17030 	if (ill->ill_state_flags & ILL_CONDEMNED)
17031 		return;
17032 
17033 	if (ill->ill_fragtimer_executing) {
17034 		/*
17035 		 * ill_frag_timer is currently executing. Just record the
17036 		 * the fact that we want the timer to be restarted.
17037 		 * ill_frag_timer will post a timeout before it returns,
17038 		 * ensuring it will be called again.
17039 		 */
17040 		ill->ill_fragtimer_needrestart = 1;
17041 		return;
17042 	}
17043 
17044 	if (ill->ill_frag_timer_id == 0) {
17045 		/*
17046 		 * The timer is neither running nor is the timeout handler
17047 		 * executing. Post a timeout so that ill_frag_timer will be
17048 		 * called
17049 		 */
17050 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17051 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
17052 		ill->ill_fragtimer_needrestart = 0;
17053 	}
17054 }
17055 
17056 /*
17057  * This routine is needed for loopback when forwarding multicasts.
17058  *
17059  * IPQoS Notes:
17060  * IPPF processing is done in fanout routines.
17061  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17062  * processing for IPsec packets is done when it comes back in clear.
17063  * NOTE : The callers of this function need to do the ire_refrele for the
17064  *	  ire that is being passed in.
17065  */
17066 void
17067 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17068     ill_t *recv_ill, boolean_t esp_in_udp_packet)
17069 {
17070 	ill_t	*ill = (ill_t *)q->q_ptr;
17071 	uint32_t	sum;
17072 	uint32_t	u1;
17073 	uint32_t	u2;
17074 	int		hdr_length;
17075 	boolean_t	mctl_present;
17076 	mblk_t		*first_mp = mp;
17077 	mblk_t		*hada_mp = NULL;
17078 	ipha_t		*inner_ipha;
17079 	ip_stack_t	*ipst;
17080 
17081 	ASSERT(recv_ill != NULL);
17082 	ipst = recv_ill->ill_ipst;
17083 
17084 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17085 	    "ip_rput_locl_start: q %p", q);
17086 
17087 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17088 	ASSERT(ill != NULL);
17089 
17090 
17091 #define	rptr	((uchar_t *)ipha)
17092 #define	iphs	((uint16_t *)ipha)
17093 
17094 	/*
17095 	 * no UDP or TCP packet should come here anymore.
17096 	 */
17097 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
17098 	    ipha->ipha_protocol != IPPROTO_UDP);
17099 
17100 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17101 	if (mctl_present &&
17102 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17103 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17104 
17105 		/*
17106 		 * It's an IPsec accelerated packet.
17107 		 * Keep a pointer to the data attributes around until
17108 		 * we allocate the ipsec_info_t.
17109 		 */
17110 		IPSECHW_DEBUG(IPSECHW_PKT,
17111 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17112 		hada_mp = first_mp;
17113 		hada_mp->b_cont = NULL;
17114 		/*
17115 		 * Since it is accelerated, it comes directly from
17116 		 * the ill and the data attributes is followed by
17117 		 * the packet data.
17118 		 */
17119 		ASSERT(mp->b_datap->db_type != M_CTL);
17120 		first_mp = mp;
17121 		mctl_present = B_FALSE;
17122 	}
17123 
17124 	/*
17125 	 * IF M_CTL is not present, then ipsec_in_is_secure
17126 	 * should return B_TRUE. There is a case where loopback
17127 	 * packets has an M_CTL in the front with all the
17128 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17129 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17130 	 * packets never comes here, it is safe to ASSERT the
17131 	 * following.
17132 	 */
17133 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17134 
17135 	/*
17136 	 * Also, we should never have an mctl_present if this is an
17137 	 * ESP-in-UDP packet.
17138 	 */
17139 	ASSERT(!mctl_present || !esp_in_udp_packet);
17140 
17141 
17142 	/* u1 is # words of IP options */
17143 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17144 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17145 
17146 	if (u1 || (!esp_in_udp_packet && !mctl_present)) {
17147 		if (u1) {
17148 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17149 				if (hada_mp != NULL)
17150 					freemsg(hada_mp);
17151 				return;
17152 			}
17153 		} else {
17154 			/* Check the IP header checksum.  */
17155 #define	uph	((uint16_t *)ipha)
17156 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17157 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17158 #undef  uph
17159 			/* finish doing IP checksum */
17160 			sum = (sum & 0xFFFF) + (sum >> 16);
17161 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17162 			if (sum && sum != 0xFFFF) {
17163 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17164 				goto drop_pkt;
17165 			}
17166 		}
17167 	}
17168 
17169 	/*
17170 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17171 	 * might be called more than once for secure packets, count only
17172 	 * the first time.
17173 	 */
17174 	if (!mctl_present) {
17175 		UPDATE_IB_PKT_COUNT(ire);
17176 		ire->ire_last_used_time = lbolt;
17177 	}
17178 
17179 	/* Check for fragmentation offset. */
17180 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17181 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17182 	if (u1) {
17183 		/*
17184 		 * We re-assemble fragments before we do the AH/ESP
17185 		 * processing. Thus, M_CTL should not be present
17186 		 * while we are re-assembling.
17187 		 */
17188 		ASSERT(!mctl_present);
17189 		ASSERT(first_mp == mp);
17190 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
17191 			return;
17192 		}
17193 		/*
17194 		 * Make sure that first_mp points back to mp as
17195 		 * the mp we came in with could have changed in
17196 		 * ip_rput_fragment().
17197 		 */
17198 		ipha = (ipha_t *)mp->b_rptr;
17199 		first_mp = mp;
17200 	}
17201 
17202 	/*
17203 	 * Clear hardware checksumming flag as it is currently only
17204 	 * used by TCP and UDP.
17205 	 */
17206 	DB_CKSUMFLAGS(mp) = 0;
17207 
17208 	/* Now we have a complete datagram, destined for this machine. */
17209 	u1 = IPH_HDR_LENGTH(ipha);
17210 	switch (ipha->ipha_protocol) {
17211 	case IPPROTO_ICMP: {
17212 		ire_t		*ire_zone;
17213 		ilm_t		*ilm;
17214 		mblk_t		*mp1;
17215 		zoneid_t	last_zoneid;
17216 
17217 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17218 			ASSERT(ire->ire_type == IRE_BROADCAST);
17219 			/*
17220 			 * In the multicast case, applications may have joined
17221 			 * the group from different zones, so we need to deliver
17222 			 * the packet to each of them. Loop through the
17223 			 * multicast memberships structures (ilm) on the receive
17224 			 * ill and send a copy of the packet up each matching
17225 			 * one. However, we don't do this for multicasts sent on
17226 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17227 			 * they must stay in the sender's zone.
17228 			 *
17229 			 * ilm_add_v6() ensures that ilms in the same zone are
17230 			 * contiguous in the ill_ilm list. We use this property
17231 			 * to avoid sending duplicates needed when two
17232 			 * applications in the same zone join the same group on
17233 			 * different logical interfaces: we ignore the ilm if
17234 			 * its zoneid is the same as the last matching one.
17235 			 * In addition, the sending of the packet for
17236 			 * ire_zoneid is delayed until all of the other ilms
17237 			 * have been exhausted.
17238 			 */
17239 			last_zoneid = -1;
17240 			ILM_WALKER_HOLD(recv_ill);
17241 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17242 			    ilm = ilm->ilm_next) {
17243 				if ((ilm->ilm_flags & ILM_DELETED) ||
17244 				    ipha->ipha_dst != ilm->ilm_addr ||
17245 				    ilm->ilm_zoneid == last_zoneid ||
17246 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17247 				    ilm->ilm_zoneid == ALL_ZONES ||
17248 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17249 					continue;
17250 				mp1 = ip_copymsg(first_mp);
17251 				if (mp1 == NULL)
17252 					continue;
17253 				icmp_inbound(q, mp1, B_TRUE, ill,
17254 				    0, sum, mctl_present, B_TRUE,
17255 				    recv_ill, ilm->ilm_zoneid);
17256 				last_zoneid = ilm->ilm_zoneid;
17257 			}
17258 			ILM_WALKER_RELE(recv_ill);
17259 		} else if (ire->ire_type == IRE_BROADCAST) {
17260 			/*
17261 			 * In the broadcast case, there may be many zones
17262 			 * which need a copy of the packet delivered to them.
17263 			 * There is one IRE_BROADCAST per broadcast address
17264 			 * and per zone; we walk those using a helper function.
17265 			 * In addition, the sending of the packet for ire is
17266 			 * delayed until all of the other ires have been
17267 			 * processed.
17268 			 */
17269 			IRB_REFHOLD(ire->ire_bucket);
17270 			ire_zone = NULL;
17271 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17272 			    ire)) != NULL) {
17273 				mp1 = ip_copymsg(first_mp);
17274 				if (mp1 == NULL)
17275 					continue;
17276 
17277 				UPDATE_IB_PKT_COUNT(ire_zone);
17278 				ire_zone->ire_last_used_time = lbolt;
17279 				icmp_inbound(q, mp1, B_TRUE, ill,
17280 				    0, sum, mctl_present, B_TRUE,
17281 				    recv_ill, ire_zone->ire_zoneid);
17282 			}
17283 			IRB_REFRELE(ire->ire_bucket);
17284 		}
17285 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17286 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17287 		    ire->ire_zoneid);
17288 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17289 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17290 		return;
17291 	}
17292 	case IPPROTO_IGMP:
17293 		/*
17294 		 * If we are not willing to accept IGMP packets in clear,
17295 		 * then check with global policy.
17296 		 */
17297 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17298 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17299 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17300 			if (first_mp == NULL)
17301 				return;
17302 		}
17303 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17304 			freemsg(first_mp);
17305 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17306 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17307 			return;
17308 		}
17309 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17310 			/* Bad packet - discarded by igmp_input */
17311 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17312 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17313 			if (mctl_present)
17314 				freeb(first_mp);
17315 			return;
17316 		}
17317 		/*
17318 		 * igmp_input() may have returned the pulled up message.
17319 		 * So first_mp and ipha need to be reinitialized.
17320 		 */
17321 		ipha = (ipha_t *)mp->b_rptr;
17322 		if (mctl_present)
17323 			first_mp->b_cont = mp;
17324 		else
17325 			first_mp = mp;
17326 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17327 		    connf_head != NULL) {
17328 			/* No user-level listener for IGMP packets */
17329 			goto drop_pkt;
17330 		}
17331 		/* deliver to local raw users */
17332 		break;
17333 	case IPPROTO_PIM:
17334 		/*
17335 		 * If we are not willing to accept PIM packets in clear,
17336 		 * then check with global policy.
17337 		 */
17338 		if (ipst->ips_pim_accept_clear_messages == 0) {
17339 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17340 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17341 			if (first_mp == NULL)
17342 				return;
17343 		}
17344 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17345 			freemsg(first_mp);
17346 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17347 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17348 			return;
17349 		}
17350 		if (pim_input(q, mp, ill) != 0) {
17351 			/* Bad packet - discarded by pim_input */
17352 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17353 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17354 			if (mctl_present)
17355 				freeb(first_mp);
17356 			return;
17357 		}
17358 
17359 		/*
17360 		 * pim_input() may have pulled up the message so ipha needs to
17361 		 * be reinitialized.
17362 		 */
17363 		ipha = (ipha_t *)mp->b_rptr;
17364 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17365 		    connf_head != NULL) {
17366 			/* No user-level listener for PIM packets */
17367 			goto drop_pkt;
17368 		}
17369 		/* deliver to local raw users */
17370 		break;
17371 	case IPPROTO_ENCAP:
17372 		/*
17373 		 * Handle self-encapsulated packets (IP-in-IP where
17374 		 * the inner addresses == the outer addresses).
17375 		 */
17376 		hdr_length = IPH_HDR_LENGTH(ipha);
17377 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17378 		    mp->b_wptr) {
17379 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17380 			    sizeof (ipha_t) - mp->b_rptr)) {
17381 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17382 				freemsg(first_mp);
17383 				return;
17384 			}
17385 			ipha = (ipha_t *)mp->b_rptr;
17386 		}
17387 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17388 		/*
17389 		 * Check the sanity of the inner IP header.
17390 		 */
17391 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17392 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17393 			freemsg(first_mp);
17394 			return;
17395 		}
17396 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17397 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17398 			freemsg(first_mp);
17399 			return;
17400 		}
17401 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17402 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17403 			ipsec_in_t *ii;
17404 
17405 			/*
17406 			 * Self-encapsulated tunnel packet. Remove
17407 			 * the outer IP header and fanout again.
17408 			 * We also need to make sure that the inner
17409 			 * header is pulled up until options.
17410 			 */
17411 			mp->b_rptr = (uchar_t *)inner_ipha;
17412 			ipha = inner_ipha;
17413 			hdr_length = IPH_HDR_LENGTH(ipha);
17414 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17415 				if (!pullupmsg(mp, (uchar_t *)ipha +
17416 				    + hdr_length - mp->b_rptr)) {
17417 					freemsg(first_mp);
17418 					return;
17419 				}
17420 				ipha = (ipha_t *)mp->b_rptr;
17421 			}
17422 			if (!mctl_present) {
17423 				ASSERT(first_mp == mp);
17424 				/*
17425 				 * This means that somebody is sending
17426 				 * Self-encapsualted packets without AH/ESP.
17427 				 * If AH/ESP was present, we would have already
17428 				 * allocated the first_mp.
17429 				 */
17430 				first_mp = ipsec_in_alloc(B_TRUE,
17431 				    ipst->ips_netstack);
17432 				if (first_mp == NULL) {
17433 					ip1dbg(("ip_proto_input: IPSEC_IN "
17434 					    "allocation failure.\n"));
17435 					BUMP_MIB(ill->ill_ip_mib,
17436 					    ipIfStatsInDiscards);
17437 					freemsg(mp);
17438 					return;
17439 				}
17440 				first_mp->b_cont = mp;
17441 			}
17442 			/*
17443 			 * We generally store the ill_index if we need to
17444 			 * do IPsec processing as we lose the ill queue when
17445 			 * we come back. But in this case, we never should
17446 			 * have to store the ill_index here as it should have
17447 			 * been stored previously when we processed the
17448 			 * AH/ESP header in this routine or for non-ipsec
17449 			 * cases, we still have the queue. But for some bad
17450 			 * packets from the wire, we can get to IPsec after
17451 			 * this and we better store the index for that case.
17452 			 */
17453 			ill = (ill_t *)q->q_ptr;
17454 			ii = (ipsec_in_t *)first_mp->b_rptr;
17455 			ii->ipsec_in_ill_index =
17456 			    ill->ill_phyint->phyint_ifindex;
17457 			ii->ipsec_in_rill_index =
17458 			    recv_ill->ill_phyint->phyint_ifindex;
17459 			if (ii->ipsec_in_decaps) {
17460 				/*
17461 				 * This packet is self-encapsulated multiple
17462 				 * times. We don't want to recurse infinitely.
17463 				 * To keep it simple, drop the packet.
17464 				 */
17465 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17466 				freemsg(first_mp);
17467 				return;
17468 			}
17469 			ii->ipsec_in_decaps = B_TRUE;
17470 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17471 			    ire);
17472 			return;
17473 		}
17474 		break;
17475 	case IPPROTO_AH:
17476 	case IPPROTO_ESP: {
17477 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17478 
17479 		/*
17480 		 * Fast path for AH/ESP. If this is the first time
17481 		 * we are sending a datagram to AH/ESP, allocate
17482 		 * a IPSEC_IN message and prepend it. Otherwise,
17483 		 * just fanout.
17484 		 */
17485 
17486 		int ipsec_rc;
17487 		ipsec_in_t *ii;
17488 		netstack_t *ns = ipst->ips_netstack;
17489 
17490 		IP_STAT(ipst, ipsec_proto_ahesp);
17491 		if (!mctl_present) {
17492 			ASSERT(first_mp == mp);
17493 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17494 			if (first_mp == NULL) {
17495 				ip1dbg(("ip_proto_input: IPSEC_IN "
17496 				    "allocation failure.\n"));
17497 				freemsg(hada_mp); /* okay ifnull */
17498 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17499 				freemsg(mp);
17500 				return;
17501 			}
17502 			/*
17503 			 * Store the ill_index so that when we come back
17504 			 * from IPsec we ride on the same queue.
17505 			 */
17506 			ill = (ill_t *)q->q_ptr;
17507 			ii = (ipsec_in_t *)first_mp->b_rptr;
17508 			ii->ipsec_in_ill_index =
17509 			    ill->ill_phyint->phyint_ifindex;
17510 			ii->ipsec_in_rill_index =
17511 			    recv_ill->ill_phyint->phyint_ifindex;
17512 			first_mp->b_cont = mp;
17513 			/*
17514 			 * Cache hardware acceleration info.
17515 			 */
17516 			if (hada_mp != NULL) {
17517 				IPSECHW_DEBUG(IPSECHW_PKT,
17518 				    ("ip_rput_local: caching data attr.\n"));
17519 				ii->ipsec_in_accelerated = B_TRUE;
17520 				ii->ipsec_in_da = hada_mp;
17521 				hada_mp = NULL;
17522 			}
17523 		} else {
17524 			ii = (ipsec_in_t *)first_mp->b_rptr;
17525 		}
17526 
17527 		if (!ipsec_loaded(ipss)) {
17528 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17529 			    ire->ire_zoneid, ipst);
17530 			return;
17531 		}
17532 
17533 		ns = ipst->ips_netstack;
17534 		/* select inbound SA and have IPsec process the pkt */
17535 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17536 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17537 			boolean_t esp_in_udp_sa;
17538 			if (esph == NULL)
17539 				return;
17540 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17541 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17542 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
17543 			    IPSA_F_NATT) != 0);
17544 			/*
17545 			 * The following is a fancy, but quick, way of saying:
17546 			 * ESP-in-UDP SA and Raw ESP packet --> drop
17547 			 *    OR
17548 			 * ESP SA and ESP-in-UDP packet --> drop
17549 			 */
17550 			if (esp_in_udp_sa != esp_in_udp_packet) {
17551 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17552 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
17553 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
17554 				    &ns->netstack_ipsec->ipsec_dropper);
17555 				return;
17556 			}
17557 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17558 			    first_mp, esph);
17559 		} else {
17560 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17561 			if (ah == NULL)
17562 				return;
17563 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17564 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17565 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17566 			    first_mp, ah);
17567 		}
17568 
17569 		switch (ipsec_rc) {
17570 		case IPSEC_STATUS_SUCCESS:
17571 			break;
17572 		case IPSEC_STATUS_FAILED:
17573 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17574 			/* FALLTHRU */
17575 		case IPSEC_STATUS_PENDING:
17576 			return;
17577 		}
17578 		/* we're done with IPsec processing, send it up */
17579 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17580 		return;
17581 	}
17582 	default:
17583 		break;
17584 	}
17585 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17586 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17587 		    ire->ire_zoneid));
17588 		goto drop_pkt;
17589 	}
17590 	/*
17591 	 * Handle protocols with which IP is less intimate.  There
17592 	 * can be more than one stream bound to a particular
17593 	 * protocol.  When this is the case, each one gets a copy
17594 	 * of any incoming packets.
17595 	 */
17596 	ip_fanout_proto(q, first_mp, ill, ipha,
17597 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17598 	    B_TRUE, recv_ill, ire->ire_zoneid);
17599 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17600 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17601 	return;
17602 
17603 drop_pkt:
17604 	freemsg(first_mp);
17605 	if (hada_mp != NULL)
17606 		freeb(hada_mp);
17607 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17608 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17609 #undef	rptr
17610 #undef  iphs
17611 
17612 }
17613 
17614 /*
17615  * Update any source route, record route or timestamp options.
17616  * Check that we are at end of strict source route.
17617  * The options have already been checked for sanity in ip_rput_options().
17618  */
17619 static boolean_t
17620 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17621     ip_stack_t *ipst)
17622 {
17623 	ipoptp_t	opts;
17624 	uchar_t		*opt;
17625 	uint8_t		optval;
17626 	uint8_t		optlen;
17627 	ipaddr_t	dst;
17628 	uint32_t	ts;
17629 	ire_t		*dst_ire;
17630 	timestruc_t	now;
17631 	zoneid_t	zoneid;
17632 	ill_t		*ill;
17633 
17634 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17635 
17636 	ip2dbg(("ip_rput_local_options\n"));
17637 
17638 	for (optval = ipoptp_first(&opts, ipha);
17639 	    optval != IPOPT_EOL;
17640 	    optval = ipoptp_next(&opts)) {
17641 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17642 		opt = opts.ipoptp_cur;
17643 		optlen = opts.ipoptp_len;
17644 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17645 		    optval, optlen));
17646 		switch (optval) {
17647 			uint32_t off;
17648 		case IPOPT_SSRR:
17649 		case IPOPT_LSRR:
17650 			off = opt[IPOPT_OFFSET];
17651 			off--;
17652 			if (optlen < IP_ADDR_LEN ||
17653 			    off > optlen - IP_ADDR_LEN) {
17654 				/* End of source route */
17655 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17656 				break;
17657 			}
17658 			/*
17659 			 * This will only happen if two consecutive entries
17660 			 * in the source route contains our address or if
17661 			 * it is a packet with a loose source route which
17662 			 * reaches us before consuming the whole source route
17663 			 */
17664 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17665 			if (optval == IPOPT_SSRR) {
17666 				goto bad_src_route;
17667 			}
17668 			/*
17669 			 * Hack: instead of dropping the packet truncate the
17670 			 * source route to what has been used by filling the
17671 			 * rest with IPOPT_NOP.
17672 			 */
17673 			opt[IPOPT_OLEN] = (uint8_t)off;
17674 			while (off < optlen) {
17675 				opt[off++] = IPOPT_NOP;
17676 			}
17677 			break;
17678 		case IPOPT_RR:
17679 			off = opt[IPOPT_OFFSET];
17680 			off--;
17681 			if (optlen < IP_ADDR_LEN ||
17682 			    off > optlen - IP_ADDR_LEN) {
17683 				/* No more room - ignore */
17684 				ip1dbg((
17685 				    "ip_rput_local_options: end of RR\n"));
17686 				break;
17687 			}
17688 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17689 			    IP_ADDR_LEN);
17690 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17691 			break;
17692 		case IPOPT_TS:
17693 			/* Insert timestamp if there is romm */
17694 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17695 			case IPOPT_TS_TSONLY:
17696 				off = IPOPT_TS_TIMELEN;
17697 				break;
17698 			case IPOPT_TS_PRESPEC:
17699 			case IPOPT_TS_PRESPEC_RFC791:
17700 				/* Verify that the address matched */
17701 				off = opt[IPOPT_OFFSET] - 1;
17702 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17703 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17704 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
17705 				    ipst);
17706 				if (dst_ire == NULL) {
17707 					/* Not for us */
17708 					break;
17709 				}
17710 				ire_refrele(dst_ire);
17711 				/* FALLTHRU */
17712 			case IPOPT_TS_TSANDADDR:
17713 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17714 				break;
17715 			default:
17716 				/*
17717 				 * ip_*put_options should have already
17718 				 * dropped this packet.
17719 				 */
17720 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17721 				    "unknown IT - bug in ip_rput_options?\n");
17722 				return (B_TRUE);	/* Keep "lint" happy */
17723 			}
17724 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17725 				/* Increase overflow counter */
17726 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17727 				opt[IPOPT_POS_OV_FLG] =
17728 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17729 				    (off << 4));
17730 				break;
17731 			}
17732 			off = opt[IPOPT_OFFSET] - 1;
17733 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17734 			case IPOPT_TS_PRESPEC:
17735 			case IPOPT_TS_PRESPEC_RFC791:
17736 			case IPOPT_TS_TSANDADDR:
17737 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17738 				    IP_ADDR_LEN);
17739 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17740 				/* FALLTHRU */
17741 			case IPOPT_TS_TSONLY:
17742 				off = opt[IPOPT_OFFSET] - 1;
17743 				/* Compute # of milliseconds since midnight */
17744 				gethrestime(&now);
17745 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17746 				    now.tv_nsec / (NANOSEC / MILLISEC);
17747 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17748 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17749 				break;
17750 			}
17751 			break;
17752 		}
17753 	}
17754 	return (B_TRUE);
17755 
17756 bad_src_route:
17757 	q = WR(q);
17758 	if (q->q_next != NULL)
17759 		ill = q->q_ptr;
17760 	else
17761 		ill = NULL;
17762 
17763 	/* make sure we clear any indication of a hardware checksum */
17764 	DB_CKSUMFLAGS(mp) = 0;
17765 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
17766 	if (zoneid == ALL_ZONES)
17767 		freemsg(mp);
17768 	else
17769 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17770 	return (B_FALSE);
17771 
17772 }
17773 
17774 /*
17775  * Process IP options in an inbound packet.  If an option affects the
17776  * effective destination address, return the next hop address via dstp.
17777  * Returns -1 if something fails in which case an ICMP error has been sent
17778  * and mp freed.
17779  */
17780 static int
17781 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
17782     ip_stack_t *ipst)
17783 {
17784 	ipoptp_t	opts;
17785 	uchar_t		*opt;
17786 	uint8_t		optval;
17787 	uint8_t		optlen;
17788 	ipaddr_t	dst;
17789 	intptr_t	code = 0;
17790 	ire_t		*ire = NULL;
17791 	zoneid_t	zoneid;
17792 	ill_t		*ill;
17793 
17794 	ip2dbg(("ip_rput_options\n"));
17795 	dst = ipha->ipha_dst;
17796 	for (optval = ipoptp_first(&opts, ipha);
17797 	    optval != IPOPT_EOL;
17798 	    optval = ipoptp_next(&opts)) {
17799 		opt = opts.ipoptp_cur;
17800 		optlen = opts.ipoptp_len;
17801 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17802 		    optval, optlen));
17803 		/*
17804 		 * Note: we need to verify the checksum before we
17805 		 * modify anything thus this routine only extracts the next
17806 		 * hop dst from any source route.
17807 		 */
17808 		switch (optval) {
17809 			uint32_t off;
17810 		case IPOPT_SSRR:
17811 		case IPOPT_LSRR:
17812 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17813 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17814 			if (ire == NULL) {
17815 				if (optval == IPOPT_SSRR) {
17816 					ip1dbg(("ip_rput_options: not next"
17817 					    " strict source route 0x%x\n",
17818 					    ntohl(dst)));
17819 					code = (char *)&ipha->ipha_dst -
17820 					    (char *)ipha;
17821 					goto param_prob; /* RouterReq's */
17822 				}
17823 				ip2dbg(("ip_rput_options: "
17824 				    "not next source route 0x%x\n",
17825 				    ntohl(dst)));
17826 				break;
17827 			}
17828 			ire_refrele(ire);
17829 
17830 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17831 				ip1dbg((
17832 				    "ip_rput_options: bad option offset\n"));
17833 				code = (char *)&opt[IPOPT_OLEN] -
17834 				    (char *)ipha;
17835 				goto param_prob;
17836 			}
17837 			off = opt[IPOPT_OFFSET];
17838 			off--;
17839 		redo_srr:
17840 			if (optlen < IP_ADDR_LEN ||
17841 			    off > optlen - IP_ADDR_LEN) {
17842 				/* End of source route */
17843 				ip1dbg(("ip_rput_options: end of SR\n"));
17844 				break;
17845 			}
17846 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17847 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
17848 			    ntohl(dst)));
17849 
17850 			/*
17851 			 * Check if our address is present more than
17852 			 * once as consecutive hops in source route.
17853 			 * XXX verify per-interface ip_forwarding
17854 			 * for source route?
17855 			 */
17856 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17857 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17858 
17859 			if (ire != NULL) {
17860 				ire_refrele(ire);
17861 				off += IP_ADDR_LEN;
17862 				goto redo_srr;
17863 			}
17864 
17865 			if (dst == htonl(INADDR_LOOPBACK)) {
17866 				ip1dbg(("ip_rput_options: loopback addr in "
17867 				    "source route!\n"));
17868 				goto bad_src_route;
17869 			}
17870 			/*
17871 			 * For strict: verify that dst is directly
17872 			 * reachable.
17873 			 */
17874 			if (optval == IPOPT_SSRR) {
17875 				ire = ire_ftable_lookup(dst, 0, 0,
17876 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
17877 				    MBLK_GETLABEL(mp),
17878 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
17879 				if (ire == NULL) {
17880 					ip1dbg(("ip_rput_options: SSRR not "
17881 					    "directly reachable: 0x%x\n",
17882 					    ntohl(dst)));
17883 					goto bad_src_route;
17884 				}
17885 				ire_refrele(ire);
17886 			}
17887 			/*
17888 			 * Defer update of the offset and the record route
17889 			 * until the packet is forwarded.
17890 			 */
17891 			break;
17892 		case IPOPT_RR:
17893 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17894 				ip1dbg((
17895 				    "ip_rput_options: bad option offset\n"));
17896 				code = (char *)&opt[IPOPT_OLEN] -
17897 				    (char *)ipha;
17898 				goto param_prob;
17899 			}
17900 			break;
17901 		case IPOPT_TS:
17902 			/*
17903 			 * Verify that length >= 5 and that there is either
17904 			 * room for another timestamp or that the overflow
17905 			 * counter is not maxed out.
17906 			 */
17907 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
17908 			if (optlen < IPOPT_MINLEN_IT) {
17909 				goto param_prob;
17910 			}
17911 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17912 				ip1dbg((
17913 				    "ip_rput_options: bad option offset\n"));
17914 				code = (char *)&opt[IPOPT_OFFSET] -
17915 				    (char *)ipha;
17916 				goto param_prob;
17917 			}
17918 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17919 			case IPOPT_TS_TSONLY:
17920 				off = IPOPT_TS_TIMELEN;
17921 				break;
17922 			case IPOPT_TS_TSANDADDR:
17923 			case IPOPT_TS_PRESPEC:
17924 			case IPOPT_TS_PRESPEC_RFC791:
17925 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17926 				break;
17927 			default:
17928 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
17929 				    (char *)ipha;
17930 				goto param_prob;
17931 			}
17932 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
17933 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
17934 				/*
17935 				 * No room and the overflow counter is 15
17936 				 * already.
17937 				 */
17938 				goto param_prob;
17939 			}
17940 			break;
17941 		}
17942 	}
17943 
17944 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
17945 		*dstp = dst;
17946 		return (0);
17947 	}
17948 
17949 	ip1dbg(("ip_rput_options: error processing IP options."));
17950 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
17951 
17952 param_prob:
17953 	q = WR(q);
17954 	if (q->q_next != NULL)
17955 		ill = q->q_ptr;
17956 	else
17957 		ill = NULL;
17958 
17959 	/* make sure we clear any indication of a hardware checksum */
17960 	DB_CKSUMFLAGS(mp) = 0;
17961 	/* Don't know whether this is for non-global or global/forwarding */
17962 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
17963 	if (zoneid == ALL_ZONES)
17964 		freemsg(mp);
17965 	else
17966 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
17967 	return (-1);
17968 
17969 bad_src_route:
17970 	q = WR(q);
17971 	if (q->q_next != NULL)
17972 		ill = q->q_ptr;
17973 	else
17974 		ill = NULL;
17975 
17976 	/* make sure we clear any indication of a hardware checksum */
17977 	DB_CKSUMFLAGS(mp) = 0;
17978 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
17979 	if (zoneid == ALL_ZONES)
17980 		freemsg(mp);
17981 	else
17982 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17983 	return (-1);
17984 }
17985 
17986 /*
17987  * IP & ICMP info in >=14 msg's ...
17988  *  - ip fixed part (mib2_ip_t)
17989  *  - icmp fixed part (mib2_icmp_t)
17990  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
17991  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
17992  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
17993  *  - ipRouteAttributeTable (ip 102)	labeled routes
17994  *  - ip multicast membership (ip_member_t)
17995  *  - ip multicast source filtering (ip_grpsrc_t)
17996  *  - igmp fixed part (struct igmpstat)
17997  *  - multicast routing stats (struct mrtstat)
17998  *  - multicast routing vifs (array of struct vifctl)
17999  *  - multicast routing routes (array of struct mfcctl)
18000  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18001  *					One per ill plus one generic
18002  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18003  *					One per ill plus one generic
18004  *  - ipv6RouteEntry			all IPv6 IREs
18005  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18006  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18007  *  - ipv6AddrEntry			all IPv6 ipifs
18008  *  - ipv6 multicast membership (ipv6_member_t)
18009  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18010  *
18011  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18012  *
18013  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18014  * already filled in by the caller.
18015  * Return value of 0 indicates that no messages were sent and caller
18016  * should free mpctl.
18017  */
18018 int
18019 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
18020 {
18021 	ip_stack_t *ipst;
18022 	sctp_stack_t *sctps;
18023 
18024 	if (q->q_next != NULL) {
18025 		ipst = ILLQ_TO_IPST(q);
18026 	} else {
18027 		ipst = CONNQ_TO_IPST(q);
18028 	}
18029 	ASSERT(ipst != NULL);
18030 	sctps = ipst->ips_netstack->netstack_sctp;
18031 
18032 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18033 		return (0);
18034 	}
18035 
18036 	/*
18037 	 * For the purposes of the (broken) packet shell use
18038 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
18039 	 * to make TCP and UDP appear first in the list of mib items.
18040 	 * TBD: We could expand this and use it in netstat so that
18041 	 * the kernel doesn't have to produce large tables (connections,
18042 	 * routes, etc) when netstat only wants the statistics or a particular
18043 	 * table.
18044 	 */
18045 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
18046 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
18047 			return (1);
18048 		}
18049 	}
18050 
18051 	if (level != MIB2_TCP) {
18052 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
18053 			return (1);
18054 		}
18055 	}
18056 
18057 	if (level != MIB2_UDP) {
18058 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
18059 			return (1);
18060 		}
18061 	}
18062 
18063 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18064 	    ipst)) == NULL) {
18065 		return (1);
18066 	}
18067 
18068 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18069 		return (1);
18070 	}
18071 
18072 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18073 		return (1);
18074 	}
18075 
18076 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18077 		return (1);
18078 	}
18079 
18080 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18081 		return (1);
18082 	}
18083 
18084 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18085 		return (1);
18086 	}
18087 
18088 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18089 		return (1);
18090 	}
18091 
18092 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18093 		return (1);
18094 	}
18095 
18096 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18097 		return (1);
18098 	}
18099 
18100 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18101 		return (1);
18102 	}
18103 
18104 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18105 		return (1);
18106 	}
18107 
18108 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18109 		return (1);
18110 	}
18111 
18112 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18113 		return (1);
18114 	}
18115 
18116 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18117 		return (1);
18118 	}
18119 
18120 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, ipst)) == NULL) {
18121 		return (1);
18122 	}
18123 
18124 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, ipst);
18125 	if (mpctl == NULL) {
18126 		return (1);
18127 	}
18128 
18129 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18130 		return (1);
18131 	}
18132 	freemsg(mpctl);
18133 	return (1);
18134 }
18135 
18136 
18137 /* Get global (legacy) IPv4 statistics */
18138 static mblk_t *
18139 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18140     ip_stack_t *ipst)
18141 {
18142 	mib2_ip_t		old_ip_mib;
18143 	struct opthdr		*optp;
18144 	mblk_t			*mp2ctl;
18145 
18146 	/*
18147 	 * make a copy of the original message
18148 	 */
18149 	mp2ctl = copymsg(mpctl);
18150 
18151 	/* fixed length IP structure... */
18152 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18153 	optp->level = MIB2_IP;
18154 	optp->name = 0;
18155 	SET_MIB(old_ip_mib.ipForwarding,
18156 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18157 	SET_MIB(old_ip_mib.ipDefaultTTL,
18158 	    (uint32_t)ipst->ips_ip_def_ttl);
18159 	SET_MIB(old_ip_mib.ipReasmTimeout,
18160 	    ipst->ips_ip_g_frag_timeout);
18161 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18162 	    sizeof (mib2_ipAddrEntry_t));
18163 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18164 	    sizeof (mib2_ipRouteEntry_t));
18165 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18166 	    sizeof (mib2_ipNetToMediaEntry_t));
18167 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18168 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18169 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18170 	    sizeof (mib2_ipAttributeEntry_t));
18171 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18172 
18173 	/*
18174 	 * Grab the statistics from the new IP MIB
18175 	 */
18176 	SET_MIB(old_ip_mib.ipInReceives,
18177 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18178 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18179 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18180 	SET_MIB(old_ip_mib.ipForwDatagrams,
18181 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18182 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18183 	    ipmib->ipIfStatsInUnknownProtos);
18184 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18185 	SET_MIB(old_ip_mib.ipInDelivers,
18186 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18187 	SET_MIB(old_ip_mib.ipOutRequests,
18188 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18189 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18190 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18191 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18192 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18193 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18194 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18195 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18196 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18197 
18198 	/* ipRoutingDiscards is not being used */
18199 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18200 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18201 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18202 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18203 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18204 	    ipmib->ipIfStatsReasmDuplicates);
18205 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18206 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18207 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18208 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18209 	SET_MIB(old_ip_mib.rawipInOverflows,
18210 	    ipmib->rawipIfStatsInOverflows);
18211 
18212 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18213 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18214 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18215 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18216 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18217 	    ipmib->ipIfStatsOutSwitchIPVersion);
18218 
18219 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18220 	    (int)sizeof (old_ip_mib))) {
18221 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18222 		    (uint_t)sizeof (old_ip_mib)));
18223 	}
18224 
18225 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18226 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18227 	    (int)optp->level, (int)optp->name, (int)optp->len));
18228 	qreply(q, mpctl);
18229 	return (mp2ctl);
18230 }
18231 
18232 /* Per interface IPv4 statistics */
18233 static mblk_t *
18234 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18235 {
18236 	struct opthdr		*optp;
18237 	mblk_t			*mp2ctl;
18238 	ill_t			*ill;
18239 	ill_walk_context_t	ctx;
18240 	mblk_t			*mp_tail = NULL;
18241 	mib2_ipIfStatsEntry_t	global_ip_mib;
18242 
18243 	/*
18244 	 * Make a copy of the original message
18245 	 */
18246 	mp2ctl = copymsg(mpctl);
18247 
18248 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18249 	optp->level = MIB2_IP;
18250 	optp->name = MIB2_IP_TRAFFIC_STATS;
18251 	/* Include "unknown interface" ip_mib */
18252 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18253 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18254 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18255 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18256 	    (ipst->ips_ip_g_forward ? 1 : 2));
18257 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18258 	    (uint32_t)ipst->ips_ip_def_ttl);
18259 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18260 	    sizeof (mib2_ipIfStatsEntry_t));
18261 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18262 	    sizeof (mib2_ipAddrEntry_t));
18263 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18264 	    sizeof (mib2_ipRouteEntry_t));
18265 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18266 	    sizeof (mib2_ipNetToMediaEntry_t));
18267 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18268 	    sizeof (ip_member_t));
18269 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18270 	    sizeof (ip_grpsrc_t));
18271 
18272 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18273 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18274 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18275 		    "failed to allocate %u bytes\n",
18276 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18277 	}
18278 
18279 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18280 
18281 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18282 	ill = ILL_START_WALK_V4(&ctx, ipst);
18283 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18284 		ill->ill_ip_mib->ipIfStatsIfIndex =
18285 		    ill->ill_phyint->phyint_ifindex;
18286 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18287 		    (ipst->ips_ip_g_forward ? 1 : 2));
18288 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18289 		    (uint32_t)ipst->ips_ip_def_ttl);
18290 
18291 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18292 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18293 		    (char *)ill->ill_ip_mib,
18294 		    (int)sizeof (*ill->ill_ip_mib))) {
18295 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18296 			    "failed to allocate %u bytes\n",
18297 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18298 		}
18299 	}
18300 	rw_exit(&ipst->ips_ill_g_lock);
18301 
18302 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18303 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18304 	    "level %d, name %d, len %d\n",
18305 	    (int)optp->level, (int)optp->name, (int)optp->len));
18306 	qreply(q, mpctl);
18307 
18308 	if (mp2ctl == NULL)
18309 		return (NULL);
18310 
18311 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18312 }
18313 
18314 /* Global IPv4 ICMP statistics */
18315 static mblk_t *
18316 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18317 {
18318 	struct opthdr		*optp;
18319 	mblk_t			*mp2ctl;
18320 
18321 	/*
18322 	 * Make a copy of the original message
18323 	 */
18324 	mp2ctl = copymsg(mpctl);
18325 
18326 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18327 	optp->level = MIB2_ICMP;
18328 	optp->name = 0;
18329 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18330 	    (int)sizeof (ipst->ips_icmp_mib))) {
18331 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18332 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18333 	}
18334 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18335 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18336 	    (int)optp->level, (int)optp->name, (int)optp->len));
18337 	qreply(q, mpctl);
18338 	return (mp2ctl);
18339 }
18340 
18341 /* Global IPv4 IGMP statistics */
18342 static mblk_t *
18343 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18344 {
18345 	struct opthdr		*optp;
18346 	mblk_t			*mp2ctl;
18347 
18348 	/*
18349 	 * make a copy of the original message
18350 	 */
18351 	mp2ctl = copymsg(mpctl);
18352 
18353 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18354 	optp->level = EXPER_IGMP;
18355 	optp->name = 0;
18356 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18357 	    (int)sizeof (ipst->ips_igmpstat))) {
18358 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18359 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18360 	}
18361 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18362 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18363 	    (int)optp->level, (int)optp->name, (int)optp->len));
18364 	qreply(q, mpctl);
18365 	return (mp2ctl);
18366 }
18367 
18368 /* Global IPv4 Multicast Routing statistics */
18369 static mblk_t *
18370 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18371 {
18372 	struct opthdr		*optp;
18373 	mblk_t			*mp2ctl;
18374 
18375 	/*
18376 	 * make a copy of the original message
18377 	 */
18378 	mp2ctl = copymsg(mpctl);
18379 
18380 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18381 	optp->level = EXPER_DVMRP;
18382 	optp->name = 0;
18383 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18384 		ip0dbg(("ip_mroute_stats: failed\n"));
18385 	}
18386 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18387 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18388 	    (int)optp->level, (int)optp->name, (int)optp->len));
18389 	qreply(q, mpctl);
18390 	return (mp2ctl);
18391 }
18392 
18393 /* IPv4 address information */
18394 static mblk_t *
18395 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18396 {
18397 	struct opthdr		*optp;
18398 	mblk_t			*mp2ctl;
18399 	mblk_t			*mp_tail = NULL;
18400 	ill_t			*ill;
18401 	ipif_t			*ipif;
18402 	uint_t			bitval;
18403 	mib2_ipAddrEntry_t	mae;
18404 	zoneid_t		zoneid;
18405 	ill_walk_context_t ctx;
18406 
18407 	/*
18408 	 * make a copy of the original message
18409 	 */
18410 	mp2ctl = copymsg(mpctl);
18411 
18412 	/* ipAddrEntryTable */
18413 
18414 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18415 	optp->level = MIB2_IP;
18416 	optp->name = MIB2_IP_ADDR;
18417 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18418 
18419 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18420 	ill = ILL_START_WALK_V4(&ctx, ipst);
18421 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18422 		for (ipif = ill->ill_ipif; ipif != NULL;
18423 		    ipif = ipif->ipif_next) {
18424 			if (ipif->ipif_zoneid != zoneid &&
18425 			    ipif->ipif_zoneid != ALL_ZONES)
18426 				continue;
18427 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18428 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18429 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18430 
18431 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18432 			    OCTET_LENGTH);
18433 			mae.ipAdEntIfIndex.o_length =
18434 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18435 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18436 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18437 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18438 			mae.ipAdEntInfo.ae_subnet_len =
18439 			    ip_mask_to_plen(ipif->ipif_net_mask);
18440 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18441 			for (bitval = 1;
18442 			    bitval &&
18443 			    !(bitval & ipif->ipif_brd_addr);
18444 			    bitval <<= 1)
18445 				noop;
18446 			mae.ipAdEntBcastAddr = bitval;
18447 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18448 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18449 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18450 			mae.ipAdEntInfo.ae_broadcast_addr =
18451 			    ipif->ipif_brd_addr;
18452 			mae.ipAdEntInfo.ae_pp_dst_addr =
18453 			    ipif->ipif_pp_dst_addr;
18454 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18455 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18456 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18457 
18458 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18459 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18460 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18461 				    "allocate %u bytes\n",
18462 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18463 			}
18464 		}
18465 	}
18466 	rw_exit(&ipst->ips_ill_g_lock);
18467 
18468 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18469 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18470 	    (int)optp->level, (int)optp->name, (int)optp->len));
18471 	qreply(q, mpctl);
18472 	return (mp2ctl);
18473 }
18474 
18475 /* IPv6 address information */
18476 static mblk_t *
18477 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18478 {
18479 	struct opthdr		*optp;
18480 	mblk_t			*mp2ctl;
18481 	mblk_t			*mp_tail = NULL;
18482 	ill_t			*ill;
18483 	ipif_t			*ipif;
18484 	mib2_ipv6AddrEntry_t	mae6;
18485 	zoneid_t		zoneid;
18486 	ill_walk_context_t	ctx;
18487 
18488 	/*
18489 	 * make a copy of the original message
18490 	 */
18491 	mp2ctl = copymsg(mpctl);
18492 
18493 	/* ipv6AddrEntryTable */
18494 
18495 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18496 	optp->level = MIB2_IP6;
18497 	optp->name = MIB2_IP6_ADDR;
18498 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18499 
18500 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18501 	ill = ILL_START_WALK_V6(&ctx, ipst);
18502 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18503 		for (ipif = ill->ill_ipif; ipif != NULL;
18504 		    ipif = ipif->ipif_next) {
18505 			if (ipif->ipif_zoneid != zoneid &&
18506 			    ipif->ipif_zoneid != ALL_ZONES)
18507 				continue;
18508 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18509 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18510 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18511 
18512 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18513 			    OCTET_LENGTH);
18514 			mae6.ipv6AddrIfIndex.o_length =
18515 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18516 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18517 			mae6.ipv6AddrPfxLength =
18518 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18519 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18520 			mae6.ipv6AddrInfo.ae_subnet_len =
18521 			    mae6.ipv6AddrPfxLength;
18522 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18523 
18524 			/* Type: stateless(1), stateful(2), unknown(3) */
18525 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18526 				mae6.ipv6AddrType = 1;
18527 			else
18528 				mae6.ipv6AddrType = 2;
18529 			/* Anycast: true(1), false(2) */
18530 			if (ipif->ipif_flags & IPIF_ANYCAST)
18531 				mae6.ipv6AddrAnycastFlag = 1;
18532 			else
18533 				mae6.ipv6AddrAnycastFlag = 2;
18534 
18535 			/*
18536 			 * Address status: preferred(1), deprecated(2),
18537 			 * invalid(3), inaccessible(4), unknown(5)
18538 			 */
18539 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18540 				mae6.ipv6AddrStatus = 3;
18541 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18542 				mae6.ipv6AddrStatus = 2;
18543 			else
18544 				mae6.ipv6AddrStatus = 1;
18545 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18546 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18547 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18548 			    ipif->ipif_v6pp_dst_addr;
18549 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18550 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18551 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18552 			mae6.ipv6AddrIdentifier = ill->ill_token;
18553 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18554 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18555 			mae6.ipv6AddrRetransmitTime =
18556 			    ill->ill_reachable_retrans_time;
18557 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18558 			    (char *)&mae6,
18559 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18560 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18561 				    "allocate %u bytes\n",
18562 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18563 			}
18564 		}
18565 	}
18566 	rw_exit(&ipst->ips_ill_g_lock);
18567 
18568 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18569 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18570 	    (int)optp->level, (int)optp->name, (int)optp->len));
18571 	qreply(q, mpctl);
18572 	return (mp2ctl);
18573 }
18574 
18575 /* IPv4 multicast group membership. */
18576 static mblk_t *
18577 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18578 {
18579 	struct opthdr		*optp;
18580 	mblk_t			*mp2ctl;
18581 	ill_t			*ill;
18582 	ipif_t			*ipif;
18583 	ilm_t			*ilm;
18584 	ip_member_t		ipm;
18585 	mblk_t			*mp_tail = NULL;
18586 	ill_walk_context_t	ctx;
18587 	zoneid_t		zoneid;
18588 
18589 	/*
18590 	 * make a copy of the original message
18591 	 */
18592 	mp2ctl = copymsg(mpctl);
18593 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18594 
18595 	/* ipGroupMember table */
18596 	optp = (struct opthdr *)&mpctl->b_rptr[
18597 	    sizeof (struct T_optmgmt_ack)];
18598 	optp->level = MIB2_IP;
18599 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18600 
18601 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18602 	ill = ILL_START_WALK_V4(&ctx, ipst);
18603 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18604 		ILM_WALKER_HOLD(ill);
18605 		for (ipif = ill->ill_ipif; ipif != NULL;
18606 		    ipif = ipif->ipif_next) {
18607 			if (ipif->ipif_zoneid != zoneid &&
18608 			    ipif->ipif_zoneid != ALL_ZONES)
18609 				continue;	/* not this zone */
18610 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
18611 			    OCTET_LENGTH);
18612 			ipm.ipGroupMemberIfIndex.o_length =
18613 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18614 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18615 				ASSERT(ilm->ilm_ipif != NULL);
18616 				ASSERT(ilm->ilm_ill == NULL);
18617 				if (ilm->ilm_ipif != ipif)
18618 					continue;
18619 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18620 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18621 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18622 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18623 				    (char *)&ipm, (int)sizeof (ipm))) {
18624 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18625 					    "failed to allocate %u bytes\n",
18626 					    (uint_t)sizeof (ipm)));
18627 				}
18628 			}
18629 		}
18630 		ILM_WALKER_RELE(ill);
18631 	}
18632 	rw_exit(&ipst->ips_ill_g_lock);
18633 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18634 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18635 	    (int)optp->level, (int)optp->name, (int)optp->len));
18636 	qreply(q, mpctl);
18637 	return (mp2ctl);
18638 }
18639 
18640 /* IPv6 multicast group membership. */
18641 static mblk_t *
18642 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18643 {
18644 	struct opthdr		*optp;
18645 	mblk_t			*mp2ctl;
18646 	ill_t			*ill;
18647 	ilm_t			*ilm;
18648 	ipv6_member_t		ipm6;
18649 	mblk_t			*mp_tail = NULL;
18650 	ill_walk_context_t	ctx;
18651 	zoneid_t		zoneid;
18652 
18653 	/*
18654 	 * make a copy of the original message
18655 	 */
18656 	mp2ctl = copymsg(mpctl);
18657 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18658 
18659 	/* ip6GroupMember table */
18660 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18661 	optp->level = MIB2_IP6;
18662 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18663 
18664 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18665 	ill = ILL_START_WALK_V6(&ctx, ipst);
18666 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18667 		ILM_WALKER_HOLD(ill);
18668 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18669 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18670 			ASSERT(ilm->ilm_ipif == NULL);
18671 			ASSERT(ilm->ilm_ill != NULL);
18672 			if (ilm->ilm_zoneid != zoneid)
18673 				continue;	/* not this zone */
18674 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18675 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18676 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18677 			if (!snmp_append_data2(mpctl->b_cont,
18678 			    &mp_tail,
18679 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18680 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18681 				    "failed to allocate %u bytes\n",
18682 				    (uint_t)sizeof (ipm6)));
18683 			}
18684 		}
18685 		ILM_WALKER_RELE(ill);
18686 	}
18687 	rw_exit(&ipst->ips_ill_g_lock);
18688 
18689 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18690 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18691 	    (int)optp->level, (int)optp->name, (int)optp->len));
18692 	qreply(q, mpctl);
18693 	return (mp2ctl);
18694 }
18695 
18696 /* IP multicast filtered sources */
18697 static mblk_t *
18698 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18699 {
18700 	struct opthdr		*optp;
18701 	mblk_t			*mp2ctl;
18702 	ill_t			*ill;
18703 	ipif_t			*ipif;
18704 	ilm_t			*ilm;
18705 	ip_grpsrc_t		ips;
18706 	mblk_t			*mp_tail = NULL;
18707 	ill_walk_context_t	ctx;
18708 	zoneid_t		zoneid;
18709 	int			i;
18710 	slist_t			*sl;
18711 
18712 	/*
18713 	 * make a copy of the original message
18714 	 */
18715 	mp2ctl = copymsg(mpctl);
18716 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18717 
18718 	/* ipGroupSource table */
18719 	optp = (struct opthdr *)&mpctl->b_rptr[
18720 	    sizeof (struct T_optmgmt_ack)];
18721 	optp->level = MIB2_IP;
18722 	optp->name = EXPER_IP_GROUP_SOURCES;
18723 
18724 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18725 	ill = ILL_START_WALK_V4(&ctx, ipst);
18726 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18727 		ILM_WALKER_HOLD(ill);
18728 		for (ipif = ill->ill_ipif; ipif != NULL;
18729 		    ipif = ipif->ipif_next) {
18730 			if (ipif->ipif_zoneid != zoneid)
18731 				continue;	/* not this zone */
18732 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
18733 			    OCTET_LENGTH);
18734 			ips.ipGroupSourceIfIndex.o_length =
18735 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18736 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18737 				ASSERT(ilm->ilm_ipif != NULL);
18738 				ASSERT(ilm->ilm_ill == NULL);
18739 				sl = ilm->ilm_filter;
18740 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18741 					continue;
18742 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18743 				for (i = 0; i < sl->sl_numsrc; i++) {
18744 					if (!IN6_IS_ADDR_V4MAPPED(
18745 					    &sl->sl_addr[i]))
18746 						continue;
18747 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18748 					    ips.ipGroupSourceAddress);
18749 					if (snmp_append_data2(mpctl->b_cont,
18750 					    &mp_tail, (char *)&ips,
18751 					    (int)sizeof (ips)) == 0) {
18752 						ip1dbg(("ip_snmp_get_mib2_"
18753 						    "ip_group_src: failed to "
18754 						    "allocate %u bytes\n",
18755 						    (uint_t)sizeof (ips)));
18756 					}
18757 				}
18758 			}
18759 		}
18760 		ILM_WALKER_RELE(ill);
18761 	}
18762 	rw_exit(&ipst->ips_ill_g_lock);
18763 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18764 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18765 	    (int)optp->level, (int)optp->name, (int)optp->len));
18766 	qreply(q, mpctl);
18767 	return (mp2ctl);
18768 }
18769 
18770 /* IPv6 multicast filtered sources. */
18771 static mblk_t *
18772 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18773 {
18774 	struct opthdr		*optp;
18775 	mblk_t			*mp2ctl;
18776 	ill_t			*ill;
18777 	ilm_t			*ilm;
18778 	ipv6_grpsrc_t		ips6;
18779 	mblk_t			*mp_tail = NULL;
18780 	ill_walk_context_t	ctx;
18781 	zoneid_t		zoneid;
18782 	int			i;
18783 	slist_t			*sl;
18784 
18785 	/*
18786 	 * make a copy of the original message
18787 	 */
18788 	mp2ctl = copymsg(mpctl);
18789 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18790 
18791 	/* ip6GroupMember table */
18792 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18793 	optp->level = MIB2_IP6;
18794 	optp->name = EXPER_IP6_GROUP_SOURCES;
18795 
18796 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18797 	ill = ILL_START_WALK_V6(&ctx, ipst);
18798 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18799 		ILM_WALKER_HOLD(ill);
18800 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18801 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18802 			ASSERT(ilm->ilm_ipif == NULL);
18803 			ASSERT(ilm->ilm_ill != NULL);
18804 			sl = ilm->ilm_filter;
18805 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18806 				continue;
18807 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18808 			for (i = 0; i < sl->sl_numsrc; i++) {
18809 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18810 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18811 				    (char *)&ips6, (int)sizeof (ips6))) {
18812 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18813 					    "group_src: failed to allocate "
18814 					    "%u bytes\n",
18815 					    (uint_t)sizeof (ips6)));
18816 				}
18817 			}
18818 		}
18819 		ILM_WALKER_RELE(ill);
18820 	}
18821 	rw_exit(&ipst->ips_ill_g_lock);
18822 
18823 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18824 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18825 	    (int)optp->level, (int)optp->name, (int)optp->len));
18826 	qreply(q, mpctl);
18827 	return (mp2ctl);
18828 }
18829 
18830 /* Multicast routing virtual interface table. */
18831 static mblk_t *
18832 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18833 {
18834 	struct opthdr		*optp;
18835 	mblk_t			*mp2ctl;
18836 
18837 	/*
18838 	 * make a copy of the original message
18839 	 */
18840 	mp2ctl = copymsg(mpctl);
18841 
18842 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18843 	optp->level = EXPER_DVMRP;
18844 	optp->name = EXPER_DVMRP_VIF;
18845 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
18846 		ip0dbg(("ip_mroute_vif: failed\n"));
18847 	}
18848 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18849 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
18850 	    (int)optp->level, (int)optp->name, (int)optp->len));
18851 	qreply(q, mpctl);
18852 	return (mp2ctl);
18853 }
18854 
18855 /* Multicast routing table. */
18856 static mblk_t *
18857 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18858 {
18859 	struct opthdr		*optp;
18860 	mblk_t			*mp2ctl;
18861 
18862 	/*
18863 	 * make a copy of the original message
18864 	 */
18865 	mp2ctl = copymsg(mpctl);
18866 
18867 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18868 	optp->level = EXPER_DVMRP;
18869 	optp->name = EXPER_DVMRP_MRT;
18870 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
18871 		ip0dbg(("ip_mroute_mrt: failed\n"));
18872 	}
18873 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18874 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
18875 	    (int)optp->level, (int)optp->name, (int)optp->len));
18876 	qreply(q, mpctl);
18877 	return (mp2ctl);
18878 }
18879 
18880 /*
18881  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
18882  * in one IRE walk.
18883  */
18884 static mblk_t *
18885 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18886 {
18887 	struct opthdr	*optp;
18888 	mblk_t		*mp2ctl;	/* Returned */
18889 	mblk_t		*mp3ctl;	/* nettomedia */
18890 	mblk_t		*mp4ctl;	/* routeattrs */
18891 	iproutedata_t	ird;
18892 	zoneid_t	zoneid;
18893 
18894 	/*
18895 	 * make copies of the original message
18896 	 *	- mp2ctl is returned unchanged to the caller for his use
18897 	 *	- mpctl is sent upstream as ipRouteEntryTable
18898 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
18899 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
18900 	 */
18901 	mp2ctl = copymsg(mpctl);
18902 	mp3ctl = copymsg(mpctl);
18903 	mp4ctl = copymsg(mpctl);
18904 	if (mp3ctl == NULL || mp4ctl == NULL) {
18905 		freemsg(mp4ctl);
18906 		freemsg(mp3ctl);
18907 		freemsg(mp2ctl);
18908 		freemsg(mpctl);
18909 		return (NULL);
18910 	}
18911 
18912 	bzero(&ird, sizeof (ird));
18913 
18914 	ird.ird_route.lp_head = mpctl->b_cont;
18915 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18916 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18917 
18918 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18919 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
18920 
18921 	/* ipRouteEntryTable in mpctl */
18922 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18923 	optp->level = MIB2_IP;
18924 	optp->name = MIB2_IP_ROUTE;
18925 	optp->len = msgdsize(ird.ird_route.lp_head);
18926 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18927 	    (int)optp->level, (int)optp->name, (int)optp->len));
18928 	qreply(q, mpctl);
18929 
18930 	/* ipNetToMediaEntryTable in mp3ctl */
18931 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18932 	optp->level = MIB2_IP;
18933 	optp->name = MIB2_IP_MEDIA;
18934 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18935 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18936 	    (int)optp->level, (int)optp->name, (int)optp->len));
18937 	qreply(q, mp3ctl);
18938 
18939 	/* ipRouteAttributeTable in mp4ctl */
18940 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18941 	optp->level = MIB2_IP;
18942 	optp->name = EXPER_IP_RTATTR;
18943 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18944 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18945 	    (int)optp->level, (int)optp->name, (int)optp->len));
18946 	if (optp->len == 0)
18947 		freemsg(mp4ctl);
18948 	else
18949 		qreply(q, mp4ctl);
18950 
18951 	return (mp2ctl);
18952 }
18953 
18954 /*
18955  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
18956  * ipv6NetToMediaEntryTable in an NDP walk.
18957  */
18958 static mblk_t *
18959 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18960 {
18961 	struct opthdr	*optp;
18962 	mblk_t		*mp2ctl;	/* Returned */
18963 	mblk_t		*mp3ctl;	/* nettomedia */
18964 	mblk_t		*mp4ctl;	/* routeattrs */
18965 	iproutedata_t	ird;
18966 	zoneid_t	zoneid;
18967 
18968 	/*
18969 	 * make copies of the original message
18970 	 *	- mp2ctl is returned unchanged to the caller for his use
18971 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
18972 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
18973 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
18974 	 */
18975 	mp2ctl = copymsg(mpctl);
18976 	mp3ctl = copymsg(mpctl);
18977 	mp4ctl = copymsg(mpctl);
18978 	if (mp3ctl == NULL || mp4ctl == NULL) {
18979 		freemsg(mp4ctl);
18980 		freemsg(mp3ctl);
18981 		freemsg(mp2ctl);
18982 		freemsg(mpctl);
18983 		return (NULL);
18984 	}
18985 
18986 	bzero(&ird, sizeof (ird));
18987 
18988 	ird.ird_route.lp_head = mpctl->b_cont;
18989 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18990 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18991 
18992 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18993 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
18994 
18995 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18996 	optp->level = MIB2_IP6;
18997 	optp->name = MIB2_IP6_ROUTE;
18998 	optp->len = msgdsize(ird.ird_route.lp_head);
18999 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19000 	    (int)optp->level, (int)optp->name, (int)optp->len));
19001 	qreply(q, mpctl);
19002 
19003 	/* ipv6NetToMediaEntryTable in mp3ctl */
19004 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19005 
19006 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19007 	optp->level = MIB2_IP6;
19008 	optp->name = MIB2_IP6_MEDIA;
19009 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19010 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19011 	    (int)optp->level, (int)optp->name, (int)optp->len));
19012 	qreply(q, mp3ctl);
19013 
19014 	/* ipv6RouteAttributeTable in mp4ctl */
19015 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19016 	optp->level = MIB2_IP6;
19017 	optp->name = EXPER_IP_RTATTR;
19018 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19019 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19020 	    (int)optp->level, (int)optp->name, (int)optp->len));
19021 	if (optp->len == 0)
19022 		freemsg(mp4ctl);
19023 	else
19024 		qreply(q, mp4ctl);
19025 
19026 	return (mp2ctl);
19027 }
19028 
19029 /*
19030  * IPv6 mib: One per ill
19031  */
19032 static mblk_t *
19033 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19034 {
19035 	struct opthdr		*optp;
19036 	mblk_t			*mp2ctl;
19037 	ill_t			*ill;
19038 	ill_walk_context_t	ctx;
19039 	mblk_t			*mp_tail = NULL;
19040 
19041 	/*
19042 	 * Make a copy of the original message
19043 	 */
19044 	mp2ctl = copymsg(mpctl);
19045 
19046 	/* fixed length IPv6 structure ... */
19047 
19048 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19049 	optp->level = MIB2_IP6;
19050 	optp->name = 0;
19051 	/* Include "unknown interface" ip6_mib */
19052 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19053 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19054 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19055 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19056 	    ipst->ips_ipv6_forward ? 1 : 2);
19057 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19058 	    ipst->ips_ipv6_def_hops);
19059 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19060 	    sizeof (mib2_ipIfStatsEntry_t));
19061 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19062 	    sizeof (mib2_ipv6AddrEntry_t));
19063 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19064 	    sizeof (mib2_ipv6RouteEntry_t));
19065 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19066 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19067 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19068 	    sizeof (ipv6_member_t));
19069 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19070 	    sizeof (ipv6_grpsrc_t));
19071 
19072 	/*
19073 	 * Synchronize 64- and 32-bit counters
19074 	 */
19075 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19076 	    ipIfStatsHCInReceives);
19077 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19078 	    ipIfStatsHCInDelivers);
19079 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19080 	    ipIfStatsHCOutRequests);
19081 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19082 	    ipIfStatsHCOutForwDatagrams);
19083 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19084 	    ipIfStatsHCOutMcastPkts);
19085 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19086 	    ipIfStatsHCInMcastPkts);
19087 
19088 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19089 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19090 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19091 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19092 	}
19093 
19094 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19095 	ill = ILL_START_WALK_V6(&ctx, ipst);
19096 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19097 		ill->ill_ip_mib->ipIfStatsIfIndex =
19098 		    ill->ill_phyint->phyint_ifindex;
19099 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19100 		    ipst->ips_ipv6_forward ? 1 : 2);
19101 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19102 		    ill->ill_max_hops);
19103 
19104 		/*
19105 		 * Synchronize 64- and 32-bit counters
19106 		 */
19107 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19108 		    ipIfStatsHCInReceives);
19109 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19110 		    ipIfStatsHCInDelivers);
19111 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19112 		    ipIfStatsHCOutRequests);
19113 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19114 		    ipIfStatsHCOutForwDatagrams);
19115 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19116 		    ipIfStatsHCOutMcastPkts);
19117 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19118 		    ipIfStatsHCInMcastPkts);
19119 
19120 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19121 		    (char *)ill->ill_ip_mib,
19122 		    (int)sizeof (*ill->ill_ip_mib))) {
19123 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19124 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19125 		}
19126 	}
19127 	rw_exit(&ipst->ips_ill_g_lock);
19128 
19129 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19130 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19131 	    (int)optp->level, (int)optp->name, (int)optp->len));
19132 	qreply(q, mpctl);
19133 	return (mp2ctl);
19134 }
19135 
19136 /*
19137  * ICMPv6 mib: One per ill
19138  */
19139 static mblk_t *
19140 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19141 {
19142 	struct opthdr		*optp;
19143 	mblk_t			*mp2ctl;
19144 	ill_t			*ill;
19145 	ill_walk_context_t	ctx;
19146 	mblk_t			*mp_tail = NULL;
19147 	/*
19148 	 * Make a copy of the original message
19149 	 */
19150 	mp2ctl = copymsg(mpctl);
19151 
19152 	/* fixed length ICMPv6 structure ... */
19153 
19154 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19155 	optp->level = MIB2_ICMP6;
19156 	optp->name = 0;
19157 	/* Include "unknown interface" icmp6_mib */
19158 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19159 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19160 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19161 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19162 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19163 	    (char *)&ipst->ips_icmp6_mib,
19164 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19165 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19166 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19167 	}
19168 
19169 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19170 	ill = ILL_START_WALK_V6(&ctx, ipst);
19171 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19172 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19173 		    ill->ill_phyint->phyint_ifindex;
19174 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19175 		    (char *)ill->ill_icmp6_mib,
19176 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19177 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19178 			    "%u bytes\n",
19179 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19180 		}
19181 	}
19182 	rw_exit(&ipst->ips_ill_g_lock);
19183 
19184 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19185 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19186 	    (int)optp->level, (int)optp->name, (int)optp->len));
19187 	qreply(q, mpctl);
19188 	return (mp2ctl);
19189 }
19190 
19191 /*
19192  * ire_walk routine to create both ipRouteEntryTable and
19193  * ipRouteAttributeTable in one IRE walk
19194  */
19195 static void
19196 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19197 {
19198 	ill_t				*ill;
19199 	ipif_t				*ipif;
19200 	mib2_ipRouteEntry_t		*re;
19201 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19202 	ipaddr_t			gw_addr;
19203 	tsol_ire_gw_secattr_t		*attrp;
19204 	tsol_gc_t			*gc = NULL;
19205 	tsol_gcgrp_t			*gcgrp = NULL;
19206 	uint_t				sacnt = 0;
19207 	int				i;
19208 
19209 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19210 
19211 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19212 		return;
19213 
19214 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19215 		mutex_enter(&attrp->igsa_lock);
19216 		if ((gc = attrp->igsa_gc) != NULL) {
19217 			gcgrp = gc->gc_grp;
19218 			ASSERT(gcgrp != NULL);
19219 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19220 			sacnt = 1;
19221 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19222 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19223 			gc = gcgrp->gcgrp_head;
19224 			sacnt = gcgrp->gcgrp_count;
19225 		}
19226 		mutex_exit(&attrp->igsa_lock);
19227 
19228 		/* do nothing if there's no gc to report */
19229 		if (gc == NULL) {
19230 			ASSERT(sacnt == 0);
19231 			if (gcgrp != NULL) {
19232 				/* we might as well drop the lock now */
19233 				rw_exit(&gcgrp->gcgrp_rwlock);
19234 				gcgrp = NULL;
19235 			}
19236 			attrp = NULL;
19237 		}
19238 
19239 		ASSERT(gc == NULL || (gcgrp != NULL &&
19240 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19241 	}
19242 	ASSERT(sacnt == 0 || gc != NULL);
19243 
19244 	if (sacnt != 0 &&
19245 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19246 		kmem_free(re, sizeof (*re));
19247 		rw_exit(&gcgrp->gcgrp_rwlock);
19248 		return;
19249 	}
19250 
19251 	/*
19252 	 * Return all IRE types for route table... let caller pick and choose
19253 	 */
19254 	re->ipRouteDest = ire->ire_addr;
19255 	ipif = ire->ire_ipif;
19256 	re->ipRouteIfIndex.o_length = 0;
19257 	if (ire->ire_type == IRE_CACHE) {
19258 		ill = (ill_t *)ire->ire_stq->q_ptr;
19259 		re->ipRouteIfIndex.o_length =
19260 		    ill->ill_name_length == 0 ? 0 :
19261 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19262 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19263 		    re->ipRouteIfIndex.o_length);
19264 	} else if (ipif != NULL) {
19265 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19266 		re->ipRouteIfIndex.o_length =
19267 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19268 	}
19269 	re->ipRouteMetric1 = -1;
19270 	re->ipRouteMetric2 = -1;
19271 	re->ipRouteMetric3 = -1;
19272 	re->ipRouteMetric4 = -1;
19273 
19274 	gw_addr = ire->ire_gateway_addr;
19275 
19276 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19277 		re->ipRouteNextHop = ire->ire_src_addr;
19278 	else
19279 		re->ipRouteNextHop = gw_addr;
19280 	/* indirect(4), direct(3), or invalid(2) */
19281 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19282 		re->ipRouteType = 2;
19283 	else
19284 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19285 	re->ipRouteProto = -1;
19286 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19287 	re->ipRouteMask = ire->ire_mask;
19288 	re->ipRouteMetric5 = -1;
19289 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19290 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19291 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19292 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19293 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19294 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19295 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19296 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19297 
19298 	if (ire->ire_flags & RTF_DYNAMIC) {
19299 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19300 	} else {
19301 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19302 	}
19303 
19304 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19305 	    (char *)re, (int)sizeof (*re))) {
19306 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19307 		    (uint_t)sizeof (*re)));
19308 	}
19309 
19310 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19311 		iaeptr->iae_routeidx = ird->ird_idx;
19312 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19313 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19314 	}
19315 
19316 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19317 	    (char *)iae, sacnt * sizeof (*iae))) {
19318 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19319 		    (unsigned)(sacnt * sizeof (*iae))));
19320 	}
19321 
19322 	/* bump route index for next pass */
19323 	ird->ird_idx++;
19324 
19325 	kmem_free(re, sizeof (*re));
19326 	if (sacnt != 0)
19327 		kmem_free(iae, sacnt * sizeof (*iae));
19328 
19329 	if (gcgrp != NULL)
19330 		rw_exit(&gcgrp->gcgrp_rwlock);
19331 }
19332 
19333 /*
19334  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19335  */
19336 static void
19337 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19338 {
19339 	ill_t				*ill;
19340 	ipif_t				*ipif;
19341 	mib2_ipv6RouteEntry_t		*re;
19342 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19343 	in6_addr_t			gw_addr_v6;
19344 	tsol_ire_gw_secattr_t		*attrp;
19345 	tsol_gc_t			*gc = NULL;
19346 	tsol_gcgrp_t			*gcgrp = NULL;
19347 	uint_t				sacnt = 0;
19348 	int				i;
19349 
19350 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19351 
19352 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19353 		return;
19354 
19355 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19356 		mutex_enter(&attrp->igsa_lock);
19357 		if ((gc = attrp->igsa_gc) != NULL) {
19358 			gcgrp = gc->gc_grp;
19359 			ASSERT(gcgrp != NULL);
19360 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19361 			sacnt = 1;
19362 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19363 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19364 			gc = gcgrp->gcgrp_head;
19365 			sacnt = gcgrp->gcgrp_count;
19366 		}
19367 		mutex_exit(&attrp->igsa_lock);
19368 
19369 		/* do nothing if there's no gc to report */
19370 		if (gc == NULL) {
19371 			ASSERT(sacnt == 0);
19372 			if (gcgrp != NULL) {
19373 				/* we might as well drop the lock now */
19374 				rw_exit(&gcgrp->gcgrp_rwlock);
19375 				gcgrp = NULL;
19376 			}
19377 			attrp = NULL;
19378 		}
19379 
19380 		ASSERT(gc == NULL || (gcgrp != NULL &&
19381 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19382 	}
19383 	ASSERT(sacnt == 0 || gc != NULL);
19384 
19385 	if (sacnt != 0 &&
19386 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19387 		kmem_free(re, sizeof (*re));
19388 		rw_exit(&gcgrp->gcgrp_rwlock);
19389 		return;
19390 	}
19391 
19392 	/*
19393 	 * Return all IRE types for route table... let caller pick and choose
19394 	 */
19395 	re->ipv6RouteDest = ire->ire_addr_v6;
19396 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19397 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19398 	re->ipv6RouteIfIndex.o_length = 0;
19399 	ipif = ire->ire_ipif;
19400 	if (ire->ire_type == IRE_CACHE) {
19401 		ill = (ill_t *)ire->ire_stq->q_ptr;
19402 		re->ipv6RouteIfIndex.o_length =
19403 		    ill->ill_name_length == 0 ? 0 :
19404 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19405 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19406 		    re->ipv6RouteIfIndex.o_length);
19407 	} else if (ipif != NULL) {
19408 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19409 		re->ipv6RouteIfIndex.o_length =
19410 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19411 	}
19412 
19413 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19414 
19415 	mutex_enter(&ire->ire_lock);
19416 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19417 	mutex_exit(&ire->ire_lock);
19418 
19419 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19420 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19421 	else
19422 		re->ipv6RouteNextHop = gw_addr_v6;
19423 
19424 	/* remote(4), local(3), or discard(2) */
19425 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19426 		re->ipv6RouteType = 2;
19427 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19428 		re->ipv6RouteType = 3;
19429 	else
19430 		re->ipv6RouteType = 4;
19431 
19432 	re->ipv6RouteProtocol	= -1;
19433 	re->ipv6RoutePolicy	= 0;
19434 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19435 	re->ipv6RouteNextHopRDI	= 0;
19436 	re->ipv6RouteWeight	= 0;
19437 	re->ipv6RouteMetric	= 0;
19438 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19439 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19440 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19441 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19442 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19443 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19444 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19445 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19446 
19447 	if (ire->ire_flags & RTF_DYNAMIC) {
19448 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19449 	} else {
19450 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19451 	}
19452 
19453 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19454 	    (char *)re, (int)sizeof (*re))) {
19455 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19456 		    (uint_t)sizeof (*re)));
19457 	}
19458 
19459 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19460 		iaeptr->iae_routeidx = ird->ird_idx;
19461 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19462 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19463 	}
19464 
19465 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19466 	    (char *)iae, sacnt * sizeof (*iae))) {
19467 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19468 		    (unsigned)(sacnt * sizeof (*iae))));
19469 	}
19470 
19471 	/* bump route index for next pass */
19472 	ird->ird_idx++;
19473 
19474 	kmem_free(re, sizeof (*re));
19475 	if (sacnt != 0)
19476 		kmem_free(iae, sacnt * sizeof (*iae));
19477 
19478 	if (gcgrp != NULL)
19479 		rw_exit(&gcgrp->gcgrp_rwlock);
19480 }
19481 
19482 /*
19483  * ndp_walk routine to create ipv6NetToMediaEntryTable
19484  */
19485 static int
19486 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19487 {
19488 	ill_t				*ill;
19489 	mib2_ipv6NetToMediaEntry_t	ntme;
19490 	dl_unitdata_req_t		*dl;
19491 
19492 	ill = nce->nce_ill;
19493 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19494 		return (0);
19495 
19496 	/*
19497 	 * Neighbor cache entry attached to IRE with on-link
19498 	 * destination.
19499 	 */
19500 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19501 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19502 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19503 	    (nce->nce_res_mp != NULL)) {
19504 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19505 		ntme.ipv6NetToMediaPhysAddress.o_length =
19506 		    dl->dl_dest_addr_length;
19507 	} else {
19508 		ntme.ipv6NetToMediaPhysAddress.o_length =
19509 		    ill->ill_phys_addr_length;
19510 	}
19511 	if (nce->nce_res_mp != NULL) {
19512 		bcopy((char *)nce->nce_res_mp->b_rptr +
19513 		    NCE_LL_ADDR_OFFSET(ill),
19514 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19515 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19516 	} else {
19517 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19518 		    ill->ill_phys_addr_length);
19519 	}
19520 	/*
19521 	 * Note: Returns ND_* states. Should be:
19522 	 * reachable(1), stale(2), delay(3), probe(4),
19523 	 * invalid(5), unknown(6)
19524 	 */
19525 	ntme.ipv6NetToMediaState = nce->nce_state;
19526 	ntme.ipv6NetToMediaLastUpdated = 0;
19527 
19528 	/* other(1), dynamic(2), static(3), local(4) */
19529 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19530 		ntme.ipv6NetToMediaType = 4;
19531 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19532 		ntme.ipv6NetToMediaType = 1;
19533 	} else {
19534 		ntme.ipv6NetToMediaType = 2;
19535 	}
19536 
19537 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19538 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19539 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19540 		    (uint_t)sizeof (ntme)));
19541 	}
19542 	return (0);
19543 }
19544 
19545 /*
19546  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19547  */
19548 /* ARGSUSED */
19549 int
19550 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19551 {
19552 	switch (level) {
19553 	case MIB2_IP:
19554 	case MIB2_ICMP:
19555 		switch (name) {
19556 		default:
19557 			break;
19558 		}
19559 		return (1);
19560 	default:
19561 		return (1);
19562 	}
19563 }
19564 
19565 /*
19566  * When there exists both a 64- and 32-bit counter of a particular type
19567  * (i.e., InReceives), only the 64-bit counters are added.
19568  */
19569 void
19570 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19571 {
19572 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19573 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19574 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19575 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19576 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19577 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19578 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19579 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19580 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19581 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19582 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19583 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19584 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19585 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19586 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19587 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19588 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19589 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19590 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19591 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19592 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19593 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19594 	    o2->ipIfStatsInWrongIPVersion);
19595 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19596 	    o2->ipIfStatsInWrongIPVersion);
19597 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19598 	    o2->ipIfStatsOutSwitchIPVersion);
19599 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19600 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19601 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19602 	    o2->ipIfStatsHCInForwDatagrams);
19603 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19604 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19605 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19606 	    o2->ipIfStatsHCOutForwDatagrams);
19607 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19608 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19609 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19610 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19611 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19612 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19613 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19614 	    o2->ipIfStatsHCOutMcastOctets);
19615 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19616 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19617 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19618 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19619 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19620 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19621 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19622 }
19623 
19624 void
19625 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19626 {
19627 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19628 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19629 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19630 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19631 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19632 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19633 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19634 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19635 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19636 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19637 	    o2->ipv6IfIcmpInRouterSolicits);
19638 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19639 	    o2->ipv6IfIcmpInRouterAdvertisements);
19640 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19641 	    o2->ipv6IfIcmpInNeighborSolicits);
19642 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19643 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19644 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19645 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19646 	    o2->ipv6IfIcmpInGroupMembQueries);
19647 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19648 	    o2->ipv6IfIcmpInGroupMembResponses);
19649 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19650 	    o2->ipv6IfIcmpInGroupMembReductions);
19651 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19652 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19653 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19654 	    o2->ipv6IfIcmpOutDestUnreachs);
19655 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19656 	    o2->ipv6IfIcmpOutAdminProhibs);
19657 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19658 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19659 	    o2->ipv6IfIcmpOutParmProblems);
19660 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19661 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19662 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19663 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19664 	    o2->ipv6IfIcmpOutRouterSolicits);
19665 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19666 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19667 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19668 	    o2->ipv6IfIcmpOutNeighborSolicits);
19669 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19670 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19671 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19672 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19673 	    o2->ipv6IfIcmpOutGroupMembQueries);
19674 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19675 	    o2->ipv6IfIcmpOutGroupMembResponses);
19676 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19677 	    o2->ipv6IfIcmpOutGroupMembReductions);
19678 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19679 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19680 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19681 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19682 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19683 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19684 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19685 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19686 	    o2->ipv6IfIcmpInGroupMembTotal);
19687 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19688 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19689 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19690 	    o2->ipv6IfIcmpInGroupMembBadReports);
19691 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19692 	    o2->ipv6IfIcmpInGroupMembOurReports);
19693 }
19694 
19695 /*
19696  * Called before the options are updated to check if this packet will
19697  * be source routed from here.
19698  * This routine assumes that the options are well formed i.e. that they
19699  * have already been checked.
19700  */
19701 static boolean_t
19702 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
19703 {
19704 	ipoptp_t	opts;
19705 	uchar_t		*opt;
19706 	uint8_t		optval;
19707 	uint8_t		optlen;
19708 	ipaddr_t	dst;
19709 	ire_t		*ire;
19710 
19711 	if (IS_SIMPLE_IPH(ipha)) {
19712 		ip2dbg(("not source routed\n"));
19713 		return (B_FALSE);
19714 	}
19715 	dst = ipha->ipha_dst;
19716 	for (optval = ipoptp_first(&opts, ipha);
19717 	    optval != IPOPT_EOL;
19718 	    optval = ipoptp_next(&opts)) {
19719 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19720 		opt = opts.ipoptp_cur;
19721 		optlen = opts.ipoptp_len;
19722 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19723 		    optval, optlen));
19724 		switch (optval) {
19725 			uint32_t off;
19726 		case IPOPT_SSRR:
19727 		case IPOPT_LSRR:
19728 			/*
19729 			 * If dst is one of our addresses and there are some
19730 			 * entries left in the source route return (true).
19731 			 */
19732 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19733 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
19734 			if (ire == NULL) {
19735 				ip2dbg(("ip_source_routed: not next"
19736 				    " source route 0x%x\n",
19737 				    ntohl(dst)));
19738 				return (B_FALSE);
19739 			}
19740 			ire_refrele(ire);
19741 			off = opt[IPOPT_OFFSET];
19742 			off--;
19743 			if (optlen < IP_ADDR_LEN ||
19744 			    off > optlen - IP_ADDR_LEN) {
19745 				/* End of source route */
19746 				ip1dbg(("ip_source_routed: end of SR\n"));
19747 				return (B_FALSE);
19748 			}
19749 			return (B_TRUE);
19750 		}
19751 	}
19752 	ip2dbg(("not source routed\n"));
19753 	return (B_FALSE);
19754 }
19755 
19756 /*
19757  * Check if the packet contains any source route.
19758  */
19759 static boolean_t
19760 ip_source_route_included(ipha_t *ipha)
19761 {
19762 	ipoptp_t	opts;
19763 	uint8_t		optval;
19764 
19765 	if (IS_SIMPLE_IPH(ipha))
19766 		return (B_FALSE);
19767 	for (optval = ipoptp_first(&opts, ipha);
19768 	    optval != IPOPT_EOL;
19769 	    optval = ipoptp_next(&opts)) {
19770 		switch (optval) {
19771 		case IPOPT_SSRR:
19772 		case IPOPT_LSRR:
19773 			return (B_TRUE);
19774 		}
19775 	}
19776 	return (B_FALSE);
19777 }
19778 
19779 /*
19780  * Called when the IRE expiration timer fires.
19781  */
19782 void
19783 ip_trash_timer_expire(void *args)
19784 {
19785 	int			flush_flag = 0;
19786 	ire_expire_arg_t	iea;
19787 	ip_stack_t		*ipst = (ip_stack_t *)args;
19788 
19789 	iea.iea_ipst = ipst;	/* No netstack_hold */
19790 
19791 	/*
19792 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19793 	 * This lock makes sure that a new invocation of this function
19794 	 * that occurs due to an almost immediate timer firing will not
19795 	 * progress beyond this point until the current invocation is done
19796 	 */
19797 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19798 	ipst->ips_ip_ire_expire_id = 0;
19799 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19800 
19801 	/* Periodic timer */
19802 	if (ipst->ips_ip_ire_arp_time_elapsed >=
19803 	    ipst->ips_ip_ire_arp_interval) {
19804 		/*
19805 		 * Remove all IRE_CACHE entries since they might
19806 		 * contain arp information.
19807 		 */
19808 		flush_flag |= FLUSH_ARP_TIME;
19809 		ipst->ips_ip_ire_arp_time_elapsed = 0;
19810 		IP_STAT(ipst, ip_ire_arp_timer_expired);
19811 	}
19812 	if (ipst->ips_ip_ire_rd_time_elapsed >=
19813 	    ipst->ips_ip_ire_redir_interval) {
19814 		/* Remove all redirects */
19815 		flush_flag |= FLUSH_REDIRECT_TIME;
19816 		ipst->ips_ip_ire_rd_time_elapsed = 0;
19817 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
19818 	}
19819 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
19820 	    ipst->ips_ip_ire_pathmtu_interval) {
19821 		/* Increase path mtu */
19822 		flush_flag |= FLUSH_MTU_TIME;
19823 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
19824 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
19825 	}
19826 
19827 	/*
19828 	 * Optimize for the case when there are no redirects in the
19829 	 * ftable, that is, no need to walk the ftable in that case.
19830 	 */
19831 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
19832 		iea.iea_flush_flag = flush_flag;
19833 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
19834 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
19835 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
19836 		    NULL, ALL_ZONES, ipst);
19837 	}
19838 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
19839 	    ipst->ips_ip_redirect_cnt > 0) {
19840 		iea.iea_flush_flag = flush_flag;
19841 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
19842 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
19843 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
19844 	}
19845 	if (flush_flag & FLUSH_MTU_TIME) {
19846 		/*
19847 		 * Walk all IPv6 IRE's and update them
19848 		 * Note that ARP and redirect timers are not
19849 		 * needed since NUD handles stale entries.
19850 		 */
19851 		flush_flag = FLUSH_MTU_TIME;
19852 		iea.iea_flush_flag = flush_flag;
19853 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
19854 		    ALL_ZONES, ipst);
19855 	}
19856 
19857 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
19858 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
19859 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
19860 
19861 	/*
19862 	 * Hold the lock to serialize timeout calls and prevent
19863 	 * stale values in ip_ire_expire_id. Otherwise it is possible
19864 	 * for the timer to fire and a new invocation of this function
19865 	 * to start before the return value of timeout has been stored
19866 	 * in ip_ire_expire_id by the current invocation.
19867 	 */
19868 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19869 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
19870 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
19871 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19872 }
19873 
19874 /*
19875  * Called by the memory allocator subsystem directly, when the system
19876  * is running low on memory.
19877  */
19878 /* ARGSUSED */
19879 void
19880 ip_trash_ire_reclaim(void *args)
19881 {
19882 	netstack_handle_t nh;
19883 	netstack_t *ns;
19884 
19885 	netstack_next_init(&nh);
19886 	while ((ns = netstack_next(&nh)) != NULL) {
19887 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
19888 		netstack_rele(ns);
19889 	}
19890 	netstack_next_fini(&nh);
19891 }
19892 
19893 static void
19894 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
19895 {
19896 	ire_cache_count_t icc;
19897 	ire_cache_reclaim_t icr;
19898 	ncc_cache_count_t ncc;
19899 	nce_cache_reclaim_t ncr;
19900 	uint_t delete_cnt;
19901 	/*
19902 	 * Memory reclaim call back.
19903 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
19904 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
19905 	 * entries, determine what fraction to free for
19906 	 * each category of IRE_CACHE entries giving absolute priority
19907 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
19908 	 * entry will be freed unless all offlink entries are freed).
19909 	 */
19910 	icc.icc_total = 0;
19911 	icc.icc_unused = 0;
19912 	icc.icc_offlink = 0;
19913 	icc.icc_pmtu = 0;
19914 	icc.icc_onlink = 0;
19915 	ire_walk(ire_cache_count, (char *)&icc, ipst);
19916 
19917 	/*
19918 	 * Free NCEs for IPv6 like the onlink ires.
19919 	 */
19920 	ncc.ncc_total = 0;
19921 	ncc.ncc_host = 0;
19922 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
19923 
19924 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
19925 	    icc.icc_pmtu + icc.icc_onlink);
19926 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
19927 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
19928 	if (delete_cnt == 0)
19929 		return;
19930 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
19931 	/* Always delete all unused offlink entries */
19932 	icr.icr_ipst = ipst;
19933 	icr.icr_unused = 1;
19934 	if (delete_cnt <= icc.icc_unused) {
19935 		/*
19936 		 * Only need to free unused entries.  In other words,
19937 		 * there are enough unused entries to free to meet our
19938 		 * target number of freed ire cache entries.
19939 		 */
19940 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
19941 		ncr.ncr_host = 0;
19942 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
19943 		/*
19944 		 * Only need to free unused entries, plus a fraction of offlink
19945 		 * entries.  It follows from the first if statement that
19946 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
19947 		 */
19948 		delete_cnt -= icc.icc_unused;
19949 		/* Round up # deleted by truncating fraction */
19950 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
19951 		icr.icr_pmtu = icr.icr_onlink = 0;
19952 		ncr.ncr_host = 0;
19953 	} else if (delete_cnt <=
19954 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
19955 		/*
19956 		 * Free all unused and offlink entries, plus a fraction of
19957 		 * pmtu entries.  It follows from the previous if statement
19958 		 * that icc_pmtu is non-zero, and that
19959 		 * delete_cnt != icc_unused + icc_offlink.
19960 		 */
19961 		icr.icr_offlink = 1;
19962 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
19963 		/* Round up # deleted by truncating fraction */
19964 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
19965 		icr.icr_onlink = 0;
19966 		ncr.ncr_host = 0;
19967 	} else {
19968 		/*
19969 		 * Free all unused, offlink, and pmtu entries, plus a fraction
19970 		 * of onlink entries.  If we're here, then we know that
19971 		 * icc_onlink is non-zero, and that
19972 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
19973 		 */
19974 		icr.icr_offlink = icr.icr_pmtu = 1;
19975 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
19976 		    icc.icc_pmtu;
19977 		/* Round up # deleted by truncating fraction */
19978 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
19979 		/* Using the same delete fraction as for onlink IREs */
19980 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
19981 	}
19982 #ifdef DEBUG
19983 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
19984 	    "fractions %d/%d/%d/%d\n",
19985 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
19986 	    icc.icc_unused, icc.icc_offlink,
19987 	    icc.icc_pmtu, icc.icc_onlink,
19988 	    icr.icr_unused, icr.icr_offlink,
19989 	    icr.icr_pmtu, icr.icr_onlink));
19990 #endif
19991 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
19992 	if (ncr.ncr_host != 0)
19993 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
19994 		    (uchar_t *)&ncr, ipst);
19995 #ifdef DEBUG
19996 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
19997 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
19998 	ire_walk(ire_cache_count, (char *)&icc, ipst);
19999 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20000 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20001 	    icc.icc_pmtu, icc.icc_onlink));
20002 #endif
20003 }
20004 
20005 /*
20006  * ip_unbind is called when a copy of an unbind request is received from the
20007  * upper level protocol.  We remove this conn from any fanout hash list it is
20008  * on, and zero out the bind information.  No reply is expected up above.
20009  */
20010 mblk_t *
20011 ip_unbind(queue_t *q, mblk_t *mp)
20012 {
20013 	conn_t	*connp = Q_TO_CONN(q);
20014 
20015 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20016 
20017 	if (is_system_labeled() && connp->conn_anon_port) {
20018 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20019 		    connp->conn_mlp_type, connp->conn_ulp,
20020 		    ntohs(connp->conn_lport), B_FALSE);
20021 		connp->conn_anon_port = 0;
20022 	}
20023 	connp->conn_mlp_type = mlptSingle;
20024 
20025 	ipcl_hash_remove(connp);
20026 
20027 	ASSERT(mp->b_cont == NULL);
20028 	/*
20029 	 * Convert mp into a T_OK_ACK
20030 	 */
20031 	mp = mi_tpi_ok_ack_alloc(mp);
20032 
20033 	/*
20034 	 * should not happen in practice... T_OK_ACK is smaller than the
20035 	 * original message.
20036 	 */
20037 	if (mp == NULL)
20038 		return (NULL);
20039 
20040 	return (mp);
20041 }
20042 
20043 /*
20044  * Write side put procedure.  Outbound data, IOCTLs, responses from
20045  * resolvers, etc, come down through here.
20046  *
20047  * arg2 is always a queue_t *.
20048  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20049  * the zoneid.
20050  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20051  */
20052 void
20053 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20054 {
20055 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20056 }
20057 
20058 void
20059 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20060     ip_opt_info_t *infop)
20061 {
20062 	conn_t		*connp = NULL;
20063 	queue_t		*q = (queue_t *)arg2;
20064 	ipha_t		*ipha;
20065 #define	rptr	((uchar_t *)ipha)
20066 	ire_t		*ire = NULL;
20067 	ire_t		*sctp_ire = NULL;
20068 	uint32_t	v_hlen_tos_len;
20069 	ipaddr_t	dst;
20070 	mblk_t		*first_mp = NULL;
20071 	boolean_t	mctl_present;
20072 	ipsec_out_t	*io;
20073 	int		match_flags;
20074 	ill_t		*attach_ill = NULL;
20075 					/* Bind to IPIF_NOFAILOVER ill etc. */
20076 	ill_t		*xmit_ill = NULL;	/* IP_PKTINFO etc. */
20077 	ipif_t		*dst_ipif;
20078 	boolean_t	multirt_need_resolve = B_FALSE;
20079 	mblk_t		*copy_mp = NULL;
20080 	int		err;
20081 	zoneid_t	zoneid;
20082 	int	adjust;
20083 	uint16_t iplen;
20084 	boolean_t	need_decref = B_FALSE;
20085 	boolean_t	ignore_dontroute = B_FALSE;
20086 	boolean_t	ignore_nexthop = B_FALSE;
20087 	boolean_t	ip_nexthop = B_FALSE;
20088 	ipaddr_t	nexthop_addr;
20089 	ip_stack_t	*ipst;
20090 
20091 #ifdef	_BIG_ENDIAN
20092 #define	V_HLEN	(v_hlen_tos_len >> 24)
20093 #else
20094 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20095 #endif
20096 
20097 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20098 	    "ip_wput_start: q %p", q);
20099 
20100 	/*
20101 	 * ip_wput fast path
20102 	 */
20103 
20104 	/* is packet from ARP ? */
20105 	if (q->q_next != NULL) {
20106 		zoneid = (zoneid_t)(uintptr_t)arg;
20107 		goto qnext;
20108 	}
20109 
20110 	connp = (conn_t *)arg;
20111 	ASSERT(connp != NULL);
20112 	zoneid = connp->conn_zoneid;
20113 	ipst = connp->conn_netstack->netstack_ip;
20114 
20115 	/* is queue flow controlled? */
20116 	if ((q->q_first != NULL || connp->conn_draining) &&
20117 	    (caller == IP_WPUT)) {
20118 		ASSERT(!need_decref);
20119 		(void) putq(q, mp);
20120 		return;
20121 	}
20122 
20123 	/* Multidata transmit? */
20124 	if (DB_TYPE(mp) == M_MULTIDATA) {
20125 		/*
20126 		 * We should never get here, since all Multidata messages
20127 		 * originating from tcp should have been directed over to
20128 		 * tcp_multisend() in the first place.
20129 		 */
20130 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20131 		freemsg(mp);
20132 		return;
20133 	} else if (DB_TYPE(mp) != M_DATA)
20134 		goto notdata;
20135 
20136 	if (mp->b_flag & MSGHASREF) {
20137 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20138 		mp->b_flag &= ~MSGHASREF;
20139 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20140 		need_decref = B_TRUE;
20141 	}
20142 	ipha = (ipha_t *)mp->b_rptr;
20143 
20144 	/* is IP header non-aligned or mblk smaller than basic IP header */
20145 #ifndef SAFETY_BEFORE_SPEED
20146 	if (!OK_32PTR(rptr) ||
20147 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20148 		goto hdrtoosmall;
20149 #endif
20150 
20151 	ASSERT(OK_32PTR(ipha));
20152 
20153 	/*
20154 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20155 	 * wrong version, we'll catch it again in ip_output_v6.
20156 	 *
20157 	 * Note that this is *only* locally-generated output here, and never
20158 	 * forwarded data, and that we need to deal only with transports that
20159 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20160 	 * label.)
20161 	 */
20162 	if (is_system_labeled() &&
20163 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20164 	    !connp->conn_ulp_labeled) {
20165 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
20166 		    connp->conn_mac_exempt, ipst);
20167 		ipha = (ipha_t *)mp->b_rptr;
20168 		if (err != 0) {
20169 			first_mp = mp;
20170 			if (err == EINVAL)
20171 				goto icmp_parameter_problem;
20172 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20173 			goto discard_pkt;
20174 		}
20175 		iplen = ntohs(ipha->ipha_length) + adjust;
20176 		ipha->ipha_length = htons(iplen);
20177 	}
20178 
20179 	ASSERT(infop != NULL);
20180 
20181 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20182 		/*
20183 		 * IP_PKTINFO ancillary option is present.
20184 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20185 		 * allows using address of any zone as the source address.
20186 		 */
20187 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20188 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20189 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20190 		if (ire == NULL)
20191 			goto drop_pkt;
20192 		ire_refrele(ire);
20193 		ire = NULL;
20194 	}
20195 
20196 	/*
20197 	 * IP_DONTFAILOVER_IF and IP_BOUND_IF have precedence over ill index
20198 	 * passed in IP_PKTINFO.
20199 	 */
20200 	if (infop->ip_opt_ill_index != 0 &&
20201 	    connp->conn_outgoing_ill == NULL &&
20202 	    connp->conn_nofailover_ill == NULL) {
20203 
20204 		xmit_ill = ill_lookup_on_ifindex(
20205 		    infop->ip_opt_ill_index, B_FALSE, NULL, NULL, NULL, NULL,
20206 		    ipst);
20207 
20208 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20209 			goto drop_pkt;
20210 		/*
20211 		 * check that there is an ipif belonging
20212 		 * to our zone. IPCL_ZONEID is not used because
20213 		 * IP_ALLZONES option is valid only when the ill is
20214 		 * accessible from all zones i.e has a valid ipif in
20215 		 * all zones.
20216 		 */
20217 		if (!ipif_lookup_zoneid_group(xmit_ill, zoneid, 0, NULL)) {
20218 			goto drop_pkt;
20219 		}
20220 	}
20221 
20222 	/*
20223 	 * If there is a policy, try to attach an ipsec_out in
20224 	 * the front. At the end, first_mp either points to a
20225 	 * M_DATA message or IPSEC_OUT message linked to a
20226 	 * M_DATA message. We have to do it now as we might
20227 	 * lose the "conn" if we go through ip_newroute.
20228 	 */
20229 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20230 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20231 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20232 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20233 			if (need_decref)
20234 				CONN_DEC_REF(connp);
20235 			return;
20236 		} else {
20237 			ASSERT(mp->b_datap->db_type == M_CTL);
20238 			first_mp = mp;
20239 			mp = mp->b_cont;
20240 			mctl_present = B_TRUE;
20241 		}
20242 	} else {
20243 		first_mp = mp;
20244 		mctl_present = B_FALSE;
20245 	}
20246 
20247 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20248 
20249 	/* is wrong version or IP options present */
20250 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20251 		goto version_hdrlen_check;
20252 	dst = ipha->ipha_dst;
20253 
20254 	if (connp->conn_nofailover_ill != NULL) {
20255 		attach_ill = conn_get_held_ill(connp,
20256 		    &connp->conn_nofailover_ill, &err);
20257 		if (err == ILL_LOOKUP_FAILED) {
20258 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20259 			if (need_decref)
20260 				CONN_DEC_REF(connp);
20261 			freemsg(first_mp);
20262 			return;
20263 		}
20264 	}
20265 
20266 	/* If IP_BOUND_IF has been set, use that ill. */
20267 	if (connp->conn_outgoing_ill != NULL) {
20268 		xmit_ill = conn_get_held_ill(connp,
20269 		    &connp->conn_outgoing_ill, &err);
20270 		if (err == ILL_LOOKUP_FAILED)
20271 			goto drop_pkt;
20272 
20273 		goto send_from_ill;
20274 	}
20275 
20276 	/* is packet multicast? */
20277 	if (CLASSD(dst))
20278 		goto multicast;
20279 
20280 	/*
20281 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20282 	 * takes precedence over conn_dontroute and conn_nexthop_set
20283 	 */
20284 	if (xmit_ill != NULL)
20285 		goto send_from_ill;
20286 
20287 	if (connp->conn_dontroute || connp->conn_nexthop_set) {
20288 		/*
20289 		 * If the destination is a broadcast, local, or loopback
20290 		 * address, SO_DONTROUTE and IP_NEXTHOP go through the
20291 		 * standard path.
20292 		 */
20293 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20294 		if ((ire == NULL) || (ire->ire_type &
20295 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK)) == 0) {
20296 			if (ire != NULL) {
20297 				ire_refrele(ire);
20298 				/* No more access to ire */
20299 				ire = NULL;
20300 			}
20301 			/*
20302 			 * bypass routing checks and go directly to interface.
20303 			 */
20304 			if (connp->conn_dontroute)
20305 				goto dontroute;
20306 
20307 			ASSERT(connp->conn_nexthop_set);
20308 			ip_nexthop = B_TRUE;
20309 			nexthop_addr = connp->conn_nexthop_v4;
20310 			goto send_from_ill;
20311 		}
20312 
20313 		/* Must be a broadcast, a loopback or a local ire */
20314 		ire_refrele(ire);
20315 		/* No more access to ire */
20316 		ire = NULL;
20317 	}
20318 
20319 	if (attach_ill != NULL)
20320 		goto send_from_ill;
20321 
20322 	/*
20323 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20324 	 * this for the tcp global queue and listen end point
20325 	 * as it does not really have a real destination to
20326 	 * talk to.  This is also true for SCTP.
20327 	 */
20328 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20329 	    !connp->conn_fully_bound) {
20330 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20331 		if (ire == NULL)
20332 			goto noirefound;
20333 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20334 		    "ip_wput_end: q %p (%S)", q, "end");
20335 
20336 		/*
20337 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20338 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20339 		 */
20340 		if (ire->ire_flags & RTF_MULTIRT) {
20341 
20342 			/*
20343 			 * Force the TTL of multirouted packets if required.
20344 			 * The TTL of such packets is bounded by the
20345 			 * ip_multirt_ttl ndd variable.
20346 			 */
20347 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20348 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20349 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20350 				    "(was %d), dst 0x%08x\n",
20351 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20352 				    ntohl(ire->ire_addr)));
20353 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20354 			}
20355 			/*
20356 			 * We look at this point if there are pending
20357 			 * unresolved routes. ire_multirt_resolvable()
20358 			 * checks in O(n) that all IRE_OFFSUBNET ire
20359 			 * entries for the packet's destination and
20360 			 * flagged RTF_MULTIRT are currently resolved.
20361 			 * If some remain unresolved, we make a copy
20362 			 * of the current message. It will be used
20363 			 * to initiate additional route resolutions.
20364 			 */
20365 			multirt_need_resolve =
20366 			    ire_multirt_need_resolve(ire->ire_addr,
20367 			    MBLK_GETLABEL(first_mp), ipst);
20368 			ip2dbg(("ip_wput[TCP]: ire %p, "
20369 			    "multirt_need_resolve %d, first_mp %p\n",
20370 			    (void *)ire, multirt_need_resolve,
20371 			    (void *)first_mp));
20372 			if (multirt_need_resolve) {
20373 				copy_mp = copymsg(first_mp);
20374 				if (copy_mp != NULL) {
20375 					MULTIRT_DEBUG_TAG(copy_mp);
20376 				}
20377 			}
20378 		}
20379 
20380 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20381 
20382 		/*
20383 		 * Try to resolve another multiroute if
20384 		 * ire_multirt_need_resolve() deemed it necessary.
20385 		 */
20386 		if (copy_mp != NULL)
20387 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20388 		if (need_decref)
20389 			CONN_DEC_REF(connp);
20390 		return;
20391 	}
20392 
20393 	/*
20394 	 * Access to conn_ire_cache. (protected by conn_lock)
20395 	 *
20396 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20397 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20398 	 * send a packet or two with the IRE_CACHE that is going away.
20399 	 * Access to the ire requires an ire refhold on the ire prior to
20400 	 * its use since an interface unplumb thread may delete the cached
20401 	 * ire and release the refhold at any time.
20402 	 *
20403 	 * Caching an ire in the conn_ire_cache
20404 	 *
20405 	 * o Caching an ire pointer in the conn requires a strict check for
20406 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20407 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20408 	 * in the conn is done after making sure under the bucket lock that the
20409 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20410 	 * caching an ire after the unplumb thread has cleaned up the conn.
20411 	 * If the conn does not send a packet subsequently the unplumb thread
20412 	 * will be hanging waiting for the ire count to drop to zero.
20413 	 *
20414 	 * o We also need to atomically test for a null conn_ire_cache and
20415 	 * set the conn_ire_cache under the the protection of the conn_lock
20416 	 * to avoid races among concurrent threads trying to simultaneously
20417 	 * cache an ire in the conn_ire_cache.
20418 	 */
20419 	mutex_enter(&connp->conn_lock);
20420 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20421 
20422 	if (ire != NULL && ire->ire_addr == dst &&
20423 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20424 
20425 		IRE_REFHOLD(ire);
20426 		mutex_exit(&connp->conn_lock);
20427 
20428 	} else {
20429 		boolean_t cached = B_FALSE;
20430 		connp->conn_ire_cache = NULL;
20431 		mutex_exit(&connp->conn_lock);
20432 		/* Release the old ire */
20433 		if (ire != NULL && sctp_ire == NULL)
20434 			IRE_REFRELE_NOTR(ire);
20435 
20436 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20437 		if (ire == NULL)
20438 			goto noirefound;
20439 		IRE_REFHOLD_NOTR(ire);
20440 
20441 		mutex_enter(&connp->conn_lock);
20442 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20443 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20444 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20445 				if (connp->conn_ulp == IPPROTO_TCP)
20446 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20447 				connp->conn_ire_cache = ire;
20448 				cached = B_TRUE;
20449 			}
20450 			rw_exit(&ire->ire_bucket->irb_lock);
20451 		}
20452 		mutex_exit(&connp->conn_lock);
20453 
20454 		/*
20455 		 * We can continue to use the ire but since it was
20456 		 * not cached, we should drop the extra reference.
20457 		 */
20458 		if (!cached)
20459 			IRE_REFRELE_NOTR(ire);
20460 	}
20461 
20462 
20463 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20464 	    "ip_wput_end: q %p (%S)", q, "end");
20465 
20466 	/*
20467 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20468 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20469 	 */
20470 	if (ire->ire_flags & RTF_MULTIRT) {
20471 
20472 		/*
20473 		 * Force the TTL of multirouted packets if required.
20474 		 * The TTL of such packets is bounded by the
20475 		 * ip_multirt_ttl ndd variable.
20476 		 */
20477 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20478 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20479 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20480 			    "(was %d), dst 0x%08x\n",
20481 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20482 			    ntohl(ire->ire_addr)));
20483 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20484 		}
20485 
20486 		/*
20487 		 * At this point, we check to see if there are any pending
20488 		 * unresolved routes. ire_multirt_resolvable()
20489 		 * checks in O(n) that all IRE_OFFSUBNET ire
20490 		 * entries for the packet's destination and
20491 		 * flagged RTF_MULTIRT are currently resolved.
20492 		 * If some remain unresolved, we make a copy
20493 		 * of the current message. It will be used
20494 		 * to initiate additional route resolutions.
20495 		 */
20496 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20497 		    MBLK_GETLABEL(first_mp), ipst);
20498 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20499 		    "multirt_need_resolve %d, first_mp %p\n",
20500 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20501 		if (multirt_need_resolve) {
20502 			copy_mp = copymsg(first_mp);
20503 			if (copy_mp != NULL) {
20504 				MULTIRT_DEBUG_TAG(copy_mp);
20505 			}
20506 		}
20507 	}
20508 
20509 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20510 
20511 	/*
20512 	 * Try to resolve another multiroute if
20513 	 * ire_multirt_resolvable() deemed it necessary
20514 	 */
20515 	if (copy_mp != NULL)
20516 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20517 	if (need_decref)
20518 		CONN_DEC_REF(connp);
20519 	return;
20520 
20521 qnext:
20522 	/*
20523 	 * Upper Level Protocols pass down complete IP datagrams
20524 	 * as M_DATA messages.	Everything else is a sideshow.
20525 	 *
20526 	 * 1) We could be re-entering ip_wput because of ip_neworute
20527 	 *    in which case we could have a IPSEC_OUT message. We
20528 	 *    need to pass through ip_wput like other datagrams and
20529 	 *    hence cannot branch to ip_wput_nondata.
20530 	 *
20531 	 * 2) ARP, AH, ESP, and other clients who are on the module
20532 	 *    instance of IP stream, give us something to deal with.
20533 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20534 	 *
20535 	 * 3) ICMP replies also could come here.
20536 	 */
20537 	ipst = ILLQ_TO_IPST(q);
20538 
20539 	if (DB_TYPE(mp) != M_DATA) {
20540 notdata:
20541 		if (DB_TYPE(mp) == M_CTL) {
20542 			/*
20543 			 * M_CTL messages are used by ARP, AH and ESP to
20544 			 * communicate with IP. We deal with IPSEC_IN and
20545 			 * IPSEC_OUT here. ip_wput_nondata handles other
20546 			 * cases.
20547 			 */
20548 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20549 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20550 				first_mp = mp->b_cont;
20551 				first_mp->b_flag &= ~MSGHASREF;
20552 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20553 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20554 				CONN_DEC_REF(connp);
20555 				connp = NULL;
20556 			}
20557 			if (ii->ipsec_info_type == IPSEC_IN) {
20558 				/*
20559 				 * Either this message goes back to
20560 				 * IPsec for further processing or to
20561 				 * ULP after policy checks.
20562 				 */
20563 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20564 				return;
20565 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20566 				io = (ipsec_out_t *)ii;
20567 				if (io->ipsec_out_proc_begin) {
20568 					/*
20569 					 * IPsec processing has already started.
20570 					 * Complete it.
20571 					 * IPQoS notes: We don't care what is
20572 					 * in ipsec_out_ill_index since this
20573 					 * won't be processed for IPQoS policies
20574 					 * in ipsec_out_process.
20575 					 */
20576 					ipsec_out_process(q, mp, NULL,
20577 					    io->ipsec_out_ill_index);
20578 					return;
20579 				} else {
20580 					connp = (q->q_next != NULL) ?
20581 					    NULL : Q_TO_CONN(q);
20582 					first_mp = mp;
20583 					mp = mp->b_cont;
20584 					mctl_present = B_TRUE;
20585 				}
20586 				zoneid = io->ipsec_out_zoneid;
20587 				ASSERT(zoneid != ALL_ZONES);
20588 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20589 				/*
20590 				 * It's an IPsec control message requesting
20591 				 * an SADB update to be sent to the IPsec
20592 				 * hardware acceleration capable ills.
20593 				 */
20594 				ipsec_ctl_t *ipsec_ctl =
20595 				    (ipsec_ctl_t *)mp->b_rptr;
20596 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20597 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20598 				mblk_t *cmp = mp->b_cont;
20599 
20600 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20601 				ASSERT(cmp != NULL);
20602 
20603 				freeb(mp);
20604 				ill_ipsec_capab_send_all(satype, cmp, sa,
20605 				    ipst->ips_netstack);
20606 				return;
20607 			} else {
20608 				/*
20609 				 * This must be ARP or special TSOL signaling.
20610 				 */
20611 				ip_wput_nondata(NULL, q, mp, NULL);
20612 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20613 				    "ip_wput_end: q %p (%S)", q, "nondata");
20614 				return;
20615 			}
20616 		} else {
20617 			/*
20618 			 * This must be non-(ARP/AH/ESP) messages.
20619 			 */
20620 			ASSERT(!need_decref);
20621 			ip_wput_nondata(NULL, q, mp, NULL);
20622 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20623 			    "ip_wput_end: q %p (%S)", q, "nondata");
20624 			return;
20625 		}
20626 	} else {
20627 		first_mp = mp;
20628 		mctl_present = B_FALSE;
20629 	}
20630 
20631 	ASSERT(first_mp != NULL);
20632 	/*
20633 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20634 	 * to make sure that this packet goes out on the same interface it
20635 	 * came in. We handle that here.
20636 	 */
20637 	if (mctl_present) {
20638 		uint_t ifindex;
20639 
20640 		io = (ipsec_out_t *)first_mp->b_rptr;
20641 		if (io->ipsec_out_attach_if || io->ipsec_out_ip_nexthop) {
20642 			/*
20643 			 * We may have lost the conn context if we are
20644 			 * coming here from ip_newroute(). Copy the
20645 			 * nexthop information.
20646 			 */
20647 			if (io->ipsec_out_ip_nexthop) {
20648 				ip_nexthop = B_TRUE;
20649 				nexthop_addr = io->ipsec_out_nexthop_addr;
20650 
20651 				ipha = (ipha_t *)mp->b_rptr;
20652 				dst = ipha->ipha_dst;
20653 				goto send_from_ill;
20654 			} else {
20655 				ASSERT(io->ipsec_out_ill_index != 0);
20656 				ifindex = io->ipsec_out_ill_index;
20657 				attach_ill = ill_lookup_on_ifindex(ifindex,
20658 				    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20659 				if (attach_ill == NULL) {
20660 					ASSERT(xmit_ill == NULL);
20661 					ip1dbg(("ip_output: bad ifindex for "
20662 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20663 					    ifindex));
20664 					freemsg(first_mp);
20665 					BUMP_MIB(&ipst->ips_ip_mib,
20666 					    ipIfStatsOutDiscards);
20667 					ASSERT(!need_decref);
20668 					return;
20669 				}
20670 			}
20671 		}
20672 	}
20673 
20674 	ASSERT(xmit_ill == NULL);
20675 
20676 	/* We have a complete IP datagram heading outbound. */
20677 	ipha = (ipha_t *)mp->b_rptr;
20678 
20679 #ifndef SPEED_BEFORE_SAFETY
20680 	/*
20681 	 * Make sure we have a full-word aligned message and that at least
20682 	 * a simple IP header is accessible in the first message.  If not,
20683 	 * try a pullup.
20684 	 */
20685 	if (!OK_32PTR(rptr) ||
20686 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
20687 hdrtoosmall:
20688 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20689 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20690 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20691 			if (first_mp == NULL)
20692 				first_mp = mp;
20693 			goto discard_pkt;
20694 		}
20695 
20696 		/* This function assumes that mp points to an IPv4 packet. */
20697 		if (is_system_labeled() && q->q_next == NULL &&
20698 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20699 		    !connp->conn_ulp_labeled) {
20700 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20701 			    &adjust, connp->conn_mac_exempt, ipst);
20702 			ipha = (ipha_t *)mp->b_rptr;
20703 			if (first_mp != NULL)
20704 				first_mp->b_cont = mp;
20705 			if (err != 0) {
20706 				if (first_mp == NULL)
20707 					first_mp = mp;
20708 				if (err == EINVAL)
20709 					goto icmp_parameter_problem;
20710 				ip2dbg(("ip_wput: label check failed (%d)\n",
20711 				    err));
20712 				goto discard_pkt;
20713 			}
20714 			iplen = ntohs(ipha->ipha_length) + adjust;
20715 			ipha->ipha_length = htons(iplen);
20716 		}
20717 
20718 		ipha = (ipha_t *)mp->b_rptr;
20719 		if (first_mp == NULL) {
20720 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20721 			/*
20722 			 * If we got here because of "goto hdrtoosmall"
20723 			 * We need to attach a IPSEC_OUT.
20724 			 */
20725 			if (connp->conn_out_enforce_policy) {
20726 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
20727 				    NULL, ipha->ipha_protocol,
20728 				    ipst->ips_netstack)) == NULL)) {
20729 					BUMP_MIB(&ipst->ips_ip_mib,
20730 					    ipIfStatsOutDiscards);
20731 					if (need_decref)
20732 						CONN_DEC_REF(connp);
20733 					return;
20734 				} else {
20735 					ASSERT(mp->b_datap->db_type == M_CTL);
20736 					first_mp = mp;
20737 					mp = mp->b_cont;
20738 					mctl_present = B_TRUE;
20739 				}
20740 			} else {
20741 				first_mp = mp;
20742 				mctl_present = B_FALSE;
20743 			}
20744 		}
20745 	}
20746 #endif
20747 
20748 	/* Most of the code below is written for speed, not readability */
20749 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20750 
20751 	/*
20752 	 * If ip_newroute() fails, we're going to need a full
20753 	 * header for the icmp wraparound.
20754 	 */
20755 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20756 		uint_t	v_hlen;
20757 version_hdrlen_check:
20758 		ASSERT(first_mp != NULL);
20759 		v_hlen = V_HLEN;
20760 		/*
20761 		 * siphon off IPv6 packets coming down from transport
20762 		 * layer modules here.
20763 		 * Note: high-order bit carries NUD reachability confirmation
20764 		 */
20765 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20766 			/*
20767 			 * FIXME: assume that callers of ip_output* call
20768 			 * the right version?
20769 			 */
20770 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
20771 			ASSERT(xmit_ill == NULL);
20772 			if (attach_ill != NULL)
20773 				ill_refrele(attach_ill);
20774 			if (need_decref)
20775 				mp->b_flag |= MSGHASREF;
20776 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20777 			return;
20778 		}
20779 
20780 		if ((v_hlen >> 4) != IP_VERSION) {
20781 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20782 			    "ip_wput_end: q %p (%S)", q, "badvers");
20783 			goto discard_pkt;
20784 		}
20785 		/*
20786 		 * Is the header length at least 20 bytes?
20787 		 *
20788 		 * Are there enough bytes accessible in the header?  If
20789 		 * not, try a pullup.
20790 		 */
20791 		v_hlen &= 0xF;
20792 		v_hlen <<= 2;
20793 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20794 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20795 			    "ip_wput_end: q %p (%S)", q, "badlen");
20796 			goto discard_pkt;
20797 		}
20798 		if (v_hlen > (mp->b_wptr - rptr)) {
20799 			if (!pullupmsg(mp, v_hlen)) {
20800 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20801 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20802 				goto discard_pkt;
20803 			}
20804 			ipha = (ipha_t *)mp->b_rptr;
20805 		}
20806 		/*
20807 		 * Move first entry from any source route into ipha_dst and
20808 		 * verify the options
20809 		 */
20810 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
20811 		    zoneid, ipst)) {
20812 			ASSERT(xmit_ill == NULL);
20813 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20814 			if (attach_ill != NULL)
20815 				ill_refrele(attach_ill);
20816 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20817 			    "ip_wput_end: q %p (%S)", q, "badopts");
20818 			if (need_decref)
20819 				CONN_DEC_REF(connp);
20820 			return;
20821 		}
20822 	}
20823 	dst = ipha->ipha_dst;
20824 
20825 	/*
20826 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20827 	 * we have to run the packet through ip_newroute which will take
20828 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
20829 	 * a resolver, or assigning a default gateway, etc.
20830 	 */
20831 	if (CLASSD(dst)) {
20832 		ipif_t	*ipif;
20833 		uint32_t setsrc = 0;
20834 
20835 multicast:
20836 		ASSERT(first_mp != NULL);
20837 		ip2dbg(("ip_wput: CLASSD\n"));
20838 		if (connp == NULL) {
20839 			/*
20840 			 * Use the first good ipif on the ill.
20841 			 * XXX Should this ever happen? (Appears
20842 			 * to show up with just ppp and no ethernet due
20843 			 * to in.rdisc.)
20844 			 * However, ire_send should be able to
20845 			 * call ip_wput_ire directly.
20846 			 *
20847 			 * XXX Also, this can happen for ICMP and other packets
20848 			 * with multicast source addresses.  Perhaps we should
20849 			 * fix things so that we drop the packet in question,
20850 			 * but for now, just run with it.
20851 			 */
20852 			ill_t *ill = (ill_t *)q->q_ptr;
20853 
20854 			/*
20855 			 * Don't honor attach_if for this case. If ill
20856 			 * is part of the group, ipif could belong to
20857 			 * any ill and we cannot maintain attach_ill
20858 			 * and ipif_ill same anymore and the assert
20859 			 * below would fail.
20860 			 */
20861 			if (mctl_present && io->ipsec_out_attach_if) {
20862 				io->ipsec_out_ill_index = 0;
20863 				io->ipsec_out_attach_if = B_FALSE;
20864 				ASSERT(attach_ill != NULL);
20865 				ill_refrele(attach_ill);
20866 				attach_ill = NULL;
20867 			}
20868 
20869 			ASSERT(attach_ill == NULL);
20870 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
20871 			if (ipif == NULL) {
20872 				if (need_decref)
20873 					CONN_DEC_REF(connp);
20874 				freemsg(first_mp);
20875 				return;
20876 			}
20877 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
20878 			    ntohl(dst), ill->ill_name));
20879 		} else {
20880 			/*
20881 			 * The order of precedence is IP_BOUND_IF, IP_PKTINFO
20882 			 * and IP_MULTICAST_IF.  The block comment above this
20883 			 * function explains the locking mechanism used here.
20884 			 */
20885 			if (xmit_ill == NULL) {
20886 				xmit_ill = conn_get_held_ill(connp,
20887 				    &connp->conn_outgoing_ill, &err);
20888 				if (err == ILL_LOOKUP_FAILED) {
20889 					ip1dbg(("ip_wput: No ill for "
20890 					    "IP_BOUND_IF\n"));
20891 					BUMP_MIB(&ipst->ips_ip_mib,
20892 					    ipIfStatsOutNoRoutes);
20893 					goto drop_pkt;
20894 				}
20895 			}
20896 
20897 			if (xmit_ill == NULL) {
20898 				ipif = conn_get_held_ipif(connp,
20899 				    &connp->conn_multicast_ipif, &err);
20900 				if (err == IPIF_LOOKUP_FAILED) {
20901 					ip1dbg(("ip_wput: No ipif for "
20902 					    "multicast\n"));
20903 					BUMP_MIB(&ipst->ips_ip_mib,
20904 					    ipIfStatsOutNoRoutes);
20905 					goto drop_pkt;
20906 				}
20907 			}
20908 			if (xmit_ill != NULL) {
20909 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20910 				if (ipif == NULL) {
20911 					ip1dbg(("ip_wput: No ipif for "
20912 					    "xmit_ill\n"));
20913 					BUMP_MIB(&ipst->ips_ip_mib,
20914 					    ipIfStatsOutNoRoutes);
20915 					goto drop_pkt;
20916 				}
20917 			} else if (ipif == NULL || ipif->ipif_isv6) {
20918 				/*
20919 				 * We must do this ipif determination here
20920 				 * else we could pass through ip_newroute
20921 				 * and come back here without the conn context.
20922 				 *
20923 				 * Note: we do late binding i.e. we bind to
20924 				 * the interface when the first packet is sent.
20925 				 * For performance reasons we do not rebind on
20926 				 * each packet but keep the binding until the
20927 				 * next IP_MULTICAST_IF option.
20928 				 *
20929 				 * conn_multicast_{ipif,ill} are shared between
20930 				 * IPv4 and IPv6 and AF_INET6 sockets can
20931 				 * send both IPv4 and IPv6 packets. Hence
20932 				 * we have to check that "isv6" matches above.
20933 				 */
20934 				if (ipif != NULL)
20935 					ipif_refrele(ipif);
20936 				ipif = ipif_lookup_group(dst, zoneid, ipst);
20937 				if (ipif == NULL) {
20938 					ip1dbg(("ip_wput: No ipif for "
20939 					    "multicast\n"));
20940 					BUMP_MIB(&ipst->ips_ip_mib,
20941 					    ipIfStatsOutNoRoutes);
20942 					goto drop_pkt;
20943 				}
20944 				err = conn_set_held_ipif(connp,
20945 				    &connp->conn_multicast_ipif, ipif);
20946 				if (err == IPIF_LOOKUP_FAILED) {
20947 					ipif_refrele(ipif);
20948 					ip1dbg(("ip_wput: No ipif for "
20949 					    "multicast\n"));
20950 					BUMP_MIB(&ipst->ips_ip_mib,
20951 					    ipIfStatsOutNoRoutes);
20952 					goto drop_pkt;
20953 				}
20954 			}
20955 		}
20956 		ASSERT(!ipif->ipif_isv6);
20957 		/*
20958 		 * As we may lose the conn by the time we reach ip_wput_ire,
20959 		 * we copy conn_multicast_loop and conn_dontroute on to an
20960 		 * ipsec_out. In case if this datagram goes out secure,
20961 		 * we need the ill_index also. Copy that also into the
20962 		 * ipsec_out.
20963 		 */
20964 		if (mctl_present) {
20965 			io = (ipsec_out_t *)first_mp->b_rptr;
20966 			ASSERT(first_mp->b_datap->db_type == M_CTL);
20967 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
20968 		} else {
20969 			ASSERT(mp == first_mp);
20970 			if ((first_mp = allocb(sizeof (ipsec_info_t),
20971 			    BPRI_HI)) == NULL) {
20972 				ipif_refrele(ipif);
20973 				first_mp = mp;
20974 				goto discard_pkt;
20975 			}
20976 			first_mp->b_datap->db_type = M_CTL;
20977 			first_mp->b_wptr += sizeof (ipsec_info_t);
20978 			/* ipsec_out_secure is B_FALSE now */
20979 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
20980 			io = (ipsec_out_t *)first_mp->b_rptr;
20981 			io->ipsec_out_type = IPSEC_OUT;
20982 			io->ipsec_out_len = sizeof (ipsec_out_t);
20983 			io->ipsec_out_use_global_policy = B_TRUE;
20984 			io->ipsec_out_ns = ipst->ips_netstack;
20985 			first_mp->b_cont = mp;
20986 			mctl_present = B_TRUE;
20987 		}
20988 		if (attach_ill != NULL) {
20989 			ASSERT(attach_ill == ipif->ipif_ill);
20990 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
20991 
20992 			/*
20993 			 * Check if we need an ire that will not be
20994 			 * looked up by anybody else i.e. HIDDEN.
20995 			 */
20996 			if (ill_is_probeonly(attach_ill)) {
20997 				match_flags |= MATCH_IRE_MARK_HIDDEN;
20998 			}
20999 			io->ipsec_out_ill_index =
21000 			    attach_ill->ill_phyint->phyint_ifindex;
21001 			io->ipsec_out_attach_if = B_TRUE;
21002 		} else {
21003 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21004 			io->ipsec_out_ill_index =
21005 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21006 		}
21007 		if (connp != NULL) {
21008 			io->ipsec_out_multicast_loop =
21009 			    connp->conn_multicast_loop;
21010 			io->ipsec_out_dontroute = connp->conn_dontroute;
21011 			io->ipsec_out_zoneid = connp->conn_zoneid;
21012 		}
21013 		/*
21014 		 * If the application uses IP_MULTICAST_IF with
21015 		 * different logical addresses of the same ILL, we
21016 		 * need to make sure that the soruce address of
21017 		 * the packet matches the logical IP address used
21018 		 * in the option. We do it by initializing ipha_src
21019 		 * here. This should keep IPsec also happy as
21020 		 * when we return from IPsec processing, we don't
21021 		 * have to worry about getting the right address on
21022 		 * the packet. Thus it is sufficient to look for
21023 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21024 		 * MATCH_IRE_IPIF.
21025 		 *
21026 		 * NOTE : We need to do it for non-secure case also as
21027 		 * this might go out secure if there is a global policy
21028 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
21029 		 * address, the source should be initialized already and
21030 		 * hence we won't be initializing here.
21031 		 *
21032 		 * As we do not have the ire yet, it is possible that
21033 		 * we set the source address here and then later discover
21034 		 * that the ire implies the source address to be assigned
21035 		 * through the RTF_SETSRC flag.
21036 		 * In that case, the setsrc variable will remind us
21037 		 * that overwritting the source address by the one
21038 		 * of the RTF_SETSRC-flagged ire is allowed.
21039 		 */
21040 		if (ipha->ipha_src == INADDR_ANY &&
21041 		    (connp == NULL || !connp->conn_unspec_src)) {
21042 			ipha->ipha_src = ipif->ipif_src_addr;
21043 			setsrc = RTF_SETSRC;
21044 		}
21045 		/*
21046 		 * Find an IRE which matches the destination and the outgoing
21047 		 * queue (i.e. the outgoing interface.)
21048 		 * For loopback use a unicast IP address for
21049 		 * the ire lookup.
21050 		 */
21051 		if (IS_LOOPBACK(ipif->ipif_ill))
21052 			dst = ipif->ipif_lcl_addr;
21053 
21054 		/*
21055 		 * If xmit_ill is set, we branch out to ip_newroute_ipif.
21056 		 * We don't need to lookup ire in ctable as the packet
21057 		 * needs to be sent to the destination through the specified
21058 		 * ill irrespective of ires in the cache table.
21059 		 */
21060 		ire = NULL;
21061 		if (xmit_ill == NULL) {
21062 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21063 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21064 		}
21065 
21066 		/*
21067 		 * refrele attach_ill as its not needed anymore.
21068 		 */
21069 		if (attach_ill != NULL) {
21070 			ill_refrele(attach_ill);
21071 			attach_ill = NULL;
21072 		}
21073 
21074 		if (ire == NULL) {
21075 			/*
21076 			 * Multicast loopback and multicast forwarding is
21077 			 * done in ip_wput_ire.
21078 			 *
21079 			 * Mark this packet to make it be delivered to
21080 			 * ip_wput_ire after the new ire has been
21081 			 * created.
21082 			 *
21083 			 * The call to ip_newroute_ipif takes into account
21084 			 * the setsrc reminder. In any case, we take care
21085 			 * of the RTF_MULTIRT flag.
21086 			 */
21087 			mp->b_prev = mp->b_next = NULL;
21088 			if (xmit_ill == NULL ||
21089 			    xmit_ill->ill_ipif_up_count > 0) {
21090 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21091 				    setsrc | RTF_MULTIRT, zoneid, infop);
21092 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21093 				    "ip_wput_end: q %p (%S)", q, "noire");
21094 			} else {
21095 				freemsg(first_mp);
21096 			}
21097 			ipif_refrele(ipif);
21098 			if (xmit_ill != NULL)
21099 				ill_refrele(xmit_ill);
21100 			if (need_decref)
21101 				CONN_DEC_REF(connp);
21102 			return;
21103 		}
21104 
21105 		ipif_refrele(ipif);
21106 		ipif = NULL;
21107 		ASSERT(xmit_ill == NULL);
21108 
21109 		/*
21110 		 * Honor the RTF_SETSRC flag for multicast packets,
21111 		 * if allowed by the setsrc reminder.
21112 		 */
21113 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21114 			ipha->ipha_src = ire->ire_src_addr;
21115 		}
21116 
21117 		/*
21118 		 * Unconditionally force the TTL to 1 for
21119 		 * multirouted multicast packets:
21120 		 * multirouted multicast should not cross
21121 		 * multicast routers.
21122 		 */
21123 		if (ire->ire_flags & RTF_MULTIRT) {
21124 			if (ipha->ipha_ttl > 1) {
21125 				ip2dbg(("ip_wput: forcing multicast "
21126 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21127 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21128 				ipha->ipha_ttl = 1;
21129 			}
21130 		}
21131 	} else {
21132 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
21133 		if ((ire != NULL) && (ire->ire_type &
21134 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21135 			ignore_dontroute = B_TRUE;
21136 			ignore_nexthop = B_TRUE;
21137 		}
21138 		if (ire != NULL) {
21139 			ire_refrele(ire);
21140 			ire = NULL;
21141 		}
21142 		/*
21143 		 * Guard against coming in from arp in which case conn is NULL.
21144 		 * Also guard against non M_DATA with dontroute set but
21145 		 * destined to local, loopback or broadcast addresses.
21146 		 */
21147 		if (connp != NULL && connp->conn_dontroute &&
21148 		    !ignore_dontroute) {
21149 dontroute:
21150 			/*
21151 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21152 			 * routing protocols from seeing false direct
21153 			 * connectivity.
21154 			 */
21155 			ipha->ipha_ttl = 1;
21156 
21157 			/* If suitable ipif not found, drop packet */
21158 			dst_ipif = ipif_lookup_onlink_addr(dst, zoneid, ipst);
21159 			if (dst_ipif == NULL) {
21160 noroute:
21161 				ip1dbg(("ip_wput: no route for dst using"
21162 				    " SO_DONTROUTE\n"));
21163 				BUMP_MIB(&ipst->ips_ip_mib,
21164 				    ipIfStatsOutNoRoutes);
21165 				mp->b_prev = mp->b_next = NULL;
21166 				if (first_mp == NULL)
21167 					first_mp = mp;
21168 				goto drop_pkt;
21169 			} else {
21170 				/*
21171 				 * If suitable ipif has been found, set
21172 				 * xmit_ill to the corresponding
21173 				 * ipif_ill because we'll be using the
21174 				 * send_from_ill logic below.
21175 				 */
21176 				ASSERT(xmit_ill == NULL);
21177 				xmit_ill = dst_ipif->ipif_ill;
21178 				mutex_enter(&xmit_ill->ill_lock);
21179 				if (!ILL_CAN_LOOKUP(xmit_ill)) {
21180 					mutex_exit(&xmit_ill->ill_lock);
21181 					xmit_ill = NULL;
21182 					ipif_refrele(dst_ipif);
21183 					goto noroute;
21184 				}
21185 				ill_refhold_locked(xmit_ill);
21186 				mutex_exit(&xmit_ill->ill_lock);
21187 				ipif_refrele(dst_ipif);
21188 			}
21189 		}
21190 		/*
21191 		 * If we are bound to IPIF_NOFAILOVER address, look for
21192 		 * an IRE_CACHE matching the ill.
21193 		 */
21194 send_from_ill:
21195 		if (attach_ill != NULL) {
21196 			ipif_t	*attach_ipif;
21197 
21198 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21199 
21200 			/*
21201 			 * Check if we need an ire that will not be
21202 			 * looked up by anybody else i.e. HIDDEN.
21203 			 */
21204 			if (ill_is_probeonly(attach_ill)) {
21205 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21206 			}
21207 
21208 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
21209 			if (attach_ipif == NULL) {
21210 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
21211 				goto discard_pkt;
21212 			}
21213 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
21214 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21215 			ipif_refrele(attach_ipif);
21216 		} else if (xmit_ill != NULL) {
21217 			ipif_t *ipif;
21218 
21219 			/*
21220 			 * Mark this packet as originated locally
21221 			 */
21222 			mp->b_prev = mp->b_next = NULL;
21223 
21224 			/*
21225 			 * Could be SO_DONTROUTE case also.
21226 			 * Verify that at least one ipif is up on the ill.
21227 			 */
21228 			if (xmit_ill->ill_ipif_up_count == 0) {
21229 				ip1dbg(("ip_output: xmit_ill %s is down\n",
21230 				    xmit_ill->ill_name));
21231 				goto drop_pkt;
21232 			}
21233 
21234 			ipif = ipif_get_next_ipif(NULL, xmit_ill);
21235 			if (ipif == NULL) {
21236 				ip1dbg(("ip_output: xmit_ill %s NULL ipif\n",
21237 				    xmit_ill->ill_name));
21238 				goto drop_pkt;
21239 			}
21240 
21241 			/*
21242 			 * Look for a ire that is part of the group,
21243 			 * if found use it else call ip_newroute_ipif.
21244 			 * IPCL_ZONEID is not used for matching because
21245 			 * IP_ALLZONES option is valid only when the
21246 			 * ill is accessible from all zones i.e has a
21247 			 * valid ipif in all zones.
21248 			 */
21249 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21250 			ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21251 			    MBLK_GETLABEL(mp), match_flags, ipst);
21252 			/*
21253 			 * If an ire exists use it or else create
21254 			 * an ire but don't add it to the cache.
21255 			 * Adding an ire may cause issues with
21256 			 * asymmetric routing.
21257 			 * In case of multiroute always act as if
21258 			 * ire does not exist.
21259 			 */
21260 			if (ire == NULL || ire->ire_flags & RTF_MULTIRT) {
21261 				if (ire != NULL)
21262 					ire_refrele(ire);
21263 				ip_newroute_ipif(q, first_mp, ipif,
21264 				    dst, connp, 0, zoneid, infop);
21265 				ipif_refrele(ipif);
21266 				ip1dbg(("ip_output: xmit_ill via %s\n",
21267 				    xmit_ill->ill_name));
21268 				ill_refrele(xmit_ill);
21269 				if (need_decref)
21270 					CONN_DEC_REF(connp);
21271 				return;
21272 			}
21273 			ipif_refrele(ipif);
21274 		} else if (ip_nexthop || (connp != NULL &&
21275 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21276 			if (!ip_nexthop) {
21277 				ip_nexthop = B_TRUE;
21278 				nexthop_addr = connp->conn_nexthop_v4;
21279 			}
21280 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21281 			    MATCH_IRE_GW;
21282 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21283 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21284 		} else {
21285 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp),
21286 			    ipst);
21287 		}
21288 		if (!ire) {
21289 			/*
21290 			 * Make sure we don't load spread if this
21291 			 * is IPIF_NOFAILOVER case.
21292 			 */
21293 			if ((attach_ill != NULL) ||
21294 			    (ip_nexthop && !ignore_nexthop)) {
21295 				if (mctl_present) {
21296 					io = (ipsec_out_t *)first_mp->b_rptr;
21297 					ASSERT(first_mp->b_datap->db_type ==
21298 					    M_CTL);
21299 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21300 				} else {
21301 					ASSERT(mp == first_mp);
21302 					first_mp = allocb(
21303 					    sizeof (ipsec_info_t), BPRI_HI);
21304 					if (first_mp == NULL) {
21305 						first_mp = mp;
21306 						goto discard_pkt;
21307 					}
21308 					first_mp->b_datap->db_type = M_CTL;
21309 					first_mp->b_wptr +=
21310 					    sizeof (ipsec_info_t);
21311 					/* ipsec_out_secure is B_FALSE now */
21312 					bzero(first_mp->b_rptr,
21313 					    sizeof (ipsec_info_t));
21314 					io = (ipsec_out_t *)first_mp->b_rptr;
21315 					io->ipsec_out_type = IPSEC_OUT;
21316 					io->ipsec_out_len =
21317 					    sizeof (ipsec_out_t);
21318 					io->ipsec_out_use_global_policy =
21319 					    B_TRUE;
21320 					io->ipsec_out_ns = ipst->ips_netstack;
21321 					first_mp->b_cont = mp;
21322 					mctl_present = B_TRUE;
21323 				}
21324 				if (attach_ill != NULL) {
21325 					io->ipsec_out_ill_index = attach_ill->
21326 					    ill_phyint->phyint_ifindex;
21327 					io->ipsec_out_attach_if = B_TRUE;
21328 				} else {
21329 					io->ipsec_out_ip_nexthop = ip_nexthop;
21330 					io->ipsec_out_nexthop_addr =
21331 					    nexthop_addr;
21332 				}
21333 			}
21334 noirefound:
21335 			/*
21336 			 * Mark this packet as having originated on
21337 			 * this machine.  This will be noted in
21338 			 * ire_add_then_send, which needs to know
21339 			 * whether to run it back through ip_wput or
21340 			 * ip_rput following successful resolution.
21341 			 */
21342 			mp->b_prev = NULL;
21343 			mp->b_next = NULL;
21344 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21345 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21346 			    "ip_wput_end: q %p (%S)", q, "newroute");
21347 			if (attach_ill != NULL)
21348 				ill_refrele(attach_ill);
21349 			if (xmit_ill != NULL)
21350 				ill_refrele(xmit_ill);
21351 			if (need_decref)
21352 				CONN_DEC_REF(connp);
21353 			return;
21354 		}
21355 	}
21356 
21357 	/* We now know where we are going with it. */
21358 
21359 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21360 	    "ip_wput_end: q %p (%S)", q, "end");
21361 
21362 	/*
21363 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21364 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21365 	 */
21366 	if (ire->ire_flags & RTF_MULTIRT) {
21367 		/*
21368 		 * Force the TTL of multirouted packets if required.
21369 		 * The TTL of such packets is bounded by the
21370 		 * ip_multirt_ttl ndd variable.
21371 		 */
21372 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21373 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21374 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21375 			    "(was %d), dst 0x%08x\n",
21376 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21377 			    ntohl(ire->ire_addr)));
21378 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21379 		}
21380 		/*
21381 		 * At this point, we check to see if there are any pending
21382 		 * unresolved routes. ire_multirt_resolvable()
21383 		 * checks in O(n) that all IRE_OFFSUBNET ire
21384 		 * entries for the packet's destination and
21385 		 * flagged RTF_MULTIRT are currently resolved.
21386 		 * If some remain unresolved, we make a copy
21387 		 * of the current message. It will be used
21388 		 * to initiate additional route resolutions.
21389 		 */
21390 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21391 		    MBLK_GETLABEL(first_mp), ipst);
21392 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21393 		    "multirt_need_resolve %d, first_mp %p\n",
21394 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21395 		if (multirt_need_resolve) {
21396 			copy_mp = copymsg(first_mp);
21397 			if (copy_mp != NULL) {
21398 				MULTIRT_DEBUG_TAG(copy_mp);
21399 			}
21400 		}
21401 	}
21402 
21403 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21404 	/*
21405 	 * Try to resolve another multiroute if
21406 	 * ire_multirt_resolvable() deemed it necessary.
21407 	 * At this point, we need to distinguish
21408 	 * multicasts from other packets. For multicasts,
21409 	 * we call ip_newroute_ipif() and request that both
21410 	 * multirouting and setsrc flags are checked.
21411 	 */
21412 	if (copy_mp != NULL) {
21413 		if (CLASSD(dst)) {
21414 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21415 			if (ipif) {
21416 				ASSERT(infop->ip_opt_ill_index == 0);
21417 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21418 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21419 				ipif_refrele(ipif);
21420 			} else {
21421 				MULTIRT_DEBUG_UNTAG(copy_mp);
21422 				freemsg(copy_mp);
21423 				copy_mp = NULL;
21424 			}
21425 		} else {
21426 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21427 		}
21428 	}
21429 	if (attach_ill != NULL)
21430 		ill_refrele(attach_ill);
21431 	if (xmit_ill != NULL)
21432 		ill_refrele(xmit_ill);
21433 	if (need_decref)
21434 		CONN_DEC_REF(connp);
21435 	return;
21436 
21437 icmp_parameter_problem:
21438 	/* could not have originated externally */
21439 	ASSERT(mp->b_prev == NULL);
21440 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21441 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21442 		/* it's the IP header length that's in trouble */
21443 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21444 		first_mp = NULL;
21445 	}
21446 
21447 discard_pkt:
21448 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21449 drop_pkt:
21450 	ip1dbg(("ip_wput: dropped packet\n"));
21451 	if (ire != NULL)
21452 		ire_refrele(ire);
21453 	if (need_decref)
21454 		CONN_DEC_REF(connp);
21455 	freemsg(first_mp);
21456 	if (attach_ill != NULL)
21457 		ill_refrele(attach_ill);
21458 	if (xmit_ill != NULL)
21459 		ill_refrele(xmit_ill);
21460 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21461 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21462 }
21463 
21464 /*
21465  * If this is a conn_t queue, then we pass in the conn. This includes the
21466  * zoneid.
21467  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21468  * in which case we use the global zoneid since those are all part of
21469  * the global zone.
21470  */
21471 void
21472 ip_wput(queue_t *q, mblk_t *mp)
21473 {
21474 	if (CONN_Q(q))
21475 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21476 	else
21477 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21478 }
21479 
21480 /*
21481  *
21482  * The following rules must be observed when accessing any ipif or ill
21483  * that has been cached in the conn. Typically conn_nofailover_ill,
21484  * conn_outgoing_ill, conn_multicast_ipif and conn_multicast_ill.
21485  *
21486  * Access: The ipif or ill pointed to from the conn can be accessed under
21487  * the protection of the conn_lock or after it has been refheld under the
21488  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21489  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21490  * The reason for this is that a concurrent unplumb could actually be
21491  * cleaning up these cached pointers by walking the conns and might have
21492  * finished cleaning up the conn in question. The macros check that an
21493  * unplumb has not yet started on the ipif or ill.
21494  *
21495  * Caching: An ipif or ill pointer may be cached in the conn only after
21496  * making sure that an unplumb has not started. So the caching is done
21497  * while holding both the conn_lock and the ill_lock and after using the
21498  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21499  * flag before starting the cleanup of conns.
21500  *
21501  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21502  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21503  * or a reference to the ipif or a reference to an ire that references the
21504  * ipif. An ipif does not change its ill except for failover/failback. Since
21505  * failover/failback happens only after bringing down the ipif and making sure
21506  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
21507  * the above holds.
21508  */
21509 ipif_t *
21510 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21511 {
21512 	ipif_t	*ipif;
21513 	ill_t	*ill;
21514 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21515 
21516 	*err = 0;
21517 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21518 	mutex_enter(&connp->conn_lock);
21519 	ipif = *ipifp;
21520 	if (ipif != NULL) {
21521 		ill = ipif->ipif_ill;
21522 		mutex_enter(&ill->ill_lock);
21523 		if (IPIF_CAN_LOOKUP(ipif)) {
21524 			ipif_refhold_locked(ipif);
21525 			mutex_exit(&ill->ill_lock);
21526 			mutex_exit(&connp->conn_lock);
21527 			rw_exit(&ipst->ips_ill_g_lock);
21528 			return (ipif);
21529 		} else {
21530 			*err = IPIF_LOOKUP_FAILED;
21531 		}
21532 		mutex_exit(&ill->ill_lock);
21533 	}
21534 	mutex_exit(&connp->conn_lock);
21535 	rw_exit(&ipst->ips_ill_g_lock);
21536 	return (NULL);
21537 }
21538 
21539 ill_t *
21540 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21541 {
21542 	ill_t	*ill;
21543 
21544 	*err = 0;
21545 	mutex_enter(&connp->conn_lock);
21546 	ill = *illp;
21547 	if (ill != NULL) {
21548 		mutex_enter(&ill->ill_lock);
21549 		if (ILL_CAN_LOOKUP(ill)) {
21550 			ill_refhold_locked(ill);
21551 			mutex_exit(&ill->ill_lock);
21552 			mutex_exit(&connp->conn_lock);
21553 			return (ill);
21554 		} else {
21555 			*err = ILL_LOOKUP_FAILED;
21556 		}
21557 		mutex_exit(&ill->ill_lock);
21558 	}
21559 	mutex_exit(&connp->conn_lock);
21560 	return (NULL);
21561 }
21562 
21563 static int
21564 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21565 {
21566 	ill_t	*ill;
21567 
21568 	ill = ipif->ipif_ill;
21569 	mutex_enter(&connp->conn_lock);
21570 	mutex_enter(&ill->ill_lock);
21571 	if (IPIF_CAN_LOOKUP(ipif)) {
21572 		*ipifp = ipif;
21573 		mutex_exit(&ill->ill_lock);
21574 		mutex_exit(&connp->conn_lock);
21575 		return (0);
21576 	}
21577 	mutex_exit(&ill->ill_lock);
21578 	mutex_exit(&connp->conn_lock);
21579 	return (IPIF_LOOKUP_FAILED);
21580 }
21581 
21582 /*
21583  * This is called if the outbound datagram needs fragmentation.
21584  *
21585  * NOTE : This function does not ire_refrele the ire argument passed in.
21586  */
21587 static void
21588 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21589     ip_stack_t *ipst)
21590 {
21591 	ipha_t		*ipha;
21592 	mblk_t		*mp;
21593 	uint32_t	v_hlen_tos_len;
21594 	uint32_t	max_frag;
21595 	uint32_t	frag_flag;
21596 	boolean_t	dont_use;
21597 
21598 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21599 		mp = ipsec_mp->b_cont;
21600 	} else {
21601 		mp = ipsec_mp;
21602 	}
21603 
21604 	ipha = (ipha_t *)mp->b_rptr;
21605 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21606 
21607 #ifdef	_BIG_ENDIAN
21608 #define	V_HLEN	(v_hlen_tos_len >> 24)
21609 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21610 #else
21611 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21612 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21613 #endif
21614 
21615 #ifndef SPEED_BEFORE_SAFETY
21616 	/*
21617 	 * Check that ipha_length is consistent with
21618 	 * the mblk length
21619 	 */
21620 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21621 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21622 		    LENGTH, msgdsize(mp)));
21623 		freemsg(ipsec_mp);
21624 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21625 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21626 		    "packet length mismatch");
21627 		return;
21628 	}
21629 #endif
21630 	/*
21631 	 * Don't use frag_flag if pre-built packet or source
21632 	 * routed or if multicast (since multicast packets do not solicit
21633 	 * ICMP "packet too big" messages). Get the values of
21634 	 * max_frag and frag_flag atomically by acquiring the
21635 	 * ire_lock.
21636 	 */
21637 	mutex_enter(&ire->ire_lock);
21638 	max_frag = ire->ire_max_frag;
21639 	frag_flag = ire->ire_frag_flag;
21640 	mutex_exit(&ire->ire_lock);
21641 
21642 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21643 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21644 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21645 
21646 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21647 	    (dont_use ? 0 : frag_flag), zoneid, ipst);
21648 }
21649 
21650 /*
21651  * Used for deciding the MSS size for the upper layer. Thus
21652  * we need to check the outbound policy values in the conn.
21653  */
21654 int
21655 conn_ipsec_length(conn_t *connp)
21656 {
21657 	ipsec_latch_t *ipl;
21658 
21659 	ipl = connp->conn_latch;
21660 	if (ipl == NULL)
21661 		return (0);
21662 
21663 	if (ipl->ipl_out_policy == NULL)
21664 		return (0);
21665 
21666 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21667 }
21668 
21669 /*
21670  * Returns an estimate of the IPsec headers size. This is used if
21671  * we don't want to call into IPsec to get the exact size.
21672  */
21673 int
21674 ipsec_out_extra_length(mblk_t *ipsec_mp)
21675 {
21676 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21677 	ipsec_action_t *a;
21678 
21679 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21680 	if (!io->ipsec_out_secure)
21681 		return (0);
21682 
21683 	a = io->ipsec_out_act;
21684 
21685 	if (a == NULL) {
21686 		ASSERT(io->ipsec_out_policy != NULL);
21687 		a = io->ipsec_out_policy->ipsp_act;
21688 	}
21689 	ASSERT(a != NULL);
21690 
21691 	return (a->ipa_ovhd);
21692 }
21693 
21694 /*
21695  * Returns an estimate of the IPsec headers size. This is used if
21696  * we don't want to call into IPsec to get the exact size.
21697  */
21698 int
21699 ipsec_in_extra_length(mblk_t *ipsec_mp)
21700 {
21701 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21702 	ipsec_action_t *a;
21703 
21704 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21705 
21706 	a = ii->ipsec_in_action;
21707 	return (a == NULL ? 0 : a->ipa_ovhd);
21708 }
21709 
21710 /*
21711  * If there are any source route options, return the true final
21712  * destination. Otherwise, return the destination.
21713  */
21714 ipaddr_t
21715 ip_get_dst(ipha_t *ipha)
21716 {
21717 	ipoptp_t	opts;
21718 	uchar_t		*opt;
21719 	uint8_t		optval;
21720 	uint8_t		optlen;
21721 	ipaddr_t	dst;
21722 	uint32_t off;
21723 
21724 	dst = ipha->ipha_dst;
21725 
21726 	if (IS_SIMPLE_IPH(ipha))
21727 		return (dst);
21728 
21729 	for (optval = ipoptp_first(&opts, ipha);
21730 	    optval != IPOPT_EOL;
21731 	    optval = ipoptp_next(&opts)) {
21732 		opt = opts.ipoptp_cur;
21733 		optlen = opts.ipoptp_len;
21734 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21735 		switch (optval) {
21736 		case IPOPT_SSRR:
21737 		case IPOPT_LSRR:
21738 			off = opt[IPOPT_OFFSET];
21739 			/*
21740 			 * If one of the conditions is true, it means
21741 			 * end of options and dst already has the right
21742 			 * value.
21743 			 */
21744 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21745 				off = optlen - IP_ADDR_LEN;
21746 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21747 			}
21748 			return (dst);
21749 		default:
21750 			break;
21751 		}
21752 	}
21753 
21754 	return (dst);
21755 }
21756 
21757 mblk_t *
21758 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21759     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21760 {
21761 	ipsec_out_t	*io;
21762 	mblk_t		*first_mp;
21763 	boolean_t policy_present;
21764 	ip_stack_t	*ipst;
21765 	ipsec_stack_t	*ipss;
21766 
21767 	ASSERT(ire != NULL);
21768 	ipst = ire->ire_ipst;
21769 	ipss = ipst->ips_netstack->netstack_ipsec;
21770 
21771 	first_mp = mp;
21772 	if (mp->b_datap->db_type == M_CTL) {
21773 		io = (ipsec_out_t *)first_mp->b_rptr;
21774 		/*
21775 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21776 		 *
21777 		 * 1) There is per-socket policy (including cached global
21778 		 *    policy) or a policy on the IP-in-IP tunnel.
21779 		 * 2) There is no per-socket policy, but it is
21780 		 *    a multicast packet that needs to go out
21781 		 *    on a specific interface. This is the case
21782 		 *    where (ip_wput and ip_wput_multicast) attaches
21783 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21784 		 *
21785 		 * In case (2) we check with global policy to
21786 		 * see if there is a match and set the ill_index
21787 		 * appropriately so that we can lookup the ire
21788 		 * properly in ip_wput_ipsec_out.
21789 		 */
21790 
21791 		/*
21792 		 * ipsec_out_use_global_policy is set to B_FALSE
21793 		 * in ipsec_in_to_out(). Refer to that function for
21794 		 * details.
21795 		 */
21796 		if ((io->ipsec_out_latch == NULL) &&
21797 		    (io->ipsec_out_use_global_policy)) {
21798 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21799 			    ire, connp, unspec_src, zoneid));
21800 		}
21801 		if (!io->ipsec_out_secure) {
21802 			/*
21803 			 * If this is not a secure packet, drop
21804 			 * the IPSEC_OUT mp and treat it as a clear
21805 			 * packet. This happens when we are sending
21806 			 * a ICMP reply back to a clear packet. See
21807 			 * ipsec_in_to_out() for details.
21808 			 */
21809 			mp = first_mp->b_cont;
21810 			freeb(first_mp);
21811 		}
21812 		return (mp);
21813 	}
21814 	/*
21815 	 * See whether we need to attach a global policy here. We
21816 	 * don't depend on the conn (as it could be null) for deciding
21817 	 * what policy this datagram should go through because it
21818 	 * should have happened in ip_wput if there was some
21819 	 * policy. This normally happens for connections which are not
21820 	 * fully bound preventing us from caching policies in
21821 	 * ip_bind. Packets coming from the TCP listener/global queue
21822 	 * - which are non-hard_bound - could also be affected by
21823 	 * applying policy here.
21824 	 *
21825 	 * If this packet is coming from tcp global queue or listener,
21826 	 * we will be applying policy here.  This may not be *right*
21827 	 * if these packets are coming from the detached connection as
21828 	 * it could have gone in clear before. This happens only if a
21829 	 * TCP connection started when there is no policy and somebody
21830 	 * added policy before it became detached. Thus packets of the
21831 	 * detached connection could go out secure and the other end
21832 	 * would drop it because it will be expecting in clear. The
21833 	 * converse is not true i.e if somebody starts a TCP
21834 	 * connection and deletes the policy, all the packets will
21835 	 * still go out with the policy that existed before deleting
21836 	 * because ip_unbind sends up policy information which is used
21837 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21838 	 * TCP to attach a dummy IPSEC_OUT and set
21839 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21840 	 * affect performance for normal cases, we are not doing it.
21841 	 * Thus, set policy before starting any TCP connections.
21842 	 *
21843 	 * NOTE - We might apply policy even for a hard bound connection
21844 	 * - for which we cached policy in ip_bind - if somebody added
21845 	 * global policy after we inherited the policy in ip_bind.
21846 	 * This means that the packets that were going out in clear
21847 	 * previously would start going secure and hence get dropped
21848 	 * on the other side. To fix this, TCP attaches a dummy
21849 	 * ipsec_out and make sure that we don't apply global policy.
21850 	 */
21851 	if (ipha != NULL)
21852 		policy_present = ipss->ipsec_outbound_v4_policy_present;
21853 	else
21854 		policy_present = ipss->ipsec_outbound_v6_policy_present;
21855 	if (!policy_present)
21856 		return (mp);
21857 
21858 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21859 	    zoneid));
21860 }
21861 
21862 ire_t *
21863 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
21864 {
21865 	ipaddr_t addr;
21866 	ire_t *save_ire;
21867 	irb_t *irb;
21868 	ill_group_t *illgrp;
21869 	int	err;
21870 
21871 	save_ire = ire;
21872 	addr = ire->ire_addr;
21873 
21874 	ASSERT(ire->ire_type == IRE_BROADCAST);
21875 
21876 	illgrp = connp->conn_outgoing_ill->ill_group;
21877 	if (illgrp == NULL) {
21878 		*conn_outgoing_ill = conn_get_held_ill(connp,
21879 		    &connp->conn_outgoing_ill, &err);
21880 		if (err == ILL_LOOKUP_FAILED) {
21881 			ire_refrele(save_ire);
21882 			return (NULL);
21883 		}
21884 		return (save_ire);
21885 	}
21886 	/*
21887 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
21888 	 * If it is part of the group, we need to send on the ire
21889 	 * that has been cleared of IRE_MARK_NORECV and that belongs
21890 	 * to this group. This is okay as IP_BOUND_IF really means
21891 	 * any ill in the group. We depend on the fact that the
21892 	 * first ire in the group is always cleared of IRE_MARK_NORECV
21893 	 * if such an ire exists. This is possible only if you have
21894 	 * at least one ill in the group that has not failed.
21895 	 *
21896 	 * First get to the ire that matches the address and group.
21897 	 *
21898 	 * We don't look for an ire with a matching zoneid because a given zone
21899 	 * won't always have broadcast ires on all ills in the group.
21900 	 */
21901 	irb = ire->ire_bucket;
21902 	rw_enter(&irb->irb_lock, RW_READER);
21903 	if (ire->ire_marks & IRE_MARK_NORECV) {
21904 		/*
21905 		 * If the current zone only has an ire broadcast for this
21906 		 * address marked NORECV, the ire we want is ahead in the
21907 		 * bucket, so we look it up deliberately ignoring the zoneid.
21908 		 */
21909 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
21910 			if (ire->ire_addr != addr)
21911 				continue;
21912 			/* skip over deleted ires */
21913 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
21914 				continue;
21915 		}
21916 	}
21917 	while (ire != NULL) {
21918 		/*
21919 		 * If a new interface is coming up, we could end up
21920 		 * seeing the loopback ire and the non-loopback ire
21921 		 * may not have been added yet. So check for ire_stq
21922 		 */
21923 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
21924 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
21925 			break;
21926 		}
21927 		ire = ire->ire_next;
21928 	}
21929 	if (ire != NULL && ire->ire_addr == addr &&
21930 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
21931 		IRE_REFHOLD(ire);
21932 		rw_exit(&irb->irb_lock);
21933 		ire_refrele(save_ire);
21934 		*conn_outgoing_ill = ire_to_ill(ire);
21935 		/*
21936 		 * Refhold the ill to make the conn_outgoing_ill
21937 		 * independent of the ire. ip_wput_ire goes in a loop
21938 		 * and may refrele the ire. Since we have an ire at this
21939 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
21940 		 */
21941 		ill_refhold(*conn_outgoing_ill);
21942 		return (ire);
21943 	}
21944 	rw_exit(&irb->irb_lock);
21945 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
21946 	/*
21947 	 * If we can't find a suitable ire, return the original ire.
21948 	 */
21949 	return (save_ire);
21950 }
21951 
21952 /*
21953  * This function does the ire_refrele of the ire passed in as the
21954  * argument. As this function looks up more ires i.e broadcast ires,
21955  * it needs to REFRELE them. Currently, for simplicity we don't
21956  * differentiate the one passed in and looked up here. We always
21957  * REFRELE.
21958  * IPQoS Notes:
21959  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
21960  * IPsec packets are done in ipsec_out_process.
21961  *
21962  */
21963 void
21964 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
21965     zoneid_t zoneid)
21966 {
21967 	ipha_t		*ipha;
21968 #define	rptr	((uchar_t *)ipha)
21969 	queue_t		*stq;
21970 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
21971 	uint32_t	v_hlen_tos_len;
21972 	uint32_t	ttl_protocol;
21973 	ipaddr_t	src;
21974 	ipaddr_t	dst;
21975 	uint32_t	cksum;
21976 	ipaddr_t	orig_src;
21977 	ire_t		*ire1;
21978 	mblk_t		*next_mp;
21979 	uint_t		hlen;
21980 	uint16_t	*up;
21981 	uint32_t	max_frag = ire->ire_max_frag;
21982 	ill_t		*ill = ire_to_ill(ire);
21983 	int		clusterwide;
21984 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
21985 	int		ipsec_len;
21986 	mblk_t		*first_mp;
21987 	ipsec_out_t	*io;
21988 	boolean_t	conn_dontroute;		/* conn value for multicast */
21989 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
21990 	boolean_t	multicast_forward;	/* Should we forward ? */
21991 	boolean_t	unspec_src;
21992 	ill_t		*conn_outgoing_ill = NULL;
21993 	ill_t		*ire_ill;
21994 	ill_t		*ire1_ill;
21995 	ill_t		*out_ill;
21996 	uint32_t 	ill_index = 0;
21997 	boolean_t	multirt_send = B_FALSE;
21998 	int		err;
21999 	ipxmit_state_t	pktxmit_state;
22000 	ip_stack_t	*ipst = ire->ire_ipst;
22001 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22002 
22003 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22004 	    "ip_wput_ire_start: q %p", q);
22005 
22006 	multicast_forward = B_FALSE;
22007 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22008 
22009 	if (ire->ire_flags & RTF_MULTIRT) {
22010 		/*
22011 		 * Multirouting case. The bucket where ire is stored
22012 		 * probably holds other RTF_MULTIRT flagged ire
22013 		 * to the destination. In this call to ip_wput_ire,
22014 		 * we attempt to send the packet through all
22015 		 * those ires. Thus, we first ensure that ire is the
22016 		 * first RTF_MULTIRT ire in the bucket,
22017 		 * before walking the ire list.
22018 		 */
22019 		ire_t *first_ire;
22020 		irb_t *irb = ire->ire_bucket;
22021 		ASSERT(irb != NULL);
22022 
22023 		/* Make sure we do not omit any multiroute ire. */
22024 		IRB_REFHOLD(irb);
22025 		for (first_ire = irb->irb_ire;
22026 		    first_ire != NULL;
22027 		    first_ire = first_ire->ire_next) {
22028 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22029 			    (first_ire->ire_addr == ire->ire_addr) &&
22030 			    !(first_ire->ire_marks &
22031 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
22032 				break;
22033 			}
22034 		}
22035 
22036 		if ((first_ire != NULL) && (first_ire != ire)) {
22037 			IRE_REFHOLD(first_ire);
22038 			ire_refrele(ire);
22039 			ire = first_ire;
22040 			ill = ire_to_ill(ire);
22041 		}
22042 		IRB_REFRELE(irb);
22043 	}
22044 
22045 	/*
22046 	 * conn_outgoing_ill variable is used only in the broadcast loop.
22047 	 * for performance we don't grab the mutexs in the fastpath
22048 	 */
22049 	if ((connp != NULL) &&
22050 	    (ire->ire_type == IRE_BROADCAST) &&
22051 	    ((connp->conn_nofailover_ill != NULL) ||
22052 	    (connp->conn_outgoing_ill != NULL))) {
22053 		/*
22054 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
22055 		 * option. So, see if this endpoint is bound to a
22056 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
22057 		 * that if the interface is failed, we will still send
22058 		 * the packet on the same ill which is what we want.
22059 		 */
22060 		conn_outgoing_ill = conn_get_held_ill(connp,
22061 		    &connp->conn_nofailover_ill, &err);
22062 		if (err == ILL_LOOKUP_FAILED) {
22063 			ire_refrele(ire);
22064 			freemsg(mp);
22065 			return;
22066 		}
22067 		if (conn_outgoing_ill == NULL) {
22068 			/*
22069 			 * Choose a good ill in the group to send the
22070 			 * packets on.
22071 			 */
22072 			ire = conn_set_outgoing_ill(connp, ire,
22073 			    &conn_outgoing_ill);
22074 			if (ire == NULL) {
22075 				freemsg(mp);
22076 				return;
22077 			}
22078 		}
22079 	}
22080 
22081 	if (mp->b_datap->db_type != M_CTL) {
22082 		ipha = (ipha_t *)mp->b_rptr;
22083 	} else {
22084 		io = (ipsec_out_t *)mp->b_rptr;
22085 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22086 		ASSERT(zoneid == io->ipsec_out_zoneid);
22087 		ASSERT(zoneid != ALL_ZONES);
22088 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22089 		dst = ipha->ipha_dst;
22090 		/*
22091 		 * For the multicast case, ipsec_out carries conn_dontroute and
22092 		 * conn_multicast_loop as conn may not be available here. We
22093 		 * need this for multicast loopback and forwarding which is done
22094 		 * later in the code.
22095 		 */
22096 		if (CLASSD(dst)) {
22097 			conn_dontroute = io->ipsec_out_dontroute;
22098 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22099 			/*
22100 			 * If conn_dontroute is not set or conn_multicast_loop
22101 			 * is set, we need to do forwarding/loopback. For
22102 			 * datagrams from ip_wput_multicast, conn_dontroute is
22103 			 * set to B_TRUE and conn_multicast_loop is set to
22104 			 * B_FALSE so that we neither do forwarding nor
22105 			 * loopback.
22106 			 */
22107 			if (!conn_dontroute || conn_multicast_loop)
22108 				multicast_forward = B_TRUE;
22109 		}
22110 	}
22111 
22112 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22113 	    ire->ire_zoneid != ALL_ZONES) {
22114 		/*
22115 		 * When a zone sends a packet to another zone, we try to deliver
22116 		 * the packet under the same conditions as if the destination
22117 		 * was a real node on the network. To do so, we look for a
22118 		 * matching route in the forwarding table.
22119 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22120 		 * ip_newroute() does.
22121 		 * Note that IRE_LOCAL are special, since they are used
22122 		 * when the zoneid doesn't match in some cases. This means that
22123 		 * we need to handle ipha_src differently since ire_src_addr
22124 		 * belongs to the receiving zone instead of the sending zone.
22125 		 * When ip_restrict_interzone_loopback is set, then
22126 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22127 		 * for loopback between zones when the logical "Ethernet" would
22128 		 * have looped them back.
22129 		 */
22130 		ire_t *src_ire;
22131 
22132 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22133 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22134 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22135 		if (src_ire != NULL &&
22136 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22137 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22138 		    ire_local_same_ill_group(ire, src_ire))) {
22139 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22140 				ipha->ipha_src = src_ire->ire_src_addr;
22141 			ire_refrele(src_ire);
22142 		} else {
22143 			ire_refrele(ire);
22144 			if (conn_outgoing_ill != NULL)
22145 				ill_refrele(conn_outgoing_ill);
22146 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22147 			if (src_ire != NULL) {
22148 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22149 					ire_refrele(src_ire);
22150 					freemsg(mp);
22151 					return;
22152 				}
22153 				ire_refrele(src_ire);
22154 			}
22155 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22156 				/* Failed */
22157 				freemsg(mp);
22158 				return;
22159 			}
22160 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22161 			    ipst);
22162 			return;
22163 		}
22164 	}
22165 
22166 	if (mp->b_datap->db_type == M_CTL ||
22167 	    ipss->ipsec_outbound_v4_policy_present) {
22168 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22169 		    unspec_src, zoneid);
22170 		if (mp == NULL) {
22171 			ire_refrele(ire);
22172 			if (conn_outgoing_ill != NULL)
22173 				ill_refrele(conn_outgoing_ill);
22174 			return;
22175 		}
22176 	}
22177 
22178 	first_mp = mp;
22179 	ipsec_len = 0;
22180 
22181 	if (first_mp->b_datap->db_type == M_CTL) {
22182 		io = (ipsec_out_t *)first_mp->b_rptr;
22183 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22184 		mp = first_mp->b_cont;
22185 		ipsec_len = ipsec_out_extra_length(first_mp);
22186 		ASSERT(ipsec_len >= 0);
22187 		/* We already picked up the zoneid from the M_CTL above */
22188 		ASSERT(zoneid == io->ipsec_out_zoneid);
22189 		ASSERT(zoneid != ALL_ZONES);
22190 
22191 		/*
22192 		 * Drop M_CTL here if IPsec processing is not needed.
22193 		 * (Non-IPsec use of M_CTL extracted any information it
22194 		 * needed above).
22195 		 */
22196 		if (ipsec_len == 0) {
22197 			freeb(first_mp);
22198 			first_mp = mp;
22199 		}
22200 	}
22201 
22202 	/*
22203 	 * Fast path for ip_wput_ire
22204 	 */
22205 
22206 	ipha = (ipha_t *)mp->b_rptr;
22207 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22208 	dst = ipha->ipha_dst;
22209 
22210 	/*
22211 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22212 	 * if the socket is a SOCK_RAW type. The transport checksum should
22213 	 * be provided in the pre-built packet, so we don't need to compute it.
22214 	 * Also, other application set flags, like DF, should not be altered.
22215 	 * Other transport MUST pass down zero.
22216 	 */
22217 	ip_hdr_included = ipha->ipha_ident;
22218 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22219 
22220 	if (CLASSD(dst)) {
22221 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22222 		    ntohl(dst),
22223 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22224 		    ntohl(ire->ire_addr)));
22225 	}
22226 
22227 /* Macros to extract header fields from data already in registers */
22228 #ifdef	_BIG_ENDIAN
22229 #define	V_HLEN	(v_hlen_tos_len >> 24)
22230 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22231 #define	PROTO	(ttl_protocol & 0xFF)
22232 #else
22233 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22234 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22235 #define	PROTO	(ttl_protocol >> 8)
22236 #endif
22237 
22238 
22239 	orig_src = src = ipha->ipha_src;
22240 	/* (The loop back to "another" is explained down below.) */
22241 another:;
22242 	/*
22243 	 * Assign an ident value for this packet.  We assign idents on
22244 	 * a per destination basis out of the IRE.  There could be
22245 	 * other threads targeting the same destination, so we have to
22246 	 * arrange for a atomic increment.  Note that we use a 32-bit
22247 	 * atomic add because it has better performance than its
22248 	 * 16-bit sibling.
22249 	 *
22250 	 * If running in cluster mode and if the source address
22251 	 * belongs to a replicated service then vector through
22252 	 * cl_inet_ipident vector to allocate ip identifier
22253 	 * NOTE: This is a contract private interface with the
22254 	 * clustering group.
22255 	 */
22256 	clusterwide = 0;
22257 	if (cl_inet_ipident) {
22258 		ASSERT(cl_inet_isclusterwide);
22259 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
22260 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
22261 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
22262 			    AF_INET, (uint8_t *)(uintptr_t)src,
22263 			    (uint8_t *)(uintptr_t)dst);
22264 			clusterwide = 1;
22265 		}
22266 	}
22267 	if (!clusterwide) {
22268 		ipha->ipha_ident =
22269 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22270 	}
22271 
22272 #ifndef _BIG_ENDIAN
22273 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22274 #endif
22275 
22276 	/*
22277 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22278 	 * This is needed to obey conn_unspec_src when packets go through
22279 	 * ip_newroute + arp.
22280 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22281 	 */
22282 	if (src == INADDR_ANY && !unspec_src) {
22283 		/*
22284 		 * Assign the appropriate source address from the IRE if none
22285 		 * was specified.
22286 		 */
22287 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22288 
22289 		/*
22290 		 * With IP multipathing, broadcast packets are sent on the ire
22291 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
22292 		 * the group. However, this ire might not be in the same zone so
22293 		 * we can't always use its source address. We look for a
22294 		 * broadcast ire in the same group and in the right zone.
22295 		 */
22296 		if (ire->ire_type == IRE_BROADCAST &&
22297 		    ire->ire_zoneid != zoneid) {
22298 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
22299 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
22300 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
22301 			if (src_ire != NULL) {
22302 				src = src_ire->ire_src_addr;
22303 				ire_refrele(src_ire);
22304 			} else {
22305 				ire_refrele(ire);
22306 				if (conn_outgoing_ill != NULL)
22307 					ill_refrele(conn_outgoing_ill);
22308 				freemsg(first_mp);
22309 				if (ill != NULL) {
22310 					BUMP_MIB(ill->ill_ip_mib,
22311 					    ipIfStatsOutDiscards);
22312 				} else {
22313 					BUMP_MIB(&ipst->ips_ip_mib,
22314 					    ipIfStatsOutDiscards);
22315 				}
22316 				return;
22317 			}
22318 		} else {
22319 			src = ire->ire_src_addr;
22320 		}
22321 
22322 		if (connp == NULL) {
22323 			ip1dbg(("ip_wput_ire: no connp and no src "
22324 			    "address for dst 0x%x, using src 0x%x\n",
22325 			    ntohl(dst),
22326 			    ntohl(src)));
22327 		}
22328 		ipha->ipha_src = src;
22329 	}
22330 	stq = ire->ire_stq;
22331 
22332 	/*
22333 	 * We only allow ire chains for broadcasts since there will
22334 	 * be multiple IRE_CACHE entries for the same multicast
22335 	 * address (one per ipif).
22336 	 */
22337 	next_mp = NULL;
22338 
22339 	/* broadcast packet */
22340 	if (ire->ire_type == IRE_BROADCAST)
22341 		goto broadcast;
22342 
22343 	/* loopback ? */
22344 	if (stq == NULL)
22345 		goto nullstq;
22346 
22347 	/* The ill_index for outbound ILL */
22348 	ill_index = Q_TO_INDEX(stq);
22349 
22350 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22351 	ttl_protocol = ((uint16_t *)ipha)[4];
22352 
22353 	/* pseudo checksum (do it in parts for IP header checksum) */
22354 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22355 
22356 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22357 		queue_t *dev_q = stq->q_next;
22358 
22359 		/* flow controlled */
22360 		if ((dev_q->q_next || dev_q->q_first) &&
22361 		    !canput(dev_q))
22362 			goto blocked;
22363 		if ((PROTO == IPPROTO_UDP) &&
22364 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22365 			hlen = (V_HLEN & 0xF) << 2;
22366 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22367 			if (*up != 0) {
22368 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22369 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22370 				/* Software checksum? */
22371 				if (DB_CKSUMFLAGS(mp) == 0) {
22372 					IP_STAT(ipst, ip_out_sw_cksum);
22373 					IP_STAT_UPDATE(ipst,
22374 					    ip_udp_out_sw_cksum_bytes,
22375 					    LENGTH - hlen);
22376 				}
22377 			}
22378 		}
22379 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22380 		hlen = (V_HLEN & 0xF) << 2;
22381 		if (PROTO == IPPROTO_TCP) {
22382 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22383 			/*
22384 			 * The packet header is processed once and for all, even
22385 			 * in the multirouting case. We disable hardware
22386 			 * checksum if the packet is multirouted, as it will be
22387 			 * replicated via several interfaces, and not all of
22388 			 * them may have this capability.
22389 			 */
22390 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22391 			    LENGTH, max_frag, ipsec_len, cksum);
22392 			/* Software checksum? */
22393 			if (DB_CKSUMFLAGS(mp) == 0) {
22394 				IP_STAT(ipst, ip_out_sw_cksum);
22395 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22396 				    LENGTH - hlen);
22397 			}
22398 		} else {
22399 			sctp_hdr_t	*sctph;
22400 
22401 			ASSERT(PROTO == IPPROTO_SCTP);
22402 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22403 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22404 			/*
22405 			 * Zero out the checksum field to ensure proper
22406 			 * checksum calculation.
22407 			 */
22408 			sctph->sh_chksum = 0;
22409 #ifdef	DEBUG
22410 			if (!skip_sctp_cksum)
22411 #endif
22412 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22413 		}
22414 	}
22415 
22416 	/*
22417 	 * If this is a multicast packet and originated from ip_wput
22418 	 * we need to do loopback and forwarding checks. If it comes
22419 	 * from ip_wput_multicast, we SHOULD not do this.
22420 	 */
22421 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22422 
22423 	/* checksum */
22424 	cksum += ttl_protocol;
22425 
22426 	/* fragment the packet */
22427 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22428 		goto fragmentit;
22429 	/*
22430 	 * Don't use frag_flag if packet is pre-built or source
22431 	 * routed or if multicast (since multicast packets do
22432 	 * not solicit ICMP "packet too big" messages).
22433 	 */
22434 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22435 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22436 	    !ip_source_route_included(ipha)) &&
22437 	    !CLASSD(ipha->ipha_dst))
22438 		ipha->ipha_fragment_offset_and_flags |=
22439 		    htons(ire->ire_frag_flag);
22440 
22441 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22442 		/* calculate IP header checksum */
22443 		cksum += ipha->ipha_ident;
22444 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22445 		cksum += ipha->ipha_fragment_offset_and_flags;
22446 
22447 		/* IP options present */
22448 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22449 		if (hlen)
22450 			goto checksumoptions;
22451 
22452 		/* calculate hdr checksum */
22453 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22454 		cksum = ~(cksum + (cksum >> 16));
22455 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22456 	}
22457 	if (ipsec_len != 0) {
22458 		/*
22459 		 * We will do the rest of the processing after
22460 		 * we come back from IPsec in ip_wput_ipsec_out().
22461 		 */
22462 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22463 
22464 		io = (ipsec_out_t *)first_mp->b_rptr;
22465 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
22466 		    ill_phyint->phyint_ifindex;
22467 
22468 		ipsec_out_process(q, first_mp, ire, ill_index);
22469 		ire_refrele(ire);
22470 		if (conn_outgoing_ill != NULL)
22471 			ill_refrele(conn_outgoing_ill);
22472 		return;
22473 	}
22474 
22475 	/*
22476 	 * In most cases, the emission loop below is entered only
22477 	 * once. Only in the case where the ire holds the
22478 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22479 	 * flagged ires in the bucket, and send the packet
22480 	 * through all crossed RTF_MULTIRT routes.
22481 	 */
22482 	if (ire->ire_flags & RTF_MULTIRT) {
22483 		multirt_send = B_TRUE;
22484 	}
22485 	do {
22486 		if (multirt_send) {
22487 			irb_t *irb;
22488 			/*
22489 			 * We are in a multiple send case, need to get
22490 			 * the next ire and make a duplicate of the packet.
22491 			 * ire1 holds here the next ire to process in the
22492 			 * bucket. If multirouting is expected,
22493 			 * any non-RTF_MULTIRT ire that has the
22494 			 * right destination address is ignored.
22495 			 */
22496 			irb = ire->ire_bucket;
22497 			ASSERT(irb != NULL);
22498 
22499 			IRB_REFHOLD(irb);
22500 			for (ire1 = ire->ire_next;
22501 			    ire1 != NULL;
22502 			    ire1 = ire1->ire_next) {
22503 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22504 					continue;
22505 				if (ire1->ire_addr != ire->ire_addr)
22506 					continue;
22507 				if (ire1->ire_marks &
22508 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22509 					continue;
22510 
22511 				/* Got one */
22512 				IRE_REFHOLD(ire1);
22513 				break;
22514 			}
22515 			IRB_REFRELE(irb);
22516 
22517 			if (ire1 != NULL) {
22518 				next_mp = copyb(mp);
22519 				if ((next_mp == NULL) ||
22520 				    ((mp->b_cont != NULL) &&
22521 				    ((next_mp->b_cont =
22522 				    dupmsg(mp->b_cont)) == NULL))) {
22523 					freemsg(next_mp);
22524 					next_mp = NULL;
22525 					ire_refrele(ire1);
22526 					ire1 = NULL;
22527 				}
22528 			}
22529 
22530 			/* Last multiroute ire; don't loop anymore. */
22531 			if (ire1 == NULL) {
22532 				multirt_send = B_FALSE;
22533 			}
22534 		}
22535 
22536 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22537 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22538 		    mblk_t *, mp);
22539 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22540 		    ipst->ips_ipv4firewall_physical_out,
22541 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, ipst);
22542 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22543 		if (mp == NULL)
22544 			goto release_ire_and_ill;
22545 
22546 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22547 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22548 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
22549 		if ((pktxmit_state == SEND_FAILED) ||
22550 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22551 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22552 			    "- packet dropped\n"));
22553 release_ire_and_ill:
22554 			ire_refrele(ire);
22555 			if (next_mp != NULL) {
22556 				freemsg(next_mp);
22557 				ire_refrele(ire1);
22558 			}
22559 			if (conn_outgoing_ill != NULL)
22560 				ill_refrele(conn_outgoing_ill);
22561 			return;
22562 		}
22563 
22564 		if (CLASSD(dst)) {
22565 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22566 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22567 			    LENGTH);
22568 		}
22569 
22570 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22571 		    "ip_wput_ire_end: q %p (%S)",
22572 		    q, "last copy out");
22573 		IRE_REFRELE(ire);
22574 
22575 		if (multirt_send) {
22576 			ASSERT(ire1);
22577 			/*
22578 			 * Proceed with the next RTF_MULTIRT ire,
22579 			 * Also set up the send-to queue accordingly.
22580 			 */
22581 			ire = ire1;
22582 			ire1 = NULL;
22583 			stq = ire->ire_stq;
22584 			mp = next_mp;
22585 			next_mp = NULL;
22586 			ipha = (ipha_t *)mp->b_rptr;
22587 			ill_index = Q_TO_INDEX(stq);
22588 			ill = (ill_t *)stq->q_ptr;
22589 		}
22590 	} while (multirt_send);
22591 	if (conn_outgoing_ill != NULL)
22592 		ill_refrele(conn_outgoing_ill);
22593 	return;
22594 
22595 	/*
22596 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22597 	 */
22598 broadcast:
22599 	{
22600 		/*
22601 		 * To avoid broadcast storms, we usually set the TTL to 1 for
22602 		 * broadcasts.  However, if SO_DONTROUTE isn't set, this value
22603 		 * can be overridden stack-wide through the ip_broadcast_ttl
22604 		 * ndd tunable, or on a per-connection basis through the
22605 		 * IP_BROADCAST_TTL socket option.
22606 		 *
22607 		 * In the event that we are replying to incoming ICMP packets,
22608 		 * connp could be NULL.
22609 		 */
22610 		ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22611 		if (connp != NULL) {
22612 			if (connp->conn_dontroute)
22613 				ipha->ipha_ttl = 1;
22614 			else if (connp->conn_broadcast_ttl != 0)
22615 				ipha->ipha_ttl = connp->conn_broadcast_ttl;
22616 		}
22617 
22618 		/*
22619 		 * Note that we are not doing a IRB_REFHOLD here.
22620 		 * Actually we don't care if the list changes i.e
22621 		 * if somebody deletes an IRE from the list while
22622 		 * we drop the lock, the next time we come around
22623 		 * ire_next will be NULL and hence we won't send
22624 		 * out multiple copies which is fine.
22625 		 */
22626 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22627 		ire1 = ire->ire_next;
22628 		if (conn_outgoing_ill != NULL) {
22629 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22630 				ASSERT(ire1 == ire->ire_next);
22631 				if (ire1 != NULL && ire1->ire_addr == dst) {
22632 					ire_refrele(ire);
22633 					ire = ire1;
22634 					IRE_REFHOLD(ire);
22635 					ire1 = ire->ire_next;
22636 					continue;
22637 				}
22638 				rw_exit(&ire->ire_bucket->irb_lock);
22639 				/* Did not find a matching ill */
22640 				ip1dbg(("ip_wput_ire: broadcast with no "
22641 				    "matching IP_BOUND_IF ill %s dst %x\n",
22642 				    conn_outgoing_ill->ill_name, dst));
22643 				freemsg(first_mp);
22644 				if (ire != NULL)
22645 					ire_refrele(ire);
22646 				ill_refrele(conn_outgoing_ill);
22647 				return;
22648 			}
22649 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22650 			/*
22651 			 * If the next IRE has the same address and is not one
22652 			 * of the two copies that we need to send, try to see
22653 			 * whether this copy should be sent at all. This
22654 			 * assumes that we insert loopbacks first and then
22655 			 * non-loopbacks. This is acheived by inserting the
22656 			 * loopback always before non-loopback.
22657 			 * This is used to send a single copy of a broadcast
22658 			 * packet out all physical interfaces that have an
22659 			 * matching IRE_BROADCAST while also looping
22660 			 * back one copy (to ip_wput_local) for each
22661 			 * matching physical interface. However, we avoid
22662 			 * sending packets out different logical that match by
22663 			 * having ipif_up/ipif_down supress duplicate
22664 			 * IRE_BROADCASTS.
22665 			 *
22666 			 * This feature is currently used to get broadcasts
22667 			 * sent to multiple interfaces, when the broadcast
22668 			 * address being used applies to multiple interfaces.
22669 			 * For example, a whole net broadcast will be
22670 			 * replicated on every connected subnet of
22671 			 * the target net.
22672 			 *
22673 			 * Each zone has its own set of IRE_BROADCASTs, so that
22674 			 * we're able to distribute inbound packets to multiple
22675 			 * zones who share a broadcast address. We avoid looping
22676 			 * back outbound packets in different zones but on the
22677 			 * same ill, as the application would see duplicates.
22678 			 *
22679 			 * If the interfaces are part of the same group,
22680 			 * we would want to send only one copy out for
22681 			 * whole group.
22682 			 *
22683 			 * This logic assumes that ire_add_v4() groups the
22684 			 * IRE_BROADCAST entries so that those with the same
22685 			 * ire_addr and ill_group are kept together.
22686 			 */
22687 			ire_ill = ire->ire_ipif->ipif_ill;
22688 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22689 				if (ire_ill->ill_group != NULL &&
22690 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22691 					/*
22692 					 * If the current zone only has an ire
22693 					 * broadcast for this address marked
22694 					 * NORECV, the ire we want is ahead in
22695 					 * the bucket, so we look it up
22696 					 * deliberately ignoring the zoneid.
22697 					 */
22698 					for (ire1 = ire->ire_bucket->irb_ire;
22699 					    ire1 != NULL;
22700 					    ire1 = ire1->ire_next) {
22701 						ire1_ill =
22702 						    ire1->ire_ipif->ipif_ill;
22703 						if (ire1->ire_addr != dst)
22704 							continue;
22705 						/* skip over the current ire */
22706 						if (ire1 == ire)
22707 							continue;
22708 						/* skip over deleted ires */
22709 						if (ire1->ire_marks &
22710 						    IRE_MARK_CONDEMNED)
22711 							continue;
22712 						/*
22713 						 * non-loopback ire in our
22714 						 * group: use it for the next
22715 						 * pass in the loop
22716 						 */
22717 						if (ire1->ire_stq != NULL &&
22718 						    ire1_ill->ill_group ==
22719 						    ire_ill->ill_group)
22720 							break;
22721 					}
22722 				}
22723 			} else {
22724 				while (ire1 != NULL && ire1->ire_addr == dst) {
22725 					ire1_ill = ire1->ire_ipif->ipif_ill;
22726 					/*
22727 					 * We can have two broadcast ires on the
22728 					 * same ill in different zones; here
22729 					 * we'll send a copy of the packet on
22730 					 * each ill and the fanout code will
22731 					 * call conn_wantpacket() to check that
22732 					 * the zone has the broadcast address
22733 					 * configured on the ill. If the two
22734 					 * ires are in the same group we only
22735 					 * send one copy up.
22736 					 */
22737 					if (ire1_ill != ire_ill &&
22738 					    (ire1_ill->ill_group == NULL ||
22739 					    ire_ill->ill_group == NULL ||
22740 					    ire1_ill->ill_group !=
22741 					    ire_ill->ill_group)) {
22742 						break;
22743 					}
22744 					ire1 = ire1->ire_next;
22745 				}
22746 			}
22747 		}
22748 		ASSERT(multirt_send == B_FALSE);
22749 		if (ire1 != NULL && ire1->ire_addr == dst) {
22750 			if ((ire->ire_flags & RTF_MULTIRT) &&
22751 			    (ire1->ire_flags & RTF_MULTIRT)) {
22752 				/*
22753 				 * We are in the multirouting case.
22754 				 * The message must be sent at least
22755 				 * on both ires. These ires have been
22756 				 * inserted AFTER the standard ones
22757 				 * in ip_rt_add(). There are thus no
22758 				 * other ire entries for the destination
22759 				 * address in the rest of the bucket
22760 				 * that do not have the RTF_MULTIRT
22761 				 * flag. We don't process a copy
22762 				 * of the message here. This will be
22763 				 * done in the final sending loop.
22764 				 */
22765 				multirt_send = B_TRUE;
22766 			} else {
22767 				next_mp = ip_copymsg(first_mp);
22768 				if (next_mp != NULL)
22769 					IRE_REFHOLD(ire1);
22770 			}
22771 		}
22772 		rw_exit(&ire->ire_bucket->irb_lock);
22773 	}
22774 
22775 	if (stq) {
22776 		/*
22777 		 * A non-NULL send-to queue means this packet is going
22778 		 * out of this machine.
22779 		 */
22780 		out_ill = (ill_t *)stq->q_ptr;
22781 
22782 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22783 		ttl_protocol = ((uint16_t *)ipha)[4];
22784 		/*
22785 		 * We accumulate the pseudo header checksum in cksum.
22786 		 * This is pretty hairy code, so watch close.  One
22787 		 * thing to keep in mind is that UDP and TCP have
22788 		 * stored their respective datagram lengths in their
22789 		 * checksum fields.  This lines things up real nice.
22790 		 */
22791 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22792 		    (src >> 16) + (src & 0xFFFF);
22793 		/*
22794 		 * We assume the udp checksum field contains the
22795 		 * length, so to compute the pseudo header checksum,
22796 		 * all we need is the protocol number and src/dst.
22797 		 */
22798 		/* Provide the checksums for UDP and TCP. */
22799 		if ((PROTO == IPPROTO_TCP) &&
22800 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22801 			/* hlen gets the number of uchar_ts in the IP header */
22802 			hlen = (V_HLEN & 0xF) << 2;
22803 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22804 			IP_STAT(ipst, ip_out_sw_cksum);
22805 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22806 			    LENGTH - hlen);
22807 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22808 		} else if (PROTO == IPPROTO_SCTP &&
22809 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22810 			sctp_hdr_t	*sctph;
22811 
22812 			hlen = (V_HLEN & 0xF) << 2;
22813 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22814 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22815 			sctph->sh_chksum = 0;
22816 #ifdef	DEBUG
22817 			if (!skip_sctp_cksum)
22818 #endif
22819 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22820 		} else {
22821 			queue_t *dev_q = stq->q_next;
22822 
22823 			if ((dev_q->q_next || dev_q->q_first) &&
22824 			    !canput(dev_q)) {
22825 blocked:
22826 				ipha->ipha_ident = ip_hdr_included;
22827 				/*
22828 				 * If we don't have a conn to apply
22829 				 * backpressure, free the message.
22830 				 * In the ire_send path, we don't know
22831 				 * the position to requeue the packet. Rather
22832 				 * than reorder packets, we just drop this
22833 				 * packet.
22834 				 */
22835 				if (ipst->ips_ip_output_queue &&
22836 				    connp != NULL &&
22837 				    caller != IRE_SEND) {
22838 					if (caller == IP_WSRV) {
22839 						connp->conn_did_putbq = 1;
22840 						(void) putbq(connp->conn_wq,
22841 						    first_mp);
22842 						conn_drain_insert(connp);
22843 						/*
22844 						 * This is the service thread,
22845 						 * and the queue is already
22846 						 * noenabled. The check for
22847 						 * canput and the putbq is not
22848 						 * atomic. So we need to check
22849 						 * again.
22850 						 */
22851 						if (canput(stq->q_next))
22852 							connp->conn_did_putbq
22853 							    = 0;
22854 						IP_STAT(ipst, ip_conn_flputbq);
22855 					} else {
22856 						/*
22857 						 * We are not the service proc.
22858 						 * ip_wsrv will be scheduled or
22859 						 * is already running.
22860 						 */
22861 						(void) putq(connp->conn_wq,
22862 						    first_mp);
22863 					}
22864 				} else {
22865 					out_ill = (ill_t *)stq->q_ptr;
22866 					BUMP_MIB(out_ill->ill_ip_mib,
22867 					    ipIfStatsOutDiscards);
22868 					freemsg(first_mp);
22869 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22870 					    "ip_wput_ire_end: q %p (%S)",
22871 					    q, "discard");
22872 				}
22873 				ire_refrele(ire);
22874 				if (next_mp) {
22875 					ire_refrele(ire1);
22876 					freemsg(next_mp);
22877 				}
22878 				if (conn_outgoing_ill != NULL)
22879 					ill_refrele(conn_outgoing_ill);
22880 				return;
22881 			}
22882 			if ((PROTO == IPPROTO_UDP) &&
22883 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22884 				/*
22885 				 * hlen gets the number of uchar_ts in the
22886 				 * IP header
22887 				 */
22888 				hlen = (V_HLEN & 0xF) << 2;
22889 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22890 				max_frag = ire->ire_max_frag;
22891 				if (*up != 0) {
22892 					IP_CKSUM_XMIT(out_ill, ire, mp, ipha,
22893 					    up, PROTO, hlen, LENGTH, max_frag,
22894 					    ipsec_len, cksum);
22895 					/* Software checksum? */
22896 					if (DB_CKSUMFLAGS(mp) == 0) {
22897 						IP_STAT(ipst, ip_out_sw_cksum);
22898 						IP_STAT_UPDATE(ipst,
22899 						    ip_udp_out_sw_cksum_bytes,
22900 						    LENGTH - hlen);
22901 					}
22902 				}
22903 			}
22904 		}
22905 		/*
22906 		 * Need to do this even when fragmenting. The local
22907 		 * loopback can be done without computing checksums
22908 		 * but forwarding out other interface must be done
22909 		 * after the IP checksum (and ULP checksums) have been
22910 		 * computed.
22911 		 *
22912 		 * NOTE : multicast_forward is set only if this packet
22913 		 * originated from ip_wput. For packets originating from
22914 		 * ip_wput_multicast, it is not set.
22915 		 */
22916 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
22917 multi_loopback:
22918 			ip2dbg(("ip_wput: multicast, loop %d\n",
22919 			    conn_multicast_loop));
22920 
22921 			/*  Forget header checksum offload */
22922 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
22923 
22924 			/*
22925 			 * Local loopback of multicasts?  Check the
22926 			 * ill.
22927 			 *
22928 			 * Note that the loopback function will not come
22929 			 * in through ip_rput - it will only do the
22930 			 * client fanout thus we need to do an mforward
22931 			 * as well.  The is different from the BSD
22932 			 * logic.
22933 			 */
22934 			if (ill != NULL) {
22935 				ilm_t	*ilm;
22936 
22937 				ILM_WALKER_HOLD(ill);
22938 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
22939 				    ALL_ZONES);
22940 				ILM_WALKER_RELE(ill);
22941 				if (ilm != NULL) {
22942 					/*
22943 					 * Pass along the virtual output q.
22944 					 * ip_wput_local() will distribute the
22945 					 * packet to all the matching zones,
22946 					 * except the sending zone when
22947 					 * IP_MULTICAST_LOOP is false.
22948 					 */
22949 					ip_multicast_loopback(q, ill, first_mp,
22950 					    conn_multicast_loop ? 0 :
22951 					    IP_FF_NO_MCAST_LOOP, zoneid);
22952 				}
22953 			}
22954 			if (ipha->ipha_ttl == 0) {
22955 				/*
22956 				 * 0 => only to this host i.e. we are
22957 				 * done. We are also done if this was the
22958 				 * loopback interface since it is sufficient
22959 				 * to loopback one copy of a multicast packet.
22960 				 */
22961 				freemsg(first_mp);
22962 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22963 				    "ip_wput_ire_end: q %p (%S)",
22964 				    q, "loopback");
22965 				ire_refrele(ire);
22966 				if (conn_outgoing_ill != NULL)
22967 					ill_refrele(conn_outgoing_ill);
22968 				return;
22969 			}
22970 			/*
22971 			 * ILLF_MULTICAST is checked in ip_newroute
22972 			 * i.e. we don't need to check it here since
22973 			 * all IRE_CACHEs come from ip_newroute.
22974 			 * For multicast traffic, SO_DONTROUTE is interpreted
22975 			 * to mean only send the packet out the interface
22976 			 * (optionally specified with IP_MULTICAST_IF)
22977 			 * and do not forward it out additional interfaces.
22978 			 * RSVP and the rsvp daemon is an example of a
22979 			 * protocol and user level process that
22980 			 * handles it's own routing. Hence, it uses the
22981 			 * SO_DONTROUTE option to accomplish this.
22982 			 */
22983 
22984 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
22985 			    ill != NULL) {
22986 				/* Unconditionally redo the checksum */
22987 				ipha->ipha_hdr_checksum = 0;
22988 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22989 
22990 				/*
22991 				 * If this needs to go out secure, we need
22992 				 * to wait till we finish the IPsec
22993 				 * processing.
22994 				 */
22995 				if (ipsec_len == 0 &&
22996 				    ip_mforward(ill, ipha, mp)) {
22997 					freemsg(first_mp);
22998 					ip1dbg(("ip_wput: mforward failed\n"));
22999 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23000 					    "ip_wput_ire_end: q %p (%S)",
23001 					    q, "mforward failed");
23002 					ire_refrele(ire);
23003 					if (conn_outgoing_ill != NULL)
23004 						ill_refrele(conn_outgoing_ill);
23005 					return;
23006 				}
23007 			}
23008 		}
23009 		max_frag = ire->ire_max_frag;
23010 		cksum += ttl_protocol;
23011 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23012 			/* No fragmentation required for this one. */
23013 			/*
23014 			 * Don't use frag_flag if packet is pre-built or source
23015 			 * routed or if multicast (since multicast packets do
23016 			 * not solicit ICMP "packet too big" messages).
23017 			 */
23018 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23019 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23020 			    !ip_source_route_included(ipha)) &&
23021 			    !CLASSD(ipha->ipha_dst))
23022 				ipha->ipha_fragment_offset_and_flags |=
23023 				    htons(ire->ire_frag_flag);
23024 
23025 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23026 				/* Complete the IP header checksum. */
23027 				cksum += ipha->ipha_ident;
23028 				cksum += (v_hlen_tos_len >> 16)+
23029 				    (v_hlen_tos_len & 0xFFFF);
23030 				cksum += ipha->ipha_fragment_offset_and_flags;
23031 				hlen = (V_HLEN & 0xF) -
23032 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23033 				if (hlen) {
23034 checksumoptions:
23035 					/*
23036 					 * Account for the IP Options in the IP
23037 					 * header checksum.
23038 					 */
23039 					up = (uint16_t *)(rptr+
23040 					    IP_SIMPLE_HDR_LENGTH);
23041 					do {
23042 						cksum += up[0];
23043 						cksum += up[1];
23044 						up += 2;
23045 					} while (--hlen);
23046 				}
23047 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23048 				cksum = ~(cksum + (cksum >> 16));
23049 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23050 			}
23051 			if (ipsec_len != 0) {
23052 				ipsec_out_process(q, first_mp, ire, ill_index);
23053 				if (!next_mp) {
23054 					ire_refrele(ire);
23055 					if (conn_outgoing_ill != NULL)
23056 						ill_refrele(conn_outgoing_ill);
23057 					return;
23058 				}
23059 				goto next;
23060 			}
23061 
23062 			/*
23063 			 * multirt_send has already been handled
23064 			 * for broadcast, but not yet for multicast
23065 			 * or IP options.
23066 			 */
23067 			if (next_mp == NULL) {
23068 				if (ire->ire_flags & RTF_MULTIRT) {
23069 					multirt_send = B_TRUE;
23070 				}
23071 			}
23072 
23073 			/*
23074 			 * In most cases, the emission loop below is
23075 			 * entered only once. Only in the case where
23076 			 * the ire holds the RTF_MULTIRT flag, do we loop
23077 			 * to process all RTF_MULTIRT ires in the bucket,
23078 			 * and send the packet through all crossed
23079 			 * RTF_MULTIRT routes.
23080 			 */
23081 			do {
23082 				if (multirt_send) {
23083 					irb_t *irb;
23084 
23085 					irb = ire->ire_bucket;
23086 					ASSERT(irb != NULL);
23087 					/*
23088 					 * We are in a multiple send case,
23089 					 * need to get the next IRE and make
23090 					 * a duplicate of the packet.
23091 					 */
23092 					IRB_REFHOLD(irb);
23093 					for (ire1 = ire->ire_next;
23094 					    ire1 != NULL;
23095 					    ire1 = ire1->ire_next) {
23096 						if (!(ire1->ire_flags &
23097 						    RTF_MULTIRT)) {
23098 							continue;
23099 						}
23100 						if (ire1->ire_addr !=
23101 						    ire->ire_addr) {
23102 							continue;
23103 						}
23104 						if (ire1->ire_marks &
23105 						    (IRE_MARK_CONDEMNED|
23106 						    IRE_MARK_HIDDEN)) {
23107 							continue;
23108 						}
23109 
23110 						/* Got one */
23111 						IRE_REFHOLD(ire1);
23112 						break;
23113 					}
23114 					IRB_REFRELE(irb);
23115 
23116 					if (ire1 != NULL) {
23117 						next_mp = copyb(mp);
23118 						if ((next_mp == NULL) ||
23119 						    ((mp->b_cont != NULL) &&
23120 						    ((next_mp->b_cont =
23121 						    dupmsg(mp->b_cont))
23122 						    == NULL))) {
23123 							freemsg(next_mp);
23124 							next_mp = NULL;
23125 							ire_refrele(ire1);
23126 							ire1 = NULL;
23127 						}
23128 					}
23129 
23130 					/*
23131 					 * Last multiroute ire; don't loop
23132 					 * anymore. The emission is over
23133 					 * and next_mp is NULL.
23134 					 */
23135 					if (ire1 == NULL) {
23136 						multirt_send = B_FALSE;
23137 					}
23138 				}
23139 
23140 				out_ill = ire_to_ill(ire);
23141 				DTRACE_PROBE4(ip4__physical__out__start,
23142 				    ill_t *, NULL,
23143 				    ill_t *, out_ill,
23144 				    ipha_t *, ipha, mblk_t *, mp);
23145 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23146 				    ipst->ips_ipv4firewall_physical_out,
23147 				    NULL, out_ill, ipha, mp, mp, ipst);
23148 				DTRACE_PROBE1(ip4__physical__out__end,
23149 				    mblk_t *, mp);
23150 				if (mp == NULL)
23151 					goto release_ire_and_ill_2;
23152 
23153 				ASSERT(ipsec_len == 0);
23154 				mp->b_prev =
23155 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23156 				DTRACE_PROBE2(ip__xmit__2,
23157 				    mblk_t *, mp, ire_t *, ire);
23158 				pktxmit_state = ip_xmit_v4(mp, ire,
23159 				    NULL, B_TRUE);
23160 				if ((pktxmit_state == SEND_FAILED) ||
23161 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23162 release_ire_and_ill_2:
23163 					if (next_mp) {
23164 						freemsg(next_mp);
23165 						ire_refrele(ire1);
23166 					}
23167 					ire_refrele(ire);
23168 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23169 					    "ip_wput_ire_end: q %p (%S)",
23170 					    q, "discard MDATA");
23171 					if (conn_outgoing_ill != NULL)
23172 						ill_refrele(conn_outgoing_ill);
23173 					return;
23174 				}
23175 
23176 				if (CLASSD(dst)) {
23177 					BUMP_MIB(out_ill->ill_ip_mib,
23178 					    ipIfStatsHCOutMcastPkts);
23179 					UPDATE_MIB(out_ill->ill_ip_mib,
23180 					    ipIfStatsHCOutMcastOctets,
23181 					    LENGTH);
23182 				} else if (ire->ire_type == IRE_BROADCAST) {
23183 					BUMP_MIB(out_ill->ill_ip_mib,
23184 					    ipIfStatsHCOutBcastPkts);
23185 				}
23186 
23187 				if (multirt_send) {
23188 					/*
23189 					 * We are in a multiple send case,
23190 					 * need to re-enter the sending loop
23191 					 * using the next ire.
23192 					 */
23193 					ire_refrele(ire);
23194 					ire = ire1;
23195 					stq = ire->ire_stq;
23196 					mp = next_mp;
23197 					next_mp = NULL;
23198 					ipha = (ipha_t *)mp->b_rptr;
23199 					ill_index = Q_TO_INDEX(stq);
23200 				}
23201 			} while (multirt_send);
23202 
23203 			if (!next_mp) {
23204 				/*
23205 				 * Last copy going out (the ultra-common
23206 				 * case).  Note that we intentionally replicate
23207 				 * the putnext rather than calling it before
23208 				 * the next_mp check in hopes of a little
23209 				 * tail-call action out of the compiler.
23210 				 */
23211 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23212 				    "ip_wput_ire_end: q %p (%S)",
23213 				    q, "last copy out(1)");
23214 				ire_refrele(ire);
23215 				if (conn_outgoing_ill != NULL)
23216 					ill_refrele(conn_outgoing_ill);
23217 				return;
23218 			}
23219 			/* More copies going out below. */
23220 		} else {
23221 			int offset;
23222 fragmentit:
23223 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23224 			/*
23225 			 * If this would generate a icmp_frag_needed message,
23226 			 * we need to handle it before we do the IPsec
23227 			 * processing. Otherwise, we need to strip the IPsec
23228 			 * headers before we send up the message to the ULPs
23229 			 * which becomes messy and difficult.
23230 			 */
23231 			if (ipsec_len != 0) {
23232 				if ((max_frag < (unsigned int)(LENGTH +
23233 				    ipsec_len)) && (offset & IPH_DF)) {
23234 					out_ill = (ill_t *)stq->q_ptr;
23235 					BUMP_MIB(out_ill->ill_ip_mib,
23236 					    ipIfStatsOutFragFails);
23237 					BUMP_MIB(out_ill->ill_ip_mib,
23238 					    ipIfStatsOutFragReqds);
23239 					ipha->ipha_hdr_checksum = 0;
23240 					ipha->ipha_hdr_checksum =
23241 					    (uint16_t)ip_csum_hdr(ipha);
23242 					icmp_frag_needed(ire->ire_stq, first_mp,
23243 					    max_frag, zoneid, ipst);
23244 					if (!next_mp) {
23245 						ire_refrele(ire);
23246 						if (conn_outgoing_ill != NULL) {
23247 							ill_refrele(
23248 							    conn_outgoing_ill);
23249 						}
23250 						return;
23251 					}
23252 				} else {
23253 					/*
23254 					 * This won't cause a icmp_frag_needed
23255 					 * message. to be generated. Send it on
23256 					 * the wire. Note that this could still
23257 					 * cause fragmentation and all we
23258 					 * do is the generation of the message
23259 					 * to the ULP if needed before IPsec.
23260 					 */
23261 					if (!next_mp) {
23262 						ipsec_out_process(q, first_mp,
23263 						    ire, ill_index);
23264 						TRACE_2(TR_FAC_IP,
23265 						    TR_IP_WPUT_IRE_END,
23266 						    "ip_wput_ire_end: q %p "
23267 						    "(%S)", q,
23268 						    "last ipsec_out_process");
23269 						ire_refrele(ire);
23270 						if (conn_outgoing_ill != NULL) {
23271 							ill_refrele(
23272 							    conn_outgoing_ill);
23273 						}
23274 						return;
23275 					}
23276 					ipsec_out_process(q, first_mp,
23277 					    ire, ill_index);
23278 				}
23279 			} else {
23280 				/*
23281 				 * Initiate IPPF processing. For
23282 				 * fragmentable packets we finish
23283 				 * all QOS packet processing before
23284 				 * calling:
23285 				 * ip_wput_ire_fragmentit->ip_wput_frag
23286 				 */
23287 
23288 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23289 					ip_process(IPP_LOCAL_OUT, &mp,
23290 					    ill_index);
23291 					if (mp == NULL) {
23292 						out_ill = (ill_t *)stq->q_ptr;
23293 						BUMP_MIB(out_ill->ill_ip_mib,
23294 						    ipIfStatsOutDiscards);
23295 						if (next_mp != NULL) {
23296 							freemsg(next_mp);
23297 							ire_refrele(ire1);
23298 						}
23299 						ire_refrele(ire);
23300 						TRACE_2(TR_FAC_IP,
23301 						    TR_IP_WPUT_IRE_END,
23302 						    "ip_wput_ire: q %p (%S)",
23303 						    q, "discard MDATA");
23304 						if (conn_outgoing_ill != NULL) {
23305 							ill_refrele(
23306 							    conn_outgoing_ill);
23307 						}
23308 						return;
23309 					}
23310 				}
23311 				if (!next_mp) {
23312 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23313 					    "ip_wput_ire_end: q %p (%S)",
23314 					    q, "last fragmentation");
23315 					ip_wput_ire_fragmentit(mp, ire,
23316 					    zoneid, ipst);
23317 					ire_refrele(ire);
23318 					if (conn_outgoing_ill != NULL)
23319 						ill_refrele(conn_outgoing_ill);
23320 					return;
23321 				}
23322 				ip_wput_ire_fragmentit(mp, ire, zoneid, ipst);
23323 			}
23324 		}
23325 	} else {
23326 nullstq:
23327 		/* A NULL stq means the destination address is local. */
23328 		UPDATE_OB_PKT_COUNT(ire);
23329 		ire->ire_last_used_time = lbolt;
23330 		ASSERT(ire->ire_ipif != NULL);
23331 		if (!next_mp) {
23332 			/*
23333 			 * Is there an "in" and "out" for traffic local
23334 			 * to a host (loopback)?  The code in Solaris doesn't
23335 			 * explicitly draw a line in its code for in vs out,
23336 			 * so we've had to draw a line in the sand: ip_wput_ire
23337 			 * is considered to be the "output" side and
23338 			 * ip_wput_local to be the "input" side.
23339 			 */
23340 			out_ill = ire_to_ill(ire);
23341 
23342 			DTRACE_PROBE4(ip4__loopback__out__start,
23343 			    ill_t *, NULL, ill_t *, out_ill,
23344 			    ipha_t *, ipha, mblk_t *, first_mp);
23345 
23346 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23347 			    ipst->ips_ipv4firewall_loopback_out,
23348 			    NULL, out_ill, ipha, first_mp, mp, ipst);
23349 
23350 			DTRACE_PROBE1(ip4__loopback__out_end,
23351 			    mblk_t *, first_mp);
23352 
23353 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23354 			    "ip_wput_ire_end: q %p (%S)",
23355 			    q, "local address");
23356 
23357 			if (first_mp != NULL)
23358 				ip_wput_local(q, out_ill, ipha,
23359 				    first_mp, ire, 0, ire->ire_zoneid);
23360 			ire_refrele(ire);
23361 			if (conn_outgoing_ill != NULL)
23362 				ill_refrele(conn_outgoing_ill);
23363 			return;
23364 		}
23365 
23366 		out_ill = ire_to_ill(ire);
23367 
23368 		DTRACE_PROBE4(ip4__loopback__out__start,
23369 		    ill_t *, NULL, ill_t *, out_ill,
23370 		    ipha_t *, ipha, mblk_t *, first_mp);
23371 
23372 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23373 		    ipst->ips_ipv4firewall_loopback_out,
23374 		    NULL, out_ill, ipha, first_mp, mp, ipst);
23375 
23376 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23377 
23378 		if (first_mp != NULL)
23379 			ip_wput_local(q, out_ill, ipha,
23380 			    first_mp, ire, 0, ire->ire_zoneid);
23381 	}
23382 next:
23383 	/*
23384 	 * More copies going out to additional interfaces.
23385 	 * ire1 has already been held. We don't need the
23386 	 * "ire" anymore.
23387 	 */
23388 	ire_refrele(ire);
23389 	ire = ire1;
23390 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23391 	mp = next_mp;
23392 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23393 	ill = ire_to_ill(ire);
23394 	first_mp = mp;
23395 	if (ipsec_len != 0) {
23396 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23397 		mp = mp->b_cont;
23398 	}
23399 	dst = ire->ire_addr;
23400 	ipha = (ipha_t *)mp->b_rptr;
23401 	/*
23402 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23403 	 * Restore ipha_ident "no checksum" flag.
23404 	 */
23405 	src = orig_src;
23406 	ipha->ipha_ident = ip_hdr_included;
23407 	goto another;
23408 
23409 #undef	rptr
23410 #undef	Q_TO_INDEX
23411 }
23412 
23413 /*
23414  * Routine to allocate a message that is used to notify the ULP about MDT.
23415  * The caller may provide a pointer to the link-layer MDT capabilities,
23416  * or NULL if MDT is to be disabled on the stream.
23417  */
23418 mblk_t *
23419 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23420 {
23421 	mblk_t *mp;
23422 	ip_mdt_info_t *mdti;
23423 	ill_mdt_capab_t *idst;
23424 
23425 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23426 		DB_TYPE(mp) = M_CTL;
23427 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23428 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23429 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23430 		idst = &(mdti->mdt_capab);
23431 
23432 		/*
23433 		 * If the caller provides us with the capability, copy
23434 		 * it over into our notification message; otherwise
23435 		 * we zero out the capability portion.
23436 		 */
23437 		if (isrc != NULL)
23438 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23439 		else
23440 			bzero((caddr_t)idst, sizeof (*idst));
23441 	}
23442 	return (mp);
23443 }
23444 
23445 /*
23446  * Routine which determines whether MDT can be enabled on the destination
23447  * IRE and IPC combination, and if so, allocates and returns the MDT
23448  * notification mblk that may be used by ULP.  We also check if we need to
23449  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23450  * MDT usage in the past have been lifted.  This gets called during IP
23451  * and ULP binding.
23452  */
23453 mblk_t *
23454 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23455     ill_mdt_capab_t *mdt_cap)
23456 {
23457 	mblk_t *mp;
23458 	boolean_t rc = B_FALSE;
23459 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23460 
23461 	ASSERT(dst_ire != NULL);
23462 	ASSERT(connp != NULL);
23463 	ASSERT(mdt_cap != NULL);
23464 
23465 	/*
23466 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23467 	 * Multidata, which is handled in tcp_multisend().  This
23468 	 * is the reason why we do all these checks here, to ensure
23469 	 * that we don't enable Multidata for the cases which we
23470 	 * can't handle at the moment.
23471 	 */
23472 	do {
23473 		/* Only do TCP at the moment */
23474 		if (connp->conn_ulp != IPPROTO_TCP)
23475 			break;
23476 
23477 		/*
23478 		 * IPsec outbound policy present?  Note that we get here
23479 		 * after calling ipsec_conn_cache_policy() where the global
23480 		 * policy checking is performed.  conn_latch will be
23481 		 * non-NULL as long as there's a policy defined,
23482 		 * i.e. conn_out_enforce_policy may be NULL in such case
23483 		 * when the connection is non-secure, and hence we check
23484 		 * further if the latch refers to an outbound policy.
23485 		 */
23486 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23487 			break;
23488 
23489 		/* CGTP (multiroute) is enabled? */
23490 		if (dst_ire->ire_flags & RTF_MULTIRT)
23491 			break;
23492 
23493 		/* Outbound IPQoS enabled? */
23494 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23495 			/*
23496 			 * In this case, we disable MDT for this and all
23497 			 * future connections going over the interface.
23498 			 */
23499 			mdt_cap->ill_mdt_on = 0;
23500 			break;
23501 		}
23502 
23503 		/* socket option(s) present? */
23504 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23505 			break;
23506 
23507 		rc = B_TRUE;
23508 	/* CONSTCOND */
23509 	} while (0);
23510 
23511 	/* Remember the result */
23512 	connp->conn_mdt_ok = rc;
23513 
23514 	if (!rc)
23515 		return (NULL);
23516 	else if (!mdt_cap->ill_mdt_on) {
23517 		/*
23518 		 * If MDT has been previously turned off in the past, and we
23519 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23520 		 * then enable it for this interface.
23521 		 */
23522 		mdt_cap->ill_mdt_on = 1;
23523 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23524 		    "interface %s\n", ill_name));
23525 	}
23526 
23527 	/* Allocate the MDT info mblk */
23528 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23529 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23530 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23531 		return (NULL);
23532 	}
23533 	return (mp);
23534 }
23535 
23536 /*
23537  * Routine to allocate a message that is used to notify the ULP about LSO.
23538  * The caller may provide a pointer to the link-layer LSO capabilities,
23539  * or NULL if LSO is to be disabled on the stream.
23540  */
23541 mblk_t *
23542 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23543 {
23544 	mblk_t *mp;
23545 	ip_lso_info_t *lsoi;
23546 	ill_lso_capab_t *idst;
23547 
23548 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23549 		DB_TYPE(mp) = M_CTL;
23550 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23551 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23552 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23553 		idst = &(lsoi->lso_capab);
23554 
23555 		/*
23556 		 * If the caller provides us with the capability, copy
23557 		 * it over into our notification message; otherwise
23558 		 * we zero out the capability portion.
23559 		 */
23560 		if (isrc != NULL)
23561 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23562 		else
23563 			bzero((caddr_t)idst, sizeof (*idst));
23564 	}
23565 	return (mp);
23566 }
23567 
23568 /*
23569  * Routine which determines whether LSO can be enabled on the destination
23570  * IRE and IPC combination, and if so, allocates and returns the LSO
23571  * notification mblk that may be used by ULP.  We also check if we need to
23572  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23573  * LSO usage in the past have been lifted.  This gets called during IP
23574  * and ULP binding.
23575  */
23576 mblk_t *
23577 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23578     ill_lso_capab_t *lso_cap)
23579 {
23580 	mblk_t *mp;
23581 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23582 
23583 	ASSERT(dst_ire != NULL);
23584 	ASSERT(connp != NULL);
23585 	ASSERT(lso_cap != NULL);
23586 
23587 	connp->conn_lso_ok = B_TRUE;
23588 
23589 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23590 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23591 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23592 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23593 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23594 		connp->conn_lso_ok = B_FALSE;
23595 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23596 			/*
23597 			 * Disable LSO for this and all future connections going
23598 			 * over the interface.
23599 			 */
23600 			lso_cap->ill_lso_on = 0;
23601 		}
23602 	}
23603 
23604 	if (!connp->conn_lso_ok)
23605 		return (NULL);
23606 	else if (!lso_cap->ill_lso_on) {
23607 		/*
23608 		 * If LSO has been previously turned off in the past, and we
23609 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23610 		 * then enable it for this interface.
23611 		 */
23612 		lso_cap->ill_lso_on = 1;
23613 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23614 		    ill_name));
23615 	}
23616 
23617 	/* Allocate the LSO info mblk */
23618 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23619 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23620 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23621 
23622 	return (mp);
23623 }
23624 
23625 /*
23626  * Create destination address attribute, and fill it with the physical
23627  * destination address and SAP taken from the template DL_UNITDATA_REQ
23628  * message block.
23629  */
23630 boolean_t
23631 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23632 {
23633 	dl_unitdata_req_t *dlurp;
23634 	pattr_t *pa;
23635 	pattrinfo_t pa_info;
23636 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23637 	uint_t das_len, das_off;
23638 
23639 	ASSERT(dlmp != NULL);
23640 
23641 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23642 	das_len = dlurp->dl_dest_addr_length;
23643 	das_off = dlurp->dl_dest_addr_offset;
23644 
23645 	pa_info.type = PATTR_DSTADDRSAP;
23646 	pa_info.len = sizeof (**das) + das_len - 1;
23647 
23648 	/* create and associate the attribute */
23649 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23650 	if (pa != NULL) {
23651 		ASSERT(*das != NULL);
23652 		(*das)->addr_is_group = 0;
23653 		(*das)->addr_len = (uint8_t)das_len;
23654 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23655 	}
23656 
23657 	return (pa != NULL);
23658 }
23659 
23660 /*
23661  * Create hardware checksum attribute and fill it with the values passed.
23662  */
23663 boolean_t
23664 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23665     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23666 {
23667 	pattr_t *pa;
23668 	pattrinfo_t pa_info;
23669 
23670 	ASSERT(mmd != NULL);
23671 
23672 	pa_info.type = PATTR_HCKSUM;
23673 	pa_info.len = sizeof (pattr_hcksum_t);
23674 
23675 	/* create and associate the attribute */
23676 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23677 	if (pa != NULL) {
23678 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23679 
23680 		hck->hcksum_start_offset = start_offset;
23681 		hck->hcksum_stuff_offset = stuff_offset;
23682 		hck->hcksum_end_offset = end_offset;
23683 		hck->hcksum_flags = flags;
23684 	}
23685 	return (pa != NULL);
23686 }
23687 
23688 /*
23689  * Create zerocopy attribute and fill it with the specified flags
23690  */
23691 boolean_t
23692 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23693 {
23694 	pattr_t *pa;
23695 	pattrinfo_t pa_info;
23696 
23697 	ASSERT(mmd != NULL);
23698 	pa_info.type = PATTR_ZCOPY;
23699 	pa_info.len = sizeof (pattr_zcopy_t);
23700 
23701 	/* create and associate the attribute */
23702 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23703 	if (pa != NULL) {
23704 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23705 
23706 		zcopy->zcopy_flags = flags;
23707 	}
23708 	return (pa != NULL);
23709 }
23710 
23711 /*
23712  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23713  * block chain. We could rewrite to handle arbitrary message block chains but
23714  * that would make the code complicated and slow. Right now there three
23715  * restrictions:
23716  *
23717  *   1. The first message block must contain the complete IP header and
23718  *	at least 1 byte of payload data.
23719  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23720  *	so that we can use a single Multidata message.
23721  *   3. No frag must be distributed over two or more message blocks so
23722  *	that we don't need more than two packet descriptors per frag.
23723  *
23724  * The above restrictions allow us to support userland applications (which
23725  * will send down a single message block) and NFS over UDP (which will
23726  * send down a chain of at most three message blocks).
23727  *
23728  * We also don't use MDT for payloads with less than or equal to
23729  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23730  */
23731 boolean_t
23732 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23733 {
23734 	int	blocks;
23735 	ssize_t	total, missing, size;
23736 
23737 	ASSERT(mp != NULL);
23738 	ASSERT(hdr_len > 0);
23739 
23740 	size = MBLKL(mp) - hdr_len;
23741 	if (size <= 0)
23742 		return (B_FALSE);
23743 
23744 	/* The first mblk contains the header and some payload. */
23745 	blocks = 1;
23746 	total = size;
23747 	size %= len;
23748 	missing = (size == 0) ? 0 : (len - size);
23749 	mp = mp->b_cont;
23750 
23751 	while (mp != NULL) {
23752 		/*
23753 		 * Give up if we encounter a zero length message block.
23754 		 * In practice, this should rarely happen and therefore
23755 		 * not worth the trouble of freeing and re-linking the
23756 		 * mblk from the chain to handle such case.
23757 		 */
23758 		if ((size = MBLKL(mp)) == 0)
23759 			return (B_FALSE);
23760 
23761 		/* Too many payload buffers for a single Multidata message? */
23762 		if (++blocks > MULTIDATA_MAX_PBUFS)
23763 			return (B_FALSE);
23764 
23765 		total += size;
23766 		/* Is a frag distributed over two or more message blocks? */
23767 		if (missing > size)
23768 			return (B_FALSE);
23769 		size -= missing;
23770 
23771 		size %= len;
23772 		missing = (size == 0) ? 0 : (len - size);
23773 
23774 		mp = mp->b_cont;
23775 	}
23776 
23777 	return (total > ip_wput_frag_mdt_min);
23778 }
23779 
23780 /*
23781  * Outbound IPv4 fragmentation routine using MDT.
23782  */
23783 static void
23784 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23785     uint32_t frag_flag, int offset)
23786 {
23787 	ipha_t		*ipha_orig;
23788 	int		i1, ip_data_end;
23789 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23790 	mblk_t		*hdr_mp, *md_mp = NULL;
23791 	unsigned char	*hdr_ptr, *pld_ptr;
23792 	multidata_t	*mmd;
23793 	ip_pdescinfo_t	pdi;
23794 	ill_t		*ill;
23795 	ip_stack_t	*ipst = ire->ire_ipst;
23796 
23797 	ASSERT(DB_TYPE(mp) == M_DATA);
23798 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23799 
23800 	ill = ire_to_ill(ire);
23801 	ASSERT(ill != NULL);
23802 
23803 	ipha_orig = (ipha_t *)mp->b_rptr;
23804 	mp->b_rptr += sizeof (ipha_t);
23805 
23806 	/* Calculate how many packets we will send out */
23807 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23808 	pkts = (i1 + len - 1) / len;
23809 	ASSERT(pkts > 1);
23810 
23811 	/* Allocate a message block which will hold all the IP Headers. */
23812 	wroff = ipst->ips_ip_wroff_extra;
23813 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23814 
23815 	i1 = pkts * hdr_chunk_len;
23816 	/*
23817 	 * Create the header buffer, Multidata and destination address
23818 	 * and SAP attribute that should be associated with it.
23819 	 */
23820 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23821 	    ((hdr_mp->b_wptr += i1),
23822 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23823 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23824 		freemsg(mp);
23825 		if (md_mp == NULL) {
23826 			freemsg(hdr_mp);
23827 		} else {
23828 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
23829 			freemsg(md_mp);
23830 		}
23831 		IP_STAT(ipst, ip_frag_mdt_allocfail);
23832 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
23833 		return;
23834 	}
23835 	IP_STAT(ipst, ip_frag_mdt_allocd);
23836 
23837 	/*
23838 	 * Add a payload buffer to the Multidata; this operation must not
23839 	 * fail, or otherwise our logic in this routine is broken.  There
23840 	 * is no memory allocation done by the routine, so any returned
23841 	 * failure simply tells us that we've done something wrong.
23842 	 *
23843 	 * A failure tells us that either we're adding the same payload
23844 	 * buffer more than once, or we're trying to add more buffers than
23845 	 * allowed.  None of the above cases should happen, and we panic
23846 	 * because either there's horrible heap corruption, and/or
23847 	 * programming mistake.
23848 	 */
23849 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23850 		goto pbuf_panic;
23851 
23852 	hdr_ptr = hdr_mp->b_rptr;
23853 	pld_ptr = mp->b_rptr;
23854 
23855 	/* Establish the ending byte offset, based on the starting offset. */
23856 	offset <<= 3;
23857 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23858 	    IP_SIMPLE_HDR_LENGTH;
23859 
23860 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23861 
23862 	while (pld_ptr < mp->b_wptr) {
23863 		ipha_t		*ipha;
23864 		uint16_t	offset_and_flags;
23865 		uint16_t	ip_len;
23866 		int		error;
23867 
23868 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23869 		ipha = (ipha_t *)(hdr_ptr + wroff);
23870 		ASSERT(OK_32PTR(ipha));
23871 		*ipha = *ipha_orig;
23872 
23873 		if (ip_data_end - offset > len) {
23874 			offset_and_flags = IPH_MF;
23875 		} else {
23876 			/*
23877 			 * Last frag. Set len to the length of this last piece.
23878 			 */
23879 			len = ip_data_end - offset;
23880 			/* A frag of a frag might have IPH_MF non-zero */
23881 			offset_and_flags =
23882 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23883 			    IPH_MF;
23884 		}
23885 		offset_and_flags |= (uint16_t)(offset >> 3);
23886 		offset_and_flags |= (uint16_t)frag_flag;
23887 		/* Store the offset and flags in the IP header. */
23888 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23889 
23890 		/* Store the length in the IP header. */
23891 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23892 		ipha->ipha_length = htons(ip_len);
23893 
23894 		/*
23895 		 * Set the IP header checksum.  Note that mp is just
23896 		 * the header, so this is easy to pass to ip_csum.
23897 		 */
23898 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23899 
23900 		/*
23901 		 * Record offset and size of header and data of the next packet
23902 		 * in the multidata message.
23903 		 */
23904 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
23905 		PDESC_PLD_INIT(&pdi);
23906 		i1 = MIN(mp->b_wptr - pld_ptr, len);
23907 		ASSERT(i1 > 0);
23908 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
23909 		if (i1 == len) {
23910 			pld_ptr += len;
23911 		} else {
23912 			i1 = len - i1;
23913 			mp = mp->b_cont;
23914 			ASSERT(mp != NULL);
23915 			ASSERT(MBLKL(mp) >= i1);
23916 			/*
23917 			 * Attach the next payload message block to the
23918 			 * multidata message.
23919 			 */
23920 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23921 				goto pbuf_panic;
23922 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
23923 			pld_ptr = mp->b_rptr + i1;
23924 		}
23925 
23926 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
23927 		    KM_NOSLEEP)) == NULL) {
23928 			/*
23929 			 * Any failure other than ENOMEM indicates that we
23930 			 * have passed in invalid pdesc info or parameters
23931 			 * to mmd_addpdesc, which must not happen.
23932 			 *
23933 			 * EINVAL is a result of failure on boundary checks
23934 			 * against the pdesc info contents.  It should not
23935 			 * happen, and we panic because either there's
23936 			 * horrible heap corruption, and/or programming
23937 			 * mistake.
23938 			 */
23939 			if (error != ENOMEM) {
23940 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
23941 				    "pdesc logic error detected for "
23942 				    "mmd %p pinfo %p (%d)\n",
23943 				    (void *)mmd, (void *)&pdi, error);
23944 				/* NOTREACHED */
23945 			}
23946 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
23947 			/* Free unattached payload message blocks as well */
23948 			md_mp->b_cont = mp->b_cont;
23949 			goto free_mmd;
23950 		}
23951 
23952 		/* Advance fragment offset. */
23953 		offset += len;
23954 
23955 		/* Advance to location for next header in the buffer. */
23956 		hdr_ptr += hdr_chunk_len;
23957 
23958 		/* Did we reach the next payload message block? */
23959 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
23960 			mp = mp->b_cont;
23961 			/*
23962 			 * Attach the next message block with payload
23963 			 * data to the multidata message.
23964 			 */
23965 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23966 				goto pbuf_panic;
23967 			pld_ptr = mp->b_rptr;
23968 		}
23969 	}
23970 
23971 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
23972 	ASSERT(mp->b_wptr == pld_ptr);
23973 
23974 	/* Update IP statistics */
23975 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
23976 
23977 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
23978 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
23979 
23980 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
23981 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
23982 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
23983 
23984 	if (pkt_type == OB_PKT) {
23985 		ire->ire_ob_pkt_count += pkts;
23986 		if (ire->ire_ipif != NULL)
23987 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
23988 	} else {
23989 		/* The type is IB_PKT in the forwarding path. */
23990 		ire->ire_ib_pkt_count += pkts;
23991 		ASSERT(!IRE_IS_LOCAL(ire));
23992 		if (ire->ire_type & IRE_BROADCAST) {
23993 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
23994 		} else {
23995 			UPDATE_MIB(ill->ill_ip_mib,
23996 			    ipIfStatsHCOutForwDatagrams, pkts);
23997 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
23998 		}
23999 	}
24000 	ire->ire_last_used_time = lbolt;
24001 	/* Send it down */
24002 	putnext(ire->ire_stq, md_mp);
24003 	return;
24004 
24005 pbuf_panic:
24006 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
24007 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
24008 	    pbuf_idx);
24009 	/* NOTREACHED */
24010 }
24011 
24012 /*
24013  * Outbound IP fragmentation routine.
24014  *
24015  * NOTE : This routine does not ire_refrele the ire that is passed in
24016  * as the argument.
24017  */
24018 static void
24019 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
24020     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst)
24021 {
24022 	int		i1;
24023 	mblk_t		*ll_hdr_mp;
24024 	int 		ll_hdr_len;
24025 	int		hdr_len;
24026 	mblk_t		*hdr_mp;
24027 	ipha_t		*ipha;
24028 	int		ip_data_end;
24029 	int		len;
24030 	mblk_t		*mp = mp_orig, *mp1;
24031 	int		offset;
24032 	queue_t		*q;
24033 	uint32_t	v_hlen_tos_len;
24034 	mblk_t		*first_mp;
24035 	boolean_t	mctl_present;
24036 	ill_t		*ill;
24037 	ill_t		*out_ill;
24038 	mblk_t		*xmit_mp;
24039 	mblk_t		*carve_mp;
24040 	ire_t		*ire1 = NULL;
24041 	ire_t		*save_ire = NULL;
24042 	mblk_t  	*next_mp = NULL;
24043 	boolean_t	last_frag = B_FALSE;
24044 	boolean_t	multirt_send = B_FALSE;
24045 	ire_t		*first_ire = NULL;
24046 	irb_t		*irb = NULL;
24047 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24048 
24049 	ill = ire_to_ill(ire);
24050 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24051 
24052 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24053 
24054 	if (max_frag == 0) {
24055 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24056 		    " -  dropping packet\n"));
24057 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24058 		freemsg(mp);
24059 		return;
24060 	}
24061 
24062 	/*
24063 	 * IPsec does not allow hw accelerated packets to be fragmented
24064 	 * This check is made in ip_wput_ipsec_out prior to coming here
24065 	 * via ip_wput_ire_fragmentit.
24066 	 *
24067 	 * If at this point we have an ire whose ARP request has not
24068 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24069 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24070 	 * This packet and all fragmentable packets for this ire will
24071 	 * continue to get dropped while ire_nce->nce_state remains in
24072 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24073 	 * ND_REACHABLE, all subsquent large packets for this ire will
24074 	 * get fragemented and sent out by this function.
24075 	 */
24076 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24077 		/* If nce_state is ND_INITIAL, trigger ARP query */
24078 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
24079 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24080 		    " -  dropping packet\n"));
24081 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24082 		freemsg(mp);
24083 		return;
24084 	}
24085 
24086 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24087 	    "ip_wput_frag_start:");
24088 
24089 	if (mp->b_datap->db_type == M_CTL) {
24090 		first_mp = mp;
24091 		mp_orig = mp = mp->b_cont;
24092 		mctl_present = B_TRUE;
24093 	} else {
24094 		first_mp = mp;
24095 		mctl_present = B_FALSE;
24096 	}
24097 
24098 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24099 	ipha = (ipha_t *)mp->b_rptr;
24100 
24101 	/*
24102 	 * If the Don't Fragment flag is on, generate an ICMP destination
24103 	 * unreachable, fragmentation needed.
24104 	 */
24105 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24106 	if (offset & IPH_DF) {
24107 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24108 		if (is_system_labeled()) {
24109 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24110 			    ire->ire_max_frag - max_frag, AF_INET);
24111 		}
24112 		/*
24113 		 * Need to compute hdr checksum if called from ip_wput_ire.
24114 		 * Note that ip_rput_forward verifies the checksum before
24115 		 * calling this routine so in that case this is a noop.
24116 		 */
24117 		ipha->ipha_hdr_checksum = 0;
24118 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24119 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24120 		    ipst);
24121 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24122 		    "ip_wput_frag_end:(%S)",
24123 		    "don't fragment");
24124 		return;
24125 	}
24126 	/*
24127 	 * Labeled systems adjust max_frag if they add a label
24128 	 * to send the correct path mtu.  We need the real mtu since we
24129 	 * are fragmenting the packet after label adjustment.
24130 	 */
24131 	if (is_system_labeled())
24132 		max_frag = ire->ire_max_frag;
24133 	if (mctl_present)
24134 		freeb(first_mp);
24135 	/*
24136 	 * Establish the starting offset.  May not be zero if we are fragging
24137 	 * a fragment that is being forwarded.
24138 	 */
24139 	offset = offset & IPH_OFFSET;
24140 
24141 	/* TODO why is this test needed? */
24142 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24143 	if (((max_frag - LENGTH) & ~7) < 8) {
24144 		/* TODO: notify ulp somehow */
24145 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24146 		freemsg(mp);
24147 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24148 		    "ip_wput_frag_end:(%S)",
24149 		    "len < 8");
24150 		return;
24151 	}
24152 
24153 	hdr_len = (V_HLEN & 0xF) << 2;
24154 
24155 	ipha->ipha_hdr_checksum = 0;
24156 
24157 	/*
24158 	 * Establish the number of bytes maximum per frag, after putting
24159 	 * in the header.
24160 	 */
24161 	len = (max_frag - hdr_len) & ~7;
24162 
24163 	/* Check if we can use MDT to send out the frags. */
24164 	ASSERT(!IRE_IS_LOCAL(ire));
24165 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24166 	    ipst->ips_ip_multidata_outbound &&
24167 	    !(ire->ire_flags & RTF_MULTIRT) &&
24168 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24169 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24170 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24171 		ASSERT(ill->ill_mdt_capab != NULL);
24172 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24173 			/*
24174 			 * If MDT has been previously turned off in the past,
24175 			 * and we currently can do MDT (due to IPQoS policy
24176 			 * removal, etc.) then enable it for this interface.
24177 			 */
24178 			ill->ill_mdt_capab->ill_mdt_on = 1;
24179 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24180 			    ill->ill_name));
24181 		}
24182 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24183 		    offset);
24184 		return;
24185 	}
24186 
24187 	/* Get a copy of the header for the trailing frags */
24188 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst);
24189 	if (!hdr_mp) {
24190 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24191 		freemsg(mp);
24192 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24193 		    "ip_wput_frag_end:(%S)",
24194 		    "couldn't copy hdr");
24195 		return;
24196 	}
24197 	if (DB_CRED(mp) != NULL)
24198 		mblk_setcred(hdr_mp, DB_CRED(mp));
24199 
24200 	/* Store the starting offset, with the MoreFrags flag. */
24201 	i1 = offset | IPH_MF | frag_flag;
24202 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24203 
24204 	/* Establish the ending byte offset, based on the starting offset. */
24205 	offset <<= 3;
24206 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24207 
24208 	/* Store the length of the first fragment in the IP header. */
24209 	i1 = len + hdr_len;
24210 	ASSERT(i1 <= IP_MAXPACKET);
24211 	ipha->ipha_length = htons((uint16_t)i1);
24212 
24213 	/*
24214 	 * Compute the IP header checksum for the first frag.  We have to
24215 	 * watch out that we stop at the end of the header.
24216 	 */
24217 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24218 
24219 	/*
24220 	 * Now carve off the first frag.  Note that this will include the
24221 	 * original IP header.
24222 	 */
24223 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24224 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24225 		freeb(hdr_mp);
24226 		freemsg(mp_orig);
24227 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24228 		    "ip_wput_frag_end:(%S)",
24229 		    "couldn't carve first");
24230 		return;
24231 	}
24232 
24233 	/*
24234 	 * Multirouting case. Each fragment is replicated
24235 	 * via all non-condemned RTF_MULTIRT routes
24236 	 * currently resolved.
24237 	 * We ensure that first_ire is the first RTF_MULTIRT
24238 	 * ire in the bucket.
24239 	 */
24240 	if (ire->ire_flags & RTF_MULTIRT) {
24241 		irb = ire->ire_bucket;
24242 		ASSERT(irb != NULL);
24243 
24244 		multirt_send = B_TRUE;
24245 
24246 		/* Make sure we do not omit any multiroute ire. */
24247 		IRB_REFHOLD(irb);
24248 		for (first_ire = irb->irb_ire;
24249 		    first_ire != NULL;
24250 		    first_ire = first_ire->ire_next) {
24251 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24252 			    (first_ire->ire_addr == ire->ire_addr) &&
24253 			    !(first_ire->ire_marks &
24254 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
24255 				break;
24256 			}
24257 		}
24258 
24259 		if (first_ire != NULL) {
24260 			if (first_ire != ire) {
24261 				IRE_REFHOLD(first_ire);
24262 				/*
24263 				 * Do not release the ire passed in
24264 				 * as the argument.
24265 				 */
24266 				ire = first_ire;
24267 			} else {
24268 				first_ire = NULL;
24269 			}
24270 		}
24271 		IRB_REFRELE(irb);
24272 
24273 		/*
24274 		 * Save the first ire; we will need to restore it
24275 		 * for the trailing frags.
24276 		 * We REFHOLD save_ire, as each iterated ire will be
24277 		 * REFRELEd.
24278 		 */
24279 		save_ire = ire;
24280 		IRE_REFHOLD(save_ire);
24281 	}
24282 
24283 	/*
24284 	 * First fragment emission loop.
24285 	 * In most cases, the emission loop below is entered only
24286 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24287 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24288 	 * bucket, and send the fragment through all crossed
24289 	 * RTF_MULTIRT routes.
24290 	 */
24291 	do {
24292 		if (ire->ire_flags & RTF_MULTIRT) {
24293 			/*
24294 			 * We are in a multiple send case, need to get
24295 			 * the next ire and make a copy of the packet.
24296 			 * ire1 holds here the next ire to process in the
24297 			 * bucket. If multirouting is expected,
24298 			 * any non-RTF_MULTIRT ire that has the
24299 			 * right destination address is ignored.
24300 			 *
24301 			 * We have to take into account the MTU of
24302 			 * each walked ire. max_frag is set by the
24303 			 * the caller and generally refers to
24304 			 * the primary ire entry. Here we ensure that
24305 			 * no route with a lower MTU will be used, as
24306 			 * fragments are carved once for all ires,
24307 			 * then replicated.
24308 			 */
24309 			ASSERT(irb != NULL);
24310 			IRB_REFHOLD(irb);
24311 			for (ire1 = ire->ire_next;
24312 			    ire1 != NULL;
24313 			    ire1 = ire1->ire_next) {
24314 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24315 					continue;
24316 				if (ire1->ire_addr != ire->ire_addr)
24317 					continue;
24318 				if (ire1->ire_marks &
24319 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24320 					continue;
24321 				/*
24322 				 * Ensure we do not exceed the MTU
24323 				 * of the next route.
24324 				 */
24325 				if (ire1->ire_max_frag < max_frag) {
24326 					ip_multirt_bad_mtu(ire1, max_frag);
24327 					continue;
24328 				}
24329 
24330 				/* Got one. */
24331 				IRE_REFHOLD(ire1);
24332 				break;
24333 			}
24334 			IRB_REFRELE(irb);
24335 
24336 			if (ire1 != NULL) {
24337 				next_mp = copyb(mp);
24338 				if ((next_mp == NULL) ||
24339 				    ((mp->b_cont != NULL) &&
24340 				    ((next_mp->b_cont =
24341 				    dupmsg(mp->b_cont)) == NULL))) {
24342 					freemsg(next_mp);
24343 					next_mp = NULL;
24344 					ire_refrele(ire1);
24345 					ire1 = NULL;
24346 				}
24347 			}
24348 
24349 			/* Last multiroute ire; don't loop anymore. */
24350 			if (ire1 == NULL) {
24351 				multirt_send = B_FALSE;
24352 			}
24353 		}
24354 
24355 		ll_hdr_len = 0;
24356 		LOCK_IRE_FP_MP(ire);
24357 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24358 		if (ll_hdr_mp != NULL) {
24359 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24360 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24361 		} else {
24362 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24363 		}
24364 
24365 		/* If there is a transmit header, get a copy for this frag. */
24366 		/*
24367 		 * TODO: should check db_ref before calling ip_carve_mp since
24368 		 * it might give us a dup.
24369 		 */
24370 		if (!ll_hdr_mp) {
24371 			/* No xmit header. */
24372 			xmit_mp = mp;
24373 
24374 		/* We have a link-layer header that can fit in our mblk. */
24375 		} else if (mp->b_datap->db_ref == 1 &&
24376 		    ll_hdr_len != 0 &&
24377 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24378 			/* M_DATA fastpath */
24379 			mp->b_rptr -= ll_hdr_len;
24380 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24381 			xmit_mp = mp;
24382 
24383 		/* Corner case if copyb has failed */
24384 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24385 			UNLOCK_IRE_FP_MP(ire);
24386 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24387 			freeb(hdr_mp);
24388 			freemsg(mp);
24389 			freemsg(mp_orig);
24390 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24391 			    "ip_wput_frag_end:(%S)",
24392 			    "discard");
24393 
24394 			if (multirt_send) {
24395 				ASSERT(ire1);
24396 				ASSERT(next_mp);
24397 
24398 				freemsg(next_mp);
24399 				ire_refrele(ire1);
24400 			}
24401 			if (save_ire != NULL)
24402 				IRE_REFRELE(save_ire);
24403 
24404 			if (first_ire != NULL)
24405 				ire_refrele(first_ire);
24406 			return;
24407 
24408 		/*
24409 		 * Case of res_mp OR the fastpath mp can't fit
24410 		 * in the mblk
24411 		 */
24412 		} else {
24413 			xmit_mp->b_cont = mp;
24414 			if (DB_CRED(mp) != NULL)
24415 				mblk_setcred(xmit_mp, DB_CRED(mp));
24416 			/*
24417 			 * Get priority marking, if any.
24418 			 * We propagate the CoS marking from the
24419 			 * original packet that went to QoS processing
24420 			 * in ip_wput_ire to the newly carved mp.
24421 			 */
24422 			if (DB_TYPE(xmit_mp) == M_DATA)
24423 				xmit_mp->b_band = mp->b_band;
24424 		}
24425 		UNLOCK_IRE_FP_MP(ire);
24426 
24427 		q = ire->ire_stq;
24428 		out_ill = (ill_t *)q->q_ptr;
24429 
24430 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24431 
24432 		DTRACE_PROBE4(ip4__physical__out__start,
24433 		    ill_t *, NULL, ill_t *, out_ill,
24434 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24435 
24436 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24437 		    ipst->ips_ipv4firewall_physical_out,
24438 		    NULL, out_ill, ipha, xmit_mp, mp, ipst);
24439 
24440 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24441 
24442 		if (xmit_mp != NULL) {
24443 			putnext(q, xmit_mp);
24444 
24445 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24446 			UPDATE_MIB(out_ill->ill_ip_mib,
24447 			    ipIfStatsHCOutOctets, i1);
24448 
24449 			if (pkt_type != OB_PKT) {
24450 				/*
24451 				 * Update the packet count and MIB stats
24452 				 * of trailing RTF_MULTIRT ires.
24453 				 */
24454 				UPDATE_OB_PKT_COUNT(ire);
24455 				BUMP_MIB(out_ill->ill_ip_mib,
24456 				    ipIfStatsOutFragReqds);
24457 			}
24458 		}
24459 
24460 		if (multirt_send) {
24461 			/*
24462 			 * We are in a multiple send case; look for
24463 			 * the next ire and re-enter the loop.
24464 			 */
24465 			ASSERT(ire1);
24466 			ASSERT(next_mp);
24467 			/* REFRELE the current ire before looping */
24468 			ire_refrele(ire);
24469 			ire = ire1;
24470 			ire1 = NULL;
24471 			mp = next_mp;
24472 			next_mp = NULL;
24473 		}
24474 	} while (multirt_send);
24475 
24476 	ASSERT(ire1 == NULL);
24477 
24478 	/* Restore the original ire; we need it for the trailing frags */
24479 	if (save_ire != NULL) {
24480 		/* REFRELE the last iterated ire */
24481 		ire_refrele(ire);
24482 		/* save_ire has been REFHOLDed */
24483 		ire = save_ire;
24484 		save_ire = NULL;
24485 		q = ire->ire_stq;
24486 	}
24487 
24488 	if (pkt_type == OB_PKT) {
24489 		UPDATE_OB_PKT_COUNT(ire);
24490 	} else {
24491 		out_ill = (ill_t *)q->q_ptr;
24492 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24493 		UPDATE_IB_PKT_COUNT(ire);
24494 	}
24495 
24496 	/* Advance the offset to the second frag starting point. */
24497 	offset += len;
24498 	/*
24499 	 * Update hdr_len from the copied header - there might be less options
24500 	 * in the later fragments.
24501 	 */
24502 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24503 	/* Loop until done. */
24504 	for (;;) {
24505 		uint16_t	offset_and_flags;
24506 		uint16_t	ip_len;
24507 
24508 		if (ip_data_end - offset > len) {
24509 			/*
24510 			 * Carve off the appropriate amount from the original
24511 			 * datagram.
24512 			 */
24513 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24514 				mp = NULL;
24515 				break;
24516 			}
24517 			/*
24518 			 * More frags after this one.  Get another copy
24519 			 * of the header.
24520 			 */
24521 			if (carve_mp->b_datap->db_ref == 1 &&
24522 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24523 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24524 				/* Inline IP header */
24525 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24526 				    hdr_mp->b_rptr;
24527 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24528 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24529 				mp = carve_mp;
24530 			} else {
24531 				if (!(mp = copyb(hdr_mp))) {
24532 					freemsg(carve_mp);
24533 					break;
24534 				}
24535 				/* Get priority marking, if any. */
24536 				mp->b_band = carve_mp->b_band;
24537 				mp->b_cont = carve_mp;
24538 			}
24539 			ipha = (ipha_t *)mp->b_rptr;
24540 			offset_and_flags = IPH_MF;
24541 		} else {
24542 			/*
24543 			 * Last frag.  Consume the header. Set len to
24544 			 * the length of this last piece.
24545 			 */
24546 			len = ip_data_end - offset;
24547 
24548 			/*
24549 			 * Carve off the appropriate amount from the original
24550 			 * datagram.
24551 			 */
24552 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24553 				mp = NULL;
24554 				break;
24555 			}
24556 			if (carve_mp->b_datap->db_ref == 1 &&
24557 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24558 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24559 				/* Inline IP header */
24560 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24561 				    hdr_mp->b_rptr;
24562 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24563 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24564 				mp = carve_mp;
24565 				freeb(hdr_mp);
24566 				hdr_mp = mp;
24567 			} else {
24568 				mp = hdr_mp;
24569 				/* Get priority marking, if any. */
24570 				mp->b_band = carve_mp->b_band;
24571 				mp->b_cont = carve_mp;
24572 			}
24573 			ipha = (ipha_t *)mp->b_rptr;
24574 			/* A frag of a frag might have IPH_MF non-zero */
24575 			offset_and_flags =
24576 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24577 			    IPH_MF;
24578 		}
24579 		offset_and_flags |= (uint16_t)(offset >> 3);
24580 		offset_and_flags |= (uint16_t)frag_flag;
24581 		/* Store the offset and flags in the IP header. */
24582 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24583 
24584 		/* Store the length in the IP header. */
24585 		ip_len = (uint16_t)(len + hdr_len);
24586 		ipha->ipha_length = htons(ip_len);
24587 
24588 		/*
24589 		 * Set the IP header checksum.	Note that mp is just
24590 		 * the header, so this is easy to pass to ip_csum.
24591 		 */
24592 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24593 
24594 		/* Attach a transmit header, if any, and ship it. */
24595 		if (pkt_type == OB_PKT) {
24596 			UPDATE_OB_PKT_COUNT(ire);
24597 		} else {
24598 			out_ill = (ill_t *)q->q_ptr;
24599 			BUMP_MIB(out_ill->ill_ip_mib,
24600 			    ipIfStatsHCOutForwDatagrams);
24601 			UPDATE_IB_PKT_COUNT(ire);
24602 		}
24603 
24604 		if (ire->ire_flags & RTF_MULTIRT) {
24605 			irb = ire->ire_bucket;
24606 			ASSERT(irb != NULL);
24607 
24608 			multirt_send = B_TRUE;
24609 
24610 			/*
24611 			 * Save the original ire; we will need to restore it
24612 			 * for the tailing frags.
24613 			 */
24614 			save_ire = ire;
24615 			IRE_REFHOLD(save_ire);
24616 		}
24617 		/*
24618 		 * Emission loop for this fragment, similar
24619 		 * to what is done for the first fragment.
24620 		 */
24621 		do {
24622 			if (multirt_send) {
24623 				/*
24624 				 * We are in a multiple send case, need to get
24625 				 * the next ire and make a copy of the packet.
24626 				 */
24627 				ASSERT(irb != NULL);
24628 				IRB_REFHOLD(irb);
24629 				for (ire1 = ire->ire_next;
24630 				    ire1 != NULL;
24631 				    ire1 = ire1->ire_next) {
24632 					if (!(ire1->ire_flags & RTF_MULTIRT))
24633 						continue;
24634 					if (ire1->ire_addr != ire->ire_addr)
24635 						continue;
24636 					if (ire1->ire_marks &
24637 					    (IRE_MARK_CONDEMNED|
24638 					    IRE_MARK_HIDDEN)) {
24639 						continue;
24640 					}
24641 					/*
24642 					 * Ensure we do not exceed the MTU
24643 					 * of the next route.
24644 					 */
24645 					if (ire1->ire_max_frag < max_frag) {
24646 						ip_multirt_bad_mtu(ire1,
24647 						    max_frag);
24648 						continue;
24649 					}
24650 
24651 					/* Got one. */
24652 					IRE_REFHOLD(ire1);
24653 					break;
24654 				}
24655 				IRB_REFRELE(irb);
24656 
24657 				if (ire1 != NULL) {
24658 					next_mp = copyb(mp);
24659 					if ((next_mp == NULL) ||
24660 					    ((mp->b_cont != NULL) &&
24661 					    ((next_mp->b_cont =
24662 					    dupmsg(mp->b_cont)) == NULL))) {
24663 						freemsg(next_mp);
24664 						next_mp = NULL;
24665 						ire_refrele(ire1);
24666 						ire1 = NULL;
24667 					}
24668 				}
24669 
24670 				/* Last multiroute ire; don't loop anymore. */
24671 				if (ire1 == NULL) {
24672 					multirt_send = B_FALSE;
24673 				}
24674 			}
24675 
24676 			/* Update transmit header */
24677 			ll_hdr_len = 0;
24678 			LOCK_IRE_FP_MP(ire);
24679 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24680 			if (ll_hdr_mp != NULL) {
24681 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24682 				ll_hdr_len = MBLKL(ll_hdr_mp);
24683 			} else {
24684 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24685 			}
24686 
24687 			if (!ll_hdr_mp) {
24688 				xmit_mp = mp;
24689 
24690 			/*
24691 			 * We have link-layer header that can fit in
24692 			 * our mblk.
24693 			 */
24694 			} else if (mp->b_datap->db_ref == 1 &&
24695 			    ll_hdr_len != 0 &&
24696 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24697 				/* M_DATA fastpath */
24698 				mp->b_rptr -= ll_hdr_len;
24699 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24700 				    ll_hdr_len);
24701 				xmit_mp = mp;
24702 
24703 			/*
24704 			 * Case of res_mp OR the fastpath mp can't fit
24705 			 * in the mblk
24706 			 */
24707 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24708 				xmit_mp->b_cont = mp;
24709 				if (DB_CRED(mp) != NULL)
24710 					mblk_setcred(xmit_mp, DB_CRED(mp));
24711 				/* Get priority marking, if any. */
24712 				if (DB_TYPE(xmit_mp) == M_DATA)
24713 					xmit_mp->b_band = mp->b_band;
24714 
24715 			/* Corner case if copyb failed */
24716 			} else {
24717 				/*
24718 				 * Exit both the replication and
24719 				 * fragmentation loops.
24720 				 */
24721 				UNLOCK_IRE_FP_MP(ire);
24722 				goto drop_pkt;
24723 			}
24724 			UNLOCK_IRE_FP_MP(ire);
24725 
24726 			mp1 = mp;
24727 			out_ill = (ill_t *)q->q_ptr;
24728 
24729 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24730 
24731 			DTRACE_PROBE4(ip4__physical__out__start,
24732 			    ill_t *, NULL, ill_t *, out_ill,
24733 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24734 
24735 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24736 			    ipst->ips_ipv4firewall_physical_out,
24737 			    NULL, out_ill, ipha, xmit_mp, mp, ipst);
24738 
24739 			DTRACE_PROBE1(ip4__physical__out__end,
24740 			    mblk_t *, xmit_mp);
24741 
24742 			if (mp != mp1 && hdr_mp == mp1)
24743 				hdr_mp = mp;
24744 			if (mp != mp1 && mp_orig == mp1)
24745 				mp_orig = mp;
24746 
24747 			if (xmit_mp != NULL) {
24748 				putnext(q, xmit_mp);
24749 
24750 				BUMP_MIB(out_ill->ill_ip_mib,
24751 				    ipIfStatsHCOutTransmits);
24752 				UPDATE_MIB(out_ill->ill_ip_mib,
24753 				    ipIfStatsHCOutOctets, ip_len);
24754 
24755 				if (pkt_type != OB_PKT) {
24756 					/*
24757 					 * Update the packet count of trailing
24758 					 * RTF_MULTIRT ires.
24759 					 */
24760 					UPDATE_OB_PKT_COUNT(ire);
24761 				}
24762 			}
24763 
24764 			/* All done if we just consumed the hdr_mp. */
24765 			if (mp == hdr_mp) {
24766 				last_frag = B_TRUE;
24767 				BUMP_MIB(out_ill->ill_ip_mib,
24768 				    ipIfStatsOutFragOKs);
24769 			}
24770 
24771 			if (multirt_send) {
24772 				/*
24773 				 * We are in a multiple send case; look for
24774 				 * the next ire and re-enter the loop.
24775 				 */
24776 				ASSERT(ire1);
24777 				ASSERT(next_mp);
24778 				/* REFRELE the current ire before looping */
24779 				ire_refrele(ire);
24780 				ire = ire1;
24781 				ire1 = NULL;
24782 				q = ire->ire_stq;
24783 				mp = next_mp;
24784 				next_mp = NULL;
24785 			}
24786 		} while (multirt_send);
24787 		/*
24788 		 * Restore the original ire; we need it for the
24789 		 * trailing frags
24790 		 */
24791 		if (save_ire != NULL) {
24792 			ASSERT(ire1 == NULL);
24793 			/* REFRELE the last iterated ire */
24794 			ire_refrele(ire);
24795 			/* save_ire has been REFHOLDed */
24796 			ire = save_ire;
24797 			q = ire->ire_stq;
24798 			save_ire = NULL;
24799 		}
24800 
24801 		if (last_frag) {
24802 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24803 			    "ip_wput_frag_end:(%S)",
24804 			    "consumed hdr_mp");
24805 
24806 			if (first_ire != NULL)
24807 				ire_refrele(first_ire);
24808 			return;
24809 		}
24810 		/* Otherwise, advance and loop. */
24811 		offset += len;
24812 	}
24813 
24814 drop_pkt:
24815 	/* Clean up following allocation failure. */
24816 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24817 	freemsg(mp);
24818 	if (mp != hdr_mp)
24819 		freeb(hdr_mp);
24820 	if (mp != mp_orig)
24821 		freemsg(mp_orig);
24822 
24823 	if (save_ire != NULL)
24824 		IRE_REFRELE(save_ire);
24825 	if (first_ire != NULL)
24826 		ire_refrele(first_ire);
24827 
24828 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24829 	    "ip_wput_frag_end:(%S)",
24830 	    "end--alloc failure");
24831 }
24832 
24833 /*
24834  * Copy the header plus those options which have the copy bit set
24835  */
24836 static mblk_t *
24837 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst)
24838 {
24839 	mblk_t	*mp;
24840 	uchar_t	*up;
24841 
24842 	/*
24843 	 * Quick check if we need to look for options without the copy bit
24844 	 * set
24845 	 */
24846 	mp = allocb(ipst->ips_ip_wroff_extra + hdr_len, BPRI_HI);
24847 	if (!mp)
24848 		return (mp);
24849 	mp->b_rptr += ipst->ips_ip_wroff_extra;
24850 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24851 		bcopy(rptr, mp->b_rptr, hdr_len);
24852 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
24853 		return (mp);
24854 	}
24855 	up  = mp->b_rptr;
24856 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24857 	up += IP_SIMPLE_HDR_LENGTH;
24858 	rptr += IP_SIMPLE_HDR_LENGTH;
24859 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24860 	while (hdr_len > 0) {
24861 		uint32_t optval;
24862 		uint32_t optlen;
24863 
24864 		optval = *rptr;
24865 		if (optval == IPOPT_EOL)
24866 			break;
24867 		if (optval == IPOPT_NOP)
24868 			optlen = 1;
24869 		else
24870 			optlen = rptr[1];
24871 		if (optval & IPOPT_COPY) {
24872 			bcopy(rptr, up, optlen);
24873 			up += optlen;
24874 		}
24875 		rptr += optlen;
24876 		hdr_len -= optlen;
24877 	}
24878 	/*
24879 	 * Make sure that we drop an even number of words by filling
24880 	 * with EOL to the next word boundary.
24881 	 */
24882 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
24883 	    hdr_len & 0x3; hdr_len++)
24884 		*up++ = IPOPT_EOL;
24885 	mp->b_wptr = up;
24886 	/* Update header length */
24887 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
24888 	return (mp);
24889 }
24890 
24891 /*
24892  * Delivery to local recipients including fanout to multiple recipients.
24893  * Does not do checksumming of UDP/TCP.
24894  * Note: q should be the read side queue for either the ill or conn.
24895  * Note: rq should be the read side q for the lower (ill) stream.
24896  * We don't send packets to IPPF processing, thus the last argument
24897  * to all the fanout calls are B_FALSE.
24898  */
24899 void
24900 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
24901     int fanout_flags, zoneid_t zoneid)
24902 {
24903 	uint32_t	protocol;
24904 	mblk_t		*first_mp;
24905 	boolean_t	mctl_present;
24906 	int		ire_type;
24907 #define	rptr	((uchar_t *)ipha)
24908 	ip_stack_t	*ipst = ill->ill_ipst;
24909 
24910 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
24911 	    "ip_wput_local_start: q %p", q);
24912 
24913 	if (ire != NULL) {
24914 		ire_type = ire->ire_type;
24915 	} else {
24916 		/*
24917 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
24918 		 * packet is not multicast, we can't tell the ire type.
24919 		 */
24920 		ASSERT(CLASSD(ipha->ipha_dst));
24921 		ire_type = IRE_BROADCAST;
24922 	}
24923 
24924 	first_mp = mp;
24925 	if (first_mp->b_datap->db_type == M_CTL) {
24926 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
24927 		if (!io->ipsec_out_secure) {
24928 			/*
24929 			 * This ipsec_out_t was allocated in ip_wput
24930 			 * for multicast packets to store the ill_index.
24931 			 * As this is being delivered locally, we don't
24932 			 * need this anymore.
24933 			 */
24934 			mp = first_mp->b_cont;
24935 			freeb(first_mp);
24936 			first_mp = mp;
24937 			mctl_present = B_FALSE;
24938 		} else {
24939 			/*
24940 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
24941 			 * security properties for the looped-back packet.
24942 			 */
24943 			mctl_present = B_TRUE;
24944 			mp = first_mp->b_cont;
24945 			ASSERT(mp != NULL);
24946 			ipsec_out_to_in(first_mp);
24947 		}
24948 	} else {
24949 		mctl_present = B_FALSE;
24950 	}
24951 
24952 	DTRACE_PROBE4(ip4__loopback__in__start,
24953 	    ill_t *, ill, ill_t *, NULL,
24954 	    ipha_t *, ipha, mblk_t *, first_mp);
24955 
24956 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
24957 	    ipst->ips_ipv4firewall_loopback_in,
24958 	    ill, NULL, ipha, first_mp, mp, ipst);
24959 
24960 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
24961 
24962 	if (first_mp == NULL)
24963 		return;
24964 
24965 	ipst->ips_loopback_packets++;
24966 
24967 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
24968 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
24969 	if (!IS_SIMPLE_IPH(ipha)) {
24970 		ip_wput_local_options(ipha, ipst);
24971 	}
24972 
24973 	protocol = ipha->ipha_protocol;
24974 	switch (protocol) {
24975 	case IPPROTO_ICMP: {
24976 		ire_t		*ire_zone;
24977 		ilm_t		*ilm;
24978 		mblk_t		*mp1;
24979 		zoneid_t	last_zoneid;
24980 
24981 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
24982 			ASSERT(ire_type == IRE_BROADCAST);
24983 			/*
24984 			 * In the multicast case, applications may have joined
24985 			 * the group from different zones, so we need to deliver
24986 			 * the packet to each of them. Loop through the
24987 			 * multicast memberships structures (ilm) on the receive
24988 			 * ill and send a copy of the packet up each matching
24989 			 * one. However, we don't do this for multicasts sent on
24990 			 * the loopback interface (PHYI_LOOPBACK flag set) as
24991 			 * they must stay in the sender's zone.
24992 			 *
24993 			 * ilm_add_v6() ensures that ilms in the same zone are
24994 			 * contiguous in the ill_ilm list. We use this property
24995 			 * to avoid sending duplicates needed when two
24996 			 * applications in the same zone join the same group on
24997 			 * different logical interfaces: we ignore the ilm if
24998 			 * it's zoneid is the same as the last matching one.
24999 			 * In addition, the sending of the packet for
25000 			 * ire_zoneid is delayed until all of the other ilms
25001 			 * have been exhausted.
25002 			 */
25003 			last_zoneid = -1;
25004 			ILM_WALKER_HOLD(ill);
25005 			for (ilm = ill->ill_ilm; ilm != NULL;
25006 			    ilm = ilm->ilm_next) {
25007 				if ((ilm->ilm_flags & ILM_DELETED) ||
25008 				    ipha->ipha_dst != ilm->ilm_addr ||
25009 				    ilm->ilm_zoneid == last_zoneid ||
25010 				    ilm->ilm_zoneid == zoneid ||
25011 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25012 					continue;
25013 				mp1 = ip_copymsg(first_mp);
25014 				if (mp1 == NULL)
25015 					continue;
25016 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25017 				    mctl_present, B_FALSE, ill,
25018 				    ilm->ilm_zoneid);
25019 				last_zoneid = ilm->ilm_zoneid;
25020 			}
25021 			ILM_WALKER_RELE(ill);
25022 			/*
25023 			 * Loopback case: the sending endpoint has
25024 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25025 			 * dispatch the multicast packet to the sending zone.
25026 			 */
25027 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25028 				freemsg(first_mp);
25029 				return;
25030 			}
25031 		} else if (ire_type == IRE_BROADCAST) {
25032 			/*
25033 			 * In the broadcast case, there may be many zones
25034 			 * which need a copy of the packet delivered to them.
25035 			 * There is one IRE_BROADCAST per broadcast address
25036 			 * and per zone; we walk those using a helper function.
25037 			 * In addition, the sending of the packet for zoneid is
25038 			 * delayed until all of the other ires have been
25039 			 * processed.
25040 			 */
25041 			IRB_REFHOLD(ire->ire_bucket);
25042 			ire_zone = NULL;
25043 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25044 			    ire)) != NULL) {
25045 				mp1 = ip_copymsg(first_mp);
25046 				if (mp1 == NULL)
25047 					continue;
25048 
25049 				UPDATE_IB_PKT_COUNT(ire_zone);
25050 				ire_zone->ire_last_used_time = lbolt;
25051 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25052 				    mctl_present, B_FALSE, ill,
25053 				    ire_zone->ire_zoneid);
25054 			}
25055 			IRB_REFRELE(ire->ire_bucket);
25056 		}
25057 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25058 		    0, mctl_present, B_FALSE, ill, zoneid);
25059 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25060 		    "ip_wput_local_end: q %p (%S)",
25061 		    q, "icmp");
25062 		return;
25063 	}
25064 	case IPPROTO_IGMP:
25065 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25066 			/* Bad packet - discarded by igmp_input */
25067 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25068 			    "ip_wput_local_end: q %p (%S)",
25069 			    q, "igmp_input--bad packet");
25070 			if (mctl_present)
25071 				freeb(first_mp);
25072 			return;
25073 		}
25074 		/*
25075 		 * igmp_input() may have returned the pulled up message.
25076 		 * So first_mp and ipha need to be reinitialized.
25077 		 */
25078 		ipha = (ipha_t *)mp->b_rptr;
25079 		if (mctl_present)
25080 			first_mp->b_cont = mp;
25081 		else
25082 			first_mp = mp;
25083 		/* deliver to local raw users */
25084 		break;
25085 	case IPPROTO_ENCAP:
25086 		/*
25087 		 * This case is covered by either ip_fanout_proto, or by
25088 		 * the above security processing for self-tunneled packets.
25089 		 */
25090 		break;
25091 	case IPPROTO_UDP: {
25092 		uint16_t	*up;
25093 		uint32_t	ports;
25094 
25095 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25096 		    UDP_PORTS_OFFSET);
25097 		/* Force a 'valid' checksum. */
25098 		up[3] = 0;
25099 
25100 		ports = *(uint32_t *)up;
25101 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25102 		    (ire_type == IRE_BROADCAST),
25103 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25104 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25105 		    ill, zoneid);
25106 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25107 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25108 		return;
25109 	}
25110 	case IPPROTO_TCP: {
25111 
25112 		/*
25113 		 * For TCP, discard broadcast packets.
25114 		 */
25115 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25116 			freemsg(first_mp);
25117 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25118 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25119 			return;
25120 		}
25121 
25122 		if (mp->b_datap->db_type == M_DATA) {
25123 			/*
25124 			 * M_DATA mblk, so init mblk (chain) for no struio().
25125 			 */
25126 			mblk_t	*mp1 = mp;
25127 
25128 			do {
25129 				mp1->b_datap->db_struioflag = 0;
25130 			} while ((mp1 = mp1->b_cont) != NULL);
25131 		}
25132 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25133 		    <= mp->b_wptr);
25134 		ip_fanout_tcp(q, first_mp, ill, ipha,
25135 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25136 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25137 		    mctl_present, B_FALSE, zoneid);
25138 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25139 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25140 		return;
25141 	}
25142 	case IPPROTO_SCTP:
25143 	{
25144 		uint32_t	ports;
25145 
25146 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25147 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25148 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25149 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25150 		return;
25151 	}
25152 
25153 	default:
25154 		break;
25155 	}
25156 	/*
25157 	 * Find a client for some other protocol.  We give
25158 	 * copies to multiple clients, if more than one is
25159 	 * bound.
25160 	 */
25161 	ip_fanout_proto(q, first_mp, ill, ipha,
25162 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25163 	    mctl_present, B_FALSE, ill, zoneid);
25164 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25165 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25166 #undef	rptr
25167 }
25168 
25169 /*
25170  * Update any source route, record route, or timestamp options.
25171  * Check that we are at end of strict source route.
25172  * The options have been sanity checked by ip_wput_options().
25173  */
25174 static void
25175 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25176 {
25177 	ipoptp_t	opts;
25178 	uchar_t		*opt;
25179 	uint8_t		optval;
25180 	uint8_t		optlen;
25181 	ipaddr_t	dst;
25182 	uint32_t	ts;
25183 	ire_t		*ire;
25184 	timestruc_t	now;
25185 
25186 	ip2dbg(("ip_wput_local_options\n"));
25187 	for (optval = ipoptp_first(&opts, ipha);
25188 	    optval != IPOPT_EOL;
25189 	    optval = ipoptp_next(&opts)) {
25190 		opt = opts.ipoptp_cur;
25191 		optlen = opts.ipoptp_len;
25192 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25193 		switch (optval) {
25194 			uint32_t off;
25195 		case IPOPT_SSRR:
25196 		case IPOPT_LSRR:
25197 			off = opt[IPOPT_OFFSET];
25198 			off--;
25199 			if (optlen < IP_ADDR_LEN ||
25200 			    off > optlen - IP_ADDR_LEN) {
25201 				/* End of source route */
25202 				break;
25203 			}
25204 			/*
25205 			 * This will only happen if two consecutive entries
25206 			 * in the source route contains our address or if
25207 			 * it is a packet with a loose source route which
25208 			 * reaches us before consuming the whole source route
25209 			 */
25210 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25211 			if (optval == IPOPT_SSRR) {
25212 				return;
25213 			}
25214 			/*
25215 			 * Hack: instead of dropping the packet truncate the
25216 			 * source route to what has been used by filling the
25217 			 * rest with IPOPT_NOP.
25218 			 */
25219 			opt[IPOPT_OLEN] = (uint8_t)off;
25220 			while (off < optlen) {
25221 				opt[off++] = IPOPT_NOP;
25222 			}
25223 			break;
25224 		case IPOPT_RR:
25225 			off = opt[IPOPT_OFFSET];
25226 			off--;
25227 			if (optlen < IP_ADDR_LEN ||
25228 			    off > optlen - IP_ADDR_LEN) {
25229 				/* No more room - ignore */
25230 				ip1dbg((
25231 				    "ip_wput_forward_options: end of RR\n"));
25232 				break;
25233 			}
25234 			dst = htonl(INADDR_LOOPBACK);
25235 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25236 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25237 			break;
25238 		case IPOPT_TS:
25239 			/* Insert timestamp if there is romm */
25240 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25241 			case IPOPT_TS_TSONLY:
25242 				off = IPOPT_TS_TIMELEN;
25243 				break;
25244 			case IPOPT_TS_PRESPEC:
25245 			case IPOPT_TS_PRESPEC_RFC791:
25246 				/* Verify that the address matched */
25247 				off = opt[IPOPT_OFFSET] - 1;
25248 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25249 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25250 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25251 				    ipst);
25252 				if (ire == NULL) {
25253 					/* Not for us */
25254 					break;
25255 				}
25256 				ire_refrele(ire);
25257 				/* FALLTHRU */
25258 			case IPOPT_TS_TSANDADDR:
25259 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25260 				break;
25261 			default:
25262 				/*
25263 				 * ip_*put_options should have already
25264 				 * dropped this packet.
25265 				 */
25266 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25267 				    "unknown IT - bug in ip_wput_options?\n");
25268 				return;	/* Keep "lint" happy */
25269 			}
25270 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25271 				/* Increase overflow counter */
25272 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25273 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25274 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25275 				    (off << 4);
25276 				break;
25277 			}
25278 			off = opt[IPOPT_OFFSET] - 1;
25279 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25280 			case IPOPT_TS_PRESPEC:
25281 			case IPOPT_TS_PRESPEC_RFC791:
25282 			case IPOPT_TS_TSANDADDR:
25283 				dst = htonl(INADDR_LOOPBACK);
25284 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25285 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25286 				/* FALLTHRU */
25287 			case IPOPT_TS_TSONLY:
25288 				off = opt[IPOPT_OFFSET] - 1;
25289 				/* Compute # of milliseconds since midnight */
25290 				gethrestime(&now);
25291 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25292 				    now.tv_nsec / (NANOSEC / MILLISEC);
25293 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25294 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25295 				break;
25296 			}
25297 			break;
25298 		}
25299 	}
25300 }
25301 
25302 /*
25303  * Send out a multicast packet on interface ipif.
25304  * The sender does not have an conn.
25305  * Caller verifies that this isn't a PHYI_LOOPBACK.
25306  */
25307 void
25308 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25309 {
25310 	ipha_t	*ipha;
25311 	ire_t	*ire;
25312 	ipaddr_t	dst;
25313 	mblk_t		*first_mp;
25314 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25315 
25316 	/* igmp_sendpkt always allocates a ipsec_out_t */
25317 	ASSERT(mp->b_datap->db_type == M_CTL);
25318 	ASSERT(!ipif->ipif_isv6);
25319 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25320 
25321 	first_mp = mp;
25322 	mp = first_mp->b_cont;
25323 	ASSERT(mp->b_datap->db_type == M_DATA);
25324 	ipha = (ipha_t *)mp->b_rptr;
25325 
25326 	/*
25327 	 * Find an IRE which matches the destination and the outgoing
25328 	 * queue (i.e. the outgoing interface.)
25329 	 */
25330 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25331 		dst = ipif->ipif_pp_dst_addr;
25332 	else
25333 		dst = ipha->ipha_dst;
25334 	/*
25335 	 * The source address has already been initialized by the
25336 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25337 	 * be sufficient rather than MATCH_IRE_IPIF.
25338 	 *
25339 	 * This function is used for sending IGMP packets. We need
25340 	 * to make sure that we send the packet out of the interface
25341 	 * (ipif->ipif_ill) where we joined the group. This is to
25342 	 * prevent from switches doing IGMP snooping to send us multicast
25343 	 * packets for a given group on the interface we have joined.
25344 	 * If we can't find an ire, igmp_sendpkt has already initialized
25345 	 * ipsec_out_attach_if so that this will not be load spread in
25346 	 * ip_newroute_ipif.
25347 	 */
25348 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25349 	    MATCH_IRE_ILL, ipst);
25350 	if (!ire) {
25351 		/*
25352 		 * Mark this packet to make it be delivered to
25353 		 * ip_wput_ire after the new ire has been
25354 		 * created.
25355 		 */
25356 		mp->b_prev = NULL;
25357 		mp->b_next = NULL;
25358 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25359 		    zoneid, &zero_info);
25360 		return;
25361 	}
25362 
25363 	/*
25364 	 * Honor the RTF_SETSRC flag; this is the only case
25365 	 * where we force this addr whatever the current src addr is,
25366 	 * because this address is set by igmp_sendpkt(), and
25367 	 * cannot be specified by any user.
25368 	 */
25369 	if (ire->ire_flags & RTF_SETSRC) {
25370 		ipha->ipha_src = ire->ire_src_addr;
25371 	}
25372 
25373 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25374 }
25375 
25376 /*
25377  * NOTE : This function does not ire_refrele the ire argument passed in.
25378  *
25379  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25380  * failure. The nce_fp_mp can vanish any time in the case of
25381  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25382  * the ire_lock to access the nce_fp_mp in this case.
25383  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25384  * prepending a fastpath message IPQoS processing must precede it, we also set
25385  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25386  * (IPQoS might have set the b_band for CoS marking).
25387  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25388  * must follow it so that IPQoS can mark the dl_priority field for CoS
25389  * marking, if needed.
25390  */
25391 static mblk_t *
25392 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
25393 {
25394 	uint_t	hlen;
25395 	ipha_t *ipha;
25396 	mblk_t *mp1;
25397 	boolean_t qos_done = B_FALSE;
25398 	uchar_t	*ll_hdr;
25399 	ip_stack_t	*ipst = ire->ire_ipst;
25400 
25401 #define	rptr	((uchar_t *)ipha)
25402 
25403 	ipha = (ipha_t *)mp->b_rptr;
25404 	hlen = 0;
25405 	LOCK_IRE_FP_MP(ire);
25406 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25407 		ASSERT(DB_TYPE(mp1) == M_DATA);
25408 		/* Initiate IPPF processing */
25409 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25410 			UNLOCK_IRE_FP_MP(ire);
25411 			ip_process(proc, &mp, ill_index);
25412 			if (mp == NULL)
25413 				return (NULL);
25414 
25415 			ipha = (ipha_t *)mp->b_rptr;
25416 			LOCK_IRE_FP_MP(ire);
25417 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25418 				qos_done = B_TRUE;
25419 				goto no_fp_mp;
25420 			}
25421 			ASSERT(DB_TYPE(mp1) == M_DATA);
25422 		}
25423 		hlen = MBLKL(mp1);
25424 		/*
25425 		 * Check if we have enough room to prepend fastpath
25426 		 * header
25427 		 */
25428 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25429 			ll_hdr = rptr - hlen;
25430 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25431 			/*
25432 			 * Set the b_rptr to the start of the link layer
25433 			 * header
25434 			 */
25435 			mp->b_rptr = ll_hdr;
25436 			mp1 = mp;
25437 		} else {
25438 			mp1 = copyb(mp1);
25439 			if (mp1 == NULL)
25440 				goto unlock_err;
25441 			mp1->b_band = mp->b_band;
25442 			mp1->b_cont = mp;
25443 			/*
25444 			 * certain system generated traffic may not
25445 			 * have cred/label in ip header block. This
25446 			 * is true even for a labeled system. But for
25447 			 * labeled traffic, inherit the label in the
25448 			 * new header.
25449 			 */
25450 			if (DB_CRED(mp) != NULL)
25451 				mblk_setcred(mp1, DB_CRED(mp));
25452 			/*
25453 			 * XXX disable ICK_VALID and compute checksum
25454 			 * here; can happen if nce_fp_mp changes and
25455 			 * it can't be copied now due to insufficient
25456 			 * space. (unlikely, fp mp can change, but it
25457 			 * does not increase in length)
25458 			 */
25459 		}
25460 		UNLOCK_IRE_FP_MP(ire);
25461 	} else {
25462 no_fp_mp:
25463 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25464 		if (mp1 == NULL) {
25465 unlock_err:
25466 			UNLOCK_IRE_FP_MP(ire);
25467 			freemsg(mp);
25468 			return (NULL);
25469 		}
25470 		UNLOCK_IRE_FP_MP(ire);
25471 		mp1->b_cont = mp;
25472 		/*
25473 		 * certain system generated traffic may not
25474 		 * have cred/label in ip header block. This
25475 		 * is true even for a labeled system. But for
25476 		 * labeled traffic, inherit the label in the
25477 		 * new header.
25478 		 */
25479 		if (DB_CRED(mp) != NULL)
25480 			mblk_setcred(mp1, DB_CRED(mp));
25481 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25482 			ip_process(proc, &mp1, ill_index);
25483 			if (mp1 == NULL)
25484 				return (NULL);
25485 		}
25486 	}
25487 	return (mp1);
25488 #undef rptr
25489 }
25490 
25491 /*
25492  * Finish the outbound IPsec processing for an IPv6 packet. This function
25493  * is called from ipsec_out_process() if the IPsec packet was processed
25494  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25495  * asynchronously.
25496  */
25497 void
25498 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25499     ire_t *ire_arg)
25500 {
25501 	in6_addr_t *v6dstp;
25502 	ire_t *ire;
25503 	mblk_t *mp;
25504 	ip6_t *ip6h1;
25505 	uint_t	ill_index;
25506 	ipsec_out_t *io;
25507 	boolean_t attach_if, hwaccel;
25508 	uint32_t flags = IP6_NO_IPPOLICY;
25509 	int match_flags;
25510 	zoneid_t zoneid;
25511 	boolean_t ill_need_rele = B_FALSE;
25512 	boolean_t ire_need_rele = B_FALSE;
25513 	ip_stack_t	*ipst;
25514 
25515 	mp = ipsec_mp->b_cont;
25516 	ip6h1 = (ip6_t *)mp->b_rptr;
25517 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25518 	ASSERT(io->ipsec_out_ns != NULL);
25519 	ipst = io->ipsec_out_ns->netstack_ip;
25520 	ill_index = io->ipsec_out_ill_index;
25521 	if (io->ipsec_out_reachable) {
25522 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25523 	}
25524 	attach_if = io->ipsec_out_attach_if;
25525 	hwaccel = io->ipsec_out_accelerated;
25526 	zoneid = io->ipsec_out_zoneid;
25527 	ASSERT(zoneid != ALL_ZONES);
25528 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25529 	/* Multicast addresses should have non-zero ill_index. */
25530 	v6dstp = &ip6h->ip6_dst;
25531 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25532 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25533 	ASSERT(!attach_if || ill_index != 0);
25534 	if (ill_index != 0) {
25535 		if (ill == NULL) {
25536 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
25537 			    B_TRUE, ipst);
25538 
25539 			/* Failure case frees things for us. */
25540 			if (ill == NULL)
25541 				return;
25542 
25543 			ill_need_rele = B_TRUE;
25544 		}
25545 		/*
25546 		 * If this packet needs to go out on a particular interface
25547 		 * honor it.
25548 		 */
25549 		if (attach_if) {
25550 			match_flags = MATCH_IRE_ILL;
25551 
25552 			/*
25553 			 * Check if we need an ire that will not be
25554 			 * looked up by anybody else i.e. HIDDEN.
25555 			 */
25556 			if (ill_is_probeonly(ill)) {
25557 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25558 			}
25559 		}
25560 	}
25561 	ASSERT(mp != NULL);
25562 
25563 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25564 		boolean_t unspec_src;
25565 		ipif_t	*ipif;
25566 
25567 		/*
25568 		 * Use the ill_index to get the right ill.
25569 		 */
25570 		unspec_src = io->ipsec_out_unspec_src;
25571 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25572 		if (ipif == NULL) {
25573 			if (ill_need_rele)
25574 				ill_refrele(ill);
25575 			freemsg(ipsec_mp);
25576 			return;
25577 		}
25578 
25579 		if (ire_arg != NULL) {
25580 			ire = ire_arg;
25581 		} else {
25582 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25583 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25584 			ire_need_rele = B_TRUE;
25585 		}
25586 		if (ire != NULL) {
25587 			ipif_refrele(ipif);
25588 			/*
25589 			 * XXX Do the multicast forwarding now, as the IPsec
25590 			 * processing has been done.
25591 			 */
25592 			goto send;
25593 		}
25594 
25595 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25596 		mp->b_prev = NULL;
25597 		mp->b_next = NULL;
25598 
25599 		/*
25600 		 * If the IPsec packet was processed asynchronously,
25601 		 * drop it now.
25602 		 */
25603 		if (q == NULL) {
25604 			if (ill_need_rele)
25605 				ill_refrele(ill);
25606 			freemsg(ipsec_mp);
25607 			return;
25608 		}
25609 
25610 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
25611 		    unspec_src, zoneid);
25612 		ipif_refrele(ipif);
25613 	} else {
25614 		if (attach_if) {
25615 			ipif_t	*ipif;
25616 
25617 			ipif = ipif_get_next_ipif(NULL, ill);
25618 			if (ipif == NULL) {
25619 				if (ill_need_rele)
25620 					ill_refrele(ill);
25621 				freemsg(ipsec_mp);
25622 				return;
25623 			}
25624 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25625 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25626 			ire_need_rele = B_TRUE;
25627 			ipif_refrele(ipif);
25628 		} else {
25629 			if (ire_arg != NULL) {
25630 				ire = ire_arg;
25631 			} else {
25632 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL,
25633 				    ipst);
25634 				ire_need_rele = B_TRUE;
25635 			}
25636 		}
25637 		if (ire != NULL)
25638 			goto send;
25639 		/*
25640 		 * ire disappeared underneath.
25641 		 *
25642 		 * What we need to do here is the ip_newroute
25643 		 * logic to get the ire without doing the IPsec
25644 		 * processing. Follow the same old path. But this
25645 		 * time, ip_wput or ire_add_then_send will call us
25646 		 * directly as all the IPsec operations are done.
25647 		 */
25648 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25649 		mp->b_prev = NULL;
25650 		mp->b_next = NULL;
25651 
25652 		/*
25653 		 * If the IPsec packet was processed asynchronously,
25654 		 * drop it now.
25655 		 */
25656 		if (q == NULL) {
25657 			if (ill_need_rele)
25658 				ill_refrele(ill);
25659 			freemsg(ipsec_mp);
25660 			return;
25661 		}
25662 
25663 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25664 		    zoneid, ipst);
25665 	}
25666 	if (ill != NULL && ill_need_rele)
25667 		ill_refrele(ill);
25668 	return;
25669 send:
25670 	if (ill != NULL && ill_need_rele)
25671 		ill_refrele(ill);
25672 
25673 	/* Local delivery */
25674 	if (ire->ire_stq == NULL) {
25675 		ill_t	*out_ill;
25676 		ASSERT(q != NULL);
25677 
25678 		/* PFHooks: LOOPBACK_OUT */
25679 		out_ill = ire_to_ill(ire);
25680 
25681 		DTRACE_PROBE4(ip6__loopback__out__start,
25682 		    ill_t *, NULL, ill_t *, out_ill,
25683 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25684 
25685 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25686 		    ipst->ips_ipv6firewall_loopback_out,
25687 		    NULL, out_ill, ip6h1, ipsec_mp, mp, ipst);
25688 
25689 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25690 
25691 		if (ipsec_mp != NULL)
25692 			ip_wput_local_v6(RD(q), out_ill,
25693 			    ip6h, ipsec_mp, ire, 0);
25694 		if (ire_need_rele)
25695 			ire_refrele(ire);
25696 		return;
25697 	}
25698 	/*
25699 	 * Everything is done. Send it out on the wire.
25700 	 * We force the insertion of a fragment header using the
25701 	 * IPH_FRAG_HDR flag in two cases:
25702 	 * - after reception of an ICMPv6 "packet too big" message
25703 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25704 	 * - for multirouted IPv6 packets, so that the receiver can
25705 	 *   discard duplicates according to their fragment identifier
25706 	 */
25707 	/* XXX fix flow control problems. */
25708 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25709 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25710 		if (hwaccel) {
25711 			/*
25712 			 * hardware acceleration does not handle these
25713 			 * "slow path" cases.
25714 			 */
25715 			/* IPsec KSTATS: should bump bean counter here. */
25716 			if (ire_need_rele)
25717 				ire_refrele(ire);
25718 			freemsg(ipsec_mp);
25719 			return;
25720 		}
25721 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25722 		    (mp->b_cont ? msgdsize(mp) :
25723 		    mp->b_wptr - (uchar_t *)ip6h)) {
25724 			/* IPsec KSTATS: should bump bean counter here. */
25725 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25726 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25727 			    msgdsize(mp)));
25728 			if (ire_need_rele)
25729 				ire_refrele(ire);
25730 			freemsg(ipsec_mp);
25731 			return;
25732 		}
25733 		ASSERT(mp->b_prev == NULL);
25734 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25735 		    ntohs(ip6h->ip6_plen) +
25736 		    IPV6_HDR_LEN, ire->ire_max_frag));
25737 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25738 		    ire->ire_max_frag);
25739 	} else {
25740 		UPDATE_OB_PKT_COUNT(ire);
25741 		ire->ire_last_used_time = lbolt;
25742 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25743 	}
25744 	if (ire_need_rele)
25745 		ire_refrele(ire);
25746 	freeb(ipsec_mp);
25747 }
25748 
25749 void
25750 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25751 {
25752 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25753 	da_ipsec_t *hada;	/* data attributes */
25754 	ill_t *ill = (ill_t *)q->q_ptr;
25755 
25756 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25757 
25758 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25759 		/* IPsec KSTATS: Bump lose counter here! */
25760 		freemsg(mp);
25761 		return;
25762 	}
25763 
25764 	/*
25765 	 * It's an IPsec packet that must be
25766 	 * accelerated by the Provider, and the
25767 	 * outbound ill is IPsec acceleration capable.
25768 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25769 	 * to the ill.
25770 	 * IPsec KSTATS: should bump packet counter here.
25771 	 */
25772 
25773 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25774 	if (hada_mp == NULL) {
25775 		/* IPsec KSTATS: should bump packet counter here. */
25776 		freemsg(mp);
25777 		return;
25778 	}
25779 
25780 	hada_mp->b_datap->db_type = M_CTL;
25781 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25782 	hada_mp->b_cont = mp;
25783 
25784 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25785 	bzero(hada, sizeof (da_ipsec_t));
25786 	hada->da_type = IPHADA_M_CTL;
25787 
25788 	putnext(q, hada_mp);
25789 }
25790 
25791 /*
25792  * Finish the outbound IPsec processing. This function is called from
25793  * ipsec_out_process() if the IPsec packet was processed
25794  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25795  * asynchronously.
25796  */
25797 void
25798 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25799     ire_t *ire_arg)
25800 {
25801 	uint32_t v_hlen_tos_len;
25802 	ipaddr_t	dst;
25803 	ipif_t	*ipif = NULL;
25804 	ire_t *ire;
25805 	ire_t *ire1 = NULL;
25806 	mblk_t *next_mp = NULL;
25807 	uint32_t max_frag;
25808 	boolean_t multirt_send = B_FALSE;
25809 	mblk_t *mp;
25810 	ipha_t *ipha1;
25811 	uint_t	ill_index;
25812 	ipsec_out_t *io;
25813 	boolean_t attach_if;
25814 	int match_flags;
25815 	irb_t *irb = NULL;
25816 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25817 	zoneid_t zoneid;
25818 	ipxmit_state_t	pktxmit_state;
25819 	ip_stack_t	*ipst;
25820 
25821 #ifdef	_BIG_ENDIAN
25822 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25823 #else
25824 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25825 #endif
25826 
25827 	mp = ipsec_mp->b_cont;
25828 	ipha1 = (ipha_t *)mp->b_rptr;
25829 	ASSERT(mp != NULL);
25830 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25831 	dst = ipha->ipha_dst;
25832 
25833 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25834 	ill_index = io->ipsec_out_ill_index;
25835 	attach_if = io->ipsec_out_attach_if;
25836 	zoneid = io->ipsec_out_zoneid;
25837 	ASSERT(zoneid != ALL_ZONES);
25838 	ipst = io->ipsec_out_ns->netstack_ip;
25839 	ASSERT(io->ipsec_out_ns != NULL);
25840 
25841 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25842 	if (ill_index != 0) {
25843 		if (ill == NULL) {
25844 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
25845 			    ill_index, B_FALSE, ipst);
25846 
25847 			/* Failure case frees things for us. */
25848 			if (ill == NULL)
25849 				return;
25850 
25851 			ill_need_rele = B_TRUE;
25852 		}
25853 		/*
25854 		 * If this packet needs to go out on a particular interface
25855 		 * honor it.
25856 		 */
25857 		if (attach_if) {
25858 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25859 
25860 			/*
25861 			 * Check if we need an ire that will not be
25862 			 * looked up by anybody else i.e. HIDDEN.
25863 			 */
25864 			if (ill_is_probeonly(ill)) {
25865 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25866 			}
25867 		}
25868 	}
25869 
25870 	if (CLASSD(dst)) {
25871 		boolean_t conn_dontroute;
25872 		/*
25873 		 * Use the ill_index to get the right ipif.
25874 		 */
25875 		conn_dontroute = io->ipsec_out_dontroute;
25876 		if (ill_index == 0)
25877 			ipif = ipif_lookup_group(dst, zoneid, ipst);
25878 		else
25879 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25880 		if (ipif == NULL) {
25881 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25882 			    " multicast\n"));
25883 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
25884 			freemsg(ipsec_mp);
25885 			goto done;
25886 		}
25887 		/*
25888 		 * ipha_src has already been intialized with the
25889 		 * value of the ipif in ip_wput. All we need now is
25890 		 * an ire to send this downstream.
25891 		 */
25892 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25893 		    MBLK_GETLABEL(mp), match_flags, ipst);
25894 		if (ire != NULL) {
25895 			ill_t *ill1;
25896 			/*
25897 			 * Do the multicast forwarding now, as the IPsec
25898 			 * processing has been done.
25899 			 */
25900 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
25901 			    (ill1 = ire_to_ill(ire))) {
25902 				if (ip_mforward(ill1, ipha, mp)) {
25903 					freemsg(ipsec_mp);
25904 					ip1dbg(("ip_wput_ipsec_out: mforward "
25905 					    "failed\n"));
25906 					ire_refrele(ire);
25907 					goto done;
25908 				}
25909 			}
25910 			goto send;
25911 		}
25912 
25913 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
25914 		mp->b_prev = NULL;
25915 		mp->b_next = NULL;
25916 
25917 		/*
25918 		 * If the IPsec packet was processed asynchronously,
25919 		 * drop it now.
25920 		 */
25921 		if (q == NULL) {
25922 			freemsg(ipsec_mp);
25923 			goto done;
25924 		}
25925 
25926 		/*
25927 		 * We may be using a wrong ipif to create the ire.
25928 		 * But it is okay as the source address is assigned
25929 		 * for the packet already. Next outbound packet would
25930 		 * create the IRE with the right IPIF in ip_wput.
25931 		 *
25932 		 * Also handle RTF_MULTIRT routes.
25933 		 */
25934 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
25935 		    zoneid, &zero_info);
25936 	} else {
25937 		if (attach_if) {
25938 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
25939 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25940 		} else {
25941 			if (ire_arg != NULL) {
25942 				ire = ire_arg;
25943 				ire_need_rele = B_FALSE;
25944 			} else {
25945 				ire = ire_cache_lookup(dst, zoneid,
25946 				    MBLK_GETLABEL(mp), ipst);
25947 			}
25948 		}
25949 		if (ire != NULL) {
25950 			goto send;
25951 		}
25952 
25953 		/*
25954 		 * ire disappeared underneath.
25955 		 *
25956 		 * What we need to do here is the ip_newroute
25957 		 * logic to get the ire without doing the IPsec
25958 		 * processing. Follow the same old path. But this
25959 		 * time, ip_wput or ire_add_then_put will call us
25960 		 * directly as all the IPsec operations are done.
25961 		 */
25962 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
25963 		mp->b_prev = NULL;
25964 		mp->b_next = NULL;
25965 
25966 		/*
25967 		 * If the IPsec packet was processed asynchronously,
25968 		 * drop it now.
25969 		 */
25970 		if (q == NULL) {
25971 			freemsg(ipsec_mp);
25972 			goto done;
25973 		}
25974 
25975 		/*
25976 		 * Since we're going through ip_newroute() again, we
25977 		 * need to make sure we don't:
25978 		 *
25979 		 *	1.) Trigger the ASSERT() with the ipha_ident
25980 		 *	    overloading.
25981 		 *	2.) Redo transport-layer checksumming, since we've
25982 		 *	    already done all that to get this far.
25983 		 *
25984 		 * The easiest way not do either of the above is to set
25985 		 * the ipha_ident field to IP_HDR_INCLUDED.
25986 		 */
25987 		ipha->ipha_ident = IP_HDR_INCLUDED;
25988 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
25989 		    zoneid, ipst);
25990 	}
25991 	goto done;
25992 send:
25993 	if (ire->ire_stq == NULL) {
25994 		ill_t	*out_ill;
25995 		/*
25996 		 * Loopbacks go through ip_wput_local except for one case.
25997 		 * We come here if we generate a icmp_frag_needed message
25998 		 * after IPsec processing is over. When this function calls
25999 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
26000 		 * icmp_frag_needed. The message generated comes back here
26001 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
26002 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
26003 		 * source address as it is usually set in ip_wput_ire. As
26004 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
26005 		 * and we end up here. We can't enter ip_wput_ire once the
26006 		 * IPsec processing is over and hence we need to do it here.
26007 		 */
26008 		ASSERT(q != NULL);
26009 		UPDATE_OB_PKT_COUNT(ire);
26010 		ire->ire_last_used_time = lbolt;
26011 		if (ipha->ipha_src == 0)
26012 			ipha->ipha_src = ire->ire_src_addr;
26013 
26014 		/* PFHooks: LOOPBACK_OUT */
26015 		out_ill = ire_to_ill(ire);
26016 
26017 		DTRACE_PROBE4(ip4__loopback__out__start,
26018 		    ill_t *, NULL, ill_t *, out_ill,
26019 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26020 
26021 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
26022 		    ipst->ips_ipv4firewall_loopback_out,
26023 		    NULL, out_ill, ipha1, ipsec_mp, mp, ipst);
26024 
26025 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26026 
26027 		if (ipsec_mp != NULL)
26028 			ip_wput_local(RD(q), out_ill,
26029 			    ipha, ipsec_mp, ire, 0, zoneid);
26030 		if (ire_need_rele)
26031 			ire_refrele(ire);
26032 		goto done;
26033 	}
26034 
26035 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26036 		/*
26037 		 * We are through with IPsec processing.
26038 		 * Fragment this and send it on the wire.
26039 		 */
26040 		if (io->ipsec_out_accelerated) {
26041 			/*
26042 			 * The packet has been accelerated but must
26043 			 * be fragmented. This should not happen
26044 			 * since AH and ESP must not accelerate
26045 			 * packets that need fragmentation, however
26046 			 * the configuration could have changed
26047 			 * since the AH or ESP processing.
26048 			 * Drop packet.
26049 			 * IPsec KSTATS: bump bean counter here.
26050 			 */
26051 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26052 			    "fragmented accelerated packet!\n"));
26053 			freemsg(ipsec_mp);
26054 		} else {
26055 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid, ipst);
26056 		}
26057 		if (ire_need_rele)
26058 			ire_refrele(ire);
26059 		goto done;
26060 	}
26061 
26062 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26063 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26064 	    (void *)ire->ire_ipif, (void *)ipif));
26065 
26066 	/*
26067 	 * Multiroute the secured packet, unless IPsec really
26068 	 * requires the packet to go out only through a particular
26069 	 * interface.
26070 	 */
26071 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
26072 		ire_t *first_ire;
26073 		irb = ire->ire_bucket;
26074 		ASSERT(irb != NULL);
26075 		/*
26076 		 * This ire has been looked up as the one that
26077 		 * goes through the given ipif;
26078 		 * make sure we do not omit any other multiroute ire
26079 		 * that may be present in the bucket before this one.
26080 		 */
26081 		IRB_REFHOLD(irb);
26082 		for (first_ire = irb->irb_ire;
26083 		    first_ire != NULL;
26084 		    first_ire = first_ire->ire_next) {
26085 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26086 			    (first_ire->ire_addr == ire->ire_addr) &&
26087 			    !(first_ire->ire_marks &
26088 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
26089 				break;
26090 			}
26091 		}
26092 
26093 		if ((first_ire != NULL) && (first_ire != ire)) {
26094 			/*
26095 			 * Don't change the ire if the packet must
26096 			 * be fragmented if sent via this new one.
26097 			 */
26098 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26099 				IRE_REFHOLD(first_ire);
26100 				if (ire_need_rele)
26101 					ire_refrele(ire);
26102 				else
26103 					ire_need_rele = B_TRUE;
26104 				ire = first_ire;
26105 			}
26106 		}
26107 		IRB_REFRELE(irb);
26108 
26109 		multirt_send = B_TRUE;
26110 		max_frag = ire->ire_max_frag;
26111 	} else {
26112 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
26113 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
26114 			    "flag, attach_if %d\n", attach_if));
26115 		}
26116 	}
26117 
26118 	/*
26119 	 * In most cases, the emission loop below is entered only once.
26120 	 * Only in the case where the ire holds the RTF_MULTIRT
26121 	 * flag, we loop to process all RTF_MULTIRT ires in the
26122 	 * bucket, and send the packet through all crossed
26123 	 * RTF_MULTIRT routes.
26124 	 */
26125 	do {
26126 		if (multirt_send) {
26127 			/*
26128 			 * ire1 holds here the next ire to process in the
26129 			 * bucket. If multirouting is expected,
26130 			 * any non-RTF_MULTIRT ire that has the
26131 			 * right destination address is ignored.
26132 			 */
26133 			ASSERT(irb != NULL);
26134 			IRB_REFHOLD(irb);
26135 			for (ire1 = ire->ire_next;
26136 			    ire1 != NULL;
26137 			    ire1 = ire1->ire_next) {
26138 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26139 					continue;
26140 				if (ire1->ire_addr != ire->ire_addr)
26141 					continue;
26142 				if (ire1->ire_marks &
26143 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
26144 					continue;
26145 				/* No loopback here */
26146 				if (ire1->ire_stq == NULL)
26147 					continue;
26148 				/*
26149 				 * Ensure we do not exceed the MTU
26150 				 * of the next route.
26151 				 */
26152 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26153 					ip_multirt_bad_mtu(ire1, max_frag);
26154 					continue;
26155 				}
26156 
26157 				IRE_REFHOLD(ire1);
26158 				break;
26159 			}
26160 			IRB_REFRELE(irb);
26161 			if (ire1 != NULL) {
26162 				/*
26163 				 * We are in a multiple send case, need to
26164 				 * make a copy of the packet.
26165 				 */
26166 				next_mp = copymsg(ipsec_mp);
26167 				if (next_mp == NULL) {
26168 					ire_refrele(ire1);
26169 					ire1 = NULL;
26170 				}
26171 			}
26172 		}
26173 		/*
26174 		 * Everything is done. Send it out on the wire
26175 		 *
26176 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26177 		 * either send it on the wire or, in the case of
26178 		 * HW acceleration, call ipsec_hw_putnext.
26179 		 */
26180 		if (ire->ire_nce &&
26181 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26182 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26183 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26184 			/*
26185 			 * If ire's link-layer is unresolved (this
26186 			 * would only happen if the incomplete ire
26187 			 * was added to cachetable via forwarding path)
26188 			 * don't bother going to ip_xmit_v4. Just drop the
26189 			 * packet.
26190 			 * There is a slight risk here, in that, if we
26191 			 * have the forwarding path create an incomplete
26192 			 * IRE, then until the IRE is completed, any
26193 			 * transmitted IPsec packets will be dropped
26194 			 * instead of being queued waiting for resolution.
26195 			 *
26196 			 * But the likelihood of a forwarding packet and a wput
26197 			 * packet sending to the same dst at the same time
26198 			 * and there not yet be an ARP entry for it is small.
26199 			 * Furthermore, if this actually happens, it might
26200 			 * be likely that wput would generate multiple
26201 			 * packets (and forwarding would also have a train
26202 			 * of packets) for that destination. If this is
26203 			 * the case, some of them would have been dropped
26204 			 * anyway, since ARP only queues a few packets while
26205 			 * waiting for resolution
26206 			 *
26207 			 * NOTE: We should really call ip_xmit_v4,
26208 			 * and let it queue the packet and send the
26209 			 * ARP query and have ARP come back thus:
26210 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26211 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26212 			 * hw accel work. But it's too complex to get
26213 			 * the IPsec hw  acceleration approach to fit
26214 			 * well with ip_xmit_v4 doing ARP without
26215 			 * doing IPsec simplification. For now, we just
26216 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26217 			 * that we can continue with the send on the next
26218 			 * attempt.
26219 			 *
26220 			 * XXX THis should be revisited, when
26221 			 * the IPsec/IP interaction is cleaned up
26222 			 */
26223 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26224 			    " - dropping packet\n"));
26225 			freemsg(ipsec_mp);
26226 			/*
26227 			 * Call ip_xmit_v4() to trigger ARP query
26228 			 * in case the nce_state is ND_INITIAL
26229 			 */
26230 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26231 			goto drop_pkt;
26232 		}
26233 
26234 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26235 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26236 		    mblk_t *, ipsec_mp);
26237 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26238 		    ipst->ips_ipv4firewall_physical_out,
26239 		    NULL, ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, ipst);
26240 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26241 		if (ipsec_mp == NULL)
26242 			goto drop_pkt;
26243 
26244 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26245 		pktxmit_state = ip_xmit_v4(mp, ire,
26246 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
26247 
26248 		if ((pktxmit_state ==  SEND_FAILED) ||
26249 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26250 
26251 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26252 drop_pkt:
26253 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26254 			    ipIfStatsOutDiscards);
26255 			if (ire_need_rele)
26256 				ire_refrele(ire);
26257 			if (ire1 != NULL) {
26258 				ire_refrele(ire1);
26259 				freemsg(next_mp);
26260 			}
26261 			goto done;
26262 		}
26263 
26264 		freeb(ipsec_mp);
26265 		if (ire_need_rele)
26266 			ire_refrele(ire);
26267 
26268 		if (ire1 != NULL) {
26269 			ire = ire1;
26270 			ire_need_rele = B_TRUE;
26271 			ASSERT(next_mp);
26272 			ipsec_mp = next_mp;
26273 			mp = ipsec_mp->b_cont;
26274 			ire1 = NULL;
26275 			next_mp = NULL;
26276 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26277 		} else {
26278 			multirt_send = B_FALSE;
26279 		}
26280 	} while (multirt_send);
26281 done:
26282 	if (ill != NULL && ill_need_rele)
26283 		ill_refrele(ill);
26284 	if (ipif != NULL)
26285 		ipif_refrele(ipif);
26286 }
26287 
26288 /*
26289  * Get the ill corresponding to the specified ire, and compare its
26290  * capabilities with the protocol and algorithms specified by the
26291  * the SA obtained from ipsec_out. If they match, annotate the
26292  * ipsec_out structure to indicate that the packet needs acceleration.
26293  *
26294  *
26295  * A packet is eligible for outbound hardware acceleration if the
26296  * following conditions are satisfied:
26297  *
26298  * 1. the packet will not be fragmented
26299  * 2. the provider supports the algorithm
26300  * 3. there is no pending control message being exchanged
26301  * 4. snoop is not attached
26302  * 5. the destination address is not a broadcast or multicast address.
26303  *
26304  * Rationale:
26305  *	- Hardware drivers do not support fragmentation with
26306  *	  the current interface.
26307  *	- snoop, multicast, and broadcast may result in exposure of
26308  *	  a cleartext datagram.
26309  * We check all five of these conditions here.
26310  *
26311  * XXX would like to nuke "ire_t *" parameter here; problem is that
26312  * IRE is only way to figure out if a v4 address is a broadcast and
26313  * thus ineligible for acceleration...
26314  */
26315 static void
26316 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26317 {
26318 	ipsec_out_t *io;
26319 	mblk_t *data_mp;
26320 	uint_t plen, overhead;
26321 	ip_stack_t	*ipst;
26322 
26323 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26324 		return;
26325 
26326 	if (ill == NULL)
26327 		return;
26328 	ipst = ill->ill_ipst;
26329 	/*
26330 	 * Destination address is a broadcast or multicast.  Punt.
26331 	 */
26332 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26333 	    IRE_LOCAL)))
26334 		return;
26335 
26336 	data_mp = ipsec_mp->b_cont;
26337 
26338 	if (ill->ill_isv6) {
26339 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26340 
26341 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26342 			return;
26343 
26344 		plen = ip6h->ip6_plen;
26345 	} else {
26346 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26347 
26348 		if (CLASSD(ipha->ipha_dst))
26349 			return;
26350 
26351 		plen = ipha->ipha_length;
26352 	}
26353 	/*
26354 	 * Is there a pending DLPI control message being exchanged
26355 	 * between IP/IPsec and the DLS Provider? If there is, it
26356 	 * could be a SADB update, and the state of the DLS Provider
26357 	 * SADB might not be in sync with the SADB maintained by
26358 	 * IPsec. To avoid dropping packets or using the wrong keying
26359 	 * material, we do not accelerate this packet.
26360 	 */
26361 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26362 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26363 		    "ill_dlpi_pending! don't accelerate packet\n"));
26364 		return;
26365 	}
26366 
26367 	/*
26368 	 * Is the Provider in promiscous mode? If it does, we don't
26369 	 * accelerate the packet since it will bounce back up to the
26370 	 * listeners in the clear.
26371 	 */
26372 	if (ill->ill_promisc_on_phys) {
26373 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26374 		    "ill in promiscous mode, don't accelerate packet\n"));
26375 		return;
26376 	}
26377 
26378 	/*
26379 	 * Will the packet require fragmentation?
26380 	 */
26381 
26382 	/*
26383 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26384 	 * as is used elsewhere.
26385 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26386 	 *	+ 2-byte trailer
26387 	 */
26388 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26389 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26390 
26391 	if ((plen + overhead) > ill->ill_max_mtu)
26392 		return;
26393 
26394 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26395 
26396 	/*
26397 	 * Can the ill accelerate this IPsec protocol and algorithm
26398 	 * specified by the SA?
26399 	 */
26400 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26401 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26402 		return;
26403 	}
26404 
26405 	/*
26406 	 * Tell AH or ESP that the outbound ill is capable of
26407 	 * accelerating this packet.
26408 	 */
26409 	io->ipsec_out_is_capab_ill = B_TRUE;
26410 }
26411 
26412 /*
26413  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26414  *
26415  * If this function returns B_TRUE, the requested SA's have been filled
26416  * into the ipsec_out_*_sa pointers.
26417  *
26418  * If the function returns B_FALSE, the packet has been "consumed", most
26419  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26420  *
26421  * The SA references created by the protocol-specific "select"
26422  * function will be released when the ipsec_mp is freed, thanks to the
26423  * ipsec_out_free destructor -- see spd.c.
26424  */
26425 static boolean_t
26426 ipsec_out_select_sa(mblk_t *ipsec_mp)
26427 {
26428 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26429 	ipsec_out_t *io;
26430 	ipsec_policy_t *pp;
26431 	ipsec_action_t *ap;
26432 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26433 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26434 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26435 
26436 	if (!io->ipsec_out_secure) {
26437 		/*
26438 		 * We came here by mistake.
26439 		 * Don't bother with ipsec processing
26440 		 * We should "discourage" this path in the future.
26441 		 */
26442 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26443 		return (B_FALSE);
26444 	}
26445 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26446 	ASSERT((io->ipsec_out_policy != NULL) ||
26447 	    (io->ipsec_out_act != NULL));
26448 
26449 	ASSERT(io->ipsec_out_failed == B_FALSE);
26450 
26451 	/*
26452 	 * IPsec processing has started.
26453 	 */
26454 	io->ipsec_out_proc_begin = B_TRUE;
26455 	ap = io->ipsec_out_act;
26456 	if (ap == NULL) {
26457 		pp = io->ipsec_out_policy;
26458 		ASSERT(pp != NULL);
26459 		ap = pp->ipsp_act;
26460 		ASSERT(ap != NULL);
26461 	}
26462 
26463 	/*
26464 	 * We have an action.  now, let's select SA's.
26465 	 * (In the future, we can cache this in the conn_t..)
26466 	 */
26467 	if (ap->ipa_want_esp) {
26468 		if (io->ipsec_out_esp_sa == NULL) {
26469 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26470 			    IPPROTO_ESP);
26471 		}
26472 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26473 	}
26474 
26475 	if (ap->ipa_want_ah) {
26476 		if (io->ipsec_out_ah_sa == NULL) {
26477 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26478 			    IPPROTO_AH);
26479 		}
26480 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26481 		/*
26482 		 * The ESP and AH processing order needs to be preserved
26483 		 * when both protocols are required (ESP should be applied
26484 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26485 		 * when both ESP and AH are required, and an AH ACQUIRE
26486 		 * is needed.
26487 		 */
26488 		if (ap->ipa_want_esp && need_ah_acquire)
26489 			need_esp_acquire = B_TRUE;
26490 	}
26491 
26492 	/*
26493 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26494 	 * Release SAs that got referenced, but will not be used until we
26495 	 * acquire _all_ of the SAs we need.
26496 	 */
26497 	if (need_ah_acquire || need_esp_acquire) {
26498 		if (io->ipsec_out_ah_sa != NULL) {
26499 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26500 			io->ipsec_out_ah_sa = NULL;
26501 		}
26502 		if (io->ipsec_out_esp_sa != NULL) {
26503 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26504 			io->ipsec_out_esp_sa = NULL;
26505 		}
26506 
26507 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26508 		return (B_FALSE);
26509 	}
26510 
26511 	return (B_TRUE);
26512 }
26513 
26514 /*
26515  * Process an IPSEC_OUT message and see what you can
26516  * do with it.
26517  * IPQoS Notes:
26518  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26519  * IPsec.
26520  * XXX would like to nuke ire_t.
26521  * XXX ill_index better be "real"
26522  */
26523 void
26524 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26525 {
26526 	ipsec_out_t *io;
26527 	ipsec_policy_t *pp;
26528 	ipsec_action_t *ap;
26529 	ipha_t *ipha;
26530 	ip6_t *ip6h;
26531 	mblk_t *mp;
26532 	ill_t *ill;
26533 	zoneid_t zoneid;
26534 	ipsec_status_t ipsec_rc;
26535 	boolean_t ill_need_rele = B_FALSE;
26536 	ip_stack_t	*ipst;
26537 	ipsec_stack_t	*ipss;
26538 
26539 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26540 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26541 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26542 	ipst = io->ipsec_out_ns->netstack_ip;
26543 	mp = ipsec_mp->b_cont;
26544 
26545 	/*
26546 	 * Initiate IPPF processing. We do it here to account for packets
26547 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26548 	 * We can check for ipsec_out_proc_begin even for such packets, as
26549 	 * they will always be false (asserted below).
26550 	 */
26551 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26552 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26553 		    io->ipsec_out_ill_index : ill_index);
26554 		if (mp == NULL) {
26555 			ip2dbg(("ipsec_out_process: packet dropped "\
26556 			    "during IPPF processing\n"));
26557 			freeb(ipsec_mp);
26558 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26559 			return;
26560 		}
26561 	}
26562 
26563 	if (!io->ipsec_out_secure) {
26564 		/*
26565 		 * We came here by mistake.
26566 		 * Don't bother with ipsec processing
26567 		 * Should "discourage" this path in the future.
26568 		 */
26569 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26570 		goto done;
26571 	}
26572 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26573 	ASSERT((io->ipsec_out_policy != NULL) ||
26574 	    (io->ipsec_out_act != NULL));
26575 	ASSERT(io->ipsec_out_failed == B_FALSE);
26576 
26577 	ipss = ipst->ips_netstack->netstack_ipsec;
26578 	if (!ipsec_loaded(ipss)) {
26579 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26580 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26581 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26582 		} else {
26583 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26584 		}
26585 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26586 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26587 		    &ipss->ipsec_dropper);
26588 		return;
26589 	}
26590 
26591 	/*
26592 	 * IPsec processing has started.
26593 	 */
26594 	io->ipsec_out_proc_begin = B_TRUE;
26595 	ap = io->ipsec_out_act;
26596 	if (ap == NULL) {
26597 		pp = io->ipsec_out_policy;
26598 		ASSERT(pp != NULL);
26599 		ap = pp->ipsp_act;
26600 		ASSERT(ap != NULL);
26601 	}
26602 
26603 	/*
26604 	 * Save the outbound ill index. When the packet comes back
26605 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26606 	 * before sending it the accelerated packet.
26607 	 */
26608 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26609 		int ifindex;
26610 		ill = ire_to_ill(ire);
26611 		ifindex = ill->ill_phyint->phyint_ifindex;
26612 		io->ipsec_out_capab_ill_index = ifindex;
26613 	}
26614 
26615 	/*
26616 	 * The order of processing is first insert a IP header if needed.
26617 	 * Then insert the ESP header and then the AH header.
26618 	 */
26619 	if ((io->ipsec_out_se_done == B_FALSE) &&
26620 	    (ap->ipa_want_se)) {
26621 		/*
26622 		 * First get the outer IP header before sending
26623 		 * it to ESP.
26624 		 */
26625 		ipha_t *oipha, *iipha;
26626 		mblk_t *outer_mp, *inner_mp;
26627 
26628 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26629 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26630 			    "ipsec_out_process: "
26631 			    "Self-Encapsulation failed: Out of memory\n");
26632 			freemsg(ipsec_mp);
26633 			if (ill != NULL) {
26634 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26635 			} else {
26636 				BUMP_MIB(&ipst->ips_ip_mib,
26637 				    ipIfStatsOutDiscards);
26638 			}
26639 			return;
26640 		}
26641 		inner_mp = ipsec_mp->b_cont;
26642 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26643 		oipha = (ipha_t *)outer_mp->b_rptr;
26644 		iipha = (ipha_t *)inner_mp->b_rptr;
26645 		*oipha = *iipha;
26646 		outer_mp->b_wptr += sizeof (ipha_t);
26647 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26648 		    sizeof (ipha_t));
26649 		oipha->ipha_protocol = IPPROTO_ENCAP;
26650 		oipha->ipha_version_and_hdr_length =
26651 		    IP_SIMPLE_HDR_VERSION;
26652 		oipha->ipha_hdr_checksum = 0;
26653 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26654 		outer_mp->b_cont = inner_mp;
26655 		ipsec_mp->b_cont = outer_mp;
26656 
26657 		io->ipsec_out_se_done = B_TRUE;
26658 		io->ipsec_out_tunnel = B_TRUE;
26659 	}
26660 
26661 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26662 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26663 	    !ipsec_out_select_sa(ipsec_mp))
26664 		return;
26665 
26666 	/*
26667 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26668 	 * to do the heavy lifting.
26669 	 */
26670 	zoneid = io->ipsec_out_zoneid;
26671 	ASSERT(zoneid != ALL_ZONES);
26672 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26673 		ASSERT(io->ipsec_out_esp_sa != NULL);
26674 		io->ipsec_out_esp_done = B_TRUE;
26675 		/*
26676 		 * Note that since hw accel can only apply one transform,
26677 		 * not two, we skip hw accel for ESP if we also have AH
26678 		 * This is an design limitation of the interface
26679 		 * which should be revisited.
26680 		 */
26681 		ASSERT(ire != NULL);
26682 		if (io->ipsec_out_ah_sa == NULL) {
26683 			ill = (ill_t *)ire->ire_stq->q_ptr;
26684 			ipsec_out_is_accelerated(ipsec_mp,
26685 			    io->ipsec_out_esp_sa, ill, ire);
26686 		}
26687 
26688 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26689 		switch (ipsec_rc) {
26690 		case IPSEC_STATUS_SUCCESS:
26691 			break;
26692 		case IPSEC_STATUS_FAILED:
26693 			if (ill != NULL) {
26694 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26695 			} else {
26696 				BUMP_MIB(&ipst->ips_ip_mib,
26697 				    ipIfStatsOutDiscards);
26698 			}
26699 			/* FALLTHRU */
26700 		case IPSEC_STATUS_PENDING:
26701 			return;
26702 		}
26703 	}
26704 
26705 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26706 		ASSERT(io->ipsec_out_ah_sa != NULL);
26707 		io->ipsec_out_ah_done = B_TRUE;
26708 		if (ire == NULL) {
26709 			int idx = io->ipsec_out_capab_ill_index;
26710 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26711 			    NULL, NULL, NULL, NULL, ipst);
26712 			ill_need_rele = B_TRUE;
26713 		} else {
26714 			ill = (ill_t *)ire->ire_stq->q_ptr;
26715 		}
26716 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26717 		    ire);
26718 
26719 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26720 		switch (ipsec_rc) {
26721 		case IPSEC_STATUS_SUCCESS:
26722 			break;
26723 		case IPSEC_STATUS_FAILED:
26724 			if (ill != NULL) {
26725 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26726 			} else {
26727 				BUMP_MIB(&ipst->ips_ip_mib,
26728 				    ipIfStatsOutDiscards);
26729 			}
26730 			/* FALLTHRU */
26731 		case IPSEC_STATUS_PENDING:
26732 			if (ill != NULL && ill_need_rele)
26733 				ill_refrele(ill);
26734 			return;
26735 		}
26736 	}
26737 	/*
26738 	 * We are done with IPsec processing. Send it over
26739 	 * the wire.
26740 	 */
26741 done:
26742 	mp = ipsec_mp->b_cont;
26743 	ipha = (ipha_t *)mp->b_rptr;
26744 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26745 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
26746 	} else {
26747 		ip6h = (ip6_t *)ipha;
26748 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
26749 	}
26750 	if (ill != NULL && ill_need_rele)
26751 		ill_refrele(ill);
26752 }
26753 
26754 /* ARGSUSED */
26755 void
26756 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26757 {
26758 	opt_restart_t	*or;
26759 	int	err;
26760 	conn_t	*connp;
26761 
26762 	ASSERT(CONN_Q(q));
26763 	connp = Q_TO_CONN(q);
26764 
26765 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26766 	or = (opt_restart_t *)first_mp->b_rptr;
26767 	/*
26768 	 * We don't need to pass any credentials here since this is just
26769 	 * a restart. The credentials are passed in when svr4_optcom_req
26770 	 * is called the first time (from ip_wput_nondata).
26771 	 */
26772 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26773 		err = svr4_optcom_req(q, first_mp, NULL,
26774 		    &ip_opt_obj, B_FALSE);
26775 	} else {
26776 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26777 		err = tpi_optcom_req(q, first_mp, NULL,
26778 		    &ip_opt_obj, B_FALSE);
26779 	}
26780 	if (err != EINPROGRESS) {
26781 		/* operation is done */
26782 		CONN_OPER_PENDING_DONE(connp);
26783 	}
26784 }
26785 
26786 /*
26787  * ioctls that go through a down/up sequence may need to wait for the down
26788  * to complete. This involves waiting for the ire and ipif refcnts to go down
26789  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26790  */
26791 /* ARGSUSED */
26792 void
26793 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26794 {
26795 	struct iocblk *iocp;
26796 	mblk_t *mp1;
26797 	ip_ioctl_cmd_t *ipip;
26798 	int err;
26799 	sin_t	*sin;
26800 	struct lifreq *lifr;
26801 	struct ifreq *ifr;
26802 
26803 	iocp = (struct iocblk *)mp->b_rptr;
26804 	ASSERT(ipsq != NULL);
26805 	/* Existence of mp1 verified in ip_wput_nondata */
26806 	mp1 = mp->b_cont->b_cont;
26807 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26808 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26809 		/*
26810 		 * Special case where ipsq_current_ipif is not set:
26811 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26812 		 * ill could also have become part of a ipmp group in the
26813 		 * process, we are here as were not able to complete the
26814 		 * operation in ipif_set_values because we could not become
26815 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
26816 		 * will not be set so we need to set it.
26817 		 */
26818 		ill_t *ill = q->q_ptr;
26819 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
26820 	}
26821 	ASSERT(ipsq->ipsq_current_ipif != NULL);
26822 
26823 	if (ipip->ipi_cmd_type == IF_CMD) {
26824 		/* This a old style SIOC[GS]IF* command */
26825 		ifr = (struct ifreq *)mp1->b_rptr;
26826 		sin = (sin_t *)&ifr->ifr_addr;
26827 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26828 		/* This a new style SIOC[GS]LIF* command */
26829 		lifr = (struct lifreq *)mp1->b_rptr;
26830 		sin = (sin_t *)&lifr->lifr_addr;
26831 	} else {
26832 		sin = NULL;
26833 	}
26834 
26835 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_current_ipif, sin, q, mp,
26836 	    ipip, mp1->b_rptr);
26837 
26838 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26839 }
26840 
26841 /*
26842  * ioctl processing
26843  *
26844  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
26845  * the ioctl command in the ioctl tables, determines the copyin data size
26846  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
26847  *
26848  * ioctl processing then continues when the M_IOCDATA makes its way down to
26849  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
26850  * associated 'conn' is refheld till the end of the ioctl and the general
26851  * ioctl processing function ip_process_ioctl() is called to extract the
26852  * arguments and process the ioctl.  To simplify extraction, ioctl commands
26853  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
26854  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
26855  * is used to extract the ioctl's arguments.
26856  *
26857  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26858  * so goes thru the serialization primitive ipsq_try_enter. Then the
26859  * appropriate function to handle the ioctl is called based on the entry in
26860  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26861  * which also refreleases the 'conn' that was refheld at the start of the
26862  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26863  *
26864  * Many exclusive ioctls go thru an internal down up sequence as part of
26865  * the operation. For example an attempt to change the IP address of an
26866  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26867  * does all the cleanup such as deleting all ires that use this address.
26868  * Then we need to wait till all references to the interface go away.
26869  */
26870 void
26871 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26872 {
26873 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26874 	ip_ioctl_cmd_t *ipip = arg;
26875 	ip_extract_func_t *extract_funcp;
26876 	cmd_info_t ci;
26877 	int err;
26878 	boolean_t entered_ipsq = B_FALSE;
26879 
26880 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26881 
26882 	if (ipip == NULL)
26883 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26884 
26885 	/*
26886 	 * SIOCLIFADDIF needs to go thru a special path since the
26887 	 * ill may not exist yet. This happens in the case of lo0
26888 	 * which is created using this ioctl.
26889 	 */
26890 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26891 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26892 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26893 		return;
26894 	}
26895 
26896 	ci.ci_ipif = NULL;
26897 	if (ipip->ipi_cmd_type == MISC_CMD) {
26898 		/*
26899 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
26900 		 */
26901 		if (ipip->ipi_cmd == IF_UNITSEL) {
26902 			/* ioctl comes down the ill */
26903 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
26904 			ipif_refhold(ci.ci_ipif);
26905 		}
26906 		err = 0;
26907 		ci.ci_sin = NULL;
26908 		ci.ci_sin6 = NULL;
26909 		ci.ci_lifr = NULL;
26910 	} else {
26911 		switch (ipip->ipi_cmd_type) {
26912 		case IF_CMD:
26913 		case LIF_CMD:
26914 			extract_funcp = ip_extract_lifreq;
26915 			break;
26916 
26917 		case ARP_CMD:
26918 		case XARP_CMD:
26919 			extract_funcp = ip_extract_arpreq;
26920 			break;
26921 
26922 		case TUN_CMD:
26923 			extract_funcp = ip_extract_tunreq;
26924 			break;
26925 
26926 		case MSFILT_CMD:
26927 			extract_funcp = ip_extract_msfilter;
26928 			break;
26929 
26930 		default:
26931 			ASSERT(0);
26932 		}
26933 
26934 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
26935 		if (err != 0) {
26936 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26937 			return;
26938 		}
26939 
26940 		/*
26941 		 * All of the extraction functions return a refheld ipif.
26942 		 */
26943 		ASSERT(ci.ci_ipif != NULL);
26944 	}
26945 
26946 	/*
26947 	 * If ipsq is non-null, we are already being called exclusively
26948 	 */
26949 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
26950 	if (!(ipip->ipi_flags & IPI_WR)) {
26951 		/*
26952 		 * A return value of EINPROGRESS means the ioctl is
26953 		 * either queued and waiting for some reason or has
26954 		 * already completed.
26955 		 */
26956 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
26957 		    ci.ci_lifr);
26958 		if (ci.ci_ipif != NULL)
26959 			ipif_refrele(ci.ci_ipif);
26960 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26961 		return;
26962 	}
26963 
26964 	ASSERT(ci.ci_ipif != NULL);
26965 
26966 	if (ipsq == NULL) {
26967 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
26968 		    ip_process_ioctl, NEW_OP, B_TRUE);
26969 		entered_ipsq = B_TRUE;
26970 	}
26971 	/*
26972 	 * Release the ipif so that ipif_down and friends that wait for
26973 	 * references to go away are not misled about the current ipif_refcnt
26974 	 * values. We are writer so we can access the ipif even after releasing
26975 	 * the ipif.
26976 	 */
26977 	ipif_refrele(ci.ci_ipif);
26978 	if (ipsq == NULL)
26979 		return;
26980 
26981 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
26982 
26983 	/*
26984 	 * For most set ioctls that come here, this serves as a single point
26985 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
26986 	 * be any new references to the ipif. This helps functions that go
26987 	 * through this path and end up trying to wait for the refcnts
26988 	 * associated with the ipif to go down to zero. Some exceptions are
26989 	 * Failover, Failback, and Groupname commands that operate on more than
26990 	 * just the ci.ci_ipif. These commands internally determine the
26991 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
26992 	 * flags on that set. Another exception is the Removeif command that
26993 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
26994 	 * ipif to operate on.
26995 	 */
26996 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
26997 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
26998 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
26999 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
27000 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
27001 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
27002 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
27003 
27004 	/*
27005 	 * A return value of EINPROGRESS means the ioctl is
27006 	 * either queued and waiting for some reason or has
27007 	 * already completed.
27008 	 */
27009 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
27010 
27011 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27012 
27013 	if (entered_ipsq)
27014 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
27015 }
27016 
27017 /*
27018  * Complete the ioctl. Typically ioctls use the mi package and need to
27019  * do mi_copyout/mi_copy_done.
27020  */
27021 void
27022 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
27023 {
27024 	conn_t	*connp = NULL;
27025 
27026 	if (err == EINPROGRESS)
27027 		return;
27028 
27029 	if (CONN_Q(q)) {
27030 		connp = Q_TO_CONN(q);
27031 		ASSERT(connp->conn_ref >= 2);
27032 	}
27033 
27034 	switch (mode) {
27035 	case COPYOUT:
27036 		if (err == 0)
27037 			mi_copyout(q, mp);
27038 		else
27039 			mi_copy_done(q, mp, err);
27040 		break;
27041 
27042 	case NO_COPYOUT:
27043 		mi_copy_done(q, mp, err);
27044 		break;
27045 
27046 	default:
27047 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27048 		break;
27049 	}
27050 
27051 	/*
27052 	 * The refhold placed at the start of the ioctl is released here.
27053 	 */
27054 	if (connp != NULL)
27055 		CONN_OPER_PENDING_DONE(connp);
27056 
27057 	if (ipsq != NULL)
27058 		ipsq_current_finish(ipsq);
27059 }
27060 
27061 /*
27062  * This is called from ip_wput_nondata to resume a deferred TCP bind.
27063  */
27064 /* ARGSUSED */
27065 void
27066 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
27067 {
27068 	conn_t *connp = arg;
27069 	tcp_t	*tcp;
27070 
27071 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
27072 	tcp = connp->conn_tcp;
27073 
27074 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
27075 		freemsg(mp);
27076 	else
27077 		tcp_rput_other(tcp, mp);
27078 	CONN_OPER_PENDING_DONE(connp);
27079 }
27080 
27081 /* Called from ip_wput for all non data messages */
27082 /* ARGSUSED */
27083 void
27084 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27085 {
27086 	mblk_t		*mp1;
27087 	ire_t		*ire, *fake_ire;
27088 	ill_t		*ill;
27089 	struct iocblk	*iocp;
27090 	ip_ioctl_cmd_t	*ipip;
27091 	cred_t		*cr;
27092 	conn_t		*connp;
27093 	int		err;
27094 	nce_t		*nce;
27095 	ipif_t		*ipif;
27096 	ip_stack_t	*ipst;
27097 	char		*proto_str;
27098 
27099 	if (CONN_Q(q)) {
27100 		connp = Q_TO_CONN(q);
27101 		ipst = connp->conn_netstack->netstack_ip;
27102 	} else {
27103 		connp = NULL;
27104 		ipst = ILLQ_TO_IPST(q);
27105 	}
27106 
27107 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
27108 
27109 	switch (DB_TYPE(mp)) {
27110 	case M_IOCTL:
27111 		/*
27112 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27113 		 * will arrange to copy in associated control structures.
27114 		 */
27115 		ip_sioctl_copyin_setup(q, mp);
27116 		return;
27117 	case M_IOCDATA:
27118 		/*
27119 		 * Ensure that this is associated with one of our trans-
27120 		 * parent ioctls.  If it's not ours, discard it if we're
27121 		 * running as a driver, or pass it on if we're a module.
27122 		 */
27123 		iocp = (struct iocblk *)mp->b_rptr;
27124 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27125 		if (ipip == NULL) {
27126 			if (q->q_next == NULL) {
27127 				goto nak;
27128 			} else {
27129 				putnext(q, mp);
27130 			}
27131 			return;
27132 		}
27133 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
27134 			/*
27135 			 * the ioctl is one we recognise, but is not
27136 			 * consumed by IP as a module, pass M_IOCDATA
27137 			 * for processing downstream, but only for
27138 			 * common Streams ioctls.
27139 			 */
27140 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27141 				putnext(q, mp);
27142 				return;
27143 			} else {
27144 				goto nak;
27145 			}
27146 		}
27147 
27148 		/* IOCTL continuation following copyin or copyout. */
27149 		if (mi_copy_state(q, mp, NULL) == -1) {
27150 			/*
27151 			 * The copy operation failed.  mi_copy_state already
27152 			 * cleaned up, so we're out of here.
27153 			 */
27154 			return;
27155 		}
27156 		/*
27157 		 * If we just completed a copy in, we become writer and
27158 		 * continue processing in ip_sioctl_copyin_done.  If it
27159 		 * was a copy out, we call mi_copyout again.  If there is
27160 		 * nothing more to copy out, it will complete the IOCTL.
27161 		 */
27162 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27163 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27164 				mi_copy_done(q, mp, EPROTO);
27165 				return;
27166 			}
27167 			/*
27168 			 * Check for cases that need more copying.  A return
27169 			 * value of 0 means a second copyin has been started,
27170 			 * so we return; a return value of 1 means no more
27171 			 * copying is needed, so we continue.
27172 			 */
27173 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27174 			    MI_COPY_COUNT(mp) == 1) {
27175 				if (ip_copyin_msfilter(q, mp) == 0)
27176 					return;
27177 			}
27178 			/*
27179 			 * Refhold the conn, till the ioctl completes. This is
27180 			 * needed in case the ioctl ends up in the pending mp
27181 			 * list. Every mp in the ill_pending_mp list and
27182 			 * the ipsq_pending_mp must have a refhold on the conn
27183 			 * to resume processing. The refhold is released when
27184 			 * the ioctl completes. (normally or abnormally)
27185 			 * In all cases ip_ioctl_finish is called to finish
27186 			 * the ioctl.
27187 			 */
27188 			if (connp != NULL) {
27189 				/* This is not a reentry */
27190 				ASSERT(ipsq == NULL);
27191 				CONN_INC_REF(connp);
27192 			} else {
27193 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27194 					mi_copy_done(q, mp, EINVAL);
27195 					return;
27196 				}
27197 			}
27198 
27199 			ip_process_ioctl(ipsq, q, mp, ipip);
27200 
27201 		} else {
27202 			mi_copyout(q, mp);
27203 		}
27204 		return;
27205 nak:
27206 		iocp->ioc_error = EINVAL;
27207 		mp->b_datap->db_type = M_IOCNAK;
27208 		iocp->ioc_count = 0;
27209 		qreply(q, mp);
27210 		return;
27211 
27212 	case M_IOCNAK:
27213 		/*
27214 		 * The only way we could get here is if a resolver didn't like
27215 		 * an IOCTL we sent it.	 This shouldn't happen.
27216 		 */
27217 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27218 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27219 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27220 		freemsg(mp);
27221 		return;
27222 	case M_IOCACK:
27223 		/* /dev/ip shouldn't see this */
27224 		if (CONN_Q(q))
27225 			goto nak;
27226 
27227 		/* Finish socket ioctls passed through to ARP. */
27228 		ip_sioctl_iocack(q, mp);
27229 		return;
27230 	case M_FLUSH:
27231 		if (*mp->b_rptr & FLUSHW)
27232 			flushq(q, FLUSHALL);
27233 		if (q->q_next) {
27234 			putnext(q, mp);
27235 			return;
27236 		}
27237 		if (*mp->b_rptr & FLUSHR) {
27238 			*mp->b_rptr &= ~FLUSHW;
27239 			qreply(q, mp);
27240 			return;
27241 		}
27242 		freemsg(mp);
27243 		return;
27244 	case IRE_DB_REQ_TYPE:
27245 		if (connp == NULL) {
27246 			proto_str = "IRE_DB_REQ_TYPE";
27247 			goto protonak;
27248 		}
27249 		/* An Upper Level Protocol wants a copy of an IRE. */
27250 		ip_ire_req(q, mp);
27251 		return;
27252 	case M_CTL:
27253 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27254 			break;
27255 
27256 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27257 		    TUN_HELLO) {
27258 			ASSERT(connp != NULL);
27259 			connp->conn_flags |= IPCL_IPTUN;
27260 			freeb(mp);
27261 			return;
27262 		}
27263 
27264 		/* M_CTL messages are used by ARP to tell us things. */
27265 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27266 			break;
27267 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27268 		case AR_ENTRY_SQUERY:
27269 			ip_wput_ctl(q, mp);
27270 			return;
27271 		case AR_CLIENT_NOTIFY:
27272 			ip_arp_news(q, mp);
27273 			return;
27274 		case AR_DLPIOP_DONE:
27275 			ASSERT(q->q_next != NULL);
27276 			ill = (ill_t *)q->q_ptr;
27277 			/* qwriter_ip releases the refhold */
27278 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27279 			ill_refhold(ill);
27280 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27281 			return;
27282 		case AR_ARP_CLOSING:
27283 			/*
27284 			 * ARP (above us) is closing. If no ARP bringup is
27285 			 * currently pending, ack the message so that ARP
27286 			 * can complete its close. Also mark ill_arp_closing
27287 			 * so that new ARP bringups will fail. If any
27288 			 * ARP bringup is currently in progress, we will
27289 			 * ack this when the current ARP bringup completes.
27290 			 */
27291 			ASSERT(q->q_next != NULL);
27292 			ill = (ill_t *)q->q_ptr;
27293 			mutex_enter(&ill->ill_lock);
27294 			ill->ill_arp_closing = 1;
27295 			if (!ill->ill_arp_bringup_pending) {
27296 				mutex_exit(&ill->ill_lock);
27297 				qreply(q, mp);
27298 			} else {
27299 				mutex_exit(&ill->ill_lock);
27300 				freemsg(mp);
27301 			}
27302 			return;
27303 		case AR_ARP_EXTEND:
27304 			/*
27305 			 * The ARP module above us is capable of duplicate
27306 			 * address detection.  Old ATM drivers will not send
27307 			 * this message.
27308 			 */
27309 			ASSERT(q->q_next != NULL);
27310 			ill = (ill_t *)q->q_ptr;
27311 			ill->ill_arp_extend = B_TRUE;
27312 			freemsg(mp);
27313 			return;
27314 		default:
27315 			break;
27316 		}
27317 		break;
27318 	case M_PROTO:
27319 	case M_PCPROTO:
27320 		/*
27321 		 * The only PROTO messages we expect are ULP binds and
27322 		 * copies of option negotiation acknowledgements.
27323 		 */
27324 		switch (((union T_primitives *)mp->b_rptr)->type) {
27325 		case O_T_BIND_REQ:
27326 		case T_BIND_REQ: {
27327 			/* Request can get queued in bind */
27328 			if (connp == NULL) {
27329 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27330 				goto protonak;
27331 			}
27332 			/*
27333 			 * The transports except SCTP call ip_bind_{v4,v6}()
27334 			 * directly instead of a a putnext. SCTP doesn't
27335 			 * generate any T_BIND_REQ since it has its own
27336 			 * fanout data structures. However, ESP and AH
27337 			 * come in for regular binds; all other cases are
27338 			 * bind retries.
27339 			 */
27340 			ASSERT(!IPCL_IS_SCTP(connp));
27341 
27342 			/* Don't increment refcnt if this is a re-entry */
27343 			if (ipsq == NULL)
27344 				CONN_INC_REF(connp);
27345 
27346 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27347 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27348 			if (mp == NULL)
27349 				return;
27350 			if (IPCL_IS_TCP(connp)) {
27351 				/*
27352 				 * In the case of TCP endpoint we
27353 				 * come here only for bind retries
27354 				 */
27355 				ASSERT(ipsq != NULL);
27356 				CONN_INC_REF(connp);
27357 				squeue_fill(connp->conn_sqp, mp,
27358 				    ip_resume_tcp_bind, connp,
27359 				    SQTAG_BIND_RETRY);
27360 			} else if (IPCL_IS_UDP(connp)) {
27361 				/*
27362 				 * In the case of UDP endpoint we
27363 				 * come here only for bind retries
27364 				 */
27365 				ASSERT(ipsq != NULL);
27366 				udp_resume_bind(connp, mp);
27367 			} else if (IPCL_IS_RAWIP(connp)) {
27368 				/*
27369 				 * In the case of RAWIP endpoint we
27370 				 * come here only for bind retries
27371 				 */
27372 				ASSERT(ipsq != NULL);
27373 				rawip_resume_bind(connp, mp);
27374 			} else {
27375 				/* The case of AH and ESP */
27376 				qreply(q, mp);
27377 				CONN_OPER_PENDING_DONE(connp);
27378 			}
27379 			return;
27380 		}
27381 		case T_SVR4_OPTMGMT_REQ:
27382 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27383 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27384 
27385 			if (connp == NULL) {
27386 				proto_str = "T_SVR4_OPTMGMT_REQ";
27387 				goto protonak;
27388 			}
27389 
27390 			if (!snmpcom_req(q, mp, ip_snmp_set,
27391 			    ip_snmp_get, cr)) {
27392 				/*
27393 				 * Call svr4_optcom_req so that it can
27394 				 * generate the ack. We don't come here
27395 				 * if this operation is being restarted.
27396 				 * ip_restart_optmgmt will drop the conn ref.
27397 				 * In the case of ipsec option after the ipsec
27398 				 * load is complete conn_restart_ipsec_waiter
27399 				 * drops the conn ref.
27400 				 */
27401 				ASSERT(ipsq == NULL);
27402 				CONN_INC_REF(connp);
27403 				if (ip_check_for_ipsec_opt(q, mp))
27404 					return;
27405 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj,
27406 				    B_FALSE);
27407 				if (err != EINPROGRESS) {
27408 					/* Operation is done */
27409 					CONN_OPER_PENDING_DONE(connp);
27410 				}
27411 			}
27412 			return;
27413 		case T_OPTMGMT_REQ:
27414 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27415 			/*
27416 			 * Note: No snmpcom_req support through new
27417 			 * T_OPTMGMT_REQ.
27418 			 * Call tpi_optcom_req so that it can
27419 			 * generate the ack.
27420 			 */
27421 			if (connp == NULL) {
27422 				proto_str = "T_OPTMGMT_REQ";
27423 				goto protonak;
27424 			}
27425 
27426 			ASSERT(ipsq == NULL);
27427 			/*
27428 			 * We don't come here for restart. ip_restart_optmgmt
27429 			 * will drop the conn ref. In the case of ipsec option
27430 			 * after the ipsec load is complete
27431 			 * conn_restart_ipsec_waiter drops the conn ref.
27432 			 */
27433 			CONN_INC_REF(connp);
27434 			if (ip_check_for_ipsec_opt(q, mp))
27435 				return;
27436 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj, B_FALSE);
27437 			if (err != EINPROGRESS) {
27438 				/* Operation is done */
27439 				CONN_OPER_PENDING_DONE(connp);
27440 			}
27441 			return;
27442 		case T_UNBIND_REQ:
27443 			if (connp == NULL) {
27444 				proto_str = "T_UNBIND_REQ";
27445 				goto protonak;
27446 			}
27447 			mp = ip_unbind(q, mp);
27448 			qreply(q, mp);
27449 			return;
27450 		default:
27451 			/*
27452 			 * Have to drop any DLPI messages coming down from
27453 			 * arp (such as an info_req which would cause ip
27454 			 * to receive an extra info_ack if it was passed
27455 			 * through.
27456 			 */
27457 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27458 			    (int)*(uint_t *)mp->b_rptr));
27459 			freemsg(mp);
27460 			return;
27461 		}
27462 		/* NOTREACHED */
27463 	case IRE_DB_TYPE: {
27464 		nce_t		*nce;
27465 		ill_t		*ill;
27466 		in6_addr_t	gw_addr_v6;
27467 
27468 
27469 		/*
27470 		 * This is a response back from a resolver.  It
27471 		 * consists of a message chain containing:
27472 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27473 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27474 		 * The LL_HDR_MBLK is the DLPI header to use to get
27475 		 * the attached packet, and subsequent ones for the
27476 		 * same destination, transmitted.
27477 		 */
27478 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27479 			break;
27480 		/*
27481 		 * First, check to make sure the resolution succeeded.
27482 		 * If it failed, the second mblk will be empty.
27483 		 * If it is, free the chain, dropping the packet.
27484 		 * (We must ire_delete the ire; that frees the ire mblk)
27485 		 * We're doing this now to support PVCs for ATM; it's
27486 		 * a partial xresolv implementation. When we fully implement
27487 		 * xresolv interfaces, instead of freeing everything here
27488 		 * we'll initiate neighbor discovery.
27489 		 *
27490 		 * For v4 (ARP and other external resolvers) the resolver
27491 		 * frees the message, so no check is needed. This check
27492 		 * is required, though, for a full xresolve implementation.
27493 		 * Including this code here now both shows how external
27494 		 * resolvers can NACK a resolution request using an
27495 		 * existing design that has no specific provisions for NACKs,
27496 		 * and also takes into account that the current non-ARP
27497 		 * external resolver has been coded to use this method of
27498 		 * NACKing for all IPv6 (xresolv) cases,
27499 		 * whether our xresolv implementation is complete or not.
27500 		 *
27501 		 */
27502 		ire = (ire_t *)mp->b_rptr;
27503 		ill = ire_to_ill(ire);
27504 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27505 		if (mp1->b_rptr == mp1->b_wptr) {
27506 			if (ire->ire_ipversion == IPV6_VERSION) {
27507 				/*
27508 				 * XRESOLV interface.
27509 				 */
27510 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27511 				mutex_enter(&ire->ire_lock);
27512 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27513 				mutex_exit(&ire->ire_lock);
27514 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27515 					nce = ndp_lookup_v6(ill,
27516 					    &ire->ire_addr_v6, B_FALSE);
27517 				} else {
27518 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
27519 					    B_FALSE);
27520 				}
27521 				if (nce != NULL) {
27522 					nce_resolv_failed(nce);
27523 					ndp_delete(nce);
27524 					NCE_REFRELE(nce);
27525 				}
27526 			}
27527 			mp->b_cont = NULL;
27528 			freemsg(mp1);		/* frees the pkt as well */
27529 			ASSERT(ire->ire_nce == NULL);
27530 			ire_delete((ire_t *)mp->b_rptr);
27531 			return;
27532 		}
27533 
27534 		/*
27535 		 * Split them into IRE_MBLK and pkt and feed it into
27536 		 * ire_add_then_send. Then in ire_add_then_send
27537 		 * the IRE will be added, and then the packet will be
27538 		 * run back through ip_wput. This time it will make
27539 		 * it to the wire.
27540 		 */
27541 		mp->b_cont = NULL;
27542 		mp = mp1->b_cont;		/* now, mp points to pkt */
27543 		mp1->b_cont = NULL;
27544 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27545 		if (ire->ire_ipversion == IPV6_VERSION) {
27546 			/*
27547 			 * XRESOLV interface. Find the nce and put a copy
27548 			 * of the dl_unitdata_req in nce_res_mp
27549 			 */
27550 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27551 			mutex_enter(&ire->ire_lock);
27552 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27553 			mutex_exit(&ire->ire_lock);
27554 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27555 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
27556 				    B_FALSE);
27557 			} else {
27558 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
27559 			}
27560 			if (nce != NULL) {
27561 				/*
27562 				 * We have to protect nce_res_mp here
27563 				 * from being accessed by other threads
27564 				 * while we change the mblk pointer.
27565 				 * Other functions will also lock the nce when
27566 				 * accessing nce_res_mp.
27567 				 *
27568 				 * The reason we change the mblk pointer
27569 				 * here rather than copying the resolved address
27570 				 * into the template is that, unlike with
27571 				 * ethernet, we have no guarantee that the
27572 				 * resolved address length will be
27573 				 * smaller than or equal to the lla length
27574 				 * with which the template was allocated,
27575 				 * (for ethernet, they're equal)
27576 				 * so we have to use the actual resolved
27577 				 * address mblk - which holds the real
27578 				 * dl_unitdata_req with the resolved address.
27579 				 *
27580 				 * Doing this is the same behavior as was
27581 				 * previously used in the v4 ARP case.
27582 				 */
27583 				mutex_enter(&nce->nce_lock);
27584 				if (nce->nce_res_mp != NULL)
27585 					freemsg(nce->nce_res_mp);
27586 				nce->nce_res_mp = mp1;
27587 				mutex_exit(&nce->nce_lock);
27588 				/*
27589 				 * We do a fastpath probe here because
27590 				 * we have resolved the address without
27591 				 * using Neighbor Discovery.
27592 				 * In the non-XRESOLV v6 case, the fastpath
27593 				 * probe is done right after neighbor
27594 				 * discovery completes.
27595 				 */
27596 				if (nce->nce_res_mp != NULL) {
27597 					int res;
27598 					nce_fastpath_list_add(nce);
27599 					res = ill_fastpath_probe(ill,
27600 					    nce->nce_res_mp);
27601 					if (res != 0 && res != EAGAIN)
27602 						nce_fastpath_list_delete(nce);
27603 				}
27604 
27605 				ire_add_then_send(q, ire, mp);
27606 				/*
27607 				 * Now we have to clean out any packets
27608 				 * that may have been queued on the nce
27609 				 * while it was waiting for address resolution
27610 				 * to complete.
27611 				 */
27612 				mutex_enter(&nce->nce_lock);
27613 				mp1 = nce->nce_qd_mp;
27614 				nce->nce_qd_mp = NULL;
27615 				mutex_exit(&nce->nce_lock);
27616 				while (mp1 != NULL) {
27617 					mblk_t *nxt_mp;
27618 					queue_t *fwdq = NULL;
27619 					ill_t   *inbound_ill;
27620 					uint_t ifindex;
27621 
27622 					nxt_mp = mp1->b_next;
27623 					mp1->b_next = NULL;
27624 					/*
27625 					 * Retrieve ifindex stored in
27626 					 * ip_rput_data_v6()
27627 					 */
27628 					ifindex =
27629 					    (uint_t)(uintptr_t)mp1->b_prev;
27630 					inbound_ill =
27631 					    ill_lookup_on_ifindex(ifindex,
27632 					    B_TRUE, NULL, NULL, NULL,
27633 					    NULL, ipst);
27634 					mp1->b_prev = NULL;
27635 					if (inbound_ill != NULL)
27636 						fwdq = inbound_ill->ill_rq;
27637 
27638 					if (fwdq != NULL) {
27639 						put(fwdq, mp1);
27640 						ill_refrele(inbound_ill);
27641 					} else
27642 						put(WR(ill->ill_rq), mp1);
27643 					mp1 = nxt_mp;
27644 				}
27645 				NCE_REFRELE(nce);
27646 			} else {	/* nce is NULL; clean up */
27647 				ire_delete(ire);
27648 				freemsg(mp);
27649 				freemsg(mp1);
27650 				return;
27651 			}
27652 		} else {
27653 			nce_t *arpce;
27654 			/*
27655 			 * Link layer resolution succeeded. Recompute the
27656 			 * ire_nce.
27657 			 */
27658 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27659 			if ((arpce = ndp_lookup_v4(ill,
27660 			    (ire->ire_gateway_addr != INADDR_ANY ?
27661 			    &ire->ire_gateway_addr : &ire->ire_addr),
27662 			    B_FALSE)) == NULL) {
27663 				freeb(ire->ire_mp);
27664 				freeb(mp1);
27665 				freemsg(mp);
27666 				return;
27667 			}
27668 			mutex_enter(&arpce->nce_lock);
27669 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27670 			if (arpce->nce_state == ND_REACHABLE) {
27671 				/*
27672 				 * Someone resolved this before us;
27673 				 * cleanup the res_mp. Since ire has
27674 				 * not been added yet, the call to ire_add_v4
27675 				 * from ire_add_then_send (when a dup is
27676 				 * detected) will clean up the ire.
27677 				 */
27678 				freeb(mp1);
27679 			} else {
27680 				ASSERT(arpce->nce_res_mp == NULL);
27681 				arpce->nce_res_mp = mp1;
27682 				arpce->nce_state = ND_REACHABLE;
27683 			}
27684 			mutex_exit(&arpce->nce_lock);
27685 			if (ire->ire_marks & IRE_MARK_NOADD) {
27686 				/*
27687 				 * this ire will not be added to the ire
27688 				 * cache table, so we can set the ire_nce
27689 				 * here, as there are no atomicity constraints.
27690 				 */
27691 				ire->ire_nce = arpce;
27692 				/*
27693 				 * We are associating this nce with the ire
27694 				 * so change the nce ref taken in
27695 				 * ndp_lookup_v4() from
27696 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27697 				 */
27698 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27699 			} else {
27700 				NCE_REFRELE(arpce);
27701 			}
27702 			ire_add_then_send(q, ire, mp);
27703 		}
27704 		return;	/* All is well, the packet has been sent. */
27705 	}
27706 	case IRE_ARPRESOLVE_TYPE: {
27707 
27708 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27709 			break;
27710 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27711 		mp->b_cont = NULL;
27712 		/*
27713 		 * First, check to make sure the resolution succeeded.
27714 		 * If it failed, the second mblk will be empty.
27715 		 */
27716 		if (mp1->b_rptr == mp1->b_wptr) {
27717 			/* cleanup  the incomplete ire, free queued packets */
27718 			freemsg(mp); /* fake ire */
27719 			freeb(mp1);  /* dl_unitdata response */
27720 			return;
27721 		}
27722 
27723 		/*
27724 		 * update any incomplete nce_t found. we lookup the ctable
27725 		 * and find the nce from the ire->ire_nce because we need
27726 		 * to pass the ire to ip_xmit_v4 later, and can find both
27727 		 * ire and nce in one lookup from the ctable.
27728 		 */
27729 		fake_ire = (ire_t *)mp->b_rptr;
27730 		/*
27731 		 * By the time we come back here from ARP
27732 		 * the logical outgoing interface  of the incomplete ire
27733 		 * we added in ire_forward could have disappeared,
27734 		 * causing the incomplete ire to also have
27735 		 * dissapeared. So we need to retreive the
27736 		 * proper ipif for the ire  before looking
27737 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
27738 		 */
27739 		ill = q->q_ptr;
27740 
27741 		/* Get the outgoing ipif */
27742 		mutex_enter(&ill->ill_lock);
27743 		if (ill->ill_state_flags & ILL_CONDEMNED) {
27744 			mutex_exit(&ill->ill_lock);
27745 			freemsg(mp); /* fake ire */
27746 			freeb(mp1);  /* dl_unitdata response */
27747 			return;
27748 		}
27749 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27750 
27751 		if (ipif == NULL) {
27752 			mutex_exit(&ill->ill_lock);
27753 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27754 			freemsg(mp);
27755 			freeb(mp1);
27756 			return;
27757 		}
27758 		ipif_refhold_locked(ipif);
27759 		mutex_exit(&ill->ill_lock);
27760 		ire = ire_ctable_lookup(fake_ire->ire_addr,
27761 		    fake_ire->ire_gateway_addr, IRE_CACHE,
27762 		    ipif, fake_ire->ire_zoneid, NULL,
27763 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY), ipst);
27764 		ipif_refrele(ipif);
27765 		if (ire == NULL) {
27766 			/*
27767 			 * no ire was found; check if there is an nce
27768 			 * for this lookup; if it has no ire's pointing at it
27769 			 * cleanup.
27770 			 */
27771 			if ((nce = ndp_lookup_v4(ill,
27772 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27773 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27774 			    B_FALSE)) != NULL) {
27775 				/*
27776 				 * cleanup:
27777 				 * We check for refcnt 2 (one for the nce
27778 				 * hash list + 1 for the ref taken by
27779 				 * ndp_lookup_v4) to check that there are
27780 				 * no ire's pointing at the nce.
27781 				 */
27782 				if (nce->nce_refcnt == 2)
27783 					ndp_delete(nce);
27784 				NCE_REFRELE(nce);
27785 			}
27786 			freeb(mp1);  /* dl_unitdata response */
27787 			freemsg(mp); /* fake ire */
27788 			return;
27789 		}
27790 		nce = ire->ire_nce;
27791 		DTRACE_PROBE2(ire__arpresolve__type,
27792 		    ire_t *, ire, nce_t *, nce);
27793 		ASSERT(nce->nce_state != ND_INITIAL);
27794 		mutex_enter(&nce->nce_lock);
27795 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27796 		if (nce->nce_state == ND_REACHABLE) {
27797 			/*
27798 			 * Someone resolved this before us;
27799 			 * our response is not needed any more.
27800 			 */
27801 			mutex_exit(&nce->nce_lock);
27802 			freeb(mp1);  /* dl_unitdata response */
27803 		} else {
27804 			ASSERT(nce->nce_res_mp == NULL);
27805 			nce->nce_res_mp = mp1;
27806 			nce->nce_state = ND_REACHABLE;
27807 			mutex_exit(&nce->nce_lock);
27808 			nce_fastpath(nce);
27809 		}
27810 		/*
27811 		 * The cached nce_t has been updated to be reachable;
27812 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
27813 		 */
27814 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27815 		freemsg(mp);
27816 		/*
27817 		 * send out queued packets.
27818 		 */
27819 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
27820 
27821 		IRE_REFRELE(ire);
27822 		return;
27823 	}
27824 	default:
27825 		break;
27826 	}
27827 	if (q->q_next) {
27828 		putnext(q, mp);
27829 	} else
27830 		freemsg(mp);
27831 	return;
27832 
27833 protonak:
27834 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
27835 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
27836 		qreply(q, mp);
27837 }
27838 
27839 /*
27840  * Process IP options in an outbound packet.  Modify the destination if there
27841  * is a source route option.
27842  * Returns non-zero if something fails in which case an ICMP error has been
27843  * sent and mp freed.
27844  */
27845 static int
27846 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27847     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
27848 {
27849 	ipoptp_t	opts;
27850 	uchar_t		*opt;
27851 	uint8_t		optval;
27852 	uint8_t		optlen;
27853 	ipaddr_t	dst;
27854 	intptr_t	code = 0;
27855 	mblk_t		*mp;
27856 	ire_t		*ire = NULL;
27857 
27858 	ip2dbg(("ip_wput_options\n"));
27859 	mp = ipsec_mp;
27860 	if (mctl_present) {
27861 		mp = ipsec_mp->b_cont;
27862 	}
27863 
27864 	dst = ipha->ipha_dst;
27865 	for (optval = ipoptp_first(&opts, ipha);
27866 	    optval != IPOPT_EOL;
27867 	    optval = ipoptp_next(&opts)) {
27868 		opt = opts.ipoptp_cur;
27869 		optlen = opts.ipoptp_len;
27870 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27871 		    optval, optlen));
27872 		switch (optval) {
27873 			uint32_t off;
27874 		case IPOPT_SSRR:
27875 		case IPOPT_LSRR:
27876 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27877 				ip1dbg((
27878 				    "ip_wput_options: bad option offset\n"));
27879 				code = (char *)&opt[IPOPT_OLEN] -
27880 				    (char *)ipha;
27881 				goto param_prob;
27882 			}
27883 			off = opt[IPOPT_OFFSET];
27884 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27885 			    ntohl(dst)));
27886 			/*
27887 			 * For strict: verify that dst is directly
27888 			 * reachable.
27889 			 */
27890 			if (optval == IPOPT_SSRR) {
27891 				ire = ire_ftable_lookup(dst, 0, 0,
27892 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27893 				    MBLK_GETLABEL(mp),
27894 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
27895 				if (ire == NULL) {
27896 					ip1dbg(("ip_wput_options: SSRR not"
27897 					    " directly reachable: 0x%x\n",
27898 					    ntohl(dst)));
27899 					goto bad_src_route;
27900 				}
27901 				ire_refrele(ire);
27902 			}
27903 			break;
27904 		case IPOPT_RR:
27905 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27906 				ip1dbg((
27907 				    "ip_wput_options: bad option offset\n"));
27908 				code = (char *)&opt[IPOPT_OLEN] -
27909 				    (char *)ipha;
27910 				goto param_prob;
27911 			}
27912 			break;
27913 		case IPOPT_TS:
27914 			/*
27915 			 * Verify that length >=5 and that there is either
27916 			 * room for another timestamp or that the overflow
27917 			 * counter is not maxed out.
27918 			 */
27919 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
27920 			if (optlen < IPOPT_MINLEN_IT) {
27921 				goto param_prob;
27922 			}
27923 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27924 				ip1dbg((
27925 				    "ip_wput_options: bad option offset\n"));
27926 				code = (char *)&opt[IPOPT_OFFSET] -
27927 				    (char *)ipha;
27928 				goto param_prob;
27929 			}
27930 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
27931 			case IPOPT_TS_TSONLY:
27932 				off = IPOPT_TS_TIMELEN;
27933 				break;
27934 			case IPOPT_TS_TSANDADDR:
27935 			case IPOPT_TS_PRESPEC:
27936 			case IPOPT_TS_PRESPEC_RFC791:
27937 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
27938 				break;
27939 			default:
27940 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
27941 				    (char *)ipha;
27942 				goto param_prob;
27943 			}
27944 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
27945 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
27946 				/*
27947 				 * No room and the overflow counter is 15
27948 				 * already.
27949 				 */
27950 				goto param_prob;
27951 			}
27952 			break;
27953 		}
27954 	}
27955 
27956 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
27957 		return (0);
27958 
27959 	ip1dbg(("ip_wput_options: error processing IP options."));
27960 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
27961 
27962 param_prob:
27963 	/*
27964 	 * Since ip_wput() isn't close to finished, we fill
27965 	 * in enough of the header for credible error reporting.
27966 	 */
27967 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
27968 		/* Failed */
27969 		freemsg(ipsec_mp);
27970 		return (-1);
27971 	}
27972 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
27973 	return (-1);
27974 
27975 bad_src_route:
27976 	/*
27977 	 * Since ip_wput() isn't close to finished, we fill
27978 	 * in enough of the header for credible error reporting.
27979 	 */
27980 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
27981 		/* Failed */
27982 		freemsg(ipsec_mp);
27983 		return (-1);
27984 	}
27985 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
27986 	return (-1);
27987 }
27988 
27989 /*
27990  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
27991  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
27992  * thru /etc/system.
27993  */
27994 #define	CONN_MAXDRAINCNT	64
27995 
27996 static void
27997 conn_drain_init(ip_stack_t *ipst)
27998 {
27999 	int i;
28000 
28001 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
28002 
28003 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
28004 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
28005 		/*
28006 		 * Default value of the number of drainers is the
28007 		 * number of cpus, subject to maximum of 8 drainers.
28008 		 */
28009 		if (boot_max_ncpus != -1)
28010 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
28011 		else
28012 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
28013 	}
28014 
28015 	ipst->ips_conn_drain_list = kmem_zalloc(ipst->ips_conn_drain_list_cnt *
28016 	    sizeof (idl_t), KM_SLEEP);
28017 
28018 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28019 		mutex_init(&ipst->ips_conn_drain_list[i].idl_lock, NULL,
28020 		    MUTEX_DEFAULT, NULL);
28021 	}
28022 }
28023 
28024 static void
28025 conn_drain_fini(ip_stack_t *ipst)
28026 {
28027 	int i;
28028 
28029 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++)
28030 		mutex_destroy(&ipst->ips_conn_drain_list[i].idl_lock);
28031 	kmem_free(ipst->ips_conn_drain_list,
28032 	    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28033 	ipst->ips_conn_drain_list = NULL;
28034 }
28035 
28036 /*
28037  * Note: For an overview of how flowcontrol is handled in IP please see the
28038  * IP Flowcontrol notes at the top of this file.
28039  *
28040  * Flow control has blocked us from proceeding. Insert the given conn in one
28041  * of the conn drain lists. These conn wq's will be qenabled later on when
28042  * STREAMS flow control does a backenable. conn_walk_drain will enable
28043  * the first conn in each of these drain lists. Each of these qenabled conns
28044  * in turn enables the next in the list, after it runs, or when it closes,
28045  * thus sustaining the drain process.
28046  *
28047  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
28048  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
28049  * running at any time, on a given conn, since there can be only 1 service proc
28050  * running on a queue at any time.
28051  */
28052 void
28053 conn_drain_insert(conn_t *connp)
28054 {
28055 	idl_t	*idl;
28056 	uint_t	index;
28057 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28058 
28059 	mutex_enter(&connp->conn_lock);
28060 	if (connp->conn_state_flags & CONN_CLOSING) {
28061 		/*
28062 		 * The conn is closing as a result of which CONN_CLOSING
28063 		 * is set. Return.
28064 		 */
28065 		mutex_exit(&connp->conn_lock);
28066 		return;
28067 	} else if (connp->conn_idl == NULL) {
28068 		/*
28069 		 * Assign the next drain list round robin. We dont' use
28070 		 * a lock, and thus it may not be strictly round robin.
28071 		 * Atomicity of load/stores is enough to make sure that
28072 		 * conn_drain_list_index is always within bounds.
28073 		 */
28074 		index = ipst->ips_conn_drain_list_index;
28075 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28076 		connp->conn_idl = &ipst->ips_conn_drain_list[index];
28077 		index++;
28078 		if (index == ipst->ips_conn_drain_list_cnt)
28079 			index = 0;
28080 		ipst->ips_conn_drain_list_index = index;
28081 	}
28082 	mutex_exit(&connp->conn_lock);
28083 
28084 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28085 	if ((connp->conn_drain_prev != NULL) ||
28086 	    (connp->conn_state_flags & CONN_CLOSING)) {
28087 		/*
28088 		 * The conn is already in the drain list, OR
28089 		 * the conn is closing. We need to check again for
28090 		 * the closing case again since close can happen
28091 		 * after we drop the conn_lock, and before we
28092 		 * acquire the CONN_DRAIN_LIST_LOCK.
28093 		 */
28094 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28095 		return;
28096 	} else {
28097 		idl = connp->conn_idl;
28098 	}
28099 
28100 	/*
28101 	 * The conn is not in the drain list. Insert it at the
28102 	 * tail of the drain list. The drain list is circular
28103 	 * and doubly linked. idl_conn points to the 1st element
28104 	 * in the list.
28105 	 */
28106 	if (idl->idl_conn == NULL) {
28107 		idl->idl_conn = connp;
28108 		connp->conn_drain_next = connp;
28109 		connp->conn_drain_prev = connp;
28110 	} else {
28111 		conn_t *head = idl->idl_conn;
28112 
28113 		connp->conn_drain_next = head;
28114 		connp->conn_drain_prev = head->conn_drain_prev;
28115 		head->conn_drain_prev->conn_drain_next = connp;
28116 		head->conn_drain_prev = connp;
28117 	}
28118 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28119 }
28120 
28121 /*
28122  * This conn is closing, and we are called from ip_close. OR
28123  * This conn has been serviced by ip_wsrv, and we need to do the tail
28124  * processing.
28125  * If this conn is part of the drain list, we may need to sustain the drain
28126  * process by qenabling the next conn in the drain list. We may also need to
28127  * remove this conn from the list, if it is done.
28128  */
28129 static void
28130 conn_drain_tail(conn_t *connp, boolean_t closing)
28131 {
28132 	idl_t *idl;
28133 
28134 	/*
28135 	 * connp->conn_idl is stable at this point, and no lock is needed
28136 	 * to check it. If we are called from ip_close, close has already
28137 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28138 	 * called us only because conn_idl is non-null. If we are called thru
28139 	 * service, conn_idl could be null, but it cannot change because
28140 	 * service is single-threaded per queue, and there cannot be another
28141 	 * instance of service trying to call conn_drain_insert on this conn
28142 	 * now.
28143 	 */
28144 	ASSERT(!closing || (connp->conn_idl != NULL));
28145 
28146 	/*
28147 	 * If connp->conn_idl is null, the conn has not been inserted into any
28148 	 * drain list even once since creation of the conn. Just return.
28149 	 */
28150 	if (connp->conn_idl == NULL)
28151 		return;
28152 
28153 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28154 
28155 	if (connp->conn_drain_prev == NULL) {
28156 		/* This conn is currently not in the drain list.  */
28157 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28158 		return;
28159 	}
28160 	idl = connp->conn_idl;
28161 	if (idl->idl_conn_draining == connp) {
28162 		/*
28163 		 * This conn is the current drainer. If this is the last conn
28164 		 * in the drain list, we need to do more checks, in the 'if'
28165 		 * below. Otherwwise we need to just qenable the next conn,
28166 		 * to sustain the draining, and is handled in the 'else'
28167 		 * below.
28168 		 */
28169 		if (connp->conn_drain_next == idl->idl_conn) {
28170 			/*
28171 			 * This conn is the last in this list. This round
28172 			 * of draining is complete. If idl_repeat is set,
28173 			 * it means another flow enabling has happened from
28174 			 * the driver/streams and we need to another round
28175 			 * of draining.
28176 			 * If there are more than 2 conns in the drain list,
28177 			 * do a left rotate by 1, so that all conns except the
28178 			 * conn at the head move towards the head by 1, and the
28179 			 * the conn at the head goes to the tail. This attempts
28180 			 * a more even share for all queues that are being
28181 			 * drained.
28182 			 */
28183 			if ((connp->conn_drain_next != connp) &&
28184 			    (idl->idl_conn->conn_drain_next != connp)) {
28185 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28186 			}
28187 			if (idl->idl_repeat) {
28188 				qenable(idl->idl_conn->conn_wq);
28189 				idl->idl_conn_draining = idl->idl_conn;
28190 				idl->idl_repeat = 0;
28191 			} else {
28192 				idl->idl_conn_draining = NULL;
28193 			}
28194 		} else {
28195 			/*
28196 			 * If the next queue that we are now qenable'ing,
28197 			 * is closing, it will remove itself from this list
28198 			 * and qenable the subsequent queue in ip_close().
28199 			 * Serialization is acheived thru idl_lock.
28200 			 */
28201 			qenable(connp->conn_drain_next->conn_wq);
28202 			idl->idl_conn_draining = connp->conn_drain_next;
28203 		}
28204 	}
28205 	if (!connp->conn_did_putbq || closing) {
28206 		/*
28207 		 * Remove ourself from the drain list, if we did not do
28208 		 * a putbq, or if the conn is closing.
28209 		 * Note: It is possible that q->q_first is non-null. It means
28210 		 * that these messages landed after we did a enableok() in
28211 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28212 		 * service them.
28213 		 */
28214 		if (connp->conn_drain_next == connp) {
28215 			/* Singleton in the list */
28216 			ASSERT(connp->conn_drain_prev == connp);
28217 			idl->idl_conn = NULL;
28218 			idl->idl_conn_draining = NULL;
28219 		} else {
28220 			connp->conn_drain_prev->conn_drain_next =
28221 			    connp->conn_drain_next;
28222 			connp->conn_drain_next->conn_drain_prev =
28223 			    connp->conn_drain_prev;
28224 			if (idl->idl_conn == connp)
28225 				idl->idl_conn = connp->conn_drain_next;
28226 			ASSERT(idl->idl_conn_draining != connp);
28227 
28228 		}
28229 		connp->conn_drain_next = NULL;
28230 		connp->conn_drain_prev = NULL;
28231 	}
28232 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28233 }
28234 
28235 /*
28236  * Write service routine. Shared perimeter entry point.
28237  * ip_wsrv can be called in any of the following ways.
28238  * 1. The device queue's messages has fallen below the low water mark
28239  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28240  *    the drain lists and backenable the first conn in each list.
28241  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28242  *    qenabled non-tcp upper layers. We start dequeing messages and call
28243  *    ip_wput for each message.
28244  */
28245 
28246 void
28247 ip_wsrv(queue_t *q)
28248 {
28249 	conn_t	*connp;
28250 	ill_t	*ill;
28251 	mblk_t	*mp;
28252 
28253 	if (q->q_next) {
28254 		ill = (ill_t *)q->q_ptr;
28255 		if (ill->ill_state_flags == 0) {
28256 			/*
28257 			 * The device flow control has opened up.
28258 			 * Walk through conn drain lists and qenable the
28259 			 * first conn in each list. This makes sense only
28260 			 * if the stream is fully plumbed and setup.
28261 			 * Hence the if check above.
28262 			 */
28263 			ip1dbg(("ip_wsrv: walking\n"));
28264 			conn_walk_drain(ill->ill_ipst);
28265 		}
28266 		return;
28267 	}
28268 
28269 	connp = Q_TO_CONN(q);
28270 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28271 
28272 	/*
28273 	 * 1. Set conn_draining flag to signal that service is active.
28274 	 *
28275 	 * 2. ip_output determines whether it has been called from service,
28276 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28277 	 *    has been called from service.
28278 	 *
28279 	 * 3. Message ordering is preserved by the following logic.
28280 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28281 	 *    the message at the tail, if conn_draining is set (i.e. service
28282 	 *    is running) or if q->q_first is non-null.
28283 	 *
28284 	 *    ii. If ip_output is called from service, and if ip_output cannot
28285 	 *    putnext due to flow control, it does a putbq.
28286 	 *
28287 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28288 	 *    (causing an infinite loop).
28289 	 */
28290 	ASSERT(!connp->conn_did_putbq);
28291 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28292 		connp->conn_draining = 1;
28293 		noenable(q);
28294 		while ((mp = getq(q)) != NULL) {
28295 			ASSERT(CONN_Q(q));
28296 
28297 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28298 			if (connp->conn_did_putbq) {
28299 				/* ip_wput did a putbq */
28300 				break;
28301 			}
28302 		}
28303 		/*
28304 		 * At this point, a thread coming down from top, calling
28305 		 * ip_wput, may end up queueing the message. We have not yet
28306 		 * enabled the queue, so ip_wsrv won't be called again.
28307 		 * To avoid this race, check q->q_first again (in the loop)
28308 		 * If the other thread queued the message before we call
28309 		 * enableok(), we will catch it in the q->q_first check.
28310 		 * If the other thread queues the message after we call
28311 		 * enableok(), ip_wsrv will be called again by STREAMS.
28312 		 */
28313 		connp->conn_draining = 0;
28314 		enableok(q);
28315 	}
28316 
28317 	/* Enable the next conn for draining */
28318 	conn_drain_tail(connp, B_FALSE);
28319 
28320 	connp->conn_did_putbq = 0;
28321 }
28322 
28323 /*
28324  * Walk the list of all conn's calling the function provided with the
28325  * specified argument for each.	 Note that this only walks conn's that
28326  * have been bound.
28327  * Applies to both IPv4 and IPv6.
28328  */
28329 static void
28330 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28331 {
28332 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28333 	    ipst->ips_ipcl_udp_fanout_size,
28334 	    func, arg, zoneid);
28335 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28336 	    ipst->ips_ipcl_conn_fanout_size,
28337 	    func, arg, zoneid);
28338 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28339 	    ipst->ips_ipcl_bind_fanout_size,
28340 	    func, arg, zoneid);
28341 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28342 	    IPPROTO_MAX, func, arg, zoneid);
28343 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28344 	    IPPROTO_MAX, func, arg, zoneid);
28345 }
28346 
28347 /*
28348  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28349  * of conns that need to be drained, check if drain is already in progress.
28350  * If so set the idl_repeat bit, indicating that the last conn in the list
28351  * needs to reinitiate the drain once again, for the list. If drain is not
28352  * in progress for the list, initiate the draining, by qenabling the 1st
28353  * conn in the list. The drain is self-sustaining, each qenabled conn will
28354  * in turn qenable the next conn, when it is done/blocked/closing.
28355  */
28356 static void
28357 conn_walk_drain(ip_stack_t *ipst)
28358 {
28359 	int i;
28360 	idl_t *idl;
28361 
28362 	IP_STAT(ipst, ip_conn_walk_drain);
28363 
28364 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28365 		idl = &ipst->ips_conn_drain_list[i];
28366 		mutex_enter(&idl->idl_lock);
28367 		if (idl->idl_conn == NULL) {
28368 			mutex_exit(&idl->idl_lock);
28369 			continue;
28370 		}
28371 		/*
28372 		 * If this list is not being drained currently by
28373 		 * an ip_wsrv thread, start the process.
28374 		 */
28375 		if (idl->idl_conn_draining == NULL) {
28376 			ASSERT(idl->idl_repeat == 0);
28377 			qenable(idl->idl_conn->conn_wq);
28378 			idl->idl_conn_draining = idl->idl_conn;
28379 		} else {
28380 			idl->idl_repeat = 1;
28381 		}
28382 		mutex_exit(&idl->idl_lock);
28383 	}
28384 }
28385 
28386 /*
28387  * Walk an conn hash table of `count' buckets, calling func for each entry.
28388  */
28389 static void
28390 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28391     zoneid_t zoneid)
28392 {
28393 	conn_t	*connp;
28394 
28395 	while (count-- > 0) {
28396 		mutex_enter(&connfp->connf_lock);
28397 		for (connp = connfp->connf_head; connp != NULL;
28398 		    connp = connp->conn_next) {
28399 			if (zoneid == GLOBAL_ZONEID ||
28400 			    zoneid == connp->conn_zoneid) {
28401 				CONN_INC_REF(connp);
28402 				mutex_exit(&connfp->connf_lock);
28403 				(*func)(connp, arg);
28404 				mutex_enter(&connfp->connf_lock);
28405 				CONN_DEC_REF(connp);
28406 			}
28407 		}
28408 		mutex_exit(&connfp->connf_lock);
28409 		connfp++;
28410 	}
28411 }
28412 
28413 /* conn_walk_fanout routine invoked for ip_conn_report for each conn. */
28414 static void
28415 conn_report1(conn_t *connp, void *mp)
28416 {
28417 	char	buf1[INET6_ADDRSTRLEN];
28418 	char	buf2[INET6_ADDRSTRLEN];
28419 	uint_t	print_len, buf_len;
28420 
28421 	ASSERT(connp != NULL);
28422 
28423 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28424 	if (buf_len <= 0)
28425 		return;
28426 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1));
28427 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2));
28428 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28429 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28430 	    "%5d %s/%05d %s/%05d\n",
28431 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28432 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28433 	    buf1, connp->conn_lport,
28434 	    buf2, connp->conn_fport);
28435 	if (print_len < buf_len) {
28436 		((mblk_t *)mp)->b_wptr += print_len;
28437 	} else {
28438 		((mblk_t *)mp)->b_wptr += buf_len;
28439 	}
28440 }
28441 
28442 /*
28443  * Named Dispatch routine to produce a formatted report on all conns
28444  * that are listed in one of the fanout tables.
28445  * This report is accessed by using the ndd utility to "get" ND variable
28446  * "ip_conn_status".
28447  */
28448 /* ARGSUSED */
28449 static int
28450 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28451 {
28452 	conn_t *connp = Q_TO_CONN(q);
28453 
28454 	(void) mi_mpprintf(mp,
28455 	    "CONN      " MI_COL_HDRPAD_STR
28456 	    "rfq      " MI_COL_HDRPAD_STR
28457 	    "stq      " MI_COL_HDRPAD_STR
28458 	    " zone local                 remote");
28459 
28460 	/*
28461 	 * Because of the ndd constraint, at most we can have 64K buffer
28462 	 * to put in all conn info.  So to be more efficient, just
28463 	 * allocate a 64K buffer here, assuming we need that large buffer.
28464 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28465 	 */
28466 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28467 		/* The following may work even if we cannot get a large buf. */
28468 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28469 		return (0);
28470 	}
28471 
28472 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
28473 	    connp->conn_netstack->netstack_ip);
28474 	return (0);
28475 }
28476 
28477 /*
28478  * Determine if the ill and multicast aspects of that packets
28479  * "matches" the conn.
28480  */
28481 boolean_t
28482 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28483     zoneid_t zoneid)
28484 {
28485 	ill_t *in_ill;
28486 	boolean_t found;
28487 	ipif_t *ipif;
28488 	ire_t *ire;
28489 	ipaddr_t dst, src;
28490 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28491 
28492 	dst = ipha->ipha_dst;
28493 	src = ipha->ipha_src;
28494 
28495 	/*
28496 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28497 	 * unicast, broadcast and multicast reception to
28498 	 * conn_incoming_ill. conn_wantpacket itself is called
28499 	 * only for BROADCAST and multicast.
28500 	 *
28501 	 * 1) ip_rput supresses duplicate broadcasts if the ill
28502 	 *    is part of a group. Hence, we should be receiving
28503 	 *    just one copy of broadcast for the whole group.
28504 	 *    Thus, if it is part of the group the packet could
28505 	 *    come on any ill of the group and hence we need a
28506 	 *    match on the group. Otherwise, match on ill should
28507 	 *    be sufficient.
28508 	 *
28509 	 * 2) ip_rput does not suppress duplicate multicast packets.
28510 	 *    If there are two interfaces in a ill group and we have
28511 	 *    2 applications (conns) joined a multicast group G on
28512 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
28513 	 *    will give us two packets because we join G on both the
28514 	 *    interfaces rather than nominating just one interface
28515 	 *    for receiving multicast like broadcast above. So,
28516 	 *    we have to call ilg_lookup_ill to filter out duplicate
28517 	 *    copies, if ill is part of a group.
28518 	 */
28519 	in_ill = connp->conn_incoming_ill;
28520 	if (in_ill != NULL) {
28521 		if (in_ill->ill_group == NULL) {
28522 			if (in_ill != ill)
28523 				return (B_FALSE);
28524 		} else if (in_ill->ill_group != ill->ill_group) {
28525 			return (B_FALSE);
28526 		}
28527 	}
28528 
28529 	if (!CLASSD(dst)) {
28530 		if (IPCL_ZONE_MATCH(connp, zoneid))
28531 			return (B_TRUE);
28532 		/*
28533 		 * The conn is in a different zone; we need to check that this
28534 		 * broadcast address is configured in the application's zone and
28535 		 * on one ill in the group.
28536 		 */
28537 		ipif = ipif_get_next_ipif(NULL, ill);
28538 		if (ipif == NULL)
28539 			return (B_FALSE);
28540 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28541 		    connp->conn_zoneid, NULL,
28542 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
28543 		ipif_refrele(ipif);
28544 		if (ire != NULL) {
28545 			ire_refrele(ire);
28546 			return (B_TRUE);
28547 		} else {
28548 			return (B_FALSE);
28549 		}
28550 	}
28551 
28552 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28553 	    connp->conn_zoneid == zoneid) {
28554 		/*
28555 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28556 		 * disabled, therefore we don't dispatch the multicast packet to
28557 		 * the sending zone.
28558 		 */
28559 		return (B_FALSE);
28560 	}
28561 
28562 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28563 		/*
28564 		 * Multicast packet on the loopback interface: we only match
28565 		 * conns who joined the group in the specified zone.
28566 		 */
28567 		return (B_FALSE);
28568 	}
28569 
28570 	if (connp->conn_multi_router) {
28571 		/* multicast packet and multicast router socket: send up */
28572 		return (B_TRUE);
28573 	}
28574 
28575 	mutex_enter(&connp->conn_lock);
28576 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28577 	mutex_exit(&connp->conn_lock);
28578 	return (found);
28579 }
28580 
28581 /*
28582  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28583  */
28584 /* ARGSUSED */
28585 static void
28586 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28587 {
28588 	ill_t *ill = (ill_t *)q->q_ptr;
28589 	mblk_t	*mp1, *mp2;
28590 	ipif_t  *ipif;
28591 	int err = 0;
28592 	conn_t *connp = NULL;
28593 	ipsq_t	*ipsq;
28594 	arc_t	*arc;
28595 
28596 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28597 
28598 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28599 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28600 
28601 	ASSERT(IAM_WRITER_ILL(ill));
28602 	mp2 = mp->b_cont;
28603 	mp->b_cont = NULL;
28604 
28605 	/*
28606 	 * We have now received the arp bringup completion message
28607 	 * from ARP. Mark the arp bringup as done. Also if the arp
28608 	 * stream has already started closing, send up the AR_ARP_CLOSING
28609 	 * ack now since ARP is waiting in close for this ack.
28610 	 */
28611 	mutex_enter(&ill->ill_lock);
28612 	ill->ill_arp_bringup_pending = 0;
28613 	if (ill->ill_arp_closing) {
28614 		mutex_exit(&ill->ill_lock);
28615 		/* Let's reuse the mp for sending the ack */
28616 		arc = (arc_t *)mp->b_rptr;
28617 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28618 		arc->arc_cmd = AR_ARP_CLOSING;
28619 		qreply(q, mp);
28620 	} else {
28621 		mutex_exit(&ill->ill_lock);
28622 		freeb(mp);
28623 	}
28624 
28625 	ipsq = ill->ill_phyint->phyint_ipsq;
28626 	ipif = ipsq->ipsq_pending_ipif;
28627 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28628 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28629 	if (mp1 == NULL) {
28630 		/* bringup was aborted by the user */
28631 		freemsg(mp2);
28632 		return;
28633 	}
28634 
28635 	/*
28636 	 * If an IOCTL is waiting on this (ipsq_current_ioctl != 0), then we
28637 	 * must have an associated conn_t.  Otherwise, we're bringing this
28638 	 * interface back up as part of handling an asynchronous event (e.g.,
28639 	 * physical address change).
28640 	 */
28641 	if (ipsq->ipsq_current_ioctl != 0) {
28642 		ASSERT(connp != NULL);
28643 		q = CONNP_TO_WQ(connp);
28644 	} else {
28645 		ASSERT(connp == NULL);
28646 		q = ill->ill_rq;
28647 	}
28648 
28649 	/*
28650 	 * If the DL_BIND_REQ fails, it is noted
28651 	 * in arc_name_offset.
28652 	 */
28653 	err = *((int *)mp2->b_rptr);
28654 	if (err == 0) {
28655 		if (ipif->ipif_isv6) {
28656 			if ((err = ipif_up_done_v6(ipif)) != 0)
28657 				ip0dbg(("ip_arp_done: init failed\n"));
28658 		} else {
28659 			if ((err = ipif_up_done(ipif)) != 0)
28660 				ip0dbg(("ip_arp_done: init failed\n"));
28661 		}
28662 	} else {
28663 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28664 	}
28665 
28666 	freemsg(mp2);
28667 
28668 	if ((err == 0) && (ill->ill_up_ipifs)) {
28669 		err = ill_up_ipifs(ill, q, mp1);
28670 		if (err == EINPROGRESS)
28671 			return;
28672 	}
28673 
28674 	if (ill->ill_up_ipifs)
28675 		ill_group_cleanup(ill);
28676 
28677 	/*
28678 	 * The operation must complete without EINPROGRESS since
28679 	 * ipsq_pending_mp_get() has removed the mblk from ipsq_pending_mp.
28680 	 * Otherwise, the operation will be stuck forever in the ipsq.
28681 	 */
28682 	ASSERT(err != EINPROGRESS);
28683 	if (ipsq->ipsq_current_ioctl != 0)
28684 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28685 	else
28686 		ipsq_current_finish(ipsq);
28687 }
28688 
28689 /* Allocate the private structure */
28690 static int
28691 ip_priv_alloc(void **bufp)
28692 {
28693 	void	*buf;
28694 
28695 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28696 		return (ENOMEM);
28697 
28698 	*bufp = buf;
28699 	return (0);
28700 }
28701 
28702 /* Function to delete the private structure */
28703 void
28704 ip_priv_free(void *buf)
28705 {
28706 	ASSERT(buf != NULL);
28707 	kmem_free(buf, sizeof (ip_priv_t));
28708 }
28709 
28710 /*
28711  * The entry point for IPPF processing.
28712  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28713  * routine just returns.
28714  *
28715  * When called, ip_process generates an ipp_packet_t structure
28716  * which holds the state information for this packet and invokes the
28717  * the classifier (via ipp_packet_process). The classification, depending on
28718  * configured filters, results in a list of actions for this packet. Invoking
28719  * an action may cause the packet to be dropped, in which case the resulting
28720  * mblk (*mpp) is NULL. proc indicates the callout position for
28721  * this packet and ill_index is the interface this packet on or will leave
28722  * on (inbound and outbound resp.).
28723  */
28724 void
28725 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28726 {
28727 	mblk_t		*mp;
28728 	ip_priv_t	*priv;
28729 	ipp_action_id_t	aid;
28730 	int		rc = 0;
28731 	ipp_packet_t	*pp;
28732 #define	IP_CLASS	"ip"
28733 
28734 	/* If the classifier is not loaded, return  */
28735 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28736 		return;
28737 	}
28738 
28739 	mp = *mpp;
28740 	ASSERT(mp != NULL);
28741 
28742 	/* Allocate the packet structure */
28743 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28744 	if (rc != 0) {
28745 		*mpp = NULL;
28746 		freemsg(mp);
28747 		return;
28748 	}
28749 
28750 	/* Allocate the private structure */
28751 	rc = ip_priv_alloc((void **)&priv);
28752 	if (rc != 0) {
28753 		*mpp = NULL;
28754 		freemsg(mp);
28755 		ipp_packet_free(pp);
28756 		return;
28757 	}
28758 	priv->proc = proc;
28759 	priv->ill_index = ill_index;
28760 	ipp_packet_set_private(pp, priv, ip_priv_free);
28761 	ipp_packet_set_data(pp, mp);
28762 
28763 	/* Invoke the classifier */
28764 	rc = ipp_packet_process(&pp);
28765 	if (pp != NULL) {
28766 		mp = ipp_packet_get_data(pp);
28767 		ipp_packet_free(pp);
28768 		if (rc != 0) {
28769 			freemsg(mp);
28770 			*mpp = NULL;
28771 		}
28772 	} else {
28773 		*mpp = NULL;
28774 	}
28775 #undef	IP_CLASS
28776 }
28777 
28778 /*
28779  * Propagate a multicast group membership operation (add/drop) on
28780  * all the interfaces crossed by the related multirt routes.
28781  * The call is considered successful if the operation succeeds
28782  * on at least one interface.
28783  */
28784 static int
28785 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28786     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28787     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28788     mblk_t *first_mp)
28789 {
28790 	ire_t		*ire_gw;
28791 	irb_t		*irb;
28792 	int		error = 0;
28793 	opt_restart_t	*or;
28794 	ip_stack_t	*ipst = ire->ire_ipst;
28795 
28796 	irb = ire->ire_bucket;
28797 	ASSERT(irb != NULL);
28798 
28799 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28800 
28801 	or = (opt_restart_t *)first_mp->b_rptr;
28802 	IRB_REFHOLD(irb);
28803 	for (; ire != NULL; ire = ire->ire_next) {
28804 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28805 			continue;
28806 		if (ire->ire_addr != group)
28807 			continue;
28808 
28809 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28810 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28811 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
28812 		/* No resolver exists for the gateway; skip this ire. */
28813 		if (ire_gw == NULL)
28814 			continue;
28815 
28816 		/*
28817 		 * This function can return EINPROGRESS. If so the operation
28818 		 * will be restarted from ip_restart_optmgmt which will
28819 		 * call ip_opt_set and option processing will restart for
28820 		 * this option. So we may end up calling 'fn' more than once.
28821 		 * This requires that 'fn' is idempotent except for the
28822 		 * return value. The operation is considered a success if
28823 		 * it succeeds at least once on any one interface.
28824 		 */
28825 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28826 		    NULL, fmode, src, first_mp);
28827 		if (error == 0)
28828 			or->or_private = CGTP_MCAST_SUCCESS;
28829 
28830 		if (ip_debug > 0) {
28831 			ulong_t	off;
28832 			char	*ksym;
28833 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28834 			ip2dbg(("ip_multirt_apply_membership: "
28835 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28836 			    "error %d [success %u]\n",
28837 			    ksym ? ksym : "?",
28838 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28839 			    error, or->or_private));
28840 		}
28841 
28842 		ire_refrele(ire_gw);
28843 		if (error == EINPROGRESS) {
28844 			IRB_REFRELE(irb);
28845 			return (error);
28846 		}
28847 	}
28848 	IRB_REFRELE(irb);
28849 	/*
28850 	 * Consider the call as successful if we succeeded on at least
28851 	 * one interface. Otherwise, return the last encountered error.
28852 	 */
28853 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28854 }
28855 
28856 
28857 /*
28858  * Issue a warning regarding a route crossing an interface with an
28859  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28860  * amount of time is logged.
28861  */
28862 static void
28863 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28864 {
28865 	hrtime_t	current = gethrtime();
28866 	char		buf[INET_ADDRSTRLEN];
28867 	ip_stack_t	*ipst = ire->ire_ipst;
28868 
28869 	/* Convert interval in ms to hrtime in ns */
28870 	if (ipst->ips_multirt_bad_mtu_last_time +
28871 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
28872 	    current) {
28873 		cmn_err(CE_WARN, "ip: ignoring multiroute "
28874 		    "to %s, incorrect MTU %u (expected %u)\n",
28875 		    ip_dot_addr(ire->ire_addr, buf),
28876 		    ire->ire_max_frag, max_frag);
28877 
28878 		ipst->ips_multirt_bad_mtu_last_time = current;
28879 	}
28880 }
28881 
28882 
28883 /*
28884  * Get the CGTP (multirouting) filtering status.
28885  * If 0, the CGTP hooks are transparent.
28886  */
28887 /* ARGSUSED */
28888 static int
28889 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
28890 {
28891 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28892 
28893 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
28894 	return (0);
28895 }
28896 
28897 
28898 /*
28899  * Set the CGTP (multirouting) filtering status.
28900  * If the status is changed from active to transparent
28901  * or from transparent to active, forward the new status
28902  * to the filtering module (if loaded).
28903  */
28904 /* ARGSUSED */
28905 static int
28906 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
28907     cred_t *ioc_cr)
28908 {
28909 	long		new_value;
28910 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28911 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
28912 
28913 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
28914 		return (EPERM);
28915 
28916 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
28917 	    new_value < 0 || new_value > 1) {
28918 		return (EINVAL);
28919 	}
28920 
28921 	if ((!*ip_cgtp_filter_value) && new_value) {
28922 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
28923 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28924 		    " (module not loaded)" : "");
28925 	}
28926 	if (*ip_cgtp_filter_value && (!new_value)) {
28927 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
28928 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28929 		    " (module not loaded)" : "");
28930 	}
28931 
28932 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28933 		int	res;
28934 		netstackid_t stackid;
28935 
28936 		stackid = ipst->ips_netstack->netstack_stackid;
28937 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
28938 		    new_value);
28939 		if (res)
28940 			return (res);
28941 	}
28942 
28943 	*ip_cgtp_filter_value = (boolean_t)new_value;
28944 
28945 	return (0);
28946 }
28947 
28948 
28949 /*
28950  * Return the expected CGTP hooks version number.
28951  */
28952 int
28953 ip_cgtp_filter_supported(void)
28954 {
28955 	return (ip_cgtp_filter_rev);
28956 }
28957 
28958 
28959 /*
28960  * CGTP hooks can be registered by invoking this function.
28961  * Checks that the version number matches.
28962  */
28963 int
28964 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
28965 {
28966 	netstack_t *ns;
28967 	ip_stack_t *ipst;
28968 
28969 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
28970 		return (ENOTSUP);
28971 
28972 	ns = netstack_find_by_stackid(stackid);
28973 	if (ns == NULL)
28974 		return (EINVAL);
28975 	ipst = ns->netstack_ip;
28976 	ASSERT(ipst != NULL);
28977 
28978 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28979 		netstack_rele(ns);
28980 		return (EALREADY);
28981 	}
28982 
28983 	ipst->ips_ip_cgtp_filter_ops = ops;
28984 	netstack_rele(ns);
28985 	return (0);
28986 }
28987 
28988 /*
28989  * CGTP hooks can be unregistered by invoking this function.
28990  * Returns ENXIO if there was no registration.
28991  * Returns EBUSY if the ndd variable has not been turned off.
28992  */
28993 int
28994 ip_cgtp_filter_unregister(netstackid_t stackid)
28995 {
28996 	netstack_t *ns;
28997 	ip_stack_t *ipst;
28998 
28999 	ns = netstack_find_by_stackid(stackid);
29000 	if (ns == NULL)
29001 		return (EINVAL);
29002 	ipst = ns->netstack_ip;
29003 	ASSERT(ipst != NULL);
29004 
29005 	if (ipst->ips_ip_cgtp_filter) {
29006 		netstack_rele(ns);
29007 		return (EBUSY);
29008 	}
29009 
29010 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
29011 		netstack_rele(ns);
29012 		return (ENXIO);
29013 	}
29014 	ipst->ips_ip_cgtp_filter_ops = NULL;
29015 	netstack_rele(ns);
29016 	return (0);
29017 }
29018 
29019 /*
29020  * Check whether there is a CGTP filter registration.
29021  * Returns non-zero if there is a registration, otherwise returns zero.
29022  * Note: returns zero if bad stackid.
29023  */
29024 int
29025 ip_cgtp_filter_is_registered(netstackid_t stackid)
29026 {
29027 	netstack_t *ns;
29028 	ip_stack_t *ipst;
29029 	int ret;
29030 
29031 	ns = netstack_find_by_stackid(stackid);
29032 	if (ns == NULL)
29033 		return (0);
29034 	ipst = ns->netstack_ip;
29035 	ASSERT(ipst != NULL);
29036 
29037 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
29038 		ret = 1;
29039 	else
29040 		ret = 0;
29041 
29042 	netstack_rele(ns);
29043 	return (ret);
29044 }
29045 
29046 static squeue_func_t
29047 ip_squeue_switch(int val)
29048 {
29049 	squeue_func_t rval = squeue_fill;
29050 
29051 	switch (val) {
29052 	case IP_SQUEUE_ENTER_NODRAIN:
29053 		rval = squeue_enter_nodrain;
29054 		break;
29055 	case IP_SQUEUE_ENTER:
29056 		rval = squeue_enter;
29057 		break;
29058 	default:
29059 		break;
29060 	}
29061 	return (rval);
29062 }
29063 
29064 /* ARGSUSED */
29065 static int
29066 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29067     caddr_t addr, cred_t *cr)
29068 {
29069 	int *v = (int *)addr;
29070 	long new_value;
29071 
29072 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29073 		return (EPERM);
29074 
29075 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29076 		return (EINVAL);
29077 
29078 	ip_input_proc = ip_squeue_switch(new_value);
29079 	*v = new_value;
29080 	return (0);
29081 }
29082 
29083 /*
29084  * Handle ndd set of variables which require PRIV_SYS_NET_CONFIG such as
29085  * ip_debug.
29086  */
29087 /* ARGSUSED */
29088 static int
29089 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29090     caddr_t addr, cred_t *cr)
29091 {
29092 	int *v = (int *)addr;
29093 	long new_value;
29094 
29095 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29096 		return (EPERM);
29097 
29098 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29099 		return (EINVAL);
29100 
29101 	*v = new_value;
29102 	return (0);
29103 }
29104 
29105 /*
29106  * Handle changes to ipmp_hook_emulation ndd variable.
29107  * Need to update phyint_hook_ifindex.
29108  * Also generate a nic plumb event should a new ifidex be assigned to a group.
29109  */
29110 static void
29111 ipmp_hook_emulation_changed(ip_stack_t *ipst)
29112 {
29113 	phyint_t *phyi;
29114 	phyint_t *phyi_tmp;
29115 	char *groupname;
29116 	int namelen;
29117 	ill_t	*ill;
29118 	boolean_t new_group;
29119 
29120 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29121 	/*
29122 	 * Group indicies are stored in the phyint - a common structure
29123 	 * to both IPv4 and IPv6.
29124 	 */
29125 	phyi = avl_first(&ipst->ips_phyint_g_list->phyint_list_avl_by_index);
29126 	for (; phyi != NULL;
29127 	    phyi = avl_walk(&ipst->ips_phyint_g_list->phyint_list_avl_by_index,
29128 	    phyi, AVL_AFTER)) {
29129 		/* Ignore the ones that do not have a group */
29130 		if (phyi->phyint_groupname_len == 0)
29131 			continue;
29132 
29133 		/*
29134 		 * Look for other phyint in group.
29135 		 * Clear name/namelen so the lookup doesn't find ourselves.
29136 		 */
29137 		namelen = phyi->phyint_groupname_len;
29138 		groupname = phyi->phyint_groupname;
29139 		phyi->phyint_groupname_len = 0;
29140 		phyi->phyint_groupname = NULL;
29141 
29142 		phyi_tmp = phyint_lookup_group(groupname, B_FALSE, ipst);
29143 		/* Restore */
29144 		phyi->phyint_groupname_len = namelen;
29145 		phyi->phyint_groupname = groupname;
29146 
29147 		new_group = B_FALSE;
29148 		if (ipst->ips_ipmp_hook_emulation) {
29149 			/*
29150 			 * If the group already exists and has already
29151 			 * been assigned a group ifindex, we use the existing
29152 			 * group_ifindex, otherwise we pick a new group_ifindex
29153 			 * here.
29154 			 */
29155 			if (phyi_tmp != NULL &&
29156 			    phyi_tmp->phyint_group_ifindex != 0) {
29157 				phyi->phyint_group_ifindex =
29158 				    phyi_tmp->phyint_group_ifindex;
29159 			} else {
29160 				/* XXX We need a recovery strategy here. */
29161 				if (!ip_assign_ifindex(
29162 				    &phyi->phyint_group_ifindex, ipst))
29163 					cmn_err(CE_PANIC,
29164 					    "ip_assign_ifindex() failed");
29165 				new_group = B_TRUE;
29166 			}
29167 		} else {
29168 			phyi->phyint_group_ifindex = 0;
29169 		}
29170 		if (ipst->ips_ipmp_hook_emulation)
29171 			phyi->phyint_hook_ifindex = phyi->phyint_group_ifindex;
29172 		else
29173 			phyi->phyint_hook_ifindex = phyi->phyint_ifindex;
29174 
29175 		/*
29176 		 * For IP Filter to find out the relationship between
29177 		 * names and interface indicies, we need to generate
29178 		 * a NE_PLUMB event when a new group can appear.
29179 		 * We always generate events when a new interface appears
29180 		 * (even when ipmp_hook_emulation is set) so there
29181 		 * is no need to generate NE_PLUMB events when
29182 		 * ipmp_hook_emulation is turned off.
29183 		 * And since it isn't critical for IP Filter to get
29184 		 * the NE_UNPLUMB events we skip those here.
29185 		 */
29186 		if (new_group) {
29187 			/*
29188 			 * First phyint in group - generate group PLUMB event.
29189 			 * Since we are not running inside the ipsq we do
29190 			 * the dispatch immediately.
29191 			 */
29192 			if (phyi->phyint_illv4 != NULL)
29193 				ill = phyi->phyint_illv4;
29194 			else
29195 				ill = phyi->phyint_illv6;
29196 
29197 			if (ill != NULL) {
29198 				mutex_enter(&ill->ill_lock);
29199 				ill_nic_info_plumb(ill, B_TRUE);
29200 				ill_nic_info_dispatch(ill);
29201 				mutex_exit(&ill->ill_lock);
29202 			}
29203 		}
29204 	}
29205 	rw_exit(&ipst->ips_ill_g_lock);
29206 }
29207 
29208 /* ARGSUSED */
29209 static int
29210 ipmp_hook_emulation_set(queue_t *q, mblk_t *mp, char *value,
29211     caddr_t addr, cred_t *cr)
29212 {
29213 	int *v = (int *)addr;
29214 	long new_value;
29215 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29216 
29217 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29218 		return (EINVAL);
29219 
29220 	if (*v != new_value) {
29221 		*v = new_value;
29222 		ipmp_hook_emulation_changed(ipst);
29223 	}
29224 	return (0);
29225 }
29226 
29227 static void *
29228 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29229 {
29230 	kstat_t *ksp;
29231 
29232 	ip_stat_t template = {
29233 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29234 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29235 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29236 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29237 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29238 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29239 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29240 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29241 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29242 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29243 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29244 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29245 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29246 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29247 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29248 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29249 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29250 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29251 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29252 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29253 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29254 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29255 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29256 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29257 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29258 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29259 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29260 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29261 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29262 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29263 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29264 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29265 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29266 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29267 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29268 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29269 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29270 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29271 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29272 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29273 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29274 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29275 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29276 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29277 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29278 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29279 	};
29280 
29281 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29282 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29283 	    KSTAT_FLAG_VIRTUAL, stackid);
29284 
29285 	if (ksp == NULL)
29286 		return (NULL);
29287 
29288 	bcopy(&template, ip_statisticsp, sizeof (template));
29289 	ksp->ks_data = (void *)ip_statisticsp;
29290 	ksp->ks_private = (void *)(uintptr_t)stackid;
29291 
29292 	kstat_install(ksp);
29293 	return (ksp);
29294 }
29295 
29296 static void
29297 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29298 {
29299 	if (ksp != NULL) {
29300 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29301 		kstat_delete_netstack(ksp, stackid);
29302 	}
29303 }
29304 
29305 static void *
29306 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29307 {
29308 	kstat_t	*ksp;
29309 
29310 	ip_named_kstat_t template = {
29311 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29312 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29313 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29314 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29315 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29316 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29317 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29318 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29319 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29320 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29321 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29322 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29323 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29324 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29325 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29326 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29327 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29328 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29329 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29330 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29331 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29332 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29333 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29334 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29335 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29336 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29337 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29338 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29339 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29340 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29341 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29342 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29343 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29344 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29345 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29346 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29347 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29348 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29349 	};
29350 
29351 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29352 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29353 	if (ksp == NULL || ksp->ks_data == NULL)
29354 		return (NULL);
29355 
29356 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29357 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29358 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29359 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29360 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29361 
29362 	template.netToMediaEntrySize.value.i32 =
29363 	    sizeof (mib2_ipNetToMediaEntry_t);
29364 
29365 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29366 
29367 	bcopy(&template, ksp->ks_data, sizeof (template));
29368 	ksp->ks_update = ip_kstat_update;
29369 	ksp->ks_private = (void *)(uintptr_t)stackid;
29370 
29371 	kstat_install(ksp);
29372 	return (ksp);
29373 }
29374 
29375 static void
29376 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29377 {
29378 	if (ksp != NULL) {
29379 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29380 		kstat_delete_netstack(ksp, stackid);
29381 	}
29382 }
29383 
29384 static int
29385 ip_kstat_update(kstat_t *kp, int rw)
29386 {
29387 	ip_named_kstat_t *ipkp;
29388 	mib2_ipIfStatsEntry_t ipmib;
29389 	ill_walk_context_t ctx;
29390 	ill_t *ill;
29391 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29392 	netstack_t	*ns;
29393 	ip_stack_t	*ipst;
29394 
29395 	if (kp == NULL || kp->ks_data == NULL)
29396 		return (EIO);
29397 
29398 	if (rw == KSTAT_WRITE)
29399 		return (EACCES);
29400 
29401 	ns = netstack_find_by_stackid(stackid);
29402 	if (ns == NULL)
29403 		return (-1);
29404 	ipst = ns->netstack_ip;
29405 	if (ipst == NULL) {
29406 		netstack_rele(ns);
29407 		return (-1);
29408 	}
29409 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29410 
29411 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29412 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29413 	ill = ILL_START_WALK_V4(&ctx, ipst);
29414 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29415 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29416 	rw_exit(&ipst->ips_ill_g_lock);
29417 
29418 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29419 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29420 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29421 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29422 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29423 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29424 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29425 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29426 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29427 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29428 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29429 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29430 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29431 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29432 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29433 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29434 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29435 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29436 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29437 
29438 	ipkp->routingDiscards.value.ui32 =	0;
29439 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29440 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29441 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29442 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29443 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29444 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29445 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29446 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29447 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29448 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29449 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29450 
29451 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29452 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29453 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29454 
29455 	netstack_rele(ns);
29456 
29457 	return (0);
29458 }
29459 
29460 static void *
29461 icmp_kstat_init(netstackid_t stackid)
29462 {
29463 	kstat_t	*ksp;
29464 
29465 	icmp_named_kstat_t template = {
29466 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29467 		{ "inErrors",		KSTAT_DATA_UINT32 },
29468 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29469 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29470 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29471 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29472 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29473 		{ "inEchos",		KSTAT_DATA_UINT32 },
29474 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29475 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29476 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29477 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29478 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29479 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29480 		{ "outErrors",		KSTAT_DATA_UINT32 },
29481 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29482 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29483 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29484 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29485 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29486 		{ "outEchos",		KSTAT_DATA_UINT32 },
29487 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29488 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29489 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29490 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29491 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29492 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29493 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29494 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29495 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29496 		{ "outDrops",		KSTAT_DATA_UINT32 },
29497 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29498 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29499 	};
29500 
29501 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29502 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29503 	if (ksp == NULL || ksp->ks_data == NULL)
29504 		return (NULL);
29505 
29506 	bcopy(&template, ksp->ks_data, sizeof (template));
29507 
29508 	ksp->ks_update = icmp_kstat_update;
29509 	ksp->ks_private = (void *)(uintptr_t)stackid;
29510 
29511 	kstat_install(ksp);
29512 	return (ksp);
29513 }
29514 
29515 static void
29516 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29517 {
29518 	if (ksp != NULL) {
29519 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29520 		kstat_delete_netstack(ksp, stackid);
29521 	}
29522 }
29523 
29524 static int
29525 icmp_kstat_update(kstat_t *kp, int rw)
29526 {
29527 	icmp_named_kstat_t *icmpkp;
29528 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29529 	netstack_t	*ns;
29530 	ip_stack_t	*ipst;
29531 
29532 	if ((kp == NULL) || (kp->ks_data == NULL))
29533 		return (EIO);
29534 
29535 	if (rw == KSTAT_WRITE)
29536 		return (EACCES);
29537 
29538 	ns = netstack_find_by_stackid(stackid);
29539 	if (ns == NULL)
29540 		return (-1);
29541 	ipst = ns->netstack_ip;
29542 	if (ipst == NULL) {
29543 		netstack_rele(ns);
29544 		return (-1);
29545 	}
29546 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29547 
29548 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29549 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29550 	icmpkp->inDestUnreachs.value.ui32 =
29551 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29552 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29553 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29554 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29555 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29556 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29557 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29558 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29559 	icmpkp->inTimestampReps.value.ui32 =
29560 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29561 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29562 	icmpkp->inAddrMaskReps.value.ui32 =
29563 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29564 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29565 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29566 	icmpkp->outDestUnreachs.value.ui32 =
29567 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29568 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29569 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29570 	icmpkp->outSrcQuenchs.value.ui32 =
29571 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29572 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29573 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29574 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29575 	icmpkp->outTimestamps.value.ui32 =
29576 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29577 	icmpkp->outTimestampReps.value.ui32 =
29578 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29579 	icmpkp->outAddrMasks.value.ui32 =
29580 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29581 	icmpkp->outAddrMaskReps.value.ui32 =
29582 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29583 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29584 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29585 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29586 	icmpkp->outFragNeeded.value.ui32 =
29587 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29588 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29589 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29590 	icmpkp->inBadRedirects.value.ui32 =
29591 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29592 
29593 	netstack_rele(ns);
29594 	return (0);
29595 }
29596 
29597 /*
29598  * This is the fanout function for raw socket opened for SCTP.  Note
29599  * that it is called after SCTP checks that there is no socket which
29600  * wants a packet.  Then before SCTP handles this out of the blue packet,
29601  * this function is called to see if there is any raw socket for SCTP.
29602  * If there is and it is bound to the correct address, the packet will
29603  * be sent to that socket.  Note that only one raw socket can be bound to
29604  * a port.  This is assured in ipcl_sctp_hash_insert();
29605  */
29606 void
29607 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29608     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29609     zoneid_t zoneid)
29610 {
29611 	conn_t		*connp;
29612 	queue_t		*rq;
29613 	mblk_t		*first_mp;
29614 	boolean_t	secure;
29615 	ip6_t		*ip6h;
29616 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29617 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29618 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
29619 	boolean_t	sctp_csum_err = B_FALSE;
29620 
29621 	if (flags & IP_FF_SCTP_CSUM_ERR) {
29622 		sctp_csum_err = B_TRUE;
29623 		flags &= ~IP_FF_SCTP_CSUM_ERR;
29624 	}
29625 
29626 	first_mp = mp;
29627 	if (mctl_present) {
29628 		mp = first_mp->b_cont;
29629 		secure = ipsec_in_is_secure(first_mp);
29630 		ASSERT(mp != NULL);
29631 	} else {
29632 		secure = B_FALSE;
29633 	}
29634 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29635 
29636 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29637 	if (connp == NULL) {
29638 		/*
29639 		 * Although raw sctp is not summed, OOB chunks must be.
29640 		 * Drop the packet here if the sctp checksum failed.
29641 		 */
29642 		if (sctp_csum_err) {
29643 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
29644 			freemsg(first_mp);
29645 			return;
29646 		}
29647 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29648 		return;
29649 	}
29650 	rq = connp->conn_rq;
29651 	if (!canputnext(rq)) {
29652 		CONN_DEC_REF(connp);
29653 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29654 		freemsg(first_mp);
29655 		return;
29656 	}
29657 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29658 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29659 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29660 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29661 		if (first_mp == NULL) {
29662 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29663 			CONN_DEC_REF(connp);
29664 			return;
29665 		}
29666 	}
29667 	/*
29668 	 * We probably should not send M_CTL message up to
29669 	 * raw socket.
29670 	 */
29671 	if (mctl_present)
29672 		freeb(first_mp);
29673 
29674 	/* Initiate IPPF processing here if needed. */
29675 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29676 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29677 		ip_process(IPP_LOCAL_IN, &mp,
29678 		    recv_ill->ill_phyint->phyint_ifindex);
29679 		if (mp == NULL) {
29680 			CONN_DEC_REF(connp);
29681 			return;
29682 		}
29683 	}
29684 
29685 	if (connp->conn_recvif || connp->conn_recvslla ||
29686 	    ((connp->conn_ip_recvpktinfo ||
29687 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29688 	    (flags & IP_FF_IPINFO))) {
29689 		int in_flags = 0;
29690 
29691 		/*
29692 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29693 		 * IPF_RECVIF.
29694 		 */
29695 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29696 			in_flags = IPF_RECVIF;
29697 		}
29698 		if (connp->conn_recvslla) {
29699 			in_flags |= IPF_RECVSLLA;
29700 		}
29701 		if (isv4) {
29702 			mp = ip_add_info(mp, recv_ill, in_flags,
29703 			    IPCL_ZONEID(connp), ipst);
29704 		} else {
29705 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29706 			if (mp == NULL) {
29707 				BUMP_MIB(recv_ill->ill_ip_mib,
29708 				    ipIfStatsInDiscards);
29709 				CONN_DEC_REF(connp);
29710 				return;
29711 			}
29712 		}
29713 	}
29714 
29715 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29716 	/*
29717 	 * We are sending the IPSEC_IN message also up. Refer
29718 	 * to comments above this function.
29719 	 * This is the SOCK_RAW, IPPROTO_SCTP case.
29720 	 */
29721 	(connp->conn_recv)(connp, mp, NULL);
29722 	CONN_DEC_REF(connp);
29723 }
29724 
29725 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29726 {									\
29727 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29728 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29729 }
29730 /*
29731  * This function should be called only if all packet processing
29732  * including fragmentation is complete. Callers of this function
29733  * must set mp->b_prev to one of these values:
29734  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29735  * prior to handing over the mp as first argument to this function.
29736  *
29737  * If the ire passed by caller is incomplete, this function
29738  * queues the packet and if necessary, sends ARP request and bails.
29739  * If the ire passed is fully resolved, we simply prepend
29740  * the link-layer header to the packet, do ipsec hw acceleration
29741  * work if necessary, and send the packet out on the wire.
29742  *
29743  * NOTE: IPsec will only call this function with fully resolved
29744  * ires if hw acceleration is involved.
29745  * TODO list :
29746  * 	a Handle M_MULTIDATA so that
29747  *	  tcp_multisend->tcp_multisend_data can
29748  *	  call ip_xmit_v4 directly
29749  *	b Handle post-ARP work for fragments so that
29750  *	  ip_wput_frag can call this function.
29751  */
29752 ipxmit_state_t
29753 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
29754 {
29755 	nce_t		*arpce;
29756 	queue_t		*q;
29757 	int		ill_index;
29758 	mblk_t		*nxt_mp, *first_mp;
29759 	boolean_t	xmit_drop = B_FALSE;
29760 	ip_proc_t	proc;
29761 	ill_t		*out_ill;
29762 	int		pkt_len;
29763 
29764 	arpce = ire->ire_nce;
29765 	ASSERT(arpce != NULL);
29766 
29767 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29768 
29769 	mutex_enter(&arpce->nce_lock);
29770 	switch (arpce->nce_state) {
29771 	case ND_REACHABLE:
29772 		/* If there are other queued packets, queue this packet */
29773 		if (arpce->nce_qd_mp != NULL) {
29774 			if (mp != NULL)
29775 				nce_queue_mp_common(arpce, mp, B_FALSE);
29776 			mp = arpce->nce_qd_mp;
29777 		}
29778 		arpce->nce_qd_mp = NULL;
29779 		mutex_exit(&arpce->nce_lock);
29780 
29781 		/*
29782 		 * Flush the queue.  In the common case, where the
29783 		 * ARP is already resolved,  it will go through the
29784 		 * while loop only once.
29785 		 */
29786 		while (mp != NULL) {
29787 
29788 			nxt_mp = mp->b_next;
29789 			mp->b_next = NULL;
29790 			ASSERT(mp->b_datap->db_type != M_CTL);
29791 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29792 			/*
29793 			 * This info is needed for IPQOS to do COS marking
29794 			 * in ip_wput_attach_llhdr->ip_process.
29795 			 */
29796 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29797 			mp->b_prev = NULL;
29798 
29799 			/* set up ill index for outbound qos processing */
29800 			out_ill = ire_to_ill(ire);
29801 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29802 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29803 			    ill_index);
29804 			if (first_mp == NULL) {
29805 				xmit_drop = B_TRUE;
29806 				BUMP_MIB(out_ill->ill_ip_mib,
29807 				    ipIfStatsOutDiscards);
29808 				goto next_mp;
29809 			}
29810 			/* non-ipsec hw accel case */
29811 			if (io == NULL || !io->ipsec_out_accelerated) {
29812 				/* send it */
29813 				q = ire->ire_stq;
29814 				if (proc == IPP_FWD_OUT) {
29815 					UPDATE_IB_PKT_COUNT(ire);
29816 				} else {
29817 					UPDATE_OB_PKT_COUNT(ire);
29818 				}
29819 				ire->ire_last_used_time = lbolt;
29820 
29821 				if (flow_ctl_enabled || canputnext(q)) {
29822 					if (proc == IPP_FWD_OUT) {
29823 
29824 					BUMP_MIB(out_ill->ill_ip_mib,
29825 					    ipIfStatsHCOutForwDatagrams);
29826 
29827 					}
29828 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29829 					    pkt_len);
29830 
29831 					putnext(q, first_mp);
29832 				} else {
29833 					BUMP_MIB(out_ill->ill_ip_mib,
29834 					    ipIfStatsOutDiscards);
29835 					xmit_drop = B_TRUE;
29836 					freemsg(first_mp);
29837 				}
29838 			} else {
29839 				/*
29840 				 * Safety Pup says: make sure this
29841 				 *  is going to the right interface!
29842 				 */
29843 				ill_t *ill1 =
29844 				    (ill_t *)ire->ire_stq->q_ptr;
29845 				int ifindex =
29846 				    ill1->ill_phyint->phyint_ifindex;
29847 				if (ifindex !=
29848 				    io->ipsec_out_capab_ill_index) {
29849 					xmit_drop = B_TRUE;
29850 					freemsg(mp);
29851 				} else {
29852 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
29853 					    pkt_len);
29854 					ipsec_hw_putnext(ire->ire_stq, mp);
29855 				}
29856 			}
29857 next_mp:
29858 			mp = nxt_mp;
29859 		} /* while (mp != NULL) */
29860 		if (xmit_drop)
29861 			return (SEND_FAILED);
29862 		else
29863 			return (SEND_PASSED);
29864 
29865 	case ND_INITIAL:
29866 	case ND_INCOMPLETE:
29867 
29868 		/*
29869 		 * While we do send off packets to dests that
29870 		 * use fully-resolved CGTP routes, we do not
29871 		 * handle unresolved CGTP routes.
29872 		 */
29873 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
29874 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
29875 
29876 		if (mp != NULL) {
29877 			/* queue the packet */
29878 			nce_queue_mp_common(arpce, mp, B_FALSE);
29879 		}
29880 
29881 		if (arpce->nce_state == ND_INCOMPLETE) {
29882 			mutex_exit(&arpce->nce_lock);
29883 			DTRACE_PROBE3(ip__xmit__incomplete,
29884 			    (ire_t *), ire, (mblk_t *), mp,
29885 			    (ipsec_out_t *), io);
29886 			return (LOOKUP_IN_PROGRESS);
29887 		}
29888 
29889 		arpce->nce_state = ND_INCOMPLETE;
29890 		mutex_exit(&arpce->nce_lock);
29891 		/*
29892 		 * Note that ire_add() (called from ire_forward())
29893 		 * holds a ref on the ire until ARP is completed.
29894 		 */
29895 
29896 		ire_arpresolve(ire, ire_to_ill(ire));
29897 		return (LOOKUP_IN_PROGRESS);
29898 	default:
29899 		ASSERT(0);
29900 		mutex_exit(&arpce->nce_lock);
29901 		return (LLHDR_RESLV_FAILED);
29902 	}
29903 }
29904 
29905 #undef	UPDATE_IP_MIB_OB_COUNTERS
29906 
29907 /*
29908  * Return B_TRUE if the buffers differ in length or content.
29909  * This is used for comparing extension header buffers.
29910  * Note that an extension header would be declared different
29911  * even if all that changed was the next header value in that header i.e.
29912  * what really changed is the next extension header.
29913  */
29914 boolean_t
29915 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
29916     uint_t blen)
29917 {
29918 	if (!b_valid)
29919 		blen = 0;
29920 
29921 	if (alen != blen)
29922 		return (B_TRUE);
29923 	if (alen == 0)
29924 		return (B_FALSE);	/* Both zero length */
29925 	return (bcmp(abuf, bbuf, alen));
29926 }
29927 
29928 /*
29929  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
29930  * Return B_FALSE if memory allocation fails - don't change any state!
29931  */
29932 boolean_t
29933 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29934     const void *src, uint_t srclen)
29935 {
29936 	void *dst;
29937 
29938 	if (!src_valid)
29939 		srclen = 0;
29940 
29941 	ASSERT(*dstlenp == 0);
29942 	if (src != NULL && srclen != 0) {
29943 		dst = mi_alloc(srclen, BPRI_MED);
29944 		if (dst == NULL)
29945 			return (B_FALSE);
29946 	} else {
29947 		dst = NULL;
29948 	}
29949 	if (*dstp != NULL)
29950 		mi_free(*dstp);
29951 	*dstp = dst;
29952 	*dstlenp = dst == NULL ? 0 : srclen;
29953 	return (B_TRUE);
29954 }
29955 
29956 /*
29957  * Replace what is in *dst, *dstlen with the source.
29958  * Assumes ip_allocbuf has already been called.
29959  */
29960 void
29961 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29962     const void *src, uint_t srclen)
29963 {
29964 	if (!src_valid)
29965 		srclen = 0;
29966 
29967 	ASSERT(*dstlenp == srclen);
29968 	if (src != NULL && srclen != 0)
29969 		bcopy(src, *dstp, srclen);
29970 }
29971 
29972 /*
29973  * Free the storage pointed to by the members of an ip6_pkt_t.
29974  */
29975 void
29976 ip6_pkt_free(ip6_pkt_t *ipp)
29977 {
29978 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
29979 
29980 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
29981 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
29982 		ipp->ipp_hopopts = NULL;
29983 		ipp->ipp_hopoptslen = 0;
29984 	}
29985 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
29986 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
29987 		ipp->ipp_rtdstopts = NULL;
29988 		ipp->ipp_rtdstoptslen = 0;
29989 	}
29990 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
29991 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
29992 		ipp->ipp_dstopts = NULL;
29993 		ipp->ipp_dstoptslen = 0;
29994 	}
29995 	if (ipp->ipp_fields & IPPF_RTHDR) {
29996 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
29997 		ipp->ipp_rthdr = NULL;
29998 		ipp->ipp_rthdrlen = 0;
29999 	}
30000 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
30001 	    IPPF_RTHDR);
30002 }
30003