xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision f6f4cb8ada400367a1921f6b93fb9e02f53ac5e6)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #include <sys/types.h>
29 #include <sys/stream.h>
30 #include <sys/dlpi.h>
31 #include <sys/stropts.h>
32 #include <sys/sysmacros.h>
33 #include <sys/strsubr.h>
34 #include <sys/strlog.h>
35 #include <sys/strsun.h>
36 #include <sys/zone.h>
37 #define	_SUN_TPI_VERSION 2
38 #include <sys/tihdr.h>
39 #include <sys/xti_inet.h>
40 #include <sys/ddi.h>
41 #include <sys/sunddi.h>
42 #include <sys/cmn_err.h>
43 #include <sys/debug.h>
44 #include <sys/kobj.h>
45 #include <sys/modctl.h>
46 #include <sys/atomic.h>
47 #include <sys/policy.h>
48 #include <sys/priv.h>
49 
50 #include <sys/systm.h>
51 #include <sys/param.h>
52 #include <sys/kmem.h>
53 #include <sys/sdt.h>
54 #include <sys/socket.h>
55 #include <sys/vtrace.h>
56 #include <sys/isa_defs.h>
57 #include <sys/mac.h>
58 #include <net/if.h>
59 #include <net/if_arp.h>
60 #include <net/route.h>
61 #include <sys/sockio.h>
62 #include <netinet/in.h>
63 #include <net/if_dl.h>
64 
65 #include <inet/common.h>
66 #include <inet/mi.h>
67 #include <inet/mib2.h>
68 #include <inet/nd.h>
69 #include <inet/arp.h>
70 #include <inet/snmpcom.h>
71 #include <inet/optcom.h>
72 #include <inet/kstatcom.h>
73 
74 #include <netinet/igmp_var.h>
75 #include <netinet/ip6.h>
76 #include <netinet/icmp6.h>
77 #include <netinet/sctp.h>
78 
79 #include <inet/ip.h>
80 #include <inet/ip_impl.h>
81 #include <inet/ip6.h>
82 #include <inet/ip6_asp.h>
83 #include <inet/tcp.h>
84 #include <inet/tcp_impl.h>
85 #include <inet/ip_multi.h>
86 #include <inet/ip_if.h>
87 #include <inet/ip_ire.h>
88 #include <inet/ip_ftable.h>
89 #include <inet/ip_rts.h>
90 #include <inet/ip_ndp.h>
91 #include <inet/ip_listutils.h>
92 #include <netinet/igmp.h>
93 #include <netinet/ip_mroute.h>
94 #include <inet/ipp_common.h>
95 
96 #include <net/pfkeyv2.h>
97 #include <inet/ipsec_info.h>
98 #include <inet/sadb.h>
99 #include <inet/ipsec_impl.h>
100 #include <sys/iphada.h>
101 #include <inet/tun.h>
102 #include <inet/ipdrop.h>
103 #include <inet/ip_netinfo.h>
104 
105 #include <sys/ethernet.h>
106 #include <net/if_types.h>
107 #include <sys/cpuvar.h>
108 
109 #include <ipp/ipp.h>
110 #include <ipp/ipp_impl.h>
111 #include <ipp/ipgpc/ipgpc.h>
112 
113 #include <sys/multidata.h>
114 #include <sys/pattr.h>
115 
116 #include <inet/ipclassifier.h>
117 #include <inet/sctp_ip.h>
118 #include <inet/sctp/sctp_impl.h>
119 #include <inet/udp_impl.h>
120 #include <inet/rawip_impl.h>
121 #include <inet/rts_impl.h>
122 #include <sys/sunddi.h>
123 
124 #include <sys/tsol/label.h>
125 #include <sys/tsol/tnet.h>
126 
127 #include <rpc/pmap_prot.h>
128 
129 /*
130  * Values for squeue switch:
131  * IP_SQUEUE_ENTER_NODRAIN: squeue_enter_nodrain
132  * IP_SQUEUE_ENTER: squeue_enter
133  * IP_SQUEUE_FILL: squeue_fill
134  */
135 int ip_squeue_enter = 2;	/* Setable in /etc/system */
136 
137 squeue_func_t ip_input_proc;
138 #define	SET_BPREV_FLAG(x)	((mblk_t *)(uintptr_t)(x))
139 
140 /*
141  * Setable in /etc/system
142  */
143 int ip_poll_normal_ms = 100;
144 int ip_poll_normal_ticks = 0;
145 int ip_modclose_ackwait_ms = 3000;
146 
147 /*
148  * It would be nice to have these present only in DEBUG systems, but the
149  * current design of the global symbol checking logic requires them to be
150  * unconditionally present.
151  */
152 uint_t ip_thread_data;			/* TSD key for debug support */
153 krwlock_t ip_thread_rwlock;
154 list_t	ip_thread_list;
155 
156 /*
157  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
158  */
159 
160 struct listptr_s {
161 	mblk_t	*lp_head;	/* pointer to the head of the list */
162 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
163 };
164 
165 typedef struct listptr_s listptr_t;
166 
167 /*
168  * This is used by ip_snmp_get_mib2_ip_route_media and
169  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
170  */
171 typedef struct iproutedata_s {
172 	uint_t		ird_idx;
173 	listptr_t	ird_route;	/* ipRouteEntryTable */
174 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
175 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
176 } iproutedata_t;
177 
178 /*
179  * Cluster specific hooks. These should be NULL when booted as a non-cluster
180  */
181 
182 /*
183  * Hook functions to enable cluster networking
184  * On non-clustered systems these vectors must always be NULL.
185  *
186  * Hook function to Check ip specified ip address is a shared ip address
187  * in the cluster
188  *
189  */
190 int (*cl_inet_isclusterwide)(uint8_t protocol,
191     sa_family_t addr_family, uint8_t *laddrp) = NULL;
192 
193 /*
194  * Hook function to generate cluster wide ip fragment identifier
195  */
196 uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
197     uint8_t *laddrp, uint8_t *faddrp) = NULL;
198 
199 /*
200  * Synchronization notes:
201  *
202  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
203  * MT level protection given by STREAMS. IP uses a combination of its own
204  * internal serialization mechanism and standard Solaris locking techniques.
205  * The internal serialization is per phyint (no IPMP) or per IPMP group.
206  * This is used to serialize plumbing operations, IPMP operations, certain
207  * multicast operations, most set ioctls, igmp/mld timers etc.
208  *
209  * Plumbing is a long sequence of operations involving message
210  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
211  * involved in plumbing operations. A natural model is to serialize these
212  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
213  * parallel without any interference. But various set ioctls on hme0 are best
214  * serialized. However if the system uses IPMP, the operations are easier if
215  * they are serialized on a per IPMP group basis since IPMP operations
216  * happen across ill's of a group. Thus the lowest common denominator is to
217  * serialize most set ioctls, multicast join/leave operations, IPMP operations
218  * igmp/mld timer operations, and processing of DLPI control messages received
219  * from drivers on a per IPMP group basis. If the system does not employ
220  * IPMP the serialization is on a per phyint basis. This serialization is
221  * provided by the ipsq_t and primitives operating on this. Details can
222  * be found in ip_if.c above the core primitives operating on ipsq_t.
223  *
224  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
225  * Simiarly lookup of an ire by a thread also returns a refheld ire.
226  * In addition ipif's and ill's referenced by the ire are also indirectly
227  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
228  * the ipif's address or netmask change as long as an ipif is refheld
229  * directly or indirectly. For example an SIOCLIFADDR ioctl that changes the
230  * address of an ipif has to go through the ipsq_t. This ensures that only
231  * 1 such exclusive operation proceeds at any time on the ipif. It then
232  * deletes all ires associated with this ipif, and waits for all refcnts
233  * associated with this ipif to come down to zero. The address is changed
234  * only after the ipif has been quiesced. Then the ipif is brought up again.
235  * More details are described above the comment in ip_sioctl_flags.
236  *
237  * Packet processing is based mostly on IREs and are fully multi-threaded
238  * using standard Solaris MT techniques.
239  *
240  * There are explicit locks in IP to handle:
241  * - The ip_g_head list maintained by mi_open_link() and friends.
242  *
243  * - The reassembly data structures (one lock per hash bucket)
244  *
245  * - conn_lock is meant to protect conn_t fields. The fields actually
246  *   protected by conn_lock are documented in the conn_t definition.
247  *
248  * - ire_lock to protect some of the fields of the ire, IRE tables
249  *   (one lock per hash bucket). Refer to ip_ire.c for details.
250  *
251  * - ndp_g_lock and nce_lock for protecting NCEs.
252  *
253  * - ill_lock protects fields of the ill and ipif. Details in ip.h
254  *
255  * - ill_g_lock: This is a global reader/writer lock. Protects the following
256  *	* The AVL tree based global multi list of all ills.
257  *	* The linked list of all ipifs of an ill
258  *	* The <ill-ipsq> mapping
259  *	* The ipsq->ipsq_phyint_list threaded by phyint_ipsq_next
260  *	* The illgroup list threaded by ill_group_next.
261  *	* <ill-phyint> association
262  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
263  *   into an ill, changing the <ill-ipsq> mapping of an ill, insertion/deletion
264  *   of an ill into the illgrp list, changing the <ill-phyint> assoc of an ill
265  *   will all have to hold the ill_g_lock as writer for the actual duration
266  *   of the insertion/deletion/change. More details about the <ill-ipsq> mapping
267  *   may be found in the IPMP section.
268  *
269  * - ill_lock:  This is a per ill mutex.
270  *   It protects some members of the ill and is documented below.
271  *   It also protects the <ill-ipsq> mapping
272  *   It also protects the illgroup list threaded by ill_group_next.
273  *   It also protects the <ill-phyint> assoc.
274  *   It also protects the list of ipifs hanging off the ill.
275  *
276  * - ipsq_lock: This is a per ipsq_t mutex lock.
277  *   This protects all the other members of the ipsq struct except
278  *   ipsq_refs and ipsq_phyint_list which are protected by ill_g_lock
279  *
280  * - illgrp_lock: This is a per ill_group mutex lock.
281  *   The only thing it protects is the illgrp_ill_schednext member of ill_group
282  *   which dictates which is the next ill in an ill_group that is to be chosen
283  *   for sending outgoing packets, through creation of an IRE_CACHE that
284  *   references this ill.
285  *
286  * - phyint_lock: This is a per phyint mutex lock. Protects just the
287  *   phyint_flags
288  *
289  * - ip_g_nd_lock: This is a global reader/writer lock.
290  *   Any call to nd_load to load a new parameter to the ND table must hold the
291  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
292  *   as reader.
293  *
294  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
295  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
296  *   uniqueness check also done atomically.
297  *
298  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
299  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
300  *   as a writer when adding or deleting elements from these lists, and
301  *   as a reader when walking these lists to send a SADB update to the
302  *   IPsec capable ills.
303  *
304  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
305  *   group list linked by ill_usesrc_grp_next. It also protects the
306  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
307  *   group is being added or deleted.  This lock is taken as a reader when
308  *   walking the list/group(eg: to get the number of members in a usesrc group).
309  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
310  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
311  *   example, it is not necessary to take this lock in the initial portion
312  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_groupname and
313  *   ip_sioctl_flags since the these operations are executed exclusively and
314  *   that ensures that the "usesrc group state" cannot change. The "usesrc
315  *   group state" change can happen only in the latter part of
316  *   ip_sioctl_slifusesrc and in ill_delete.
317  *
318  * Changing <ill-phyint>, <ill-ipsq>, <ill-illgroup> assocications.
319  *
320  * To change the <ill-phyint> association, the ill_g_lock must be held
321  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
322  * must be held.
323  *
324  * To change the <ill-ipsq> association the ill_g_lock must be held as writer
325  * and the ill_lock of the ill in question must be held.
326  *
327  * To change the <ill-illgroup> association the ill_g_lock must be held as
328  * writer and the ill_lock of the ill in question must be held.
329  *
330  * To add or delete an ipif from the list of ipifs hanging off the ill,
331  * ill_g_lock (writer) and ill_lock must be held and the thread must be
332  * a writer on the associated ipsq,.
333  *
334  * To add or delete an ill to the system, the ill_g_lock must be held as
335  * writer and the thread must be a writer on the associated ipsq.
336  *
337  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
338  * must be a writer on the associated ipsq.
339  *
340  * Lock hierarchy
341  *
342  * Some lock hierarchy scenarios are listed below.
343  *
344  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock
345  * ill_g_lock -> illgrp_lock -> ill_lock
346  * ill_g_lock -> ill_lock(s) -> phyint_lock
347  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
348  * ill_g_lock -> ip_addr_avail_lock
349  * conn_lock -> irb_lock -> ill_lock -> ire_lock
350  * ill_g_lock -> ip_g_nd_lock
351  *
352  * When more than 1 ill lock is needed to be held, all ill lock addresses
353  * are sorted on address and locked starting from highest addressed lock
354  * downward.
355  *
356  * IPsec scenarios
357  *
358  * ipsa_lock -> ill_g_lock -> ill_lock
359  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
360  * ipsec_capab_ills_lock -> ipsa_lock
361  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
362  *
363  * Trusted Solaris scenarios
364  *
365  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
366  * igsa_lock -> gcdb_lock
367  * gcgrp_rwlock -> ire_lock
368  * gcgrp_rwlock -> gcdb_lock
369  *
370  *
371  * Routing/forwarding table locking notes:
372  *
373  * Lock acquisition order: Radix tree lock, irb_lock.
374  * Requirements:
375  * i.  Walker must not hold any locks during the walker callback.
376  * ii  Walker must not see a truncated tree during the walk because of any node
377  *     deletion.
378  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
379  *     in many places in the code to walk the irb list. Thus even if all the
380  *     ires in a bucket have been deleted, we still can't free the radix node
381  *     until the ires have actually been inactive'd (freed).
382  *
383  * Tree traversal - Need to hold the global tree lock in read mode.
384  * Before dropping the global tree lock, need to either increment the ire_refcnt
385  * to ensure that the radix node can't be deleted.
386  *
387  * Tree add - Need to hold the global tree lock in write mode to add a
388  * radix node. To prevent the node from being deleted, increment the
389  * irb_refcnt, after the node is added to the tree. The ire itself is
390  * added later while holding the irb_lock, but not the tree lock.
391  *
392  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
393  * All associated ires must be inactive (i.e. freed), and irb_refcnt
394  * must be zero.
395  *
396  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
397  * global tree lock (read mode) for traversal.
398  *
399  * IPsec notes :
400  *
401  * IP interacts with the IPsec code (AH/ESP) by tagging a M_CTL message
402  * in front of the actual packet. For outbound datagrams, the M_CTL
403  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
404  * information used by the IPsec code for applying the right level of
405  * protection. The information initialized by IP in the ipsec_out_t
406  * is determined by the per-socket policy or global policy in the system.
407  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
408  * ipsec_info.h) which starts out with nothing in it. It gets filled
409  * with the right information if it goes through the AH/ESP code, which
410  * happens if the incoming packet is secure. The information initialized
411  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
412  * the policy requirements needed by per-socket policy or global policy
413  * is met or not.
414  *
415  * If there is both per-socket policy (set using setsockopt) and there
416  * is also global policy match for the 5 tuples of the socket,
417  * ipsec_override_policy() makes the decision of which one to use.
418  *
419  * For fully connected sockets i.e dst, src [addr, port] is known,
420  * conn_policy_cached is set indicating that policy has been cached.
421  * conn_in_enforce_policy may or may not be set depending on whether
422  * there is a global policy match or per-socket policy match.
423  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
424  * Once the right policy is set on the conn_t, policy cannot change for
425  * this socket. This makes life simpler for TCP (UDP ?) where
426  * re-transmissions go out with the same policy. For symmetry, policy
427  * is cached for fully connected UDP sockets also. Thus if policy is cached,
428  * it also implies that policy is latched i.e policy cannot change
429  * on these sockets. As we have the right policy on the conn, we don't
430  * have to lookup global policy for every outbound and inbound datagram
431  * and thus serving as an optimization. Note that a global policy change
432  * does not affect fully connected sockets if they have policy. If fully
433  * connected sockets did not have any policy associated with it, global
434  * policy change may affect them.
435  *
436  * IP Flow control notes:
437  *
438  * Non-TCP streams are flow controlled by IP. On the send side, if the packet
439  * cannot be sent down to the driver by IP, because of a canput failure, IP
440  * does a putq on the conn_wq. This will cause ip_wsrv to run on the conn_wq.
441  * ip_wsrv in turn, inserts the conn in a list of conn's that need to be drained
442  * when the flowcontrol condition subsides. Ultimately STREAMS backenables the
443  * ip_wsrv on the IP module, which in turn does a qenable of the conn_wq of the
444  * first conn in the list of conn's to be drained. ip_wsrv on this conn drains
445  * the queued messages, and removes the conn from the drain list, if all
446  * messages were drained. It also qenables the next conn in the drain list to
447  * continue the drain process.
448  *
449  * In reality the drain list is not a single list, but a configurable number
450  * of lists. The ip_wsrv on the IP module, qenables the first conn in each
451  * list. If the ip_wsrv of the next qenabled conn does not run, because the
452  * stream closes, ip_close takes responsibility to qenable the next conn in
453  * the drain list. The directly called ip_wput path always does a putq, if
454  * it cannot putnext. Thus synchronization problems are handled between
455  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
456  * functions that manipulate this drain list. Furthermore conn_drain_insert
457  * is called only from ip_wsrv, and there can be only 1 instance of ip_wsrv
458  * running on a queue at any time. conn_drain_tail can be simultaneously called
459  * from both ip_wsrv and ip_close.
460  *
461  * IPQOS notes:
462  *
463  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
464  * and IPQoS modules. IPPF includes hooks in IP at different control points
465  * (callout positions) which direct packets to IPQoS modules for policy
466  * processing. Policies, if present, are global.
467  *
468  * The callout positions are located in the following paths:
469  *		o local_in (packets destined for this host)
470  *		o local_out (packets orginating from this host )
471  *		o fwd_in  (packets forwarded by this m/c - inbound)
472  *		o fwd_out (packets forwarded by this m/c - outbound)
473  * Hooks at these callout points can be enabled/disabled using the ndd variable
474  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
475  * By default all the callout positions are enabled.
476  *
477  * Outbound (local_out)
478  * Hooks are placed in ip_wput_ire and ipsec_out_process.
479  *
480  * Inbound (local_in)
481  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
482  * TCP and UDP fanout routines.
483  *
484  * Forwarding (in and out)
485  * Hooks are placed in ip_rput_forward.
486  *
487  * IP Policy Framework processing (IPPF processing)
488  * Policy processing for a packet is initiated by ip_process, which ascertains
489  * that the classifier (ipgpc) is loaded and configured, failing which the
490  * packet resumes normal processing in IP. If the clasifier is present, the
491  * packet is acted upon by one or more IPQoS modules (action instances), per
492  * filters configured in ipgpc and resumes normal IP processing thereafter.
493  * An action instance can drop a packet in course of its processing.
494  *
495  * A boolean variable, ip_policy, is used in all the fanout routines that can
496  * invoke ip_process for a packet. This variable indicates if the packet should
497  * to be sent for policy processing. The variable is set to B_TRUE by default,
498  * i.e. when the routines are invoked in the normal ip procesing path for a
499  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
500  * ip_policy is set to B_FALSE for all the routines called in these two
501  * functions because, in the former case,  we don't process loopback traffic
502  * currently while in the latter, the packets have already been processed in
503  * icmp_inbound.
504  *
505  * Zones notes:
506  *
507  * The partitioning rules for networking are as follows:
508  * 1) Packets coming from a zone must have a source address belonging to that
509  * zone.
510  * 2) Packets coming from a zone can only be sent on a physical interface on
511  * which the zone has an IP address.
512  * 3) Between two zones on the same machine, packet delivery is only allowed if
513  * there's a matching route for the destination and zone in the forwarding
514  * table.
515  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
516  * different zones can bind to the same port with the wildcard address
517  * (INADDR_ANY).
518  *
519  * The granularity of interface partitioning is at the logical interface level.
520  * Therefore, every zone has its own IP addresses, and incoming packets can be
521  * attributed to a zone unambiguously. A logical interface is placed into a zone
522  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
523  * structure. Rule (1) is implemented by modifying the source address selection
524  * algorithm so that the list of eligible addresses is filtered based on the
525  * sending process zone.
526  *
527  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
528  * across all zones, depending on their type. Here is the break-up:
529  *
530  * IRE type				Shared/exclusive
531  * --------				----------------
532  * IRE_BROADCAST			Exclusive
533  * IRE_DEFAULT (default routes)		Shared (*)
534  * IRE_LOCAL				Exclusive (x)
535  * IRE_LOOPBACK				Exclusive
536  * IRE_PREFIX (net routes)		Shared (*)
537  * IRE_CACHE				Exclusive
538  * IRE_IF_NORESOLVER (interface routes)	Exclusive
539  * IRE_IF_RESOLVER (interface routes)	Exclusive
540  * IRE_HOST (host routes)		Shared (*)
541  *
542  * (*) A zone can only use a default or off-subnet route if the gateway is
543  * directly reachable from the zone, that is, if the gateway's address matches
544  * one of the zone's logical interfaces.
545  *
546  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
547  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
548  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
549  * address of the zone itself (the destination). Since IRE_LOCAL is used
550  * for communication between zones, ip_wput_ire has special logic to set
551  * the right source address when sending using an IRE_LOCAL.
552  *
553  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
554  * ire_cache_lookup restricts loopback using an IRE_LOCAL
555  * between zone to the case when L2 would have conceptually looped the packet
556  * back, i.e. the loopback which is required since neither Ethernet drivers
557  * nor Ethernet hardware loops them back. This is the case when the normal
558  * routes (ignoring IREs with different zoneids) would send out the packet on
559  * the same ill (or ill group) as the ill with which is IRE_LOCAL is
560  * associated.
561  *
562  * Multiple zones can share a common broadcast address; typically all zones
563  * share the 255.255.255.255 address. Incoming as well as locally originated
564  * broadcast packets must be dispatched to all the zones on the broadcast
565  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
566  * since some zones may not be on the 10.16.72/24 network. To handle this, each
567  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
568  * sent to every zone that has an IRE_BROADCAST entry for the destination
569  * address on the input ill, see conn_wantpacket().
570  *
571  * Applications in different zones can join the same multicast group address.
572  * For IPv4, group memberships are per-logical interface, so they're already
573  * inherently part of a zone. For IPv6, group memberships are per-physical
574  * interface, so we distinguish IPv6 group memberships based on group address,
575  * interface and zoneid. In both cases, received multicast packets are sent to
576  * every zone for which a group membership entry exists. On IPv6 we need to
577  * check that the target zone still has an address on the receiving physical
578  * interface; it could have been removed since the application issued the
579  * IPV6_JOIN_GROUP.
580  */
581 
582 /*
583  * Squeue Fanout flags:
584  *	0: No fanout.
585  *	1: Fanout across all squeues
586  */
587 boolean_t	ip_squeue_fanout = 0;
588 
589 /*
590  * Maximum dups allowed per packet.
591  */
592 uint_t ip_max_frag_dups = 10;
593 
594 #define	IS_SIMPLE_IPH(ipha)						\
595 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
596 
597 /* RFC1122 Conformance */
598 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
599 
600 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
601 
602 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
603 
604 static int	ip_open(queue_t *q, dev_t *devp, int flag, int sflag,
605 		    cred_t *credp, boolean_t isv6);
606 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t,
607 		    ipha_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_sa; /* for minor nos. from INET_MIN_DEV+2 thru 2^^18-1 */
789 vmem_t *ip_minor_arena_la; /* for minor nos. from 2^^18 thru 2^^32-1 */
790 
791 int	ip_debug;
792 
793 #ifdef DEBUG
794 uint32_t ipsechw_debug = 0;
795 #endif
796 
797 /*
798  * Multirouting/CGTP stuff
799  */
800 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
801 
802 /*
803  * XXX following really should only be in a header. Would need more
804  * header and .c clean up first.
805  */
806 extern optdb_obj_t	ip_opt_obj;
807 
808 ulong_t ip_squeue_enter_unbound = 0;
809 
810 /*
811  * Named Dispatch Parameter Table.
812  * All of these are alterable, within the min/max values given, at run time.
813  */
814 static ipparam_t	lcl_param_arr[] = {
815 	/* min	max	value	name */
816 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
817 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
818 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
819 	{  0,	1,	0,	"ip_respond_to_timestamp"},
820 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
821 	{  0,	1,	1,	"ip_send_redirects"},
822 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
823 	{  0,	10,	0,	"ip_mrtdebug"},
824 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
825 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
826 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
827 	{  1,	255,	255,	"ip_def_ttl" },
828 	{  0,	1,	0,	"ip_forward_src_routed"},
829 	{  0,	256,	32,	"ip_wroff_extra" },
830 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
831 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
832 	{  0,	1,	1,	"ip_path_mtu_discovery" },
833 	{  0,	240,	30,	"ip_ignore_delete_time" },
834 	{  0,	1,	0,	"ip_ignore_redirect" },
835 	{  0,	1,	1,	"ip_output_queue" },
836 	{  1,	254,	1,	"ip_broadcast_ttl" },
837 	{  0,	99999,	100,	"ip_icmp_err_interval" },
838 	{  1,	99999,	10,	"ip_icmp_err_burst" },
839 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
840 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
841 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
842 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
843 	{  0,	1,	1,	"icmp_accept_clear_messages" },
844 	{  0,	1,	1,	"igmp_accept_clear_messages" },
845 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
846 				"ip_ndp_delay_first_probe_time"},
847 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
848 				"ip_ndp_max_unicast_solicit"},
849 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
850 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
851 	{  0,	1,	0,	"ip6_forward_src_routed"},
852 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
853 	{  0,	1,	1,	"ip6_send_redirects"},
854 	{  0,	1,	0,	"ip6_ignore_redirect" },
855 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
856 
857 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
858 
859 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
860 
861 	{  0,	1,	1,	"pim_accept_clear_messages" },
862 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
863 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
864 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
865 	{  0,	15,	0,	"ip_policy_mask" },
866 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
867 	{  0,	255,	1,	"ip_multirt_ttl" },
868 	{  0,	1,	1,	"ip_multidata_outbound" },
869 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
870 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
871 	{  0,	1000,	1,	"ip_max_temp_defend" },
872 	{  0,	1000,	3,	"ip_max_defend" },
873 	{  0,	999999,	30,	"ip_defend_interval" },
874 	{  0,	3600000, 300000, "ip_dup_recovery" },
875 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
876 	{  0,	1,	1,	"ip_lso_outbound" },
877 	{  IGMP_V1_ROUTER, IGMP_V3_ROUTER, IGMP_V3_ROUTER, "igmp_max_version" },
878 	{  MLD_V1_ROUTER, MLD_V2_ROUTER, MLD_V2_ROUTER, "mld_max_version" },
879 #ifdef DEBUG
880 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
881 #else
882 	{  0,	0,	0,	"" },
883 #endif
884 };
885 
886 /*
887  * Extended NDP table
888  * The addresses for the first two are filled in to be ips_ip_g_forward
889  * and ips_ipv6_forward at init time.
890  */
891 static ipndp_t	lcl_ndp_arr[] = {
892 	/* getf			setf		data			name */
893 #define	IPNDP_IP_FORWARDING_OFFSET	0
894 	{  ip_param_generic_get,	ip_forward_set,	NULL,
895 	    "ip_forwarding" },
896 #define	IPNDP_IP6_FORWARDING_OFFSET	1
897 	{  ip_param_generic_get,	ip_forward_set,	NULL,
898 	    "ip6_forwarding" },
899 	{  ip_ill_report,	NULL,		NULL,
900 	    "ip_ill_status" },
901 	{  ip_ipif_report,	NULL,		NULL,
902 	    "ip_ipif_status" },
903 	{  ip_conn_report,	NULL,		NULL,
904 	    "ip_conn_status" },
905 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
906 	    "ip_rput_pullups" },
907 	{  ip_srcid_report,	NULL,		NULL,
908 	    "ip_srcid_status" },
909 	{ ip_param_generic_get, ip_squeue_profile_set,
910 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
911 	{ ip_param_generic_get, ip_squeue_bind_set,
912 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
913 	{ ip_param_generic_get, ip_input_proc_set,
914 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
915 	{ ip_param_generic_get, ip_int_set,
916 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
917 #define	IPNDP_CGTP_FILTER_OFFSET	11
918 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
919 	    "ip_cgtp_filter" },
920 	{ ip_param_generic_get, ip_int_set,
921 	    (caddr_t)&ip_soft_rings_cnt, "ip_soft_rings_cnt" },
922 #define	IPNDP_IPMP_HOOK_OFFSET	13
923 	{  ip_param_generic_get, ipmp_hook_emulation_set, NULL,
924 	    "ipmp_hook_emulation" },
925 	{  ip_param_generic_get, ip_int_set, (caddr_t)&ip_debug,
926 	    "ip_debug" },
927 };
928 
929 /*
930  * Table of IP ioctls encoding the various properties of the ioctl and
931  * indexed based on the last byte of the ioctl command. Occasionally there
932  * is a clash, and there is more than 1 ioctl with the same last byte.
933  * In such a case 1 ioctl is encoded in the ndx table and the remaining
934  * ioctls are encoded in the misc table. An entry in the ndx table is
935  * retrieved by indexing on the last byte of the ioctl command and comparing
936  * the ioctl command with the value in the ndx table. In the event of a
937  * mismatch the misc table is then searched sequentially for the desired
938  * ioctl command.
939  *
940  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
941  */
942 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
943 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
944 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
945 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
946 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
947 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
948 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
949 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
950 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
951 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
952 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
953 
954 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
955 			MISC_CMD, ip_siocaddrt, NULL },
956 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
957 			MISC_CMD, ip_siocdelrt, NULL },
958 
959 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
960 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
961 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
962 			IF_CMD, ip_sioctl_get_addr, NULL },
963 
964 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
965 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
966 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
967 			IPI_GET_CMD | IPI_REPL,
968 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
969 
970 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
971 			IPI_PRIV | IPI_WR | IPI_REPL,
972 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
973 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
974 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
975 			IF_CMD, ip_sioctl_get_flags, NULL },
976 
977 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
978 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
979 
980 	/* copyin size cannot be coded for SIOCGIFCONF */
981 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
982 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
983 
984 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
985 			IF_CMD, ip_sioctl_mtu, NULL },
986 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
987 			IF_CMD, ip_sioctl_get_mtu, NULL },
988 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
989 			IPI_GET_CMD | IPI_REPL,
990 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
991 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
992 			IF_CMD, ip_sioctl_brdaddr, NULL },
993 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
994 			IPI_GET_CMD | IPI_REPL,
995 			IF_CMD, ip_sioctl_get_netmask, NULL },
996 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
997 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
998 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
999 			IPI_GET_CMD | IPI_REPL,
1000 			IF_CMD, ip_sioctl_get_metric, NULL },
1001 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1002 			IF_CMD, ip_sioctl_metric, NULL },
1003 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1004 
1005 	/* See 166-168 below for extended SIOC*XARP ioctls */
1006 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1007 			ARP_CMD, ip_sioctl_arp, NULL },
1008 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1009 			ARP_CMD, ip_sioctl_arp, NULL },
1010 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1011 			ARP_CMD, ip_sioctl_arp, NULL },
1012 
1013 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1014 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1015 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1016 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1017 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1018 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1019 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1020 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1021 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1022 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1023 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1024 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1025 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1026 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1027 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1028 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1029 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1030 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1031 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1032 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1033 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1034 
1035 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1036 			MISC_CMD, if_unitsel, if_unitsel_restart },
1037 
1038 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1039 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1040 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1041 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1042 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1043 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1044 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1045 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1046 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1047 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1048 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1049 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1050 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1051 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1052 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1053 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1054 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1055 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1056 
1057 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1058 			IPI_PRIV | IPI_WR | IPI_MODOK,
1059 			IF_CMD, ip_sioctl_sifname, NULL },
1060 
1061 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1062 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1063 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1064 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1065 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1066 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1067 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1068 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1069 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1070 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1071 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1072 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1073 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1074 
1075 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1076 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1077 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1078 			IF_CMD, ip_sioctl_get_muxid, NULL },
1079 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1080 			IPI_PRIV | IPI_WR | IPI_REPL,
1081 			IF_CMD, ip_sioctl_muxid, NULL },
1082 
1083 	/* Both if and lif variants share same func */
1084 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1085 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1086 	/* Both if and lif variants share same func */
1087 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1088 			IPI_PRIV | IPI_WR | IPI_REPL,
1089 			IF_CMD, ip_sioctl_slifindex, NULL },
1090 
1091 	/* copyin size cannot be coded for SIOCGIFCONF */
1092 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
1093 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1094 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1095 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1096 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1097 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1098 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1099 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1100 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1101 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1102 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1103 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1104 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1105 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1106 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1109 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1110 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1111 
1112 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1113 			IPI_PRIV | IPI_WR | IPI_REPL,
1114 			LIF_CMD, ip_sioctl_removeif,
1115 			ip_sioctl_removeif_restart },
1116 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1117 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1118 			LIF_CMD, ip_sioctl_addif, NULL },
1119 #define	SIOCLIFADDR_NDX 112
1120 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1121 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1122 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1123 			IPI_GET_CMD | IPI_REPL,
1124 			LIF_CMD, ip_sioctl_get_addr, NULL },
1125 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1126 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1127 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1128 			IPI_GET_CMD | IPI_REPL,
1129 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1130 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1131 			IPI_PRIV | IPI_WR | IPI_REPL,
1132 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1133 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1134 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1135 			LIF_CMD, ip_sioctl_get_flags, NULL },
1136 
1137 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1138 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1139 
1140 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1141 			ip_sioctl_get_lifconf, NULL },
1142 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1143 			LIF_CMD, ip_sioctl_mtu, NULL },
1144 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1145 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1146 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1147 			IPI_GET_CMD | IPI_REPL,
1148 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1149 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1150 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1151 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1152 			IPI_GET_CMD | IPI_REPL,
1153 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1154 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1155 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1156 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1157 			IPI_GET_CMD | IPI_REPL,
1158 			LIF_CMD, ip_sioctl_get_metric, NULL },
1159 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1160 			LIF_CMD, ip_sioctl_metric, NULL },
1161 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1162 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1163 			LIF_CMD, ip_sioctl_slifname,
1164 			ip_sioctl_slifname_restart },
1165 
1166 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1167 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1168 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1169 			IPI_GET_CMD | IPI_REPL,
1170 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1171 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1172 			IPI_PRIV | IPI_WR | IPI_REPL,
1173 			LIF_CMD, ip_sioctl_muxid, NULL },
1174 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1175 			IPI_GET_CMD | IPI_REPL,
1176 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1177 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1178 			IPI_PRIV | IPI_WR | IPI_REPL,
1179 			LIF_CMD, ip_sioctl_slifindex, 0 },
1180 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1181 			LIF_CMD, ip_sioctl_token, NULL },
1182 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1183 			IPI_GET_CMD | IPI_REPL,
1184 			LIF_CMD, ip_sioctl_get_token, NULL },
1185 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1186 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1187 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1188 			IPI_GET_CMD | IPI_REPL,
1189 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1190 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1191 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1192 
1193 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1194 			IPI_GET_CMD | IPI_REPL,
1195 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1196 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1197 			LIF_CMD, ip_siocdelndp_v6, NULL },
1198 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1199 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1200 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1201 			LIF_CMD, ip_siocsetndp_v6, NULL },
1202 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1203 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1204 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1205 			MISC_CMD, ip_sioctl_tonlink, NULL },
1206 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1207 			MISC_CMD, ip_sioctl_tmysite, NULL },
1208 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1209 			TUN_CMD, ip_sioctl_tunparam, NULL },
1210 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1211 			IPI_PRIV | IPI_WR,
1212 			TUN_CMD, ip_sioctl_tunparam, NULL },
1213 
1214 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1215 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1216 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1217 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1218 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1219 
1220 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1221 			IPI_PRIV | IPI_WR | IPI_REPL,
1222 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1223 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1224 			IPI_PRIV | IPI_WR | IPI_REPL,
1225 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1226 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1227 			IPI_PRIV | IPI_WR | IPI_REPL,
1228 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1229 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1230 			IPI_GET_CMD | IPI_REPL,
1231 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1232 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1233 			IPI_GET_CMD | IPI_REPL,
1234 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1235 
1236 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1237 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1238 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1239 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1240 
1241 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1242 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1243 
1244 	/* These are handled in ip_sioctl_copyin_setup itself */
1245 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1246 			MISC_CMD, NULL, NULL },
1247 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1248 			MISC_CMD, NULL, NULL },
1249 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1250 
1251 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1252 			ip_sioctl_get_lifconf, NULL },
1253 
1254 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1255 			XARP_CMD, ip_sioctl_arp, NULL },
1256 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1257 			XARP_CMD, ip_sioctl_arp, NULL },
1258 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1259 			XARP_CMD, ip_sioctl_arp, NULL },
1260 
1261 	/* SIOCPOPSOCKFS is not handled by IP */
1262 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1263 
1264 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1265 			IPI_GET_CMD | IPI_REPL,
1266 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1267 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1268 			IPI_PRIV | IPI_WR | IPI_REPL,
1269 			LIF_CMD, ip_sioctl_slifzone,
1270 			ip_sioctl_slifzone_restart },
1271 	/* 172-174 are SCTP ioctls and not handled by IP */
1272 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1273 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1274 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1275 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1276 			IPI_GET_CMD, LIF_CMD,
1277 			ip_sioctl_get_lifusesrc, 0 },
1278 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1279 			IPI_PRIV | IPI_WR,
1280 			LIF_CMD, ip_sioctl_slifusesrc,
1281 			NULL },
1282 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1283 			ip_sioctl_get_lifsrcof, NULL },
1284 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1285 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1286 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1287 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1288 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1289 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1290 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1291 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1292 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1293 			ip_sioctl_set_ipmpfailback, NULL },
1294 	/* SIOCSENABLESDP is handled by SDP */
1295 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1296 };
1297 
1298 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1299 
1300 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1301 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1302 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1303 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1304 		TUN_CMD, ip_sioctl_tunparam, NULL },
1305 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1306 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1307 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1308 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1309 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1310 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1311 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1312 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1313 		MISC_CMD, mrt_ioctl},
1314 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1315 		MISC_CMD, mrt_ioctl},
1316 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1317 		MISC_CMD, mrt_ioctl}
1318 };
1319 
1320 int ip_misc_ioctl_count =
1321     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1322 
1323 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1324 					/* Settable in /etc/system */
1325 /* Defined in ip_ire.c */
1326 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1327 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1328 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1329 
1330 static nv_t	ire_nv_arr[] = {
1331 	{ IRE_BROADCAST, "BROADCAST" },
1332 	{ IRE_LOCAL, "LOCAL" },
1333 	{ IRE_LOOPBACK, "LOOPBACK" },
1334 	{ IRE_CACHE, "CACHE" },
1335 	{ IRE_DEFAULT, "DEFAULT" },
1336 	{ IRE_PREFIX, "PREFIX" },
1337 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1338 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1339 	{ IRE_HOST, "HOST" },
1340 	{ 0 }
1341 };
1342 
1343 nv_t	*ire_nv_tbl = ire_nv_arr;
1344 
1345 /* Simple ICMP IP Header Template */
1346 static ipha_t icmp_ipha = {
1347 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1348 };
1349 
1350 struct module_info ip_mod_info = {
1351 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1352 };
1353 
1354 /*
1355  * Duplicate static symbols within a module confuses mdb; so we avoid the
1356  * problem by making the symbols here distinct from those in udp.c.
1357  */
1358 
1359 /*
1360  * Entry points for IP as a device and as a module.
1361  * FIXME: down the road we might want a separate module and driver qinit.
1362  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1363  */
1364 static struct qinit iprinitv4 = {
1365 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1366 	&ip_mod_info
1367 };
1368 
1369 struct qinit iprinitv6 = {
1370 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1371 	&ip_mod_info
1372 };
1373 
1374 static struct qinit ipwinitv4 = {
1375 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1376 	&ip_mod_info
1377 };
1378 
1379 struct qinit ipwinitv6 = {
1380 	(pfi_t)ip_wput_v6, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1381 	&ip_mod_info
1382 };
1383 
1384 static struct qinit iplrinit = {
1385 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1386 	&ip_mod_info
1387 };
1388 
1389 static struct qinit iplwinit = {
1390 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1391 	&ip_mod_info
1392 };
1393 
1394 /* For AF_INET aka /dev/ip */
1395 struct streamtab ipinfov4 = {
1396 	&iprinitv4, &ipwinitv4, &iplrinit, &iplwinit
1397 };
1398 
1399 /* For AF_INET6 aka /dev/ip6 */
1400 struct streamtab ipinfov6 = {
1401 	&iprinitv6, &ipwinitv6, &iplrinit, &iplwinit
1402 };
1403 
1404 #ifdef	DEBUG
1405 static boolean_t skip_sctp_cksum = B_FALSE;
1406 #endif
1407 
1408 /*
1409  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1410  * ip_rput_v6(), ip_output(), etc.  If the message
1411  * block already has a M_CTL at the front of it, then simply set the zoneid
1412  * appropriately.
1413  */
1414 mblk_t *
1415 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1416 {
1417 	mblk_t		*first_mp;
1418 	ipsec_out_t	*io;
1419 
1420 	ASSERT(zoneid != ALL_ZONES);
1421 	if (mp->b_datap->db_type == M_CTL) {
1422 		io = (ipsec_out_t *)mp->b_rptr;
1423 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1424 		io->ipsec_out_zoneid = zoneid;
1425 		return (mp);
1426 	}
1427 
1428 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1429 	if (first_mp == NULL)
1430 		return (NULL);
1431 	io = (ipsec_out_t *)first_mp->b_rptr;
1432 	/* This is not a secure packet */
1433 	io->ipsec_out_secure = B_FALSE;
1434 	io->ipsec_out_zoneid = zoneid;
1435 	first_mp->b_cont = mp;
1436 	return (first_mp);
1437 }
1438 
1439 /*
1440  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1441  */
1442 mblk_t *
1443 ip_copymsg(mblk_t *mp)
1444 {
1445 	mblk_t *nmp;
1446 	ipsec_info_t *in;
1447 
1448 	if (mp->b_datap->db_type != M_CTL)
1449 		return (copymsg(mp));
1450 
1451 	in = (ipsec_info_t *)mp->b_rptr;
1452 
1453 	/*
1454 	 * Note that M_CTL is also used for delivering ICMP error messages
1455 	 * upstream to transport layers.
1456 	 */
1457 	if (in->ipsec_info_type != IPSEC_OUT &&
1458 	    in->ipsec_info_type != IPSEC_IN)
1459 		return (copymsg(mp));
1460 
1461 	nmp = copymsg(mp->b_cont);
1462 
1463 	if (in->ipsec_info_type == IPSEC_OUT) {
1464 		return (ipsec_out_tag(mp, nmp,
1465 		    ((ipsec_out_t *)in)->ipsec_out_ns));
1466 	} else {
1467 		return (ipsec_in_tag(mp, nmp,
1468 		    ((ipsec_in_t *)in)->ipsec_in_ns));
1469 	}
1470 }
1471 
1472 /* Generate an ICMP fragmentation needed message. */
1473 static void
1474 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1475     ip_stack_t *ipst)
1476 {
1477 	icmph_t	icmph;
1478 	mblk_t *first_mp;
1479 	boolean_t mctl_present;
1480 
1481 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1482 
1483 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1484 		if (mctl_present)
1485 			freeb(first_mp);
1486 		return;
1487 	}
1488 
1489 	bzero(&icmph, sizeof (icmph_t));
1490 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1491 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1492 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1493 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1494 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1495 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1496 	    ipst);
1497 }
1498 
1499 /*
1500  * icmp_inbound deals with ICMP messages in the following ways.
1501  *
1502  * 1) It needs to send a reply back and possibly delivering it
1503  *    to the "interested" upper clients.
1504  * 2) It needs to send it to the upper clients only.
1505  * 3) It needs to change some values in IP only.
1506  * 4) It needs to change some values in IP and upper layers e.g TCP.
1507  *
1508  * We need to accomodate icmp messages coming in clear until we get
1509  * everything secure from the wire. If icmp_accept_clear_messages
1510  * is zero we check with the global policy and act accordingly. If
1511  * it is non-zero, we accept the message without any checks. But
1512  * *this does not mean* that this will be delivered to the upper
1513  * clients. By accepting we might send replies back, change our MTU
1514  * value etc. but delivery to the ULP/clients depends on their policy
1515  * dispositions.
1516  *
1517  * We handle the above 4 cases in the context of IPsec in the
1518  * following way :
1519  *
1520  * 1) Send the reply back in the same way as the request came in.
1521  *    If it came in encrypted, it goes out encrypted. If it came in
1522  *    clear, it goes out in clear. Thus, this will prevent chosen
1523  *    plain text attack.
1524  * 2) The client may or may not expect things to come in secure.
1525  *    If it comes in secure, the policy constraints are checked
1526  *    before delivering it to the upper layers. If it comes in
1527  *    clear, ipsec_inbound_accept_clear will decide whether to
1528  *    accept this in clear or not. In both the cases, if the returned
1529  *    message (IP header + 8 bytes) that caused the icmp message has
1530  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1531  *    sending up. If there are only 8 bytes of returned message, then
1532  *    upper client will not be notified.
1533  * 3) Check with global policy to see whether it matches the constaints.
1534  *    But this will be done only if icmp_accept_messages_in_clear is
1535  *    zero.
1536  * 4) If we need to change both in IP and ULP, then the decision taken
1537  *    while affecting the values in IP and while delivering up to TCP
1538  *    should be the same.
1539  *
1540  * 	There are two cases.
1541  *
1542  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1543  *	   failed), we will not deliver it to the ULP, even though they
1544  *	   are *willing* to accept in *clear*. This is fine as our global
1545  *	   disposition to icmp messages asks us reject the datagram.
1546  *
1547  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1548  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1549  *	   to deliver it to ULP (policy failed), it can lead to
1550  *	   consistency problems. The cases known at this time are
1551  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1552  *	   values :
1553  *
1554  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1555  *	     and Upper layer rejects. Then the communication will
1556  *	     come to a stop. This is solved by making similar decisions
1557  *	     at both levels. Currently, when we are unable to deliver
1558  *	     to the Upper Layer (due to policy failures) while IP has
1559  *	     adjusted ire_max_frag, the next outbound datagram would
1560  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1561  *	     will be with the right level of protection. Thus the right
1562  *	     value will be communicated even if we are not able to
1563  *	     communicate when we get from the wire initially. But this
1564  *	     assumes there would be at least one outbound datagram after
1565  *	     IP has adjusted its ire_max_frag value. To make things
1566  *	     simpler, we accept in clear after the validation of
1567  *	     AH/ESP headers.
1568  *
1569  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1570  *	     upper layer depending on the level of protection the upper
1571  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1572  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1573  *	     should be accepted in clear when the Upper layer expects secure.
1574  *	     Thus the communication may get aborted by some bad ICMP
1575  *	     packets.
1576  *
1577  * IPQoS Notes:
1578  * The only instance when a packet is sent for processing is when there
1579  * isn't an ICMP client and if we are interested in it.
1580  * If there is a client, IPPF processing will take place in the
1581  * ip_fanout_proto routine.
1582  *
1583  * Zones notes:
1584  * The packet is only processed in the context of the specified zone: typically
1585  * only this zone will reply to an echo request, and only interested clients in
1586  * this zone will receive a copy of the packet. This means that the caller must
1587  * call icmp_inbound() for each relevant zone.
1588  */
1589 static void
1590 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1591     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1592     ill_t *recv_ill, zoneid_t zoneid)
1593 {
1594 	icmph_t	*icmph;
1595 	ipha_t	*ipha;
1596 	int	iph_hdr_length;
1597 	int	hdr_length;
1598 	boolean_t	interested;
1599 	uint32_t	ts;
1600 	uchar_t	*wptr;
1601 	ipif_t	*ipif;
1602 	mblk_t *first_mp;
1603 	ipsec_in_t *ii;
1604 	ire_t *src_ire;
1605 	boolean_t onlink;
1606 	timestruc_t now;
1607 	uint32_t ill_index;
1608 	ip_stack_t *ipst;
1609 
1610 	ASSERT(ill != NULL);
1611 	ipst = ill->ill_ipst;
1612 
1613 	first_mp = mp;
1614 	if (mctl_present) {
1615 		mp = first_mp->b_cont;
1616 		ASSERT(mp != NULL);
1617 	}
1618 
1619 	ipha = (ipha_t *)mp->b_rptr;
1620 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1621 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1622 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1623 		if (first_mp == NULL)
1624 			return;
1625 	}
1626 
1627 	/*
1628 	 * On a labeled system, we have to check whether the zone itself is
1629 	 * permitted to receive raw traffic.
1630 	 */
1631 	if (is_system_labeled()) {
1632 		if (zoneid == ALL_ZONES)
1633 			zoneid = tsol_packet_to_zoneid(mp);
1634 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1635 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1636 			    zoneid));
1637 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1638 			freemsg(first_mp);
1639 			return;
1640 		}
1641 	}
1642 
1643 	/*
1644 	 * We have accepted the ICMP message. It means that we will
1645 	 * respond to the packet if needed. It may not be delivered
1646 	 * to the upper client depending on the policy constraints
1647 	 * and the disposition in ipsec_inbound_accept_clear.
1648 	 */
1649 
1650 	ASSERT(ill != NULL);
1651 
1652 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1653 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1654 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1655 		/* Last chance to get real. */
1656 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1657 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1658 			freemsg(first_mp);
1659 			return;
1660 		}
1661 		/* Refresh iph following the pullup. */
1662 		ipha = (ipha_t *)mp->b_rptr;
1663 	}
1664 	/* ICMP header checksum, including checksum field, should be zero. */
1665 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1666 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1667 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1668 		freemsg(first_mp);
1669 		return;
1670 	}
1671 	/* The IP header will always be a multiple of four bytes */
1672 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1673 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1674 	    icmph->icmph_code));
1675 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1676 	/* We will set "interested" to "true" if we want a copy */
1677 	interested = B_FALSE;
1678 	switch (icmph->icmph_type) {
1679 	case ICMP_ECHO_REPLY:
1680 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1681 		break;
1682 	case ICMP_DEST_UNREACHABLE:
1683 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1684 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1685 		interested = B_TRUE;	/* Pass up to transport */
1686 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1687 		break;
1688 	case ICMP_SOURCE_QUENCH:
1689 		interested = B_TRUE;	/* Pass up to transport */
1690 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1691 		break;
1692 	case ICMP_REDIRECT:
1693 		if (!ipst->ips_ip_ignore_redirect)
1694 			interested = B_TRUE;
1695 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1696 		break;
1697 	case ICMP_ECHO_REQUEST:
1698 		/*
1699 		 * Whether to respond to echo requests that come in as IP
1700 		 * broadcasts or as IP multicast is subject to debate
1701 		 * (what isn't?).  We aim to please, you pick it.
1702 		 * Default is do it.
1703 		 */
1704 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1705 			/* unicast: always respond */
1706 			interested = B_TRUE;
1707 		} else if (CLASSD(ipha->ipha_dst)) {
1708 			/* multicast: respond based on tunable */
1709 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1710 		} else if (broadcast) {
1711 			/* broadcast: respond based on tunable */
1712 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1713 		}
1714 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1715 		break;
1716 	case ICMP_ROUTER_ADVERTISEMENT:
1717 	case ICMP_ROUTER_SOLICITATION:
1718 		break;
1719 	case ICMP_TIME_EXCEEDED:
1720 		interested = B_TRUE;	/* Pass up to transport */
1721 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1722 		break;
1723 	case ICMP_PARAM_PROBLEM:
1724 		interested = B_TRUE;	/* Pass up to transport */
1725 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1726 		break;
1727 	case ICMP_TIME_STAMP_REQUEST:
1728 		/* Response to Time Stamp Requests is local policy. */
1729 		if (ipst->ips_ip_g_resp_to_timestamp &&
1730 		    /* So is whether to respond if it was an IP broadcast. */
1731 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1732 			int tstamp_len = 3 * sizeof (uint32_t);
1733 
1734 			if (wptr +  tstamp_len > mp->b_wptr) {
1735 				if (!pullupmsg(mp, wptr + tstamp_len -
1736 				    mp->b_rptr)) {
1737 					BUMP_MIB(ill->ill_ip_mib,
1738 					    ipIfStatsInDiscards);
1739 					freemsg(first_mp);
1740 					return;
1741 				}
1742 				/* Refresh ipha following the pullup. */
1743 				ipha = (ipha_t *)mp->b_rptr;
1744 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1745 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1746 			}
1747 			interested = B_TRUE;
1748 		}
1749 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1750 		break;
1751 	case ICMP_TIME_STAMP_REPLY:
1752 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1753 		break;
1754 	case ICMP_INFO_REQUEST:
1755 		/* Per RFC 1122 3.2.2.7, ignore this. */
1756 	case ICMP_INFO_REPLY:
1757 		break;
1758 	case ICMP_ADDRESS_MASK_REQUEST:
1759 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1760 		    !broadcast) &&
1761 		    /* TODO m_pullup of complete header? */
1762 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN) {
1763 			interested = B_TRUE;
1764 		}
1765 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1766 		break;
1767 	case ICMP_ADDRESS_MASK_REPLY:
1768 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1769 		break;
1770 	default:
1771 		interested = B_TRUE;	/* Pass up to transport */
1772 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1773 		break;
1774 	}
1775 	/* See if there is an ICMP client. */
1776 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1777 		/* If there is an ICMP client and we want one too, copy it. */
1778 		mblk_t *first_mp1;
1779 
1780 		if (!interested) {
1781 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1782 			    ip_policy, recv_ill, zoneid);
1783 			return;
1784 		}
1785 		first_mp1 = ip_copymsg(first_mp);
1786 		if (first_mp1 != NULL) {
1787 			ip_fanout_proto(q, first_mp1, ill, ipha,
1788 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1789 		}
1790 	} else if (!interested) {
1791 		freemsg(first_mp);
1792 		return;
1793 	} else {
1794 		/*
1795 		 * Initiate policy processing for this packet if ip_policy
1796 		 * is true.
1797 		 */
1798 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1799 			ill_index = ill->ill_phyint->phyint_ifindex;
1800 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1801 			if (mp == NULL) {
1802 				if (mctl_present) {
1803 					freeb(first_mp);
1804 				}
1805 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1806 				return;
1807 			}
1808 		}
1809 	}
1810 	/* We want to do something with it. */
1811 	/* Check db_ref to make sure we can modify the packet. */
1812 	if (mp->b_datap->db_ref > 1) {
1813 		mblk_t	*first_mp1;
1814 
1815 		first_mp1 = ip_copymsg(first_mp);
1816 		freemsg(first_mp);
1817 		if (!first_mp1) {
1818 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1819 			return;
1820 		}
1821 		first_mp = first_mp1;
1822 		if (mctl_present) {
1823 			mp = first_mp->b_cont;
1824 			ASSERT(mp != NULL);
1825 		} else {
1826 			mp = first_mp;
1827 		}
1828 		ipha = (ipha_t *)mp->b_rptr;
1829 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1830 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1831 	}
1832 	switch (icmph->icmph_type) {
1833 	case ICMP_ADDRESS_MASK_REQUEST:
1834 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1835 		if (ipif == NULL) {
1836 			freemsg(first_mp);
1837 			return;
1838 		}
1839 		/*
1840 		 * outging interface must be IPv4
1841 		 */
1842 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1843 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1844 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1845 		ipif_refrele(ipif);
1846 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1847 		break;
1848 	case ICMP_ECHO_REQUEST:
1849 		icmph->icmph_type = ICMP_ECHO_REPLY;
1850 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1851 		break;
1852 	case ICMP_TIME_STAMP_REQUEST: {
1853 		uint32_t *tsp;
1854 
1855 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1856 		tsp = (uint32_t *)wptr;
1857 		tsp++;		/* Skip past 'originate time' */
1858 		/* Compute # of milliseconds since midnight */
1859 		gethrestime(&now);
1860 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1861 		    now.tv_nsec / (NANOSEC / MILLISEC);
1862 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1863 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1864 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1865 		break;
1866 	}
1867 	default:
1868 		ipha = (ipha_t *)&icmph[1];
1869 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1870 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1871 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1872 				freemsg(first_mp);
1873 				return;
1874 			}
1875 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1876 			ipha = (ipha_t *)&icmph[1];
1877 		}
1878 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1879 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1880 			freemsg(first_mp);
1881 			return;
1882 		}
1883 		hdr_length = IPH_HDR_LENGTH(ipha);
1884 		if (hdr_length < sizeof (ipha_t)) {
1885 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1886 			freemsg(first_mp);
1887 			return;
1888 		}
1889 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1890 			if (!pullupmsg(mp,
1891 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1892 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1893 				freemsg(first_mp);
1894 				return;
1895 			}
1896 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1897 			ipha = (ipha_t *)&icmph[1];
1898 		}
1899 		switch (icmph->icmph_type) {
1900 		case ICMP_REDIRECT:
1901 			/*
1902 			 * As there is no upper client to deliver, we don't
1903 			 * need the first_mp any more.
1904 			 */
1905 			if (mctl_present) {
1906 				freeb(first_mp);
1907 			}
1908 			icmp_redirect(ill, mp);
1909 			return;
1910 		case ICMP_DEST_UNREACHABLE:
1911 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1912 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1913 				    zoneid, mp, iph_hdr_length, ipst)) {
1914 					freemsg(first_mp);
1915 					return;
1916 				}
1917 				/*
1918 				 * icmp_inbound_too_big() may alter mp.
1919 				 * Resynch ipha and icmph accordingly.
1920 				 */
1921 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1922 				ipha = (ipha_t *)&icmph[1];
1923 			}
1924 			/* FALLTHRU */
1925 		default :
1926 			/*
1927 			 * IPQoS notes: Since we have already done IPQoS
1928 			 * processing we don't want to do it again in
1929 			 * the fanout routines called by
1930 			 * icmp_inbound_error_fanout, hence the last
1931 			 * argument, ip_policy, is B_FALSE.
1932 			 */
1933 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1934 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1935 			    B_FALSE, recv_ill, zoneid);
1936 		}
1937 		return;
1938 	}
1939 	/* Send out an ICMP packet */
1940 	icmph->icmph_checksum = 0;
1941 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1942 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1943 		ipif_t	*ipif_chosen;
1944 		/*
1945 		 * Make it look like it was directed to us, so we don't look
1946 		 * like a fool with a broadcast or multicast source address.
1947 		 */
1948 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1949 		/*
1950 		 * Make sure that we haven't grabbed an interface that's DOWN.
1951 		 */
1952 		if (ipif != NULL) {
1953 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
1954 			    ipha->ipha_src, zoneid);
1955 			if (ipif_chosen != NULL) {
1956 				ipif_refrele(ipif);
1957 				ipif = ipif_chosen;
1958 			}
1959 		}
1960 		if (ipif == NULL) {
1961 			ip0dbg(("icmp_inbound: "
1962 			    "No source for broadcast/multicast:\n"
1963 			    "\tsrc 0x%x dst 0x%x ill %p "
1964 			    "ipif_lcl_addr 0x%x\n",
1965 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
1966 			    (void *)ill,
1967 			    ill->ill_ipif->ipif_lcl_addr));
1968 			freemsg(first_mp);
1969 			return;
1970 		}
1971 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1972 		ipha->ipha_dst = ipif->ipif_src_addr;
1973 		ipif_refrele(ipif);
1974 	}
1975 	/* Reset time to live. */
1976 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1977 	{
1978 		/* Swap source and destination addresses */
1979 		ipaddr_t tmp;
1980 
1981 		tmp = ipha->ipha_src;
1982 		ipha->ipha_src = ipha->ipha_dst;
1983 		ipha->ipha_dst = tmp;
1984 	}
1985 	ipha->ipha_ident = 0;
1986 	if (!IS_SIMPLE_IPH(ipha))
1987 		icmp_options_update(ipha);
1988 
1989 	/*
1990 	 * ICMP echo replies should go out on the same interface
1991 	 * the request came on as probes used by in.mpathd for detecting
1992 	 * NIC failures are ECHO packets. We turn-off load spreading
1993 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
1994 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
1995 	 * function. This is in turn handled by ip_wput and ip_newroute
1996 	 * to make sure that the packet goes out on the interface it came
1997 	 * in on. If we don't turnoff load spreading, the packets might get
1998 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
1999 	 * to go out and in.mpathd would wrongly detect a failure or
2000 	 * mis-detect a NIC failure for link failure. As load spreading
2001 	 * can happen only if ill_group is not NULL, we do only for
2002 	 * that case and this does not affect the normal case.
2003 	 *
2004 	 * We turn off load spreading only on echo packets that came from
2005 	 * on-link hosts. If the interface route has been deleted, this will
2006 	 * not be enforced as we can't do much. For off-link hosts, as the
2007 	 * default routes in IPv4 does not typically have an ire_ipif
2008 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2009 	 * Moreover, expecting a default route through this interface may
2010 	 * not be correct. We use ipha_dst because of the swap above.
2011 	 */
2012 	onlink = B_FALSE;
2013 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2014 		/*
2015 		 * First, we need to make sure that it is not one of our
2016 		 * local addresses. If we set onlink when it is one of
2017 		 * our local addresses, we will end up creating IRE_CACHES
2018 		 * for one of our local addresses. Then, we will never
2019 		 * accept packets for them afterwards.
2020 		 */
2021 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2022 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2023 		if (src_ire == NULL) {
2024 			ipif = ipif_get_next_ipif(NULL, ill);
2025 			if (ipif == NULL) {
2026 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2027 				freemsg(mp);
2028 				return;
2029 			}
2030 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2031 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2032 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE, ipst);
2033 			ipif_refrele(ipif);
2034 			if (src_ire != NULL) {
2035 				onlink = B_TRUE;
2036 				ire_refrele(src_ire);
2037 			}
2038 		} else {
2039 			ire_refrele(src_ire);
2040 		}
2041 	}
2042 	if (!mctl_present) {
2043 		/*
2044 		 * This packet should go out the same way as it
2045 		 * came in i.e in clear. To make sure that global
2046 		 * policy will not be applied to this in ip_wput_ire,
2047 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2048 		 */
2049 		ASSERT(first_mp == mp);
2050 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2051 		if (first_mp == NULL) {
2052 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2053 			freemsg(mp);
2054 			return;
2055 		}
2056 		ii = (ipsec_in_t *)first_mp->b_rptr;
2057 
2058 		/* This is not a secure packet */
2059 		ii->ipsec_in_secure = B_FALSE;
2060 		if (onlink) {
2061 			ii->ipsec_in_attach_if = B_TRUE;
2062 			ii->ipsec_in_ill_index =
2063 			    ill->ill_phyint->phyint_ifindex;
2064 			ii->ipsec_in_rill_index =
2065 			    recv_ill->ill_phyint->phyint_ifindex;
2066 		}
2067 		first_mp->b_cont = mp;
2068 	} else if (onlink) {
2069 		ii = (ipsec_in_t *)first_mp->b_rptr;
2070 		ii->ipsec_in_attach_if = B_TRUE;
2071 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2072 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2073 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2074 	} else {
2075 		ii = (ipsec_in_t *)first_mp->b_rptr;
2076 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2077 	}
2078 	ii->ipsec_in_zoneid = zoneid;
2079 	ASSERT(zoneid != ALL_ZONES);
2080 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2081 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2082 		return;
2083 	}
2084 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2085 	put(WR(q), first_mp);
2086 }
2087 
2088 static ipaddr_t
2089 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2090 {
2091 	conn_t *connp;
2092 	connf_t *connfp;
2093 	ipaddr_t nexthop_addr = INADDR_ANY;
2094 	int hdr_length = IPH_HDR_LENGTH(ipha);
2095 	uint16_t *up;
2096 	uint32_t ports;
2097 	ip_stack_t *ipst = ill->ill_ipst;
2098 
2099 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2100 	switch (ipha->ipha_protocol) {
2101 		case IPPROTO_TCP:
2102 		{
2103 			tcph_t *tcph;
2104 
2105 			/* do a reverse lookup */
2106 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2107 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2108 			    TCPS_LISTEN, ipst);
2109 			break;
2110 		}
2111 		case IPPROTO_UDP:
2112 		{
2113 			uint32_t dstport, srcport;
2114 
2115 			((uint16_t *)&ports)[0] = up[1];
2116 			((uint16_t *)&ports)[1] = up[0];
2117 
2118 			/* Extract ports in net byte order */
2119 			dstport = htons(ntohl(ports) & 0xFFFF);
2120 			srcport = htons(ntohl(ports) >> 16);
2121 
2122 			connfp = &ipst->ips_ipcl_udp_fanout[
2123 			    IPCL_UDP_HASH(dstport, ipst)];
2124 			mutex_enter(&connfp->connf_lock);
2125 			connp = connfp->connf_head;
2126 
2127 			/* do a reverse lookup */
2128 			while ((connp != NULL) &&
2129 			    (!IPCL_UDP_MATCH(connp, dstport,
2130 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2131 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2132 				connp = connp->conn_next;
2133 			}
2134 			if (connp != NULL)
2135 				CONN_INC_REF(connp);
2136 			mutex_exit(&connfp->connf_lock);
2137 			break;
2138 		}
2139 		case IPPROTO_SCTP:
2140 		{
2141 			in6_addr_t map_src, map_dst;
2142 
2143 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2144 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2145 			((uint16_t *)&ports)[0] = up[1];
2146 			((uint16_t *)&ports)[1] = up[0];
2147 
2148 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2149 			    zoneid, ipst->ips_netstack->netstack_sctp);
2150 			if (connp == NULL) {
2151 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2152 				    zoneid, ports, ipha, ipst);
2153 			} else {
2154 				CONN_INC_REF(connp);
2155 				SCTP_REFRELE(CONN2SCTP(connp));
2156 			}
2157 			break;
2158 		}
2159 		default:
2160 		{
2161 			ipha_t ripha;
2162 
2163 			ripha.ipha_src = ipha->ipha_dst;
2164 			ripha.ipha_dst = ipha->ipha_src;
2165 			ripha.ipha_protocol = ipha->ipha_protocol;
2166 
2167 			connfp = &ipst->ips_ipcl_proto_fanout[
2168 			    ipha->ipha_protocol];
2169 			mutex_enter(&connfp->connf_lock);
2170 			connp = connfp->connf_head;
2171 			for (connp = connfp->connf_head; connp != NULL;
2172 			    connp = connp->conn_next) {
2173 				if (IPCL_PROTO_MATCH(connp,
2174 				    ipha->ipha_protocol, &ripha, ill,
2175 				    0, zoneid)) {
2176 					CONN_INC_REF(connp);
2177 					break;
2178 				}
2179 			}
2180 			mutex_exit(&connfp->connf_lock);
2181 		}
2182 	}
2183 	if (connp != NULL) {
2184 		if (connp->conn_nexthop_set)
2185 			nexthop_addr = connp->conn_nexthop_v4;
2186 		CONN_DEC_REF(connp);
2187 	}
2188 	return (nexthop_addr);
2189 }
2190 
2191 /* Table from RFC 1191 */
2192 static int icmp_frag_size_table[] =
2193 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2194 
2195 /*
2196  * Process received ICMP Packet too big.
2197  * After updating any IRE it does the fanout to any matching transport streams.
2198  * Assumes the message has been pulled up till the IP header that caused
2199  * the error.
2200  *
2201  * Returns B_FALSE on failure and B_TRUE on success.
2202  */
2203 static boolean_t
2204 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2205     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2206     ip_stack_t *ipst)
2207 {
2208 	ire_t	*ire, *first_ire;
2209 	int	mtu;
2210 	int	hdr_length;
2211 	ipaddr_t nexthop_addr;
2212 
2213 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2214 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2215 	ASSERT(ill != NULL);
2216 
2217 	hdr_length = IPH_HDR_LENGTH(ipha);
2218 
2219 	/* Drop if the original packet contained a source route */
2220 	if (ip_source_route_included(ipha)) {
2221 		return (B_FALSE);
2222 	}
2223 	/*
2224 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2225 	 * header.
2226 	 */
2227 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2228 	    mp->b_wptr) {
2229 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2230 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2231 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2232 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2233 			return (B_FALSE);
2234 		}
2235 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2236 		ipha = (ipha_t *)&icmph[1];
2237 	}
2238 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2239 	if (nexthop_addr != INADDR_ANY) {
2240 		/* nexthop set */
2241 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2242 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2243 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2244 	} else {
2245 		/* nexthop not set */
2246 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2247 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2248 	}
2249 
2250 	if (!first_ire) {
2251 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2252 		    ntohl(ipha->ipha_dst)));
2253 		return (B_FALSE);
2254 	}
2255 	/* Check for MTU discovery advice as described in RFC 1191 */
2256 	mtu = ntohs(icmph->icmph_du_mtu);
2257 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2258 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2259 	    ire = ire->ire_next) {
2260 		/*
2261 		 * Look for the connection to which this ICMP message is
2262 		 * directed. If it has the IP_NEXTHOP option set, then the
2263 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2264 		 * option. Else the search is limited to regular IREs.
2265 		 */
2266 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2267 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2268 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2269 		    (nexthop_addr != INADDR_ANY)))
2270 			continue;
2271 
2272 		mutex_enter(&ire->ire_lock);
2273 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2274 			/* Reduce the IRE max frag value as advised. */
2275 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2276 			    mtu, ire->ire_max_frag));
2277 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2278 		} else {
2279 			uint32_t length;
2280 			int	i;
2281 
2282 			/*
2283 			 * Use the table from RFC 1191 to figure out
2284 			 * the next "plateau" based on the length in
2285 			 * the original IP packet.
2286 			 */
2287 			length = ntohs(ipha->ipha_length);
2288 			if (ire->ire_max_frag <= length &&
2289 			    ire->ire_max_frag >= length - hdr_length) {
2290 				/*
2291 				 * Handle broken BSD 4.2 systems that
2292 				 * return the wrong iph_length in ICMP
2293 				 * errors.
2294 				 */
2295 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2296 				    length, ire->ire_max_frag));
2297 				length -= hdr_length;
2298 			}
2299 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2300 				if (length > icmp_frag_size_table[i])
2301 					break;
2302 			}
2303 			if (i == A_CNT(icmp_frag_size_table)) {
2304 				/* Smaller than 68! */
2305 				ip1dbg(("Too big for packet size %d\n",
2306 				    length));
2307 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2308 				ire->ire_frag_flag = 0;
2309 			} else {
2310 				mtu = icmp_frag_size_table[i];
2311 				ip1dbg(("Calculated mtu %d, packet size %d, "
2312 				    "before %d", mtu, length,
2313 				    ire->ire_max_frag));
2314 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2315 				ip1dbg((", after %d\n", ire->ire_max_frag));
2316 			}
2317 			/* Record the new max frag size for the ULP. */
2318 			icmph->icmph_du_zero = 0;
2319 			icmph->icmph_du_mtu =
2320 			    htons((uint16_t)ire->ire_max_frag);
2321 		}
2322 		mutex_exit(&ire->ire_lock);
2323 	}
2324 	rw_exit(&first_ire->ire_bucket->irb_lock);
2325 	ire_refrele(first_ire);
2326 	return (B_TRUE);
2327 }
2328 
2329 /*
2330  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2331  * calls this function.
2332  */
2333 static mblk_t *
2334 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2335 {
2336 	ipha_t *ipha;
2337 	icmph_t *icmph;
2338 	ipha_t *in_ipha;
2339 	int length;
2340 
2341 	ASSERT(mp->b_datap->db_type == M_DATA);
2342 
2343 	/*
2344 	 * For Self-encapsulated packets, we added an extra IP header
2345 	 * without the options. Inner IP header is the one from which
2346 	 * the outer IP header was formed. Thus, we need to remove the
2347 	 * outer IP header. To do this, we pullup the whole message
2348 	 * and overlay whatever follows the outer IP header over the
2349 	 * outer IP header.
2350 	 */
2351 
2352 	if (!pullupmsg(mp, -1))
2353 		return (NULL);
2354 
2355 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2356 	ipha = (ipha_t *)&icmph[1];
2357 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2358 
2359 	/*
2360 	 * The length that we want to overlay is following the inner
2361 	 * IP header. Subtracting the IP header + icmp header + outer
2362 	 * IP header's length should give us the length that we want to
2363 	 * overlay.
2364 	 */
2365 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2366 	    hdr_length;
2367 	/*
2368 	 * Overlay whatever follows the inner header over the
2369 	 * outer header.
2370 	 */
2371 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2372 
2373 	/* Set the wptr to account for the outer header */
2374 	mp->b_wptr -= hdr_length;
2375 	return (mp);
2376 }
2377 
2378 /*
2379  * Try to pass the ICMP message upstream in case the ULP cares.
2380  *
2381  * If the packet that caused the ICMP error is secure, we send
2382  * it to AH/ESP to make sure that the attached packet has a
2383  * valid association. ipha in the code below points to the
2384  * IP header of the packet that caused the error.
2385  *
2386  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2387  * in the context of IPsec. Normally we tell the upper layer
2388  * whenever we send the ire (including ip_bind), the IPsec header
2389  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2390  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2391  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2392  * same thing. As TCP has the IPsec options size that needs to be
2393  * adjusted, we just pass the MTU unchanged.
2394  *
2395  * IFN could have been generated locally or by some router.
2396  *
2397  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2398  *	    This happens because IP adjusted its value of MTU on an
2399  *	    earlier IFN message and could not tell the upper layer,
2400  *	    the new adjusted value of MTU e.g. Packet was encrypted
2401  *	    or there was not enough information to fanout to upper
2402  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2403  *	    generates the IFN, where IPsec processing has *not* been
2404  *	    done.
2405  *
2406  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2407  *	    could have generated this. This happens because ire_max_frag
2408  *	    value in IP was set to a new value, while the IPsec processing
2409  *	    was being done and after we made the fragmentation check in
2410  *	    ip_wput_ire. Thus on return from IPsec processing,
2411  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2412  *	    and generates the IFN. As IPsec processing is over, we fanout
2413  *	    to AH/ESP to remove the header.
2414  *
2415  *	    In both these cases, ipsec_in_loopback will be set indicating
2416  *	    that IFN was generated locally.
2417  *
2418  * ROUTER : IFN could be secure or non-secure.
2419  *
2420  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2421  *	      packet in error has AH/ESP headers to validate the AH/ESP
2422  *	      headers. AH/ESP will verify whether there is a valid SA or
2423  *	      not and send it back. We will fanout again if we have more
2424  *	      data in the packet.
2425  *
2426  *	      If the packet in error does not have AH/ESP, we handle it
2427  *	      like any other case.
2428  *
2429  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2430  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2431  *	      for validation. AH/ESP will verify whether there is a
2432  *	      valid SA or not and send it back. We will fanout again if
2433  *	      we have more data in the packet.
2434  *
2435  *	      If the packet in error does not have AH/ESP, we handle it
2436  *	      like any other case.
2437  */
2438 static void
2439 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2440     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2441     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2442     zoneid_t zoneid)
2443 {
2444 	uint16_t *up;	/* Pointer to ports in ULP header */
2445 	uint32_t ports;	/* reversed ports for fanout */
2446 	ipha_t ripha;	/* With reversed addresses */
2447 	mblk_t *first_mp;
2448 	ipsec_in_t *ii;
2449 	tcph_t	*tcph;
2450 	conn_t	*connp;
2451 	ip_stack_t *ipst;
2452 
2453 	ASSERT(ill != NULL);
2454 
2455 	ASSERT(recv_ill != NULL);
2456 	ipst = recv_ill->ill_ipst;
2457 
2458 	first_mp = mp;
2459 	if (mctl_present) {
2460 		mp = first_mp->b_cont;
2461 		ASSERT(mp != NULL);
2462 
2463 		ii = (ipsec_in_t *)first_mp->b_rptr;
2464 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2465 	} else {
2466 		ii = NULL;
2467 	}
2468 
2469 	switch (ipha->ipha_protocol) {
2470 	case IPPROTO_UDP:
2471 		/*
2472 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2473 		 * transport header.
2474 		 */
2475 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2476 		    mp->b_wptr) {
2477 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2478 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2479 				goto discard_pkt;
2480 			}
2481 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2482 			ipha = (ipha_t *)&icmph[1];
2483 		}
2484 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2485 
2486 		/*
2487 		 * Attempt to find a client stream based on port.
2488 		 * Note that we do a reverse lookup since the header is
2489 		 * in the form we sent it out.
2490 		 * The ripha header is only used for the IP_UDP_MATCH and we
2491 		 * only set the src and dst addresses and protocol.
2492 		 */
2493 		ripha.ipha_src = ipha->ipha_dst;
2494 		ripha.ipha_dst = ipha->ipha_src;
2495 		ripha.ipha_protocol = ipha->ipha_protocol;
2496 		((uint16_t *)&ports)[0] = up[1];
2497 		((uint16_t *)&ports)[1] = up[0];
2498 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2499 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2500 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2501 		    icmph->icmph_type, icmph->icmph_code));
2502 
2503 		/* Have to change db_type after any pullupmsg */
2504 		DB_TYPE(mp) = M_CTL;
2505 
2506 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2507 		    mctl_present, ip_policy, recv_ill, zoneid);
2508 		return;
2509 
2510 	case IPPROTO_TCP:
2511 		/*
2512 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2513 		 * transport header.
2514 		 */
2515 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2516 		    mp->b_wptr) {
2517 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2518 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2519 				goto discard_pkt;
2520 			}
2521 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2522 			ipha = (ipha_t *)&icmph[1];
2523 		}
2524 		/*
2525 		 * Find a TCP client stream for this packet.
2526 		 * Note that we do a reverse lookup since the header is
2527 		 * in the form we sent it out.
2528 		 */
2529 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2530 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2531 		    ipst);
2532 		if (connp == NULL)
2533 			goto discard_pkt;
2534 
2535 		/* Have to change db_type after any pullupmsg */
2536 		DB_TYPE(mp) = M_CTL;
2537 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2538 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2539 		return;
2540 
2541 	case IPPROTO_SCTP:
2542 		/*
2543 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2544 		 * transport header.
2545 		 */
2546 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2547 		    mp->b_wptr) {
2548 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2549 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2550 				goto discard_pkt;
2551 			}
2552 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2553 			ipha = (ipha_t *)&icmph[1];
2554 		}
2555 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2556 		/*
2557 		 * Find a SCTP client stream for this packet.
2558 		 * Note that we do a reverse lookup since the header is
2559 		 * in the form we sent it out.
2560 		 * The ripha header is only used for the matching and we
2561 		 * only set the src and dst addresses, protocol, and version.
2562 		 */
2563 		ripha.ipha_src = ipha->ipha_dst;
2564 		ripha.ipha_dst = ipha->ipha_src;
2565 		ripha.ipha_protocol = ipha->ipha_protocol;
2566 		ripha.ipha_version_and_hdr_length =
2567 		    ipha->ipha_version_and_hdr_length;
2568 		((uint16_t *)&ports)[0] = up[1];
2569 		((uint16_t *)&ports)[1] = up[0];
2570 
2571 		/* Have to change db_type after any pullupmsg */
2572 		DB_TYPE(mp) = M_CTL;
2573 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2574 		    mctl_present, ip_policy, zoneid);
2575 		return;
2576 
2577 	case IPPROTO_ESP:
2578 	case IPPROTO_AH: {
2579 		int ipsec_rc;
2580 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2581 
2582 		/*
2583 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2584 		 * We will re-use the IPSEC_IN if it is already present as
2585 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2586 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2587 		 * one and attach it in the front.
2588 		 */
2589 		if (ii != NULL) {
2590 			/*
2591 			 * ip_fanout_proto_again converts the ICMP errors
2592 			 * that come back from AH/ESP to M_DATA so that
2593 			 * if it is non-AH/ESP and we do a pullupmsg in
2594 			 * this function, it would work. Convert it back
2595 			 * to M_CTL before we send up as this is a ICMP
2596 			 * error. This could have been generated locally or
2597 			 * by some router. Validate the inner IPsec
2598 			 * headers.
2599 			 *
2600 			 * NOTE : ill_index is used by ip_fanout_proto_again
2601 			 * to locate the ill.
2602 			 */
2603 			ASSERT(ill != NULL);
2604 			ii->ipsec_in_ill_index =
2605 			    ill->ill_phyint->phyint_ifindex;
2606 			ii->ipsec_in_rill_index =
2607 			    recv_ill->ill_phyint->phyint_ifindex;
2608 			DB_TYPE(first_mp->b_cont) = M_CTL;
2609 		} else {
2610 			/*
2611 			 * IPSEC_IN is not present. We attach a ipsec_in
2612 			 * message and send up to IPsec for validating
2613 			 * and removing the IPsec headers. Clear
2614 			 * ipsec_in_secure so that when we return
2615 			 * from IPsec, we don't mistakenly think that this
2616 			 * is a secure packet came from the network.
2617 			 *
2618 			 * NOTE : ill_index is used by ip_fanout_proto_again
2619 			 * to locate the ill.
2620 			 */
2621 			ASSERT(first_mp == mp);
2622 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2623 			if (first_mp == NULL) {
2624 				freemsg(mp);
2625 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2626 				return;
2627 			}
2628 			ii = (ipsec_in_t *)first_mp->b_rptr;
2629 
2630 			/* This is not a secure packet */
2631 			ii->ipsec_in_secure = B_FALSE;
2632 			first_mp->b_cont = mp;
2633 			DB_TYPE(mp) = M_CTL;
2634 			ASSERT(ill != NULL);
2635 			ii->ipsec_in_ill_index =
2636 			    ill->ill_phyint->phyint_ifindex;
2637 			ii->ipsec_in_rill_index =
2638 			    recv_ill->ill_phyint->phyint_ifindex;
2639 		}
2640 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2641 
2642 		if (!ipsec_loaded(ipss)) {
2643 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2644 			return;
2645 		}
2646 
2647 		if (ipha->ipha_protocol == IPPROTO_ESP)
2648 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2649 		else
2650 			ipsec_rc = ipsecah_icmp_error(first_mp);
2651 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2652 			return;
2653 
2654 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2655 		return;
2656 	}
2657 	default:
2658 		/*
2659 		 * The ripha header is only used for the lookup and we
2660 		 * only set the src and dst addresses and protocol.
2661 		 */
2662 		ripha.ipha_src = ipha->ipha_dst;
2663 		ripha.ipha_dst = ipha->ipha_src;
2664 		ripha.ipha_protocol = ipha->ipha_protocol;
2665 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2666 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2667 		    ntohl(ipha->ipha_dst),
2668 		    icmph->icmph_type, icmph->icmph_code));
2669 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2670 			ipha_t *in_ipha;
2671 
2672 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2673 			    mp->b_wptr) {
2674 				if (!pullupmsg(mp, (uchar_t *)ipha +
2675 				    hdr_length + sizeof (ipha_t) -
2676 				    mp->b_rptr)) {
2677 					goto discard_pkt;
2678 				}
2679 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2680 				ipha = (ipha_t *)&icmph[1];
2681 			}
2682 			/*
2683 			 * Caller has verified that length has to be
2684 			 * at least the size of IP header.
2685 			 */
2686 			ASSERT(hdr_length >= sizeof (ipha_t));
2687 			/*
2688 			 * Check the sanity of the inner IP header like
2689 			 * we did for the outer header.
2690 			 */
2691 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2692 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2693 				goto discard_pkt;
2694 			}
2695 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2696 				goto discard_pkt;
2697 			}
2698 			/* Check for Self-encapsulated tunnels */
2699 			if (in_ipha->ipha_src == ipha->ipha_src &&
2700 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2701 
2702 				mp = icmp_inbound_self_encap_error(mp,
2703 				    iph_hdr_length, hdr_length);
2704 				if (mp == NULL)
2705 					goto discard_pkt;
2706 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2707 				ipha = (ipha_t *)&icmph[1];
2708 				hdr_length = IPH_HDR_LENGTH(ipha);
2709 				/*
2710 				 * The packet in error is self-encapsualted.
2711 				 * And we are finding it further encapsulated
2712 				 * which we could not have possibly generated.
2713 				 */
2714 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2715 					goto discard_pkt;
2716 				}
2717 				icmp_inbound_error_fanout(q, ill, first_mp,
2718 				    icmph, ipha, iph_hdr_length, hdr_length,
2719 				    mctl_present, ip_policy, recv_ill, zoneid);
2720 				return;
2721 			}
2722 		}
2723 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2724 		    ipha->ipha_protocol == IPPROTO_IPV6) &&
2725 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2726 		    ii != NULL &&
2727 		    ii->ipsec_in_loopback &&
2728 		    ii->ipsec_in_secure) {
2729 			/*
2730 			 * For IP tunnels that get a looped-back
2731 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2732 			 * reported new MTU to take into account the IPsec
2733 			 * headers protecting this configured tunnel.
2734 			 *
2735 			 * This allows the tunnel module (tun.c) to blindly
2736 			 * accept the MTU reported in an ICMP "too big"
2737 			 * message.
2738 			 *
2739 			 * Non-looped back ICMP messages will just be
2740 			 * handled by the security protocols (if needed),
2741 			 * and the first subsequent packet will hit this
2742 			 * path.
2743 			 */
2744 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2745 			    ipsec_in_extra_length(first_mp));
2746 		}
2747 		/* Have to change db_type after any pullupmsg */
2748 		DB_TYPE(mp) = M_CTL;
2749 
2750 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2751 		    ip_policy, recv_ill, zoneid);
2752 		return;
2753 	}
2754 	/* NOTREACHED */
2755 discard_pkt:
2756 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2757 drop_pkt:;
2758 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2759 	freemsg(first_mp);
2760 }
2761 
2762 /*
2763  * Common IP options parser.
2764  *
2765  * Setup routine: fill in *optp with options-parsing state, then
2766  * tail-call ipoptp_next to return the first option.
2767  */
2768 uint8_t
2769 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2770 {
2771 	uint32_t totallen; /* total length of all options */
2772 
2773 	totallen = ipha->ipha_version_and_hdr_length -
2774 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2775 	totallen <<= 2;
2776 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2777 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2778 	optp->ipoptp_flags = 0;
2779 	return (ipoptp_next(optp));
2780 }
2781 
2782 /*
2783  * Common IP options parser: extract next option.
2784  */
2785 uint8_t
2786 ipoptp_next(ipoptp_t *optp)
2787 {
2788 	uint8_t *end = optp->ipoptp_end;
2789 	uint8_t *cur = optp->ipoptp_next;
2790 	uint8_t opt, len, pointer;
2791 
2792 	/*
2793 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2794 	 * has been corrupted.
2795 	 */
2796 	ASSERT(cur <= end);
2797 
2798 	if (cur == end)
2799 		return (IPOPT_EOL);
2800 
2801 	opt = cur[IPOPT_OPTVAL];
2802 
2803 	/*
2804 	 * Skip any NOP options.
2805 	 */
2806 	while (opt == IPOPT_NOP) {
2807 		cur++;
2808 		if (cur == end)
2809 			return (IPOPT_EOL);
2810 		opt = cur[IPOPT_OPTVAL];
2811 	}
2812 
2813 	if (opt == IPOPT_EOL)
2814 		return (IPOPT_EOL);
2815 
2816 	/*
2817 	 * Option requiring a length.
2818 	 */
2819 	if ((cur + 1) >= end) {
2820 		optp->ipoptp_flags |= IPOPTP_ERROR;
2821 		return (IPOPT_EOL);
2822 	}
2823 	len = cur[IPOPT_OLEN];
2824 	if (len < 2) {
2825 		optp->ipoptp_flags |= IPOPTP_ERROR;
2826 		return (IPOPT_EOL);
2827 	}
2828 	optp->ipoptp_cur = cur;
2829 	optp->ipoptp_len = len;
2830 	optp->ipoptp_next = cur + len;
2831 	if (cur + len > end) {
2832 		optp->ipoptp_flags |= IPOPTP_ERROR;
2833 		return (IPOPT_EOL);
2834 	}
2835 
2836 	/*
2837 	 * For the options which require a pointer field, make sure
2838 	 * its there, and make sure it points to either something
2839 	 * inside this option, or the end of the option.
2840 	 */
2841 	switch (opt) {
2842 	case IPOPT_RR:
2843 	case IPOPT_TS:
2844 	case IPOPT_LSRR:
2845 	case IPOPT_SSRR:
2846 		if (len <= IPOPT_OFFSET) {
2847 			optp->ipoptp_flags |= IPOPTP_ERROR;
2848 			return (opt);
2849 		}
2850 		pointer = cur[IPOPT_OFFSET];
2851 		if (pointer - 1 > len) {
2852 			optp->ipoptp_flags |= IPOPTP_ERROR;
2853 			return (opt);
2854 		}
2855 		break;
2856 	}
2857 
2858 	/*
2859 	 * Sanity check the pointer field based on the type of the
2860 	 * option.
2861 	 */
2862 	switch (opt) {
2863 	case IPOPT_RR:
2864 	case IPOPT_SSRR:
2865 	case IPOPT_LSRR:
2866 		if (pointer < IPOPT_MINOFF_SR)
2867 			optp->ipoptp_flags |= IPOPTP_ERROR;
2868 		break;
2869 	case IPOPT_TS:
2870 		if (pointer < IPOPT_MINOFF_IT)
2871 			optp->ipoptp_flags |= IPOPTP_ERROR;
2872 		/*
2873 		 * Note that the Internet Timestamp option also
2874 		 * contains two four bit fields (the Overflow field,
2875 		 * and the Flag field), which follow the pointer
2876 		 * field.  We don't need to check that these fields
2877 		 * fall within the length of the option because this
2878 		 * was implicitely done above.  We've checked that the
2879 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2880 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2881 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2882 		 */
2883 		ASSERT(len > IPOPT_POS_OV_FLG);
2884 		break;
2885 	}
2886 
2887 	return (opt);
2888 }
2889 
2890 /*
2891  * Use the outgoing IP header to create an IP_OPTIONS option the way
2892  * it was passed down from the application.
2893  */
2894 int
2895 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2896 {
2897 	ipoptp_t	opts;
2898 	const uchar_t	*opt;
2899 	uint8_t		optval;
2900 	uint8_t		optlen;
2901 	uint32_t	len = 0;
2902 	uchar_t	*buf1 = buf;
2903 
2904 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2905 	len += IP_ADDR_LEN;
2906 	bzero(buf1, IP_ADDR_LEN);
2907 
2908 	/*
2909 	 * OK to cast away const here, as we don't store through the returned
2910 	 * opts.ipoptp_cur pointer.
2911 	 */
2912 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2913 	    optval != IPOPT_EOL;
2914 	    optval = ipoptp_next(&opts)) {
2915 		int	off;
2916 
2917 		opt = opts.ipoptp_cur;
2918 		optlen = opts.ipoptp_len;
2919 		switch (optval) {
2920 		case IPOPT_SSRR:
2921 		case IPOPT_LSRR:
2922 
2923 			/*
2924 			 * Insert ipha_dst as the first entry in the source
2925 			 * route and move down the entries on step.
2926 			 * The last entry gets placed at buf1.
2927 			 */
2928 			buf[IPOPT_OPTVAL] = optval;
2929 			buf[IPOPT_OLEN] = optlen;
2930 			buf[IPOPT_OFFSET] = optlen;
2931 
2932 			off = optlen - IP_ADDR_LEN;
2933 			if (off < 0) {
2934 				/* No entries in source route */
2935 				break;
2936 			}
2937 			/* Last entry in source route */
2938 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2939 			off -= IP_ADDR_LEN;
2940 
2941 			while (off > 0) {
2942 				bcopy(opt + off,
2943 				    buf + off + IP_ADDR_LEN,
2944 				    IP_ADDR_LEN);
2945 				off -= IP_ADDR_LEN;
2946 			}
2947 			/* ipha_dst into first slot */
2948 			bcopy(&ipha->ipha_dst,
2949 			    buf + off + IP_ADDR_LEN,
2950 			    IP_ADDR_LEN);
2951 			buf += optlen;
2952 			len += optlen;
2953 			break;
2954 
2955 		case IPOPT_COMSEC:
2956 		case IPOPT_SECURITY:
2957 			/* if passing up a label is not ok, then remove */
2958 			if (is_system_labeled())
2959 				break;
2960 			/* FALLTHROUGH */
2961 		default:
2962 			bcopy(opt, buf, optlen);
2963 			buf += optlen;
2964 			len += optlen;
2965 			break;
2966 		}
2967 	}
2968 done:
2969 	/* Pad the resulting options */
2970 	while (len & 0x3) {
2971 		*buf++ = IPOPT_EOL;
2972 		len++;
2973 	}
2974 	return (len);
2975 }
2976 
2977 /*
2978  * Update any record route or timestamp options to include this host.
2979  * Reverse any source route option.
2980  * This routine assumes that the options are well formed i.e. that they
2981  * have already been checked.
2982  */
2983 static void
2984 icmp_options_update(ipha_t *ipha)
2985 {
2986 	ipoptp_t	opts;
2987 	uchar_t		*opt;
2988 	uint8_t		optval;
2989 	ipaddr_t	src;		/* Our local address */
2990 	ipaddr_t	dst;
2991 
2992 	ip2dbg(("icmp_options_update\n"));
2993 	src = ipha->ipha_src;
2994 	dst = ipha->ipha_dst;
2995 
2996 	for (optval = ipoptp_first(&opts, ipha);
2997 	    optval != IPOPT_EOL;
2998 	    optval = ipoptp_next(&opts)) {
2999 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
3000 		opt = opts.ipoptp_cur;
3001 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
3002 		    optval, opts.ipoptp_len));
3003 		switch (optval) {
3004 			int off1, off2;
3005 		case IPOPT_SSRR:
3006 		case IPOPT_LSRR:
3007 			/*
3008 			 * Reverse the source route.  The first entry
3009 			 * should be the next to last one in the current
3010 			 * source route (the last entry is our address).
3011 			 * The last entry should be the final destination.
3012 			 */
3013 			off1 = IPOPT_MINOFF_SR - 1;
3014 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3015 			if (off2 < 0) {
3016 				/* No entries in source route */
3017 				ip1dbg((
3018 				    "icmp_options_update: bad src route\n"));
3019 				break;
3020 			}
3021 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3022 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3023 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3024 			off2 -= IP_ADDR_LEN;
3025 
3026 			while (off1 < off2) {
3027 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3028 				bcopy((char *)opt + off2, (char *)opt + off1,
3029 				    IP_ADDR_LEN);
3030 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3031 				off1 += IP_ADDR_LEN;
3032 				off2 -= IP_ADDR_LEN;
3033 			}
3034 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3035 			break;
3036 		}
3037 	}
3038 }
3039 
3040 /*
3041  * Process received ICMP Redirect messages.
3042  */
3043 static void
3044 icmp_redirect(ill_t *ill, mblk_t *mp)
3045 {
3046 	ipha_t	*ipha;
3047 	int	iph_hdr_length;
3048 	icmph_t	*icmph;
3049 	ipha_t	*ipha_err;
3050 	ire_t	*ire;
3051 	ire_t	*prev_ire;
3052 	ire_t	*save_ire;
3053 	ipaddr_t  src, dst, gateway;
3054 	iulp_t	ulp_info = { 0 };
3055 	int	error;
3056 	ip_stack_t *ipst;
3057 
3058 	ASSERT(ill != NULL);
3059 	ipst = ill->ill_ipst;
3060 
3061 	ipha = (ipha_t *)mp->b_rptr;
3062 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3063 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3064 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3065 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3066 		freemsg(mp);
3067 		return;
3068 	}
3069 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3070 	ipha_err = (ipha_t *)&icmph[1];
3071 	src = ipha->ipha_src;
3072 	dst = ipha_err->ipha_dst;
3073 	gateway = icmph->icmph_rd_gateway;
3074 	/* Make sure the new gateway is reachable somehow. */
3075 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3076 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3077 	/*
3078 	 * Make sure we had a route for the dest in question and that
3079 	 * that route was pointing to the old gateway (the source of the
3080 	 * redirect packet.)
3081 	 */
3082 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3083 	    NULL, MATCH_IRE_GW, ipst);
3084 	/*
3085 	 * Check that
3086 	 *	the redirect was not from ourselves
3087 	 *	the new gateway and the old gateway are directly reachable
3088 	 */
3089 	if (!prev_ire ||
3090 	    !ire ||
3091 	    ire->ire_type == IRE_LOCAL) {
3092 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3093 		freemsg(mp);
3094 		if (ire != NULL)
3095 			ire_refrele(ire);
3096 		if (prev_ire != NULL)
3097 			ire_refrele(prev_ire);
3098 		return;
3099 	}
3100 
3101 	/*
3102 	 * Should we use the old ULP info to create the new gateway?  From
3103 	 * a user's perspective, we should inherit the info so that it
3104 	 * is a "smooth" transition.  If we do not do that, then new
3105 	 * connections going thru the new gateway will have no route metrics,
3106 	 * which is counter-intuitive to user.  From a network point of
3107 	 * view, this may or may not make sense even though the new gateway
3108 	 * is still directly connected to us so the route metrics should not
3109 	 * change much.
3110 	 *
3111 	 * But if the old ire_uinfo is not initialized, we do another
3112 	 * recursive lookup on the dest using the new gateway.  There may
3113 	 * be a route to that.  If so, use it to initialize the redirect
3114 	 * route.
3115 	 */
3116 	if (prev_ire->ire_uinfo.iulp_set) {
3117 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3118 	} else {
3119 		ire_t *tmp_ire;
3120 		ire_t *sire;
3121 
3122 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3123 		    ALL_ZONES, 0, NULL,
3124 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3125 		    ipst);
3126 		if (sire != NULL) {
3127 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3128 			/*
3129 			 * If sire != NULL, ire_ftable_lookup() should not
3130 			 * return a NULL value.
3131 			 */
3132 			ASSERT(tmp_ire != NULL);
3133 			ire_refrele(tmp_ire);
3134 			ire_refrele(sire);
3135 		} else if (tmp_ire != NULL) {
3136 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3137 			    sizeof (iulp_t));
3138 			ire_refrele(tmp_ire);
3139 		}
3140 	}
3141 	if (prev_ire->ire_type == IRE_CACHE)
3142 		ire_delete(prev_ire);
3143 	ire_refrele(prev_ire);
3144 	/*
3145 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3146 	 * require TOS routing
3147 	 */
3148 	switch (icmph->icmph_code) {
3149 	case 0:
3150 	case 1:
3151 		/* TODO: TOS specificity for cases 2 and 3 */
3152 	case 2:
3153 	case 3:
3154 		break;
3155 	default:
3156 		freemsg(mp);
3157 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3158 		ire_refrele(ire);
3159 		return;
3160 	}
3161 	/*
3162 	 * Create a Route Association.  This will allow us to remember that
3163 	 * someone we believe told us to use the particular gateway.
3164 	 */
3165 	save_ire = ire;
3166 	ire = ire_create(
3167 	    (uchar_t *)&dst,			/* dest addr */
3168 	    (uchar_t *)&ip_g_all_ones,		/* mask */
3169 	    (uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3170 	    (uchar_t *)&gateway,		/* gateway addr */
3171 	    &save_ire->ire_max_frag,		/* max frag */
3172 	    NULL,				/* no src nce */
3173 	    NULL,				/* no rfq */
3174 	    NULL,				/* no stq */
3175 	    IRE_HOST,
3176 	    NULL,				/* ipif */
3177 	    0,					/* cmask */
3178 	    0,					/* phandle */
3179 	    0,					/* ihandle */
3180 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3181 	    &ulp_info,
3182 	    NULL,				/* tsol_gc_t */
3183 	    NULL,				/* gcgrp */
3184 	    ipst);
3185 
3186 	if (ire == NULL) {
3187 		freemsg(mp);
3188 		ire_refrele(save_ire);
3189 		return;
3190 	}
3191 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3192 	ire_refrele(save_ire);
3193 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3194 
3195 	if (error == 0) {
3196 		ire_refrele(ire);		/* Held in ire_add_v4 */
3197 		/* tell routing sockets that we received a redirect */
3198 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3199 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3200 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3201 	}
3202 
3203 	/*
3204 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3205 	 * This together with the added IRE has the effect of
3206 	 * modifying an existing redirect.
3207 	 */
3208 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3209 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3210 	if (prev_ire != NULL) {
3211 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3212 			ire_delete(prev_ire);
3213 		ire_refrele(prev_ire);
3214 	}
3215 
3216 	freemsg(mp);
3217 }
3218 
3219 /*
3220  * Generate an ICMP parameter problem message.
3221  */
3222 static void
3223 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3224 	ip_stack_t *ipst)
3225 {
3226 	icmph_t	icmph;
3227 	boolean_t mctl_present;
3228 	mblk_t *first_mp;
3229 
3230 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3231 
3232 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3233 		if (mctl_present)
3234 			freeb(first_mp);
3235 		return;
3236 	}
3237 
3238 	bzero(&icmph, sizeof (icmph_t));
3239 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3240 	icmph.icmph_pp_ptr = ptr;
3241 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3242 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3243 	    ipst);
3244 }
3245 
3246 /*
3247  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3248  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3249  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3250  * an icmp error packet can be sent.
3251  * Assigns an appropriate source address to the packet. If ipha_dst is
3252  * one of our addresses use it for source. Otherwise pick a source based
3253  * on a route lookup back to ipha_src.
3254  * Note that ipha_src must be set here since the
3255  * packet is likely to arrive on an ill queue in ip_wput() which will
3256  * not set a source address.
3257  */
3258 static void
3259 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3260     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3261 {
3262 	ipaddr_t dst;
3263 	icmph_t	*icmph;
3264 	ipha_t	*ipha;
3265 	uint_t	len_needed;
3266 	size_t	msg_len;
3267 	mblk_t	*mp1;
3268 	ipaddr_t src;
3269 	ire_t	*ire;
3270 	mblk_t *ipsec_mp;
3271 	ipsec_out_t	*io = NULL;
3272 
3273 	if (mctl_present) {
3274 		/*
3275 		 * If it is :
3276 		 *
3277 		 * 1) a IPSEC_OUT, then this is caused by outbound
3278 		 *    datagram originating on this host. IPsec processing
3279 		 *    may or may not have been done. Refer to comments above
3280 		 *    icmp_inbound_error_fanout for details.
3281 		 *
3282 		 * 2) a IPSEC_IN if we are generating a icmp_message
3283 		 *    for an incoming datagram destined for us i.e called
3284 		 *    from ip_fanout_send_icmp.
3285 		 */
3286 		ipsec_info_t *in;
3287 		ipsec_mp = mp;
3288 		mp = ipsec_mp->b_cont;
3289 
3290 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3291 		ipha = (ipha_t *)mp->b_rptr;
3292 
3293 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3294 		    in->ipsec_info_type == IPSEC_IN);
3295 
3296 		if (in->ipsec_info_type == IPSEC_IN) {
3297 			/*
3298 			 * Convert the IPSEC_IN to IPSEC_OUT.
3299 			 */
3300 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3301 				BUMP_MIB(&ipst->ips_ip_mib,
3302 				    ipIfStatsOutDiscards);
3303 				return;
3304 			}
3305 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3306 		} else {
3307 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3308 			io = (ipsec_out_t *)in;
3309 			/*
3310 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3311 			 * ire lookup.
3312 			 */
3313 			io->ipsec_out_proc_begin = B_FALSE;
3314 		}
3315 		ASSERT(zoneid == io->ipsec_out_zoneid);
3316 		ASSERT(zoneid != ALL_ZONES);
3317 	} else {
3318 		/*
3319 		 * This is in clear. The icmp message we are building
3320 		 * here should go out in clear.
3321 		 *
3322 		 * Pardon the convolution of it all, but it's easier to
3323 		 * allocate a "use cleartext" IPSEC_IN message and convert
3324 		 * it than it is to allocate a new one.
3325 		 */
3326 		ipsec_in_t *ii;
3327 		ASSERT(DB_TYPE(mp) == M_DATA);
3328 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3329 		if (ipsec_mp == NULL) {
3330 			freemsg(mp);
3331 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3332 			return;
3333 		}
3334 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3335 
3336 		/* This is not a secure packet */
3337 		ii->ipsec_in_secure = B_FALSE;
3338 		/*
3339 		 * For trusted extensions using a shared IP address we can
3340 		 * send using any zoneid.
3341 		 */
3342 		if (zoneid == ALL_ZONES)
3343 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3344 		else
3345 			ii->ipsec_in_zoneid = zoneid;
3346 		ipsec_mp->b_cont = mp;
3347 		ipha = (ipha_t *)mp->b_rptr;
3348 		/*
3349 		 * Convert the IPSEC_IN to IPSEC_OUT.
3350 		 */
3351 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3352 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3353 			return;
3354 		}
3355 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3356 	}
3357 
3358 	/* Remember our eventual destination */
3359 	dst = ipha->ipha_src;
3360 
3361 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3362 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3363 	if (ire != NULL &&
3364 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3365 		src = ipha->ipha_dst;
3366 	} else {
3367 		if (ire != NULL)
3368 			ire_refrele(ire);
3369 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3370 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3371 		    ipst);
3372 		if (ire == NULL) {
3373 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3374 			freemsg(ipsec_mp);
3375 			return;
3376 		}
3377 		src = ire->ire_src_addr;
3378 	}
3379 
3380 	if (ire != NULL)
3381 		ire_refrele(ire);
3382 
3383 	/*
3384 	 * Check if we can send back more then 8 bytes in addition to
3385 	 * the IP header.  We try to send 64 bytes of data and the internal
3386 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3387 	 */
3388 	len_needed = IPH_HDR_LENGTH(ipha);
3389 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3390 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3391 
3392 		if (!pullupmsg(mp, -1)) {
3393 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3394 			freemsg(ipsec_mp);
3395 			return;
3396 		}
3397 		ipha = (ipha_t *)mp->b_rptr;
3398 
3399 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3400 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3401 			    len_needed));
3402 		} else {
3403 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3404 
3405 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3406 			len_needed += ip_hdr_length_v6(mp, ip6h);
3407 		}
3408 	}
3409 	len_needed += ipst->ips_ip_icmp_return;
3410 	msg_len = msgdsize(mp);
3411 	if (msg_len > len_needed) {
3412 		(void) adjmsg(mp, len_needed - msg_len);
3413 		msg_len = len_needed;
3414 	}
3415 	mp1 = allocb_tmpl(sizeof (icmp_ipha) + len, mp);
3416 	if (mp1 == NULL) {
3417 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3418 		freemsg(ipsec_mp);
3419 		return;
3420 	}
3421 	mp1->b_cont = mp;
3422 	mp = mp1;
3423 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3424 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3425 	    io->ipsec_out_type == IPSEC_OUT);
3426 	ipsec_mp->b_cont = mp;
3427 
3428 	/*
3429 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3430 	 * node generates be accepted in peace by all on-host destinations.
3431 	 * If we do NOT assume that all on-host destinations trust
3432 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3433 	 * (Look for ipsec_out_icmp_loopback).
3434 	 */
3435 	io->ipsec_out_icmp_loopback = B_TRUE;
3436 
3437 	ipha = (ipha_t *)mp->b_rptr;
3438 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3439 	*ipha = icmp_ipha;
3440 	ipha->ipha_src = src;
3441 	ipha->ipha_dst = dst;
3442 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3443 	msg_len += sizeof (icmp_ipha) + len;
3444 	if (msg_len > IP_MAXPACKET) {
3445 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3446 		msg_len = IP_MAXPACKET;
3447 	}
3448 	ipha->ipha_length = htons((uint16_t)msg_len);
3449 	icmph = (icmph_t *)&ipha[1];
3450 	bcopy(stuff, icmph, len);
3451 	icmph->icmph_checksum = 0;
3452 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3453 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3454 	put(q, ipsec_mp);
3455 }
3456 
3457 /*
3458  * Determine if an ICMP error packet can be sent given the rate limit.
3459  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3460  * in milliseconds) and a burst size. Burst size number of packets can
3461  * be sent arbitrarely closely spaced.
3462  * The state is tracked using two variables to implement an approximate
3463  * token bucket filter:
3464  *	icmp_pkt_err_last - lbolt value when the last burst started
3465  *	icmp_pkt_err_sent - number of packets sent in current burst
3466  */
3467 boolean_t
3468 icmp_err_rate_limit(ip_stack_t *ipst)
3469 {
3470 	clock_t now = TICK_TO_MSEC(lbolt);
3471 	uint_t refilled; /* Number of packets refilled in tbf since last */
3472 	/* Guard against changes by loading into local variable */
3473 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3474 
3475 	if (err_interval == 0)
3476 		return (B_FALSE);
3477 
3478 	if (ipst->ips_icmp_pkt_err_last > now) {
3479 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3480 		ipst->ips_icmp_pkt_err_last = 0;
3481 		ipst->ips_icmp_pkt_err_sent = 0;
3482 	}
3483 	/*
3484 	 * If we are in a burst update the token bucket filter.
3485 	 * Update the "last" time to be close to "now" but make sure
3486 	 * we don't loose precision.
3487 	 */
3488 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3489 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3490 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3491 			ipst->ips_icmp_pkt_err_sent = 0;
3492 		} else {
3493 			ipst->ips_icmp_pkt_err_sent -= refilled;
3494 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3495 		}
3496 	}
3497 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3498 		/* Start of new burst */
3499 		ipst->ips_icmp_pkt_err_last = now;
3500 	}
3501 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3502 		ipst->ips_icmp_pkt_err_sent++;
3503 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3504 		    ipst->ips_icmp_pkt_err_sent));
3505 		return (B_FALSE);
3506 	}
3507 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3508 	return (B_TRUE);
3509 }
3510 
3511 /*
3512  * Check if it is ok to send an IPv4 ICMP error packet in
3513  * response to the IPv4 packet in mp.
3514  * Free the message and return null if no
3515  * ICMP error packet should be sent.
3516  */
3517 static mblk_t *
3518 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3519 {
3520 	icmph_t	*icmph;
3521 	ipha_t	*ipha;
3522 	uint_t	len_needed;
3523 	ire_t	*src_ire;
3524 	ire_t	*dst_ire;
3525 
3526 	if (!mp)
3527 		return (NULL);
3528 	ipha = (ipha_t *)mp->b_rptr;
3529 	if (ip_csum_hdr(ipha)) {
3530 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3531 		freemsg(mp);
3532 		return (NULL);
3533 	}
3534 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3535 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3536 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3537 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3538 	if (src_ire != NULL || dst_ire != NULL ||
3539 	    CLASSD(ipha->ipha_dst) ||
3540 	    CLASSD(ipha->ipha_src) ||
3541 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3542 		/* Note: only errors to the fragment with offset 0 */
3543 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3544 		freemsg(mp);
3545 		if (src_ire != NULL)
3546 			ire_refrele(src_ire);
3547 		if (dst_ire != NULL)
3548 			ire_refrele(dst_ire);
3549 		return (NULL);
3550 	}
3551 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3552 		/*
3553 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3554 		 * errors in response to any ICMP errors.
3555 		 */
3556 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3557 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3558 			if (!pullupmsg(mp, len_needed)) {
3559 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3560 				freemsg(mp);
3561 				return (NULL);
3562 			}
3563 			ipha = (ipha_t *)mp->b_rptr;
3564 		}
3565 		icmph = (icmph_t *)
3566 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3567 		switch (icmph->icmph_type) {
3568 		case ICMP_DEST_UNREACHABLE:
3569 		case ICMP_SOURCE_QUENCH:
3570 		case ICMP_TIME_EXCEEDED:
3571 		case ICMP_PARAM_PROBLEM:
3572 		case ICMP_REDIRECT:
3573 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3574 			freemsg(mp);
3575 			return (NULL);
3576 		default:
3577 			break;
3578 		}
3579 	}
3580 	/*
3581 	 * If this is a labeled system, then check to see if we're allowed to
3582 	 * send a response to this particular sender.  If not, then just drop.
3583 	 */
3584 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3585 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3586 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3587 		freemsg(mp);
3588 		return (NULL);
3589 	}
3590 	if (icmp_err_rate_limit(ipst)) {
3591 		/*
3592 		 * Only send ICMP error packets every so often.
3593 		 * This should be done on a per port/source basis,
3594 		 * but for now this will suffice.
3595 		 */
3596 		freemsg(mp);
3597 		return (NULL);
3598 	}
3599 	return (mp);
3600 }
3601 
3602 /*
3603  * Generate an ICMP redirect message.
3604  */
3605 static void
3606 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3607 {
3608 	icmph_t	icmph;
3609 
3610 	/*
3611 	 * We are called from ip_rput where we could
3612 	 * not have attached an IPSEC_IN.
3613 	 */
3614 	ASSERT(mp->b_datap->db_type == M_DATA);
3615 
3616 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3617 		return;
3618 	}
3619 
3620 	bzero(&icmph, sizeof (icmph_t));
3621 	icmph.icmph_type = ICMP_REDIRECT;
3622 	icmph.icmph_code = 1;
3623 	icmph.icmph_rd_gateway = gateway;
3624 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3625 	/* Redirects sent by router, and router is global zone */
3626 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3627 }
3628 
3629 /*
3630  * Generate an ICMP time exceeded message.
3631  */
3632 void
3633 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3634     ip_stack_t *ipst)
3635 {
3636 	icmph_t	icmph;
3637 	boolean_t mctl_present;
3638 	mblk_t *first_mp;
3639 
3640 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3641 
3642 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3643 		if (mctl_present)
3644 			freeb(first_mp);
3645 		return;
3646 	}
3647 
3648 	bzero(&icmph, sizeof (icmph_t));
3649 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3650 	icmph.icmph_code = code;
3651 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3652 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3653 	    ipst);
3654 }
3655 
3656 /*
3657  * Generate an ICMP unreachable message.
3658  */
3659 void
3660 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3661     ip_stack_t *ipst)
3662 {
3663 	icmph_t	icmph;
3664 	mblk_t *first_mp;
3665 	boolean_t mctl_present;
3666 
3667 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3668 
3669 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3670 		if (mctl_present)
3671 			freeb(first_mp);
3672 		return;
3673 	}
3674 
3675 	bzero(&icmph, sizeof (icmph_t));
3676 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3677 	icmph.icmph_code = code;
3678 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3679 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3680 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3681 	    zoneid, ipst);
3682 }
3683 
3684 /*
3685  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3686  * duplicate.  As long as someone else holds the address, the interface will
3687  * stay down.  When that conflict goes away, the interface is brought back up.
3688  * This is done so that accidental shutdowns of addresses aren't made
3689  * permanent.  Your server will recover from a failure.
3690  *
3691  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3692  * user space process (dhcpagent).
3693  *
3694  * Recovery completes if ARP reports that the address is now ours (via
3695  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3696  *
3697  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3698  */
3699 static void
3700 ipif_dup_recovery(void *arg)
3701 {
3702 	ipif_t *ipif = arg;
3703 	ill_t *ill = ipif->ipif_ill;
3704 	mblk_t *arp_add_mp;
3705 	mblk_t *arp_del_mp;
3706 	area_t *area;
3707 	ip_stack_t *ipst = ill->ill_ipst;
3708 
3709 	ipif->ipif_recovery_id = 0;
3710 
3711 	/*
3712 	 * No lock needed for moving or condemned check, as this is just an
3713 	 * optimization.
3714 	 */
3715 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3716 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3717 	    (ipif->ipif_state_flags & (IPIF_MOVING | IPIF_CONDEMNED))) {
3718 		/* No reason to try to bring this address back. */
3719 		return;
3720 	}
3721 
3722 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3723 		goto alloc_fail;
3724 
3725 	if (ipif->ipif_arp_del_mp == NULL) {
3726 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3727 			goto alloc_fail;
3728 		ipif->ipif_arp_del_mp = arp_del_mp;
3729 	}
3730 
3731 	/* Setting the 'unverified' flag restarts DAD */
3732 	area = (area_t *)arp_add_mp->b_rptr;
3733 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3734 	    ACE_F_UNVERIFIED;
3735 	putnext(ill->ill_rq, arp_add_mp);
3736 	return;
3737 
3738 alloc_fail:
3739 	/*
3740 	 * On allocation failure, just restart the timer.  Note that the ipif
3741 	 * is down here, so no other thread could be trying to start a recovery
3742 	 * timer.  The ill_lock protects the condemned flag and the recovery
3743 	 * timer ID.
3744 	 */
3745 	freemsg(arp_add_mp);
3746 	mutex_enter(&ill->ill_lock);
3747 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3748 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3749 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3750 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3751 	}
3752 	mutex_exit(&ill->ill_lock);
3753 }
3754 
3755 /*
3756  * This is for exclusive changes due to ARP.  Either tear down an interface due
3757  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3758  */
3759 /* ARGSUSED */
3760 static void
3761 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3762 {
3763 	ill_t	*ill = rq->q_ptr;
3764 	arh_t *arh;
3765 	ipaddr_t src;
3766 	ipif_t	*ipif;
3767 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3768 	char hbuf[MAC_STR_LEN];
3769 	char sbuf[INET_ADDRSTRLEN];
3770 	const char *failtype;
3771 	boolean_t bring_up;
3772 	ip_stack_t *ipst = ill->ill_ipst;
3773 
3774 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3775 	case AR_CN_READY:
3776 		failtype = NULL;
3777 		bring_up = B_TRUE;
3778 		break;
3779 	case AR_CN_FAILED:
3780 		failtype = "in use";
3781 		bring_up = B_FALSE;
3782 		break;
3783 	default:
3784 		failtype = "claimed";
3785 		bring_up = B_FALSE;
3786 		break;
3787 	}
3788 
3789 	arh = (arh_t *)mp->b_cont->b_rptr;
3790 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3791 
3792 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3793 	    sizeof (hbuf));
3794 	(void) ip_dot_addr(src, sbuf);
3795 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3796 
3797 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3798 		    ipif->ipif_lcl_addr != src) {
3799 			continue;
3800 		}
3801 
3802 		/*
3803 		 * If we failed on a recovery probe, then restart the timer to
3804 		 * try again later.
3805 		 */
3806 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3807 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3808 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3809 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3810 		    ipst->ips_ip_dup_recovery > 0 &&
3811 		    ipif->ipif_recovery_id == 0) {
3812 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3813 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3814 			continue;
3815 		}
3816 
3817 		/*
3818 		 * If what we're trying to do has already been done, then do
3819 		 * nothing.
3820 		 */
3821 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3822 			continue;
3823 
3824 		ipif_get_name(ipif, ibuf, sizeof (ibuf));
3825 
3826 		if (failtype == NULL) {
3827 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3828 			    ibuf);
3829 		} else {
3830 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3831 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3832 		}
3833 
3834 		if (bring_up) {
3835 			ASSERT(ill->ill_dl_up);
3836 			/*
3837 			 * Free up the ARP delete message so we can allocate
3838 			 * a fresh one through the normal path.
3839 			 */
3840 			freemsg(ipif->ipif_arp_del_mp);
3841 			ipif->ipif_arp_del_mp = NULL;
3842 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3843 			    EINPROGRESS) {
3844 				ipif->ipif_addr_ready = 1;
3845 				(void) ipif_up_done(ipif);
3846 			}
3847 			continue;
3848 		}
3849 
3850 		mutex_enter(&ill->ill_lock);
3851 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3852 		ipif->ipif_flags |= IPIF_DUPLICATE;
3853 		ill->ill_ipif_dup_count++;
3854 		mutex_exit(&ill->ill_lock);
3855 		/*
3856 		 * Already exclusive on the ill; no need to handle deferred
3857 		 * processing here.
3858 		 */
3859 		(void) ipif_down(ipif, NULL, NULL);
3860 		ipif_down_tail(ipif);
3861 		mutex_enter(&ill->ill_lock);
3862 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3863 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3864 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3865 		    ipst->ips_ip_dup_recovery > 0) {
3866 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3867 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3868 		}
3869 		mutex_exit(&ill->ill_lock);
3870 	}
3871 	freemsg(mp);
3872 }
3873 
3874 /* ARGSUSED */
3875 static void
3876 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3877 {
3878 	ill_t	*ill = rq->q_ptr;
3879 	arh_t *arh;
3880 	ipaddr_t src;
3881 	ipif_t	*ipif;
3882 
3883 	arh = (arh_t *)mp->b_cont->b_rptr;
3884 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3885 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3886 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3887 			(void) ipif_resolver_up(ipif, Res_act_defend);
3888 	}
3889 	freemsg(mp);
3890 }
3891 
3892 /*
3893  * News from ARP.  ARP sends notification of interesting events down
3894  * to its clients using M_CTL messages with the interesting ARP packet
3895  * attached via b_cont.
3896  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3897  * queue as opposed to ARP sending the message to all the clients, i.e. all
3898  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3899  * table if a cache IRE is found to delete all the entries for the address in
3900  * the packet.
3901  */
3902 static void
3903 ip_arp_news(queue_t *q, mblk_t *mp)
3904 {
3905 	arcn_t		*arcn;
3906 	arh_t		*arh;
3907 	ire_t		*ire = NULL;
3908 	char		hbuf[MAC_STR_LEN];
3909 	char		sbuf[INET_ADDRSTRLEN];
3910 	ipaddr_t	src;
3911 	in6_addr_t	v6src;
3912 	boolean_t	isv6 = B_FALSE;
3913 	ipif_t		*ipif;
3914 	ill_t		*ill;
3915 	ip_stack_t	*ipst;
3916 
3917 	if (CONN_Q(q)) {
3918 		conn_t *connp = Q_TO_CONN(q);
3919 
3920 		ipst = connp->conn_netstack->netstack_ip;
3921 	} else {
3922 		ill_t *ill = (ill_t *)q->q_ptr;
3923 
3924 		ipst = ill->ill_ipst;
3925 	}
3926 
3927 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3928 		if (q->q_next) {
3929 			putnext(q, mp);
3930 		} else
3931 			freemsg(mp);
3932 		return;
3933 	}
3934 	arh = (arh_t *)mp->b_cont->b_rptr;
3935 	/* Is it one we are interested in? */
3936 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3937 		isv6 = B_TRUE;
3938 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3939 		    IPV6_ADDR_LEN);
3940 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3941 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3942 		    IP_ADDR_LEN);
3943 	} else {
3944 		freemsg(mp);
3945 		return;
3946 	}
3947 
3948 	ill = q->q_ptr;
3949 
3950 	arcn = (arcn_t *)mp->b_rptr;
3951 	switch (arcn->arcn_code) {
3952 	case AR_CN_BOGON:
3953 		/*
3954 		 * Someone is sending ARP packets with a source protocol
3955 		 * address that we have published and for which we believe our
3956 		 * entry is authoritative and (when ill_arp_extend is set)
3957 		 * verified to be unique on the network.
3958 		 *
3959 		 * The ARP module internally handles the cases where the sender
3960 		 * is just probing (for DAD) and where the hardware address of
3961 		 * a non-authoritative entry has changed.  Thus, these are the
3962 		 * real conflicts, and we have to do resolution.
3963 		 *
3964 		 * We back away quickly from the address if it's from DHCP or
3965 		 * otherwise temporary and hasn't been used recently (or at
3966 		 * all).  We'd like to include "deprecated" addresses here as
3967 		 * well (as there's no real reason to defend something we're
3968 		 * discarding), but IPMP "reuses" this flag to mean something
3969 		 * other than the standard meaning.
3970 		 *
3971 		 * If the ARP module above is not extended (meaning that it
3972 		 * doesn't know how to defend the address), then we just log
3973 		 * the problem as we always did and continue on.  It's not
3974 		 * right, but there's little else we can do, and those old ATM
3975 		 * users are going away anyway.
3976 		 */
3977 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
3978 		    hbuf, sizeof (hbuf));
3979 		(void) ip_dot_addr(src, sbuf);
3980 		if (isv6) {
3981 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
3982 			    ipst);
3983 		} else {
3984 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
3985 		}
3986 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
3987 			uint32_t now;
3988 			uint32_t maxage;
3989 			clock_t lused;
3990 			uint_t maxdefense;
3991 			uint_t defs;
3992 
3993 			/*
3994 			 * First, figure out if this address hasn't been used
3995 			 * in a while.  If it hasn't, then it's a better
3996 			 * candidate for abandoning.
3997 			 */
3998 			ipif = ire->ire_ipif;
3999 			ASSERT(ipif != NULL);
4000 			now = gethrestime_sec();
4001 			maxage = now - ire->ire_create_time;
4002 			if (maxage > ipst->ips_ip_max_temp_idle)
4003 				maxage = ipst->ips_ip_max_temp_idle;
4004 			lused = drv_hztousec(ddi_get_lbolt() -
4005 			    ire->ire_last_used_time) / MICROSEC + 1;
4006 			if (lused >= maxage && (ipif->ipif_flags &
4007 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4008 				maxdefense = ipst->ips_ip_max_temp_defend;
4009 			else
4010 				maxdefense = ipst->ips_ip_max_defend;
4011 
4012 			/*
4013 			 * Now figure out how many times we've defended
4014 			 * ourselves.  Ignore defenses that happened long in
4015 			 * the past.
4016 			 */
4017 			mutex_enter(&ire->ire_lock);
4018 			if ((defs = ire->ire_defense_count) > 0 &&
4019 			    now - ire->ire_defense_time >
4020 			    ipst->ips_ip_defend_interval) {
4021 				ire->ire_defense_count = defs = 0;
4022 			}
4023 			ire->ire_defense_count++;
4024 			ire->ire_defense_time = now;
4025 			mutex_exit(&ire->ire_lock);
4026 			ill_refhold(ill);
4027 			ire_refrele(ire);
4028 
4029 			/*
4030 			 * If we've defended ourselves too many times already,
4031 			 * then give up and tear down the interface(s) using
4032 			 * this address.  Otherwise, defend by sending out a
4033 			 * gratuitous ARP.
4034 			 */
4035 			if (defs >= maxdefense && ill->ill_arp_extend) {
4036 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4037 				    B_FALSE);
4038 			} else {
4039 				cmn_err(CE_WARN,
4040 				    "node %s is using our IP address %s on %s",
4041 				    hbuf, sbuf, ill->ill_name);
4042 				/*
4043 				 * If this is an old (ATM) ARP module, then
4044 				 * don't try to defend the address.  Remain
4045 				 * compatible with the old behavior.  Defend
4046 				 * only with new ARP.
4047 				 */
4048 				if (ill->ill_arp_extend) {
4049 					qwriter_ip(ill, q, mp, ip_arp_defend,
4050 					    NEW_OP, B_FALSE);
4051 				} else {
4052 					ill_refrele(ill);
4053 				}
4054 			}
4055 			return;
4056 		}
4057 		cmn_err(CE_WARN,
4058 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4059 		    hbuf, sbuf, ill->ill_name);
4060 		if (ire != NULL)
4061 			ire_refrele(ire);
4062 		break;
4063 	case AR_CN_ANNOUNCE:
4064 		if (isv6) {
4065 			/*
4066 			 * For XRESOLV interfaces.
4067 			 * Delete the IRE cache entry and NCE for this
4068 			 * v6 address
4069 			 */
4070 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4071 			/*
4072 			 * If v6src is a non-zero, it's a router address
4073 			 * as below. Do the same sort of thing to clean
4074 			 * out off-net IRE_CACHE entries that go through
4075 			 * the router.
4076 			 */
4077 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4078 				ire_walk_v6(ire_delete_cache_gw_v6,
4079 				    (char *)&v6src, ALL_ZONES, ipst);
4080 			}
4081 		} else {
4082 			nce_hw_map_t hwm;
4083 
4084 			/*
4085 			 * ARP gives us a copy of any packet where it thinks
4086 			 * the address has changed, so that we can update our
4087 			 * caches.  We're responsible for caching known answers
4088 			 * in the current design.  We check whether the
4089 			 * hardware address really has changed in all of our
4090 			 * entries that have cached this mapping, and if so, we
4091 			 * blow them away.  This way we will immediately pick
4092 			 * up the rare case of a host changing hardware
4093 			 * address.
4094 			 */
4095 			if (src == 0)
4096 				break;
4097 			hwm.hwm_addr = src;
4098 			hwm.hwm_hwlen = arh->arh_hlen;
4099 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4100 			NDP_HW_CHANGE_INCR(ipst->ips_ndp4);
4101 			ndp_walk_common(ipst->ips_ndp4, NULL,
4102 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4103 			NDP_HW_CHANGE_DECR(ipst->ips_ndp4);
4104 		}
4105 		break;
4106 	case AR_CN_READY:
4107 		/* No external v6 resolver has a contract to use this */
4108 		if (isv6)
4109 			break;
4110 		/* If the link is down, we'll retry this later */
4111 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4112 			break;
4113 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4114 		    NULL, NULL, ipst);
4115 		if (ipif != NULL) {
4116 			/*
4117 			 * If this is a duplicate recovery, then we now need to
4118 			 * go exclusive to bring this thing back up.
4119 			 */
4120 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4121 			    IPIF_DUPLICATE) {
4122 				ipif_refrele(ipif);
4123 				ill_refhold(ill);
4124 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4125 				    B_FALSE);
4126 				return;
4127 			}
4128 			/*
4129 			 * If this is the first notice that this address is
4130 			 * ready, then let the user know now.
4131 			 */
4132 			if ((ipif->ipif_flags & IPIF_UP) &&
4133 			    !ipif->ipif_addr_ready) {
4134 				ipif_mask_reply(ipif);
4135 				ip_rts_ifmsg(ipif);
4136 				ip_rts_newaddrmsg(RTM_ADD, 0, ipif);
4137 				sctp_update_ipif(ipif, SCTP_IPIF_UP);
4138 			}
4139 			ipif->ipif_addr_ready = 1;
4140 			ipif_refrele(ipif);
4141 		}
4142 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp), ipst);
4143 		if (ire != NULL) {
4144 			ire->ire_defense_count = 0;
4145 			ire_refrele(ire);
4146 		}
4147 		break;
4148 	case AR_CN_FAILED:
4149 		/* No external v6 resolver has a contract to use this */
4150 		if (isv6)
4151 			break;
4152 		ill_refhold(ill);
4153 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, B_FALSE);
4154 		return;
4155 	}
4156 	freemsg(mp);
4157 }
4158 
4159 /*
4160  * Create a mblk suitable for carrying the interface index and/or source link
4161  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4162  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4163  * application.
4164  */
4165 mblk_t *
4166 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4167     ip_stack_t *ipst)
4168 {
4169 	mblk_t		*mp;
4170 	ip_pktinfo_t	*pinfo;
4171 	ipha_t *ipha;
4172 	struct ether_header *pether;
4173 
4174 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4175 	if (mp == NULL) {
4176 		ip1dbg(("ip_add_info: allocation failure.\n"));
4177 		return (data_mp);
4178 	}
4179 
4180 	ipha	= (ipha_t *)data_mp->b_rptr;
4181 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4182 	bzero(pinfo, sizeof (ip_pktinfo_t));
4183 	pinfo->ip_pkt_flags = (uchar_t)flags;
4184 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4185 
4186 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4187 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4188 	if (flags & IPF_RECVADDR) {
4189 		ipif_t	*ipif;
4190 		ire_t	*ire;
4191 
4192 		/*
4193 		 * Only valid for V4
4194 		 */
4195 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4196 		    (IPV4_VERSION << 4));
4197 
4198 		ipif = ipif_get_next_ipif(NULL, ill);
4199 		if (ipif != NULL) {
4200 			/*
4201 			 * Since a decision has already been made to deliver the
4202 			 * packet, there is no need to test for SECATTR and
4203 			 * ZONEONLY.
4204 			 * When a multicast packet is transmitted
4205 			 * a cache entry is created for the multicast address.
4206 			 * When delivering a copy of the packet or when new
4207 			 * packets are received we do not want to match on the
4208 			 * cached entry so explicitly match on
4209 			 * IRE_LOCAL and IRE_LOOPBACK
4210 			 */
4211 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4212 			    IRE_LOCAL | IRE_LOOPBACK,
4213 			    ipif, zoneid, NULL,
4214 			    MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP, ipst);
4215 			if (ire == NULL) {
4216 				/*
4217 				 * packet must have come on a different
4218 				 * interface.
4219 				 * Since a decision has already been made to
4220 				 * deliver the packet, there is no need to test
4221 				 * for SECATTR and ZONEONLY.
4222 				 * Only match on local and broadcast ire's.
4223 				 * See detailed comment above.
4224 				 */
4225 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4226 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4227 				    NULL, MATCH_IRE_TYPE, ipst);
4228 			}
4229 
4230 			if (ire == NULL) {
4231 				/*
4232 				 * This is either a multicast packet or
4233 				 * the address has been removed since
4234 				 * the packet was received.
4235 				 * Return INADDR_ANY so that normal source
4236 				 * selection occurs for the response.
4237 				 */
4238 
4239 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4240 			} else {
4241 				pinfo->ip_pkt_match_addr.s_addr =
4242 				    ire->ire_src_addr;
4243 				ire_refrele(ire);
4244 			}
4245 			ipif_refrele(ipif);
4246 		} else {
4247 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4248 		}
4249 	}
4250 
4251 	pether = (struct ether_header *)((char *)ipha
4252 	    - sizeof (struct ether_header));
4253 	/*
4254 	 * Make sure the interface is an ethernet type, since this option
4255 	 * is currently supported only on this type of interface. Also make
4256 	 * sure we are pointing correctly above db_base.
4257 	 */
4258 
4259 	if ((flags & IPF_RECVSLLA) &&
4260 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4261 	    (ill->ill_type == IFT_ETHER) &&
4262 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4263 
4264 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4265 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4266 		    (uchar_t *)pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4267 	} else {
4268 		/*
4269 		 * Clear the bit. Indicate to upper layer that IP is not
4270 		 * sending this ancillary info.
4271 		 */
4272 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4273 	}
4274 
4275 	mp->b_datap->db_type = M_CTL;
4276 	mp->b_wptr += sizeof (ip_pktinfo_t);
4277 	mp->b_cont = data_mp;
4278 
4279 	return (mp);
4280 }
4281 
4282 /*
4283  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4284  * part of the bind request.
4285  */
4286 
4287 boolean_t
4288 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4289 {
4290 	ipsec_in_t *ii;
4291 
4292 	ASSERT(policy_mp != NULL);
4293 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4294 
4295 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4296 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4297 
4298 	connp->conn_policy = ii->ipsec_in_policy;
4299 	ii->ipsec_in_policy = NULL;
4300 
4301 	if (ii->ipsec_in_action != NULL) {
4302 		if (connp->conn_latch == NULL) {
4303 			connp->conn_latch = iplatch_create();
4304 			if (connp->conn_latch == NULL)
4305 				return (B_FALSE);
4306 		}
4307 		ipsec_latch_inbound(connp->conn_latch, ii);
4308 	}
4309 	return (B_TRUE);
4310 }
4311 
4312 /*
4313  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4314  * and to arrange for power-fanout assist.  The ULP is identified by
4315  * adding a single byte at the end of the original bind message.
4316  * A ULP other than UDP or TCP that wishes to be recognized passes
4317  * down a bind with a zero length address.
4318  *
4319  * The binding works as follows:
4320  * - A zero byte address means just bind to the protocol.
4321  * - A four byte address is treated as a request to validate
4322  *   that the address is a valid local address, appropriate for
4323  *   an application to bind to. This does not affect any fanout
4324  *   information in IP.
4325  * - A sizeof sin_t byte address is used to bind to only the local address
4326  *   and port.
4327  * - A sizeof ipa_conn_t byte address contains complete fanout information
4328  *   consisting of local and remote addresses and ports.  In
4329  *   this case, the addresses are both validated as appropriate
4330  *   for this operation, and, if so, the information is retained
4331  *   for use in the inbound fanout.
4332  *
4333  * The ULP (except in the zero-length bind) can append an
4334  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4335  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4336  * a copy of the source or destination IRE (source for local bind;
4337  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4338  * policy information contained should be copied on to the conn.
4339  *
4340  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4341  */
4342 mblk_t *
4343 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4344 {
4345 	ssize_t		len;
4346 	struct T_bind_req	*tbr;
4347 	sin_t		*sin;
4348 	ipa_conn_t	*ac;
4349 	uchar_t		*ucp;
4350 	mblk_t		*mp1;
4351 	boolean_t	ire_requested;
4352 	boolean_t	ipsec_policy_set = B_FALSE;
4353 	int		error = 0;
4354 	int		protocol;
4355 	ipa_conn_x_t	*acx;
4356 
4357 	ASSERT(!connp->conn_af_isv6);
4358 	connp->conn_pkt_isv6 = B_FALSE;
4359 
4360 	len = MBLKL(mp);
4361 	if (len < (sizeof (*tbr) + 1)) {
4362 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4363 		    "ip_bind: bogus msg, len %ld", len);
4364 		/* XXX: Need to return something better */
4365 		goto bad_addr;
4366 	}
4367 	/* Back up and extract the protocol identifier. */
4368 	mp->b_wptr--;
4369 	protocol = *mp->b_wptr & 0xFF;
4370 	tbr = (struct T_bind_req *)mp->b_rptr;
4371 	/* Reset the message type in preparation for shipping it back. */
4372 	DB_TYPE(mp) = M_PCPROTO;
4373 
4374 	connp->conn_ulp = (uint8_t)protocol;
4375 
4376 	/*
4377 	 * Check for a zero length address.  This is from a protocol that
4378 	 * wants to register to receive all packets of its type.
4379 	 */
4380 	if (tbr->ADDR_length == 0) {
4381 		/*
4382 		 * These protocols are now intercepted in ip_bind_v6().
4383 		 * Reject protocol-level binds here for now.
4384 		 *
4385 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4386 		 * so that the protocol type cannot be SCTP.
4387 		 */
4388 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4389 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4390 			goto bad_addr;
4391 		}
4392 
4393 		/*
4394 		 *
4395 		 * The udp module never sends down a zero-length address,
4396 		 * and allowing this on a labeled system will break MLP
4397 		 * functionality.
4398 		 */
4399 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4400 			goto bad_addr;
4401 
4402 		if (connp->conn_mac_exempt)
4403 			goto bad_addr;
4404 
4405 		/* No hash here really.  The table is big enough. */
4406 		connp->conn_srcv6 = ipv6_all_zeros;
4407 
4408 		ipcl_proto_insert(connp, protocol);
4409 
4410 		tbr->PRIM_type = T_BIND_ACK;
4411 		return (mp);
4412 	}
4413 
4414 	/* Extract the address pointer from the message. */
4415 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4416 	    tbr->ADDR_length);
4417 	if (ucp == NULL) {
4418 		ip1dbg(("ip_bind: no address\n"));
4419 		goto bad_addr;
4420 	}
4421 	if (!OK_32PTR(ucp)) {
4422 		ip1dbg(("ip_bind: unaligned address\n"));
4423 		goto bad_addr;
4424 	}
4425 	/*
4426 	 * Check for trailing mps.
4427 	 */
4428 
4429 	mp1 = mp->b_cont;
4430 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4431 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4432 
4433 	switch (tbr->ADDR_length) {
4434 	default:
4435 		ip1dbg(("ip_bind: bad address length %d\n",
4436 		    (int)tbr->ADDR_length));
4437 		goto bad_addr;
4438 
4439 	case IP_ADDR_LEN:
4440 		/* Verification of local address only */
4441 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4442 		    ire_requested, ipsec_policy_set, B_FALSE);
4443 		break;
4444 
4445 	case sizeof (sin_t):
4446 		sin = (sin_t *)ucp;
4447 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4448 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4449 		break;
4450 
4451 	case sizeof (ipa_conn_t):
4452 		ac = (ipa_conn_t *)ucp;
4453 		/* For raw socket, the local port is not set. */
4454 		if (ac->ac_lport == 0)
4455 			ac->ac_lport = connp->conn_lport;
4456 		/* Always verify destination reachability. */
4457 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4458 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4459 		    ipsec_policy_set, B_TRUE, B_TRUE);
4460 		break;
4461 
4462 	case sizeof (ipa_conn_x_t):
4463 		acx = (ipa_conn_x_t *)ucp;
4464 		/*
4465 		 * Whether or not to verify destination reachability depends
4466 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4467 		 */
4468 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4469 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4470 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4471 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4472 		break;
4473 	}
4474 	if (error == EINPROGRESS)
4475 		return (NULL);
4476 	else if (error != 0)
4477 		goto bad_addr;
4478 	/*
4479 	 * Pass the IPsec headers size in ire_ipsec_overhead.
4480 	 * We can't do this in ip_bind_insert_ire because the policy
4481 	 * may not have been inherited at that point in time and hence
4482 	 * conn_out_enforce_policy may not be set.
4483 	 */
4484 	mp1 = mp->b_cont;
4485 	if (ire_requested && connp->conn_out_enforce_policy &&
4486 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4487 		ire_t *ire = (ire_t *)mp1->b_rptr;
4488 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4489 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4490 	}
4491 
4492 	/* Send it home. */
4493 	mp->b_datap->db_type = M_PCPROTO;
4494 	tbr->PRIM_type = T_BIND_ACK;
4495 	return (mp);
4496 
4497 bad_addr:
4498 	/*
4499 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4500 	 * a unix errno.
4501 	 */
4502 	if (error > 0)
4503 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4504 	else
4505 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4506 	return (mp);
4507 }
4508 
4509 /*
4510  * Here address is verified to be a valid local address.
4511  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4512  * address is also considered a valid local address.
4513  * In the case of a broadcast/multicast address, however, the
4514  * upper protocol is expected to reset the src address
4515  * to 0 if it sees a IRE_BROADCAST type returned so that
4516  * no packets are emitted with broadcast/multicast address as
4517  * source address (that violates hosts requirements RFC1122)
4518  * The addresses valid for bind are:
4519  *	(1) - INADDR_ANY (0)
4520  *	(2) - IP address of an UP interface
4521  *	(3) - IP address of a DOWN interface
4522  *	(4) - valid local IP broadcast addresses. In this case
4523  *	the conn will only receive packets destined to
4524  *	the specified broadcast address.
4525  *	(5) - a multicast address. In this case
4526  *	the conn will only receive packets destined to
4527  *	the specified multicast address. Note: the
4528  *	application still has to issue an
4529  *	IP_ADD_MEMBERSHIP socket option.
4530  *
4531  * On error, return -1 for TBADADDR otherwise pass the
4532  * errno with TSYSERR reply.
4533  *
4534  * In all the above cases, the bound address must be valid in the current zone.
4535  * When the address is loopback, multicast or broadcast, there might be many
4536  * matching IREs so bind has to look up based on the zone.
4537  *
4538  * Note: lport is in network byte order.
4539  */
4540 int
4541 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4542     boolean_t ire_requested, boolean_t ipsec_policy_set,
4543     boolean_t fanout_insert)
4544 {
4545 	int		error = 0;
4546 	ire_t		*src_ire;
4547 	mblk_t		*policy_mp;
4548 	ipif_t		*ipif;
4549 	zoneid_t	zoneid;
4550 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4551 
4552 	if (ipsec_policy_set) {
4553 		policy_mp = mp->b_cont;
4554 	}
4555 
4556 	/*
4557 	 * If it was previously connected, conn_fully_bound would have
4558 	 * been set.
4559 	 */
4560 	connp->conn_fully_bound = B_FALSE;
4561 
4562 	src_ire = NULL;
4563 	ipif = NULL;
4564 
4565 	zoneid = IPCL_ZONEID(connp);
4566 
4567 	if (src_addr) {
4568 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4569 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4570 		/*
4571 		 * If an address other than 0.0.0.0 is requested,
4572 		 * we verify that it is a valid address for bind
4573 		 * Note: Following code is in if-else-if form for
4574 		 * readability compared to a condition check.
4575 		 */
4576 		/* LINTED - statement has no consequent */
4577 		if (IRE_IS_LOCAL(src_ire)) {
4578 			/*
4579 			 * (2) Bind to address of local UP interface
4580 			 */
4581 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4582 			/*
4583 			 * (4) Bind to broadcast address
4584 			 * Note: permitted only from transports that
4585 			 * request IRE
4586 			 */
4587 			if (!ire_requested)
4588 				error = EADDRNOTAVAIL;
4589 		} else {
4590 			/*
4591 			 * (3) Bind to address of local DOWN interface
4592 			 * (ipif_lookup_addr() looks up all interfaces
4593 			 * but we do not get here for UP interfaces
4594 			 * - case (2) above)
4595 			 * We put the protocol byte back into the mblk
4596 			 * since we may come back via ip_wput_nondata()
4597 			 * later with this mblk if ipif_lookup_addr chooses
4598 			 * to defer processing.
4599 			 */
4600 			*mp->b_wptr++ = (char)connp->conn_ulp;
4601 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4602 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4603 			    &error, ipst)) != NULL) {
4604 				ipif_refrele(ipif);
4605 			} else if (error == EINPROGRESS) {
4606 				if (src_ire != NULL)
4607 					ire_refrele(src_ire);
4608 				return (EINPROGRESS);
4609 			} else if (CLASSD(src_addr)) {
4610 				error = 0;
4611 				if (src_ire != NULL)
4612 					ire_refrele(src_ire);
4613 				/*
4614 				 * (5) bind to multicast address.
4615 				 * Fake out the IRE returned to upper
4616 				 * layer to be a broadcast IRE.
4617 				 */
4618 				src_ire = ire_ctable_lookup(
4619 				    INADDR_BROADCAST, INADDR_ANY,
4620 				    IRE_BROADCAST, NULL, zoneid, NULL,
4621 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4622 				    ipst);
4623 				if (src_ire == NULL || !ire_requested)
4624 					error = EADDRNOTAVAIL;
4625 			} else {
4626 				/*
4627 				 * Not a valid address for bind
4628 				 */
4629 				error = EADDRNOTAVAIL;
4630 			}
4631 			/*
4632 			 * Just to keep it consistent with the processing in
4633 			 * ip_bind_v4()
4634 			 */
4635 			mp->b_wptr--;
4636 		}
4637 		if (error) {
4638 			/* Red Alert!  Attempting to be a bogon! */
4639 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4640 			    ntohl(src_addr)));
4641 			goto bad_addr;
4642 		}
4643 	}
4644 
4645 	/*
4646 	 * Allow setting new policies. For example, disconnects come
4647 	 * down as ipa_t bind. As we would have set conn_policy_cached
4648 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4649 	 * can change after the disconnect.
4650 	 */
4651 	connp->conn_policy_cached = B_FALSE;
4652 
4653 	/*
4654 	 * If not fanout_insert this was just an address verification
4655 	 */
4656 	if (fanout_insert) {
4657 		/*
4658 		 * The addresses have been verified. Time to insert in
4659 		 * the correct fanout list.
4660 		 */
4661 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4662 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4663 		connp->conn_lport = lport;
4664 		connp->conn_fport = 0;
4665 		/*
4666 		 * Do we need to add a check to reject Multicast packets
4667 		 */
4668 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4669 	}
4670 
4671 	if (error == 0) {
4672 		if (ire_requested) {
4673 			if (!ip_bind_insert_ire(mp, src_ire, NULL, ipst)) {
4674 				error = -1;
4675 				/* Falls through to bad_addr */
4676 			}
4677 		} else if (ipsec_policy_set) {
4678 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4679 				error = -1;
4680 				/* Falls through to bad_addr */
4681 			}
4682 		}
4683 	}
4684 bad_addr:
4685 	if (error != 0) {
4686 		if (connp->conn_anon_port) {
4687 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4688 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4689 			    B_FALSE);
4690 		}
4691 		connp->conn_mlp_type = mlptSingle;
4692 	}
4693 	if (src_ire != NULL)
4694 		IRE_REFRELE(src_ire);
4695 	if (ipsec_policy_set) {
4696 		ASSERT(policy_mp == mp->b_cont);
4697 		ASSERT(policy_mp != NULL);
4698 		freeb(policy_mp);
4699 		/*
4700 		 * As of now assume that nothing else accompanies
4701 		 * IPSEC_POLICY_SET.
4702 		 */
4703 		mp->b_cont = NULL;
4704 	}
4705 	return (error);
4706 }
4707 
4708 /*
4709  * Verify that both the source and destination addresses
4710  * are valid.  If verify_dst is false, then the destination address may be
4711  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4712  * destination reachability, while tunnels do not.
4713  * Note that we allow connect to broadcast and multicast
4714  * addresses when ire_requested is set. Thus the ULP
4715  * has to check for IRE_BROADCAST and multicast.
4716  *
4717  * Returns zero if ok.
4718  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4719  * (for use with TSYSERR reply).
4720  *
4721  * Note: lport and fport are in network byte order.
4722  */
4723 int
4724 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4725     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4726     boolean_t ire_requested, boolean_t ipsec_policy_set,
4727     boolean_t fanout_insert, boolean_t verify_dst)
4728 {
4729 	ire_t		*src_ire;
4730 	ire_t		*dst_ire;
4731 	int		error = 0;
4732 	int 		protocol;
4733 	mblk_t		*policy_mp;
4734 	ire_t		*sire = NULL;
4735 	ire_t		*md_dst_ire = NULL;
4736 	ire_t		*lso_dst_ire = NULL;
4737 	ill_t		*ill = NULL;
4738 	zoneid_t	zoneid;
4739 	ipaddr_t	src_addr = *src_addrp;
4740 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4741 
4742 	src_ire = dst_ire = NULL;
4743 	protocol = *mp->b_wptr & 0xFF;
4744 
4745 	/*
4746 	 * If we never got a disconnect before, clear it now.
4747 	 */
4748 	connp->conn_fully_bound = B_FALSE;
4749 
4750 	if (ipsec_policy_set) {
4751 		policy_mp = mp->b_cont;
4752 	}
4753 
4754 	zoneid = IPCL_ZONEID(connp);
4755 
4756 	if (CLASSD(dst_addr)) {
4757 		/* Pick up an IRE_BROADCAST */
4758 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4759 		    NULL, zoneid, MBLK_GETLABEL(mp),
4760 		    (MATCH_IRE_RECURSIVE |
4761 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4762 		    MATCH_IRE_SECATTR), ipst);
4763 	} else {
4764 		/*
4765 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4766 		 * and onlink ipif is not found set ENETUNREACH error.
4767 		 */
4768 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4769 			ipif_t *ipif;
4770 
4771 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4772 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4773 			if (ipif == NULL) {
4774 				error = ENETUNREACH;
4775 				goto bad_addr;
4776 			}
4777 			ipif_refrele(ipif);
4778 		}
4779 
4780 		if (connp->conn_nexthop_set) {
4781 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4782 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4783 			    MATCH_IRE_SECATTR, ipst);
4784 		} else {
4785 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4786 			    &sire, zoneid, MBLK_GETLABEL(mp),
4787 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4788 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4789 			    MATCH_IRE_SECATTR), ipst);
4790 		}
4791 	}
4792 	/*
4793 	 * dst_ire can't be a broadcast when not ire_requested.
4794 	 * We also prevent ire's with src address INADDR_ANY to
4795 	 * be used, which are created temporarily for
4796 	 * sending out packets from endpoints that have
4797 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4798 	 * reachable.  If verify_dst is false, the destination needn't be
4799 	 * reachable.
4800 	 *
4801 	 * If we match on a reject or black hole, then we've got a
4802 	 * local failure.  May as well fail out the connect() attempt,
4803 	 * since it's never going to succeed.
4804 	 */
4805 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4806 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4807 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4808 		/*
4809 		 * If we're verifying destination reachability, we always want
4810 		 * to complain here.
4811 		 *
4812 		 * If we're not verifying destination reachability but the
4813 		 * destination has a route, we still want to fail on the
4814 		 * temporary address and broadcast address tests.
4815 		 */
4816 		if (verify_dst || (dst_ire != NULL)) {
4817 			if (ip_debug > 2) {
4818 				pr_addr_dbg("ip_bind_connected: bad connected "
4819 				    "dst %s\n", AF_INET, &dst_addr);
4820 			}
4821 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4822 				error = ENETUNREACH;
4823 			else
4824 				error = EHOSTUNREACH;
4825 			goto bad_addr;
4826 		}
4827 	}
4828 
4829 	/*
4830 	 * We now know that routing will allow us to reach the destination.
4831 	 * Check whether Trusted Solaris policy allows communication with this
4832 	 * host, and pretend that the destination is unreachable if not.
4833 	 *
4834 	 * This is never a problem for TCP, since that transport is known to
4835 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4836 	 * handling.  If the remote is unreachable, it will be detected at that
4837 	 * point, so there's no reason to check it here.
4838 	 *
4839 	 * Note that for sendto (and other datagram-oriented friends), this
4840 	 * check is done as part of the data path label computation instead.
4841 	 * The check here is just to make non-TCP connect() report the right
4842 	 * error.
4843 	 */
4844 	if (dst_ire != NULL && is_system_labeled() &&
4845 	    !IPCL_IS_TCP(connp) &&
4846 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4847 	    connp->conn_mac_exempt, ipst) != 0) {
4848 		error = EHOSTUNREACH;
4849 		if (ip_debug > 2) {
4850 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4851 			    AF_INET, &dst_addr);
4852 		}
4853 		goto bad_addr;
4854 	}
4855 
4856 	/*
4857 	 * If the app does a connect(), it means that it will most likely
4858 	 * send more than 1 packet to the destination.  It makes sense
4859 	 * to clear the temporary flag.
4860 	 */
4861 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4862 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4863 		irb_t *irb = dst_ire->ire_bucket;
4864 
4865 		rw_enter(&irb->irb_lock, RW_WRITER);
4866 		/*
4867 		 * We need to recheck for IRE_MARK_TEMPORARY after acquiring
4868 		 * the lock to guarantee irb_tmp_ire_cnt.
4869 		 */
4870 		if (dst_ire->ire_marks & IRE_MARK_TEMPORARY) {
4871 			dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4872 			irb->irb_tmp_ire_cnt--;
4873 		}
4874 		rw_exit(&irb->irb_lock);
4875 	}
4876 
4877 	/*
4878 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4879 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4880 	 * eligibility tests for passive connects are handled separately
4881 	 * through tcp_adapt_ire().  We do this before the source address
4882 	 * selection, because dst_ire may change after a call to
4883 	 * ipif_select_source().  This is a best-effort check, as the
4884 	 * packet for this connection may not actually go through
4885 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4886 	 * calling ip_newroute().  This is why we further check on the
4887 	 * IRE during LSO/Multidata packet transmission in
4888 	 * tcp_lsosend()/tcp_multisend().
4889 	 */
4890 	if (!ipsec_policy_set && dst_ire != NULL &&
4891 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4892 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4893 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4894 			lso_dst_ire = dst_ire;
4895 			IRE_REFHOLD(lso_dst_ire);
4896 		} else if (ipst->ips_ip_multidata_outbound &&
4897 		    ILL_MDT_CAPABLE(ill)) {
4898 			md_dst_ire = dst_ire;
4899 			IRE_REFHOLD(md_dst_ire);
4900 		}
4901 	}
4902 
4903 	if (dst_ire != NULL &&
4904 	    dst_ire->ire_type == IRE_LOCAL &&
4905 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4906 		/*
4907 		 * If the IRE belongs to a different zone, look for a matching
4908 		 * route in the forwarding table and use the source address from
4909 		 * that route.
4910 		 */
4911 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4912 		    zoneid, 0, NULL,
4913 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4914 		    MATCH_IRE_RJ_BHOLE, ipst);
4915 		if (src_ire == NULL) {
4916 			error = EHOSTUNREACH;
4917 			goto bad_addr;
4918 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4919 			if (!(src_ire->ire_type & IRE_HOST))
4920 				error = ENETUNREACH;
4921 			else
4922 				error = EHOSTUNREACH;
4923 			goto bad_addr;
4924 		}
4925 		if (src_addr == INADDR_ANY)
4926 			src_addr = src_ire->ire_src_addr;
4927 		ire_refrele(src_ire);
4928 		src_ire = NULL;
4929 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4930 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4931 			src_addr = sire->ire_src_addr;
4932 			ire_refrele(dst_ire);
4933 			dst_ire = sire;
4934 			sire = NULL;
4935 		} else {
4936 			/*
4937 			 * Pick a source address so that a proper inbound
4938 			 * load spreading would happen.
4939 			 */
4940 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4941 			ipif_t *src_ipif = NULL;
4942 			ire_t *ipif_ire;
4943 
4944 			/*
4945 			 * Supply a local source address such that inbound
4946 			 * load spreading happens.
4947 			 *
4948 			 * Determine the best source address on this ill for
4949 			 * the destination.
4950 			 *
4951 			 * 1) For broadcast, we should return a broadcast ire
4952 			 *    found above so that upper layers know that the
4953 			 *    destination address is a broadcast address.
4954 			 *
4955 			 * 2) If this is part of a group, select a better
4956 			 *    source address so that better inbound load
4957 			 *    balancing happens. Do the same if the ipif
4958 			 *    is DEPRECATED.
4959 			 *
4960 			 * 3) If the outgoing interface is part of a usesrc
4961 			 *    group, then try selecting a source address from
4962 			 *    the usesrc ILL.
4963 			 */
4964 			if ((dst_ire->ire_zoneid != zoneid &&
4965 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4966 			    (!(dst_ire->ire_flags & RTF_SETSRC)) &&
4967 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4968 			    ((dst_ill->ill_group != NULL) ||
4969 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4970 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4971 				/*
4972 				 * If the destination is reachable via a
4973 				 * given gateway, the selected source address
4974 				 * should be in the same subnet as the gateway.
4975 				 * Otherwise, the destination is not reachable.
4976 				 *
4977 				 * If there are no interfaces on the same subnet
4978 				 * as the destination, ipif_select_source gives
4979 				 * first non-deprecated interface which might be
4980 				 * on a different subnet than the gateway.
4981 				 * This is not desirable. Hence pass the dst_ire
4982 				 * source address to ipif_select_source.
4983 				 * It is sure that the destination is reachable
4984 				 * with the dst_ire source address subnet.
4985 				 * So passing dst_ire source address to
4986 				 * ipif_select_source will make sure that the
4987 				 * selected source will be on the same subnet
4988 				 * as dst_ire source address.
4989 				 */
4990 				ipaddr_t saddr =
4991 				    dst_ire->ire_ipif->ipif_src_addr;
4992 				src_ipif = ipif_select_source(dst_ill,
4993 				    saddr, zoneid);
4994 				if (src_ipif != NULL) {
4995 					if (IS_VNI(src_ipif->ipif_ill)) {
4996 						/*
4997 						 * For VNI there is no
4998 						 * interface route
4999 						 */
5000 						src_addr =
5001 						    src_ipif->ipif_src_addr;
5002 					} else {
5003 						ipif_ire =
5004 						    ipif_to_ire(src_ipif);
5005 						if (ipif_ire != NULL) {
5006 							IRE_REFRELE(dst_ire);
5007 							dst_ire = ipif_ire;
5008 						}
5009 						src_addr =
5010 						    dst_ire->ire_src_addr;
5011 					}
5012 					ipif_refrele(src_ipif);
5013 				} else {
5014 					src_addr = dst_ire->ire_src_addr;
5015 				}
5016 			} else {
5017 				src_addr = dst_ire->ire_src_addr;
5018 			}
5019 		}
5020 	}
5021 
5022 	/*
5023 	 * We do ire_route_lookup() here (and not
5024 	 * interface lookup as we assert that
5025 	 * src_addr should only come from an
5026 	 * UP interface for hard binding.
5027 	 */
5028 	ASSERT(src_ire == NULL);
5029 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5030 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5031 	/* src_ire must be a local|loopback */
5032 	if (!IRE_IS_LOCAL(src_ire)) {
5033 		if (ip_debug > 2) {
5034 			pr_addr_dbg("ip_bind_connected: bad connected "
5035 			    "src %s\n", AF_INET, &src_addr);
5036 		}
5037 		error = EADDRNOTAVAIL;
5038 		goto bad_addr;
5039 	}
5040 
5041 	/*
5042 	 * If the source address is a loopback address, the
5043 	 * destination had best be local or multicast.
5044 	 * The transports that can't handle multicast will reject
5045 	 * those addresses.
5046 	 */
5047 	if (src_ire->ire_type == IRE_LOOPBACK &&
5048 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5049 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5050 		error = -1;
5051 		goto bad_addr;
5052 	}
5053 
5054 	/*
5055 	 * Allow setting new policies. For example, disconnects come
5056 	 * down as ipa_t bind. As we would have set conn_policy_cached
5057 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5058 	 * can change after the disconnect.
5059 	 */
5060 	connp->conn_policy_cached = B_FALSE;
5061 
5062 	/*
5063 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5064 	 * can handle their passed-in conn's.
5065 	 */
5066 
5067 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5068 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5069 	connp->conn_lport = lport;
5070 	connp->conn_fport = fport;
5071 	*src_addrp = src_addr;
5072 
5073 	ASSERT(!(ipsec_policy_set && ire_requested));
5074 	if (ire_requested) {
5075 		iulp_t *ulp_info = NULL;
5076 
5077 		/*
5078 		 * Note that sire will not be NULL if this is an off-link
5079 		 * connection and there is not cache for that dest yet.
5080 		 *
5081 		 * XXX Because of an existing bug, if there are multiple
5082 		 * default routes, the IRE returned now may not be the actual
5083 		 * default route used (default routes are chosen in a
5084 		 * round robin fashion).  So if the metrics for different
5085 		 * default routes are different, we may return the wrong
5086 		 * metrics.  This will not be a problem if the existing
5087 		 * bug is fixed.
5088 		 */
5089 		if (sire != NULL) {
5090 			ulp_info = &(sire->ire_uinfo);
5091 		}
5092 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info, ipst)) {
5093 			error = -1;
5094 			goto bad_addr;
5095 		}
5096 	} else if (ipsec_policy_set) {
5097 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5098 			error = -1;
5099 			goto bad_addr;
5100 		}
5101 	}
5102 
5103 	/*
5104 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5105 	 * we'll cache that.  If we don't, we'll inherit global policy.
5106 	 *
5107 	 * We can't insert until the conn reflects the policy. Note that
5108 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5109 	 * connections where we don't have a policy. This is to prevent
5110 	 * global policy lookups in the inbound path.
5111 	 *
5112 	 * If we insert before we set conn_policy_cached,
5113 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5114 	 * because global policy cound be non-empty. We normally call
5115 	 * ipsec_check_policy() for conn_policy_cached connections only if
5116 	 * ipc_in_enforce_policy is set. But in this case,
5117 	 * conn_policy_cached can get set anytime since we made the
5118 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5119 	 * called, which will make the above assumption false.  Thus, we
5120 	 * need to insert after we set conn_policy_cached.
5121 	 */
5122 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5123 		goto bad_addr;
5124 
5125 	if (fanout_insert) {
5126 		/*
5127 		 * The addresses have been verified. Time to insert in
5128 		 * the correct fanout list.
5129 		 */
5130 		error = ipcl_conn_insert(connp, protocol, src_addr,
5131 		    dst_addr, connp->conn_ports);
5132 	}
5133 
5134 	if (error == 0) {
5135 		connp->conn_fully_bound = B_TRUE;
5136 		/*
5137 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5138 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5139 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5140 		 * ip_xxinfo_return(), which performs further checks
5141 		 * against them and upon success, returns the LSO/MDT info
5142 		 * mblk which we will attach to the bind acknowledgment.
5143 		 */
5144 		if (lso_dst_ire != NULL) {
5145 			mblk_t *lsoinfo_mp;
5146 
5147 			ASSERT(ill->ill_lso_capab != NULL);
5148 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5149 			    ill->ill_name, ill->ill_lso_capab)) != NULL)
5150 				linkb(mp, lsoinfo_mp);
5151 		} else if (md_dst_ire != NULL) {
5152 			mblk_t *mdinfo_mp;
5153 
5154 			ASSERT(ill->ill_mdt_capab != NULL);
5155 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5156 			    ill->ill_name, ill->ill_mdt_capab)) != NULL)
5157 				linkb(mp, mdinfo_mp);
5158 		}
5159 	}
5160 bad_addr:
5161 	if (ipsec_policy_set) {
5162 		ASSERT(policy_mp == mp->b_cont);
5163 		ASSERT(policy_mp != NULL);
5164 		freeb(policy_mp);
5165 		/*
5166 		 * As of now assume that nothing else accompanies
5167 		 * IPSEC_POLICY_SET.
5168 		 */
5169 		mp->b_cont = NULL;
5170 	}
5171 	if (src_ire != NULL)
5172 		IRE_REFRELE(src_ire);
5173 	if (dst_ire != NULL)
5174 		IRE_REFRELE(dst_ire);
5175 	if (sire != NULL)
5176 		IRE_REFRELE(sire);
5177 	if (md_dst_ire != NULL)
5178 		IRE_REFRELE(md_dst_ire);
5179 	if (lso_dst_ire != NULL)
5180 		IRE_REFRELE(lso_dst_ire);
5181 	return (error);
5182 }
5183 
5184 /*
5185  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5186  * Prefers dst_ire over src_ire.
5187  */
5188 static boolean_t
5189 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5190 {
5191 	mblk_t	*mp1;
5192 	ire_t *ret_ire = NULL;
5193 
5194 	mp1 = mp->b_cont;
5195 	ASSERT(mp1 != NULL);
5196 
5197 	if (ire != NULL) {
5198 		/*
5199 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5200 		 * appended mblk. Its <upper protocol>'s
5201 		 * job to make sure there is room.
5202 		 */
5203 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5204 			return (0);
5205 
5206 		mp1->b_datap->db_type = IRE_DB_TYPE;
5207 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5208 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5209 		ret_ire = (ire_t *)mp1->b_rptr;
5210 		/*
5211 		 * Pass the latest setting of the ip_path_mtu_discovery and
5212 		 * copy the ulp info if any.
5213 		 */
5214 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5215 		    IPH_DF : 0;
5216 		if (ulp_info != NULL) {
5217 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5218 			    sizeof (iulp_t));
5219 		}
5220 		ret_ire->ire_mp = mp1;
5221 	} else {
5222 		/*
5223 		 * No IRE was found. Remove IRE mblk.
5224 		 */
5225 		mp->b_cont = mp1->b_cont;
5226 		freeb(mp1);
5227 	}
5228 
5229 	return (1);
5230 }
5231 
5232 /*
5233  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5234  * the final piece where we don't.  Return a pointer to the first mblk in the
5235  * result, and update the pointer to the next mblk to chew on.  If anything
5236  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5237  * NULL pointer.
5238  */
5239 mblk_t *
5240 ip_carve_mp(mblk_t **mpp, ssize_t len)
5241 {
5242 	mblk_t	*mp0;
5243 	mblk_t	*mp1;
5244 	mblk_t	*mp2;
5245 
5246 	if (!len || !mpp || !(mp0 = *mpp))
5247 		return (NULL);
5248 	/* If we aren't going to consume the first mblk, we need a dup. */
5249 	if (mp0->b_wptr - mp0->b_rptr > len) {
5250 		mp1 = dupb(mp0);
5251 		if (mp1) {
5252 			/* Partition the data between the two mblks. */
5253 			mp1->b_wptr = mp1->b_rptr + len;
5254 			mp0->b_rptr = mp1->b_wptr;
5255 			/*
5256 			 * after adjustments if mblk not consumed is now
5257 			 * unaligned, try to align it. If this fails free
5258 			 * all messages and let upper layer recover.
5259 			 */
5260 			if (!OK_32PTR(mp0->b_rptr)) {
5261 				if (!pullupmsg(mp0, -1)) {
5262 					freemsg(mp0);
5263 					freemsg(mp1);
5264 					*mpp = NULL;
5265 					return (NULL);
5266 				}
5267 			}
5268 		}
5269 		return (mp1);
5270 	}
5271 	/* Eat through as many mblks as we need to get len bytes. */
5272 	len -= mp0->b_wptr - mp0->b_rptr;
5273 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5274 		if (mp2->b_wptr - mp2->b_rptr > len) {
5275 			/*
5276 			 * We won't consume the entire last mblk.  Like
5277 			 * above, dup and partition it.
5278 			 */
5279 			mp1->b_cont = dupb(mp2);
5280 			mp1 = mp1->b_cont;
5281 			if (!mp1) {
5282 				/*
5283 				 * Trouble.  Rather than go to a lot of
5284 				 * trouble to clean up, we free the messages.
5285 				 * This won't be any worse than losing it on
5286 				 * the wire.
5287 				 */
5288 				freemsg(mp0);
5289 				freemsg(mp2);
5290 				*mpp = NULL;
5291 				return (NULL);
5292 			}
5293 			mp1->b_wptr = mp1->b_rptr + len;
5294 			mp2->b_rptr = mp1->b_wptr;
5295 			/*
5296 			 * after adjustments if mblk not consumed is now
5297 			 * unaligned, try to align it. If this fails free
5298 			 * all messages and let upper layer recover.
5299 			 */
5300 			if (!OK_32PTR(mp2->b_rptr)) {
5301 				if (!pullupmsg(mp2, -1)) {
5302 					freemsg(mp0);
5303 					freemsg(mp2);
5304 					*mpp = NULL;
5305 					return (NULL);
5306 				}
5307 			}
5308 			*mpp = mp2;
5309 			return (mp0);
5310 		}
5311 		/* Decrement len by the amount we just got. */
5312 		len -= mp2->b_wptr - mp2->b_rptr;
5313 	}
5314 	/*
5315 	 * len should be reduced to zero now.  If not our caller has
5316 	 * screwed up.
5317 	 */
5318 	if (len) {
5319 		/* Shouldn't happen! */
5320 		freemsg(mp0);
5321 		*mpp = NULL;
5322 		return (NULL);
5323 	}
5324 	/*
5325 	 * We consumed up to exactly the end of an mblk.  Detach the part
5326 	 * we are returning from the rest of the chain.
5327 	 */
5328 	mp1->b_cont = NULL;
5329 	*mpp = mp2;
5330 	return (mp0);
5331 }
5332 
5333 /* The ill stream is being unplumbed. Called from ip_close */
5334 int
5335 ip_modclose(ill_t *ill)
5336 {
5337 	boolean_t success;
5338 	ipsq_t	*ipsq;
5339 	ipif_t	*ipif;
5340 	queue_t	*q = ill->ill_rq;
5341 	ip_stack_t	*ipst = ill->ill_ipst;
5342 	clock_t timeout;
5343 
5344 	/*
5345 	 * Wait for the ACKs of all deferred control messages to be processed.
5346 	 * In particular, we wait for a potential capability reset initiated
5347 	 * in ip_sioctl_plink() to complete before proceeding.
5348 	 *
5349 	 * Note: we wait for at most ip_modclose_ackwait_ms (by default 3000 ms)
5350 	 * in case the driver never replies.
5351 	 */
5352 	timeout = lbolt + MSEC_TO_TICK(ip_modclose_ackwait_ms);
5353 	mutex_enter(&ill->ill_lock);
5354 	while (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
5355 		if (cv_timedwait(&ill->ill_cv, &ill->ill_lock, timeout) < 0) {
5356 			/* Timeout */
5357 			break;
5358 		}
5359 	}
5360 	mutex_exit(&ill->ill_lock);
5361 
5362 	/*
5363 	 * Forcibly enter the ipsq after some delay. This is to take
5364 	 * care of the case when some ioctl does not complete because
5365 	 * we sent a control message to the driver and it did not
5366 	 * send us a reply. We want to be able to at least unplumb
5367 	 * and replumb rather than force the user to reboot the system.
5368 	 */
5369 	success = ipsq_enter(ill, B_FALSE);
5370 
5371 	/*
5372 	 * Open/close/push/pop is guaranteed to be single threaded
5373 	 * per stream by STREAMS. FS guarantees that all references
5374 	 * from top are gone before close is called. So there can't
5375 	 * be another close thread that has set CONDEMNED on this ill.
5376 	 * and cause ipsq_enter to return failure.
5377 	 */
5378 	ASSERT(success);
5379 	ipsq = ill->ill_phyint->phyint_ipsq;
5380 
5381 	/*
5382 	 * Mark it condemned. No new reference will be made to this ill.
5383 	 * Lookup functions will return an error. Threads that try to
5384 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5385 	 * that the refcnt will drop down to zero.
5386 	 */
5387 	mutex_enter(&ill->ill_lock);
5388 	ill->ill_state_flags |= ILL_CONDEMNED;
5389 	for (ipif = ill->ill_ipif; ipif != NULL;
5390 	    ipif = ipif->ipif_next) {
5391 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5392 	}
5393 	/*
5394 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5395 	 * returns  error if ILL_CONDEMNED is set
5396 	 */
5397 	cv_broadcast(&ill->ill_cv);
5398 	mutex_exit(&ill->ill_lock);
5399 
5400 	/*
5401 	 * Send all the deferred DLPI messages downstream which came in
5402 	 * during the small window right before ipsq_enter(). We do this
5403 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5404 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5405 	 */
5406 	ill_dlpi_send_deferred(ill);
5407 
5408 	/*
5409 	 * Shut down fragmentation reassembly.
5410 	 * ill_frag_timer won't start a timer again.
5411 	 * Now cancel any existing timer
5412 	 */
5413 	(void) untimeout(ill->ill_frag_timer_id);
5414 	(void) ill_frag_timeout(ill, 0);
5415 
5416 	/*
5417 	 * If MOVE was in progress, clear the
5418 	 * move_in_progress fields also.
5419 	 */
5420 	if (ill->ill_move_in_progress) {
5421 		ILL_CLEAR_MOVE(ill);
5422 	}
5423 
5424 	/*
5425 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5426 	 * this ill. Then wait for the refcnts to drop to zero.
5427 	 * ill_is_freeable checks whether the ill is really quiescent.
5428 	 * Then make sure that threads that are waiting to enter the
5429 	 * ipsq have seen the error returned by ipsq_enter and have
5430 	 * gone away. Then we call ill_delete_tail which does the
5431 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5432 	 */
5433 	ill_delete(ill);
5434 	mutex_enter(&ill->ill_lock);
5435 	while (!ill_is_freeable(ill))
5436 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5437 	while (ill->ill_waiters)
5438 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5439 
5440 	mutex_exit(&ill->ill_lock);
5441 
5442 	/*
5443 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5444 	 * it held until the end of the function since the cleanup
5445 	 * below needs to be able to use the ip_stack_t.
5446 	 */
5447 	netstack_hold(ipst->ips_netstack);
5448 
5449 	/* qprocsoff is called in ill_delete_tail */
5450 	ill_delete_tail(ill);
5451 	ASSERT(ill->ill_ipst == NULL);
5452 
5453 	/*
5454 	 * Walk through all upper (conn) streams and qenable
5455 	 * those that have queued data.
5456 	 * close synchronization needs this to
5457 	 * be done to ensure that all upper layers blocked
5458 	 * due to flow control to the closing device
5459 	 * get unblocked.
5460 	 */
5461 	ip1dbg(("ip_wsrv: walking\n"));
5462 	conn_walk_drain(ipst);
5463 
5464 	mutex_enter(&ipst->ips_ip_mi_lock);
5465 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5466 	mutex_exit(&ipst->ips_ip_mi_lock);
5467 
5468 	/*
5469 	 * credp could be null if the open didn't succeed and ip_modopen
5470 	 * itself calls ip_close.
5471 	 */
5472 	if (ill->ill_credp != NULL)
5473 		crfree(ill->ill_credp);
5474 
5475 	mutex_enter(&ill->ill_lock);
5476 	ill_nic_info_dispatch(ill);
5477 	mutex_exit(&ill->ill_lock);
5478 
5479 	/*
5480 	 * Now we are done with the module close pieces that
5481 	 * need the netstack_t.
5482 	 */
5483 	netstack_rele(ipst->ips_netstack);
5484 
5485 	mi_close_free((IDP)ill);
5486 	q->q_ptr = WR(q)->q_ptr = NULL;
5487 
5488 	ipsq_exit(ipsq);
5489 
5490 	return (0);
5491 }
5492 
5493 /*
5494  * This is called as part of close() for IP, UDP, ICMP, and RTS
5495  * in order to quiesce the conn.
5496  */
5497 void
5498 ip_quiesce_conn(conn_t *connp)
5499 {
5500 	boolean_t	drain_cleanup_reqd = B_FALSE;
5501 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5502 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5503 	ip_stack_t	*ipst;
5504 
5505 	ASSERT(!IPCL_IS_TCP(connp));
5506 	ipst = connp->conn_netstack->netstack_ip;
5507 
5508 	/*
5509 	 * Mark the conn as closing, and this conn must not be
5510 	 * inserted in future into any list. Eg. conn_drain_insert(),
5511 	 * won't insert this conn into the conn_drain_list.
5512 	 * Similarly ill_pending_mp_add() will not add any mp to
5513 	 * the pending mp list, after this conn has started closing.
5514 	 *
5515 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5516 	 * cannot get set henceforth.
5517 	 */
5518 	mutex_enter(&connp->conn_lock);
5519 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5520 	connp->conn_state_flags |= CONN_CLOSING;
5521 	if (connp->conn_idl != NULL)
5522 		drain_cleanup_reqd = B_TRUE;
5523 	if (connp->conn_oper_pending_ill != NULL)
5524 		conn_ioctl_cleanup_reqd = B_TRUE;
5525 	if (connp->conn_dhcpinit_ill != NULL) {
5526 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
5527 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
5528 		connp->conn_dhcpinit_ill = NULL;
5529 	}
5530 	if (connp->conn_ilg_inuse != 0)
5531 		ilg_cleanup_reqd = B_TRUE;
5532 	mutex_exit(&connp->conn_lock);
5533 
5534 	if (conn_ioctl_cleanup_reqd)
5535 		conn_ioctl_cleanup(connp);
5536 
5537 	if (is_system_labeled() && connp->conn_anon_port) {
5538 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5539 		    connp->conn_mlp_type, connp->conn_ulp,
5540 		    ntohs(connp->conn_lport), B_FALSE);
5541 		connp->conn_anon_port = 0;
5542 	}
5543 	connp->conn_mlp_type = mlptSingle;
5544 
5545 	/*
5546 	 * Remove this conn from any fanout list it is on.
5547 	 * and then wait for any threads currently operating
5548 	 * on this endpoint to finish
5549 	 */
5550 	ipcl_hash_remove(connp);
5551 
5552 	/*
5553 	 * Remove this conn from the drain list, and do
5554 	 * any other cleanup that may be required.
5555 	 * (Only non-tcp streams may have a non-null conn_idl.
5556 	 * TCP streams are never flow controlled, and
5557 	 * conn_idl will be null)
5558 	 */
5559 	if (drain_cleanup_reqd)
5560 		conn_drain_tail(connp, B_TRUE);
5561 
5562 	if (connp == ipst->ips_ip_g_mrouter)
5563 		(void) ip_mrouter_done(NULL, ipst);
5564 
5565 	if (ilg_cleanup_reqd)
5566 		ilg_delete_all(connp);
5567 
5568 	conn_delete_ire(connp, NULL);
5569 
5570 	/*
5571 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5572 	 * callers from write side can't be there now because close
5573 	 * is in progress. The only other caller is ipcl_walk
5574 	 * which checks for the condemned flag.
5575 	 */
5576 	mutex_enter(&connp->conn_lock);
5577 	connp->conn_state_flags |= CONN_CONDEMNED;
5578 	while (connp->conn_ref != 1)
5579 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5580 	connp->conn_state_flags |= CONN_QUIESCED;
5581 	mutex_exit(&connp->conn_lock);
5582 }
5583 
5584 /* ARGSUSED */
5585 int
5586 ip_close(queue_t *q, int flags)
5587 {
5588 	conn_t		*connp;
5589 
5590 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5591 
5592 	/*
5593 	 * Call the appropriate delete routine depending on whether this is
5594 	 * a module or device.
5595 	 */
5596 	if (WR(q)->q_next != NULL) {
5597 		/* This is a module close */
5598 		return (ip_modclose((ill_t *)q->q_ptr));
5599 	}
5600 
5601 	connp = q->q_ptr;
5602 	ip_quiesce_conn(connp);
5603 
5604 	qprocsoff(q);
5605 
5606 	/*
5607 	 * Now we are truly single threaded on this stream, and can
5608 	 * delete the things hanging off the connp, and finally the connp.
5609 	 * We removed this connp from the fanout list, it cannot be
5610 	 * accessed thru the fanouts, and we already waited for the
5611 	 * conn_ref to drop to 0. We are already in close, so
5612 	 * there cannot be any other thread from the top. qprocsoff
5613 	 * has completed, and service has completed or won't run in
5614 	 * future.
5615 	 */
5616 	ASSERT(connp->conn_ref == 1);
5617 
5618 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
5619 
5620 	connp->conn_ref--;
5621 	ipcl_conn_destroy(connp);
5622 
5623 	q->q_ptr = WR(q)->q_ptr = NULL;
5624 	return (0);
5625 }
5626 
5627 /*
5628  * Wapper around putnext() so that ip_rts_request can merely use
5629  * conn_recv.
5630  */
5631 /*ARGSUSED2*/
5632 static void
5633 ip_conn_input(void *arg1, mblk_t *mp, void *arg2)
5634 {
5635 	conn_t *connp = (conn_t *)arg1;
5636 
5637 	putnext(connp->conn_rq, mp);
5638 }
5639 
5640 /* Return the IP checksum for the IP header at "iph". */
5641 uint16_t
5642 ip_csum_hdr(ipha_t *ipha)
5643 {
5644 	uint16_t	*uph;
5645 	uint32_t	sum;
5646 	int		opt_len;
5647 
5648 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5649 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5650 	uph = (uint16_t *)ipha;
5651 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5652 	    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5653 	if (opt_len > 0) {
5654 		do {
5655 			sum += uph[10];
5656 			sum += uph[11];
5657 			uph += 2;
5658 		} while (--opt_len);
5659 	}
5660 	sum = (sum & 0xFFFF) + (sum >> 16);
5661 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5662 	if (sum == 0xffff)
5663 		sum = 0;
5664 	return ((uint16_t)sum);
5665 }
5666 
5667 /*
5668  * Called when the module is about to be unloaded
5669  */
5670 void
5671 ip_ddi_destroy(void)
5672 {
5673 	tnet_fini();
5674 
5675 	icmp_ddi_destroy();
5676 	rts_ddi_destroy();
5677 	udp_ddi_destroy();
5678 	sctp_ddi_g_destroy();
5679 	tcp_ddi_g_destroy();
5680 	ipsec_policy_g_destroy();
5681 	ipcl_g_destroy();
5682 	ip_net_g_destroy();
5683 	ip_ire_g_fini();
5684 	inet_minor_destroy(ip_minor_arena_sa);
5685 #if defined(_LP64)
5686 	inet_minor_destroy(ip_minor_arena_la);
5687 #endif
5688 
5689 #ifdef DEBUG
5690 	list_destroy(&ip_thread_list);
5691 	rw_destroy(&ip_thread_rwlock);
5692 	tsd_destroy(&ip_thread_data);
5693 #endif
5694 
5695 	netstack_unregister(NS_IP);
5696 }
5697 
5698 /*
5699  * First step in cleanup.
5700  */
5701 /* ARGSUSED */
5702 static void
5703 ip_stack_shutdown(netstackid_t stackid, void *arg)
5704 {
5705 	ip_stack_t *ipst = (ip_stack_t *)arg;
5706 
5707 #ifdef NS_DEBUG
5708 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5709 #endif
5710 
5711 	/* Get rid of loopback interfaces and their IREs */
5712 	ip_loopback_cleanup(ipst);
5713 
5714 	/*
5715 	 * The destroy functions here will end up causing notify callbacks
5716 	 * in the hook framework and these need to be run before the shtudown
5717 	 * of the hook framework is begun - that happens from netstack after
5718 	 * IP shutdown has completed.  If we leave doing these actions until
5719 	 * ip_stack_fini then the notify callbacks for the net_*_unregister
5720 	 * are happening against a backdrop of shattered terain.
5721 	 */
5722 	ipv4_hook_destroy(ipst);
5723 	ipv6_hook_destroy(ipst);
5724 	ip_net_destroy(ipst);
5725 }
5726 
5727 /*
5728  * Free the IP stack instance.
5729  */
5730 static void
5731 ip_stack_fini(netstackid_t stackid, void *arg)
5732 {
5733 	ip_stack_t *ipst = (ip_stack_t *)arg;
5734 	int ret;
5735 
5736 #ifdef NS_DEBUG
5737 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5738 #endif
5739 	rw_destroy(&ipst->ips_srcid_lock);
5740 
5741 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5742 	ipst->ips_ip_mibkp = NULL;
5743 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5744 	ipst->ips_icmp_mibkp = NULL;
5745 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5746 	ipst->ips_ip_kstat = NULL;
5747 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5748 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5749 	ipst->ips_ip6_kstat = NULL;
5750 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5751 
5752 	nd_free(&ipst->ips_ip_g_nd);
5753 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5754 	ipst->ips_param_arr = NULL;
5755 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5756 	ipst->ips_ndp_arr = NULL;
5757 
5758 	ip_mrouter_stack_destroy(ipst);
5759 
5760 	mutex_destroy(&ipst->ips_ip_mi_lock);
5761 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5762 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5763 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5764 
5765 	ret = untimeout(ipst->ips_igmp_timeout_id);
5766 	if (ret == -1) {
5767 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5768 	} else {
5769 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5770 		ipst->ips_igmp_timeout_id = 0;
5771 	}
5772 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5773 	if (ret == -1) {
5774 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5775 	} else {
5776 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5777 		ipst->ips_igmp_slowtimeout_id = 0;
5778 	}
5779 	ret = untimeout(ipst->ips_mld_timeout_id);
5780 	if (ret == -1) {
5781 		ASSERT(ipst->ips_mld_timeout_id == 0);
5782 	} else {
5783 		ASSERT(ipst->ips_mld_timeout_id != 0);
5784 		ipst->ips_mld_timeout_id = 0;
5785 	}
5786 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5787 	if (ret == -1) {
5788 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5789 	} else {
5790 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5791 		ipst->ips_mld_slowtimeout_id = 0;
5792 	}
5793 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5794 	if (ret == -1) {
5795 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5796 	} else {
5797 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5798 		ipst->ips_ip_ire_expire_id = 0;
5799 	}
5800 
5801 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5802 	mutex_destroy(&ipst->ips_mld_timer_lock);
5803 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5804 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5805 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5806 	rw_destroy(&ipst->ips_ill_g_lock);
5807 
5808 	ip_ire_fini(ipst);
5809 	ip6_asp_free(ipst);
5810 	conn_drain_fini(ipst);
5811 	ipcl_destroy(ipst);
5812 
5813 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5814 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5815 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5816 	ipst->ips_ndp4 = NULL;
5817 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5818 	ipst->ips_ndp6 = NULL;
5819 
5820 	if (ipst->ips_loopback_ksp != NULL) {
5821 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5822 		ipst->ips_loopback_ksp = NULL;
5823 	}
5824 
5825 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5826 	ipst->ips_phyint_g_list = NULL;
5827 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5828 	ipst->ips_ill_g_heads = NULL;
5829 
5830 	kmem_free(ipst, sizeof (*ipst));
5831 }
5832 
5833 /*
5834  * This function is called from the TSD destructor, and is used to debug
5835  * reference count issues in IP. See block comment in <inet/ip_if.h> for
5836  * details.
5837  */
5838 static void
5839 ip_thread_exit(void *phash)
5840 {
5841 	th_hash_t *thh = phash;
5842 
5843 	rw_enter(&ip_thread_rwlock, RW_WRITER);
5844 	list_remove(&ip_thread_list, thh);
5845 	rw_exit(&ip_thread_rwlock);
5846 	mod_hash_destroy_hash(thh->thh_hash);
5847 	kmem_free(thh, sizeof (*thh));
5848 }
5849 
5850 /*
5851  * Called when the IP kernel module is loaded into the kernel
5852  */
5853 void
5854 ip_ddi_init(void)
5855 {
5856 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5857 
5858 	/*
5859 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5860 	 * initial devices: ip, ip6, tcp, tcp6.
5861 	 */
5862 	/*
5863 	 * If this is a 64-bit kernel, then create two separate arenas -
5864 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
5865 	 * other for socket apps in the range 2^^18 through 2^^32-1.
5866 	 */
5867 	ip_minor_arena_la = NULL;
5868 	ip_minor_arena_sa = NULL;
5869 #if defined(_LP64)
5870 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5871 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
5872 		cmn_err(CE_PANIC,
5873 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5874 	}
5875 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
5876 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
5877 		cmn_err(CE_PANIC,
5878 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
5879 	}
5880 #else
5881 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5882 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
5883 		cmn_err(CE_PANIC,
5884 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5885 	}
5886 #endif
5887 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5888 
5889 	ipcl_g_init();
5890 	ip_ire_g_init();
5891 	ip_net_g_init();
5892 
5893 #ifdef DEBUG
5894 	tsd_create(&ip_thread_data, ip_thread_exit);
5895 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
5896 	list_create(&ip_thread_list, sizeof (th_hash_t),
5897 	    offsetof(th_hash_t, thh_link));
5898 #endif
5899 
5900 	/*
5901 	 * We want to be informed each time a stack is created or
5902 	 * destroyed in the kernel, so we can maintain the
5903 	 * set of udp_stack_t's.
5904 	 */
5905 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5906 	    ip_stack_fini);
5907 
5908 	ipsec_policy_g_init();
5909 	tcp_ddi_g_init();
5910 	sctp_ddi_g_init();
5911 
5912 	tnet_init();
5913 
5914 	udp_ddi_init();
5915 	rts_ddi_init();
5916 	icmp_ddi_init();
5917 }
5918 
5919 /*
5920  * Initialize the IP stack instance.
5921  */
5922 static void *
5923 ip_stack_init(netstackid_t stackid, netstack_t *ns)
5924 {
5925 	ip_stack_t	*ipst;
5926 	ipparam_t	*pa;
5927 	ipndp_t		*na;
5928 
5929 #ifdef NS_DEBUG
5930 	printf("ip_stack_init(stack %d)\n", stackid);
5931 #endif
5932 
5933 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
5934 	ipst->ips_netstack = ns;
5935 
5936 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
5937 	    KM_SLEEP);
5938 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
5939 	    KM_SLEEP);
5940 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5941 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5942 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5943 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5944 
5945 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5946 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5947 	ipst->ips_igmp_deferred_next = INFINITY;
5948 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5949 	ipst->ips_mld_deferred_next = INFINITY;
5950 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5951 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5952 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5953 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5954 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
5955 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5956 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5957 
5958 	ipcl_init(ipst);
5959 	ip_ire_init(ipst);
5960 	ip6_asp_init(ipst);
5961 	ipif_init(ipst);
5962 	conn_drain_init(ipst);
5963 	ip_mrouter_stack_init(ipst);
5964 
5965 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
5966 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
5967 
5968 	ipst->ips_ip_multirt_log_interval = 1000;
5969 
5970 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
5971 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
5972 	ipst->ips_ill_index = 1;
5973 
5974 	ipst->ips_saved_ip_g_forward = -1;
5975 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
5976 
5977 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
5978 	ipst->ips_param_arr = pa;
5979 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
5980 
5981 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
5982 	ipst->ips_ndp_arr = na;
5983 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5984 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
5985 	    (caddr_t)&ipst->ips_ip_g_forward;
5986 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
5987 	    (caddr_t)&ipst->ips_ipv6_forward;
5988 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
5989 	    "ip_cgtp_filter") == 0);
5990 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
5991 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
5992 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_name,
5993 	    "ipmp_hook_emulation") == 0);
5994 	ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_data =
5995 	    (caddr_t)&ipst->ips_ipmp_hook_emulation;
5996 
5997 	(void) ip_param_register(&ipst->ips_ip_g_nd,
5998 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
5999 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
6000 
6001 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
6002 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
6003 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
6004 	ipst->ips_ip6_kstat =
6005 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6006 
6007 	ipst->ips_ipmp_enable_failback = B_TRUE;
6008 
6009 	ipst->ips_ip_src_id = 1;
6010 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6011 
6012 	ip_net_init(ipst, ns);
6013 	ipv4_hook_init(ipst);
6014 	ipv6_hook_init(ipst);
6015 
6016 	return (ipst);
6017 }
6018 
6019 /*
6020  * Allocate and initialize a DLPI template of the specified length.  (May be
6021  * called as writer.)
6022  */
6023 mblk_t *
6024 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6025 {
6026 	mblk_t	*mp;
6027 
6028 	mp = allocb(len, BPRI_MED);
6029 	if (!mp)
6030 		return (NULL);
6031 
6032 	/*
6033 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6034 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6035 	 * that other DLPI are M_PROTO.
6036 	 */
6037 	if (prim == DL_INFO_REQ) {
6038 		mp->b_datap->db_type = M_PCPROTO;
6039 	} else {
6040 		mp->b_datap->db_type = M_PROTO;
6041 	}
6042 
6043 	mp->b_wptr = mp->b_rptr + len;
6044 	bzero(mp->b_rptr, len);
6045 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6046 	return (mp);
6047 }
6048 
6049 /*
6050  * Debug formatting routine.  Returns a character string representation of the
6051  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6052  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6053  *
6054  * Once the ndd table-printing interfaces are removed, this can be changed to
6055  * standard dotted-decimal form.
6056  */
6057 char *
6058 ip_dot_addr(ipaddr_t addr, char *buf)
6059 {
6060 	uint8_t *ap = (uint8_t *)&addr;
6061 
6062 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6063 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6064 	return (buf);
6065 }
6066 
6067 /*
6068  * Write the given MAC address as a printable string in the usual colon-
6069  * separated format.
6070  */
6071 const char *
6072 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6073 {
6074 	char *bp;
6075 
6076 	if (alen == 0 || buflen < 4)
6077 		return ("?");
6078 	bp = buf;
6079 	for (;;) {
6080 		/*
6081 		 * If there are more MAC address bytes available, but we won't
6082 		 * have any room to print them, then add "..." to the string
6083 		 * instead.  See below for the 'magic number' explanation.
6084 		 */
6085 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6086 			(void) strcpy(bp, "...");
6087 			break;
6088 		}
6089 		(void) sprintf(bp, "%02x", *addr++);
6090 		bp += 2;
6091 		if (--alen == 0)
6092 			break;
6093 		*bp++ = ':';
6094 		buflen -= 3;
6095 		/*
6096 		 * At this point, based on the first 'if' statement above,
6097 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6098 		 * buflen >= 4.  The first case leaves room for the final "xx"
6099 		 * number and trailing NUL byte.  The second leaves room for at
6100 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6101 		 * that statement.
6102 		 */
6103 	}
6104 	return (buf);
6105 }
6106 
6107 /*
6108  * Send an ICMP error after patching up the packet appropriately.  Returns
6109  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6110  */
6111 static boolean_t
6112 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6113     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6114     zoneid_t zoneid, ip_stack_t *ipst)
6115 {
6116 	ipha_t *ipha;
6117 	mblk_t *first_mp;
6118 	boolean_t secure;
6119 	unsigned char db_type;
6120 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6121 
6122 	first_mp = mp;
6123 	if (mctl_present) {
6124 		mp = mp->b_cont;
6125 		secure = ipsec_in_is_secure(first_mp);
6126 		ASSERT(mp != NULL);
6127 	} else {
6128 		/*
6129 		 * If this is an ICMP error being reported - which goes
6130 		 * up as M_CTLs, we need to convert them to M_DATA till
6131 		 * we finish checking with global policy because
6132 		 * ipsec_check_global_policy() assumes M_DATA as clear
6133 		 * and M_CTL as secure.
6134 		 */
6135 		db_type = DB_TYPE(mp);
6136 		DB_TYPE(mp) = M_DATA;
6137 		secure = B_FALSE;
6138 	}
6139 	/*
6140 	 * We are generating an icmp error for some inbound packet.
6141 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6142 	 * Before we generate an error, check with global policy
6143 	 * to see whether this is allowed to enter the system. As
6144 	 * there is no "conn", we are checking with global policy.
6145 	 */
6146 	ipha = (ipha_t *)mp->b_rptr;
6147 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6148 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6149 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6150 		if (first_mp == NULL)
6151 			return (B_FALSE);
6152 	}
6153 
6154 	if (!mctl_present)
6155 		DB_TYPE(mp) = db_type;
6156 
6157 	if (flags & IP_FF_SEND_ICMP) {
6158 		if (flags & IP_FF_HDR_COMPLETE) {
6159 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6160 				freemsg(first_mp);
6161 				return (B_TRUE);
6162 			}
6163 		}
6164 		if (flags & IP_FF_CKSUM) {
6165 			/*
6166 			 * Have to correct checksum since
6167 			 * the packet might have been
6168 			 * fragmented and the reassembly code in ip_rput
6169 			 * does not restore the IP checksum.
6170 			 */
6171 			ipha->ipha_hdr_checksum = 0;
6172 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6173 		}
6174 		switch (icmp_type) {
6175 		case ICMP_DEST_UNREACHABLE:
6176 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6177 			    ipst);
6178 			break;
6179 		default:
6180 			freemsg(first_mp);
6181 			break;
6182 		}
6183 	} else {
6184 		freemsg(first_mp);
6185 		return (B_FALSE);
6186 	}
6187 
6188 	return (B_TRUE);
6189 }
6190 
6191 /*
6192  * Used to send an ICMP error message when a packet is received for
6193  * a protocol that is not supported. The mblk passed as argument
6194  * is consumed by this function.
6195  */
6196 void
6197 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6198     ip_stack_t *ipst)
6199 {
6200 	mblk_t *mp;
6201 	ipha_t *ipha;
6202 	ill_t *ill;
6203 	ipsec_in_t *ii;
6204 
6205 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6206 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6207 
6208 	mp = ipsec_mp->b_cont;
6209 	ipsec_mp->b_cont = NULL;
6210 	ipha = (ipha_t *)mp->b_rptr;
6211 	/* Get ill from index in ipsec_in_t. */
6212 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6213 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6214 	    ipst);
6215 	if (ill != NULL) {
6216 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6217 			if (ip_fanout_send_icmp(q, mp, flags,
6218 			    ICMP_DEST_UNREACHABLE,
6219 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6220 				BUMP_MIB(ill->ill_ip_mib,
6221 				    ipIfStatsInUnknownProtos);
6222 			}
6223 		} else {
6224 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6225 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6226 			    0, B_FALSE, zoneid, ipst)) {
6227 				BUMP_MIB(ill->ill_ip_mib,
6228 				    ipIfStatsInUnknownProtos);
6229 			}
6230 		}
6231 		ill_refrele(ill);
6232 	} else { /* re-link for the freemsg() below. */
6233 		ipsec_mp->b_cont = mp;
6234 	}
6235 
6236 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6237 	freemsg(ipsec_mp);
6238 }
6239 
6240 /*
6241  * See if the inbound datagram has had IPsec processing applied to it.
6242  */
6243 boolean_t
6244 ipsec_in_is_secure(mblk_t *ipsec_mp)
6245 {
6246 	ipsec_in_t *ii;
6247 
6248 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6249 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6250 
6251 	if (ii->ipsec_in_loopback) {
6252 		return (ii->ipsec_in_secure);
6253 	} else {
6254 		return (ii->ipsec_in_ah_sa != NULL ||
6255 		    ii->ipsec_in_esp_sa != NULL ||
6256 		    ii->ipsec_in_decaps);
6257 	}
6258 }
6259 
6260 /*
6261  * Handle protocols with which IP is less intimate.  There
6262  * can be more than one stream bound to a particular
6263  * protocol.  When this is the case, normally each one gets a copy
6264  * of any incoming packets.
6265  *
6266  * IPsec NOTE :
6267  *
6268  * Don't allow a secure packet going up a non-secure connection.
6269  * We don't allow this because
6270  *
6271  * 1) Reply might go out in clear which will be dropped at
6272  *    the sending side.
6273  * 2) If the reply goes out in clear it will give the
6274  *    adversary enough information for getting the key in
6275  *    most of the cases.
6276  *
6277  * Moreover getting a secure packet when we expect clear
6278  * implies that SA's were added without checking for
6279  * policy on both ends. This should not happen once ISAKMP
6280  * is used to negotiate SAs as SAs will be added only after
6281  * verifying the policy.
6282  *
6283  * NOTE : If the packet was tunneled and not multicast we only send
6284  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6285  * back to delivering packets to AF_INET6 raw sockets.
6286  *
6287  * IPQoS Notes:
6288  * Once we have determined the client, invoke IPPF processing.
6289  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6290  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6291  * ip_policy will be false.
6292  *
6293  * Zones notes:
6294  * Currently only applications in the global zone can create raw sockets for
6295  * protocols other than ICMP. So unlike the broadcast / multicast case of
6296  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6297  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6298  */
6299 static void
6300 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6301     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6302     zoneid_t zoneid)
6303 {
6304 	queue_t	*rq;
6305 	mblk_t	*mp1, *first_mp1;
6306 	uint_t	protocol = ipha->ipha_protocol;
6307 	ipaddr_t dst;
6308 	boolean_t one_only;
6309 	mblk_t *first_mp = mp;
6310 	boolean_t secure;
6311 	uint32_t ill_index;
6312 	conn_t	*connp, *first_connp, *next_connp;
6313 	connf_t	*connfp;
6314 	boolean_t shared_addr;
6315 	mib2_ipIfStatsEntry_t *mibptr;
6316 	ip_stack_t *ipst = recv_ill->ill_ipst;
6317 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6318 
6319 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6320 	if (mctl_present) {
6321 		mp = first_mp->b_cont;
6322 		secure = ipsec_in_is_secure(first_mp);
6323 		ASSERT(mp != NULL);
6324 	} else {
6325 		secure = B_FALSE;
6326 	}
6327 	dst = ipha->ipha_dst;
6328 	/*
6329 	 * If the packet was tunneled and not multicast we only send to it
6330 	 * the first match.
6331 	 */
6332 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6333 	    !CLASSD(dst));
6334 
6335 	shared_addr = (zoneid == ALL_ZONES);
6336 	if (shared_addr) {
6337 		/*
6338 		 * We don't allow multilevel ports for raw IP, so no need to
6339 		 * check for that here.
6340 		 */
6341 		zoneid = tsol_packet_to_zoneid(mp);
6342 	}
6343 
6344 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6345 	mutex_enter(&connfp->connf_lock);
6346 	connp = connfp->connf_head;
6347 	for (connp = connfp->connf_head; connp != NULL;
6348 	    connp = connp->conn_next) {
6349 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6350 		    zoneid) &&
6351 		    (!is_system_labeled() ||
6352 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6353 		    connp))) {
6354 			break;
6355 		}
6356 	}
6357 
6358 	if (connp == NULL || connp->conn_upq == NULL) {
6359 		/*
6360 		 * No one bound to these addresses.  Is
6361 		 * there a client that wants all
6362 		 * unclaimed datagrams?
6363 		 */
6364 		mutex_exit(&connfp->connf_lock);
6365 		/*
6366 		 * Check for IPPROTO_ENCAP...
6367 		 */
6368 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6369 			/*
6370 			 * If an IPsec mblk is here on a multicast
6371 			 * tunnel (using ip_mroute stuff), check policy here,
6372 			 * THEN ship off to ip_mroute_decap().
6373 			 *
6374 			 * BTW,  If I match a configured IP-in-IP
6375 			 * tunnel, this path will not be reached, and
6376 			 * ip_mroute_decap will never be called.
6377 			 */
6378 			first_mp = ipsec_check_global_policy(first_mp, connp,
6379 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6380 			if (first_mp != NULL) {
6381 				if (mctl_present)
6382 					freeb(first_mp);
6383 				ip_mroute_decap(q, mp, ill);
6384 			} /* Else we already freed everything! */
6385 		} else {
6386 			/*
6387 			 * Otherwise send an ICMP protocol unreachable.
6388 			 */
6389 			if (ip_fanout_send_icmp(q, first_mp, flags,
6390 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6391 			    mctl_present, zoneid, ipst)) {
6392 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6393 			}
6394 		}
6395 		return;
6396 	}
6397 	CONN_INC_REF(connp);
6398 	first_connp = connp;
6399 
6400 	/*
6401 	 * Only send message to one tunnel driver by immediately
6402 	 * terminating the loop.
6403 	 */
6404 	connp = one_only ? NULL : connp->conn_next;
6405 
6406 	for (;;) {
6407 		while (connp != NULL) {
6408 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6409 			    flags, zoneid) &&
6410 			    (!is_system_labeled() ||
6411 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6412 			    shared_addr, connp)))
6413 				break;
6414 			connp = connp->conn_next;
6415 		}
6416 
6417 		/*
6418 		 * Copy the packet.
6419 		 */
6420 		if (connp == NULL || connp->conn_upq == NULL ||
6421 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6422 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6423 			/*
6424 			 * No more interested clients or memory
6425 			 * allocation failed
6426 			 */
6427 			connp = first_connp;
6428 			break;
6429 		}
6430 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6431 		CONN_INC_REF(connp);
6432 		mutex_exit(&connfp->connf_lock);
6433 		rq = connp->conn_rq;
6434 		if (!canputnext(rq)) {
6435 			if (flags & IP_FF_RAWIP) {
6436 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6437 			} else {
6438 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6439 			}
6440 
6441 			freemsg(first_mp1);
6442 		} else {
6443 			/*
6444 			 * Don't enforce here if we're an actual tunnel -
6445 			 * let "tun" do it instead.
6446 			 */
6447 			if (!IPCL_IS_IPTUN(connp) &&
6448 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6449 			    secure)) {
6450 				first_mp1 = ipsec_check_inbound_policy
6451 				    (first_mp1, connp, ipha, NULL,
6452 				    mctl_present);
6453 			}
6454 			if (first_mp1 != NULL) {
6455 				int in_flags = 0;
6456 				/*
6457 				 * ip_fanout_proto also gets called from
6458 				 * icmp_inbound_error_fanout, in which case
6459 				 * the msg type is M_CTL.  Don't add info
6460 				 * in this case for the time being. In future
6461 				 * when there is a need for knowing the
6462 				 * inbound iface index for ICMP error msgs,
6463 				 * then this can be changed.
6464 				 */
6465 				if (connp->conn_recvif)
6466 					in_flags = IPF_RECVIF;
6467 				/*
6468 				 * The ULP may support IP_RECVPKTINFO for both
6469 				 * IP v4 and v6 so pass the appropriate argument
6470 				 * based on conn IP version.
6471 				 */
6472 				if (connp->conn_ip_recvpktinfo) {
6473 					if (connp->conn_af_isv6) {
6474 						/*
6475 						 * V6 only needs index
6476 						 */
6477 						in_flags |= IPF_RECVIF;
6478 					} else {
6479 						/*
6480 						 * V4 needs index +
6481 						 * matching address.
6482 						 */
6483 						in_flags |= IPF_RECVADDR;
6484 					}
6485 				}
6486 				if ((in_flags != 0) &&
6487 				    (mp->b_datap->db_type != M_CTL)) {
6488 					/*
6489 					 * the actual data will be
6490 					 * contained in b_cont upon
6491 					 * successful return of the
6492 					 * following call else
6493 					 * original mblk is returned
6494 					 */
6495 					ASSERT(recv_ill != NULL);
6496 					mp1 = ip_add_info(mp1, recv_ill,
6497 					    in_flags, IPCL_ZONEID(connp), ipst);
6498 				}
6499 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6500 				if (mctl_present)
6501 					freeb(first_mp1);
6502 				(connp->conn_recv)(connp, mp1, NULL);
6503 			}
6504 		}
6505 		mutex_enter(&connfp->connf_lock);
6506 		/* Follow the next pointer before releasing the conn. */
6507 		next_connp = connp->conn_next;
6508 		CONN_DEC_REF(connp);
6509 		connp = next_connp;
6510 	}
6511 
6512 	/* Last one.  Send it upstream. */
6513 	mutex_exit(&connfp->connf_lock);
6514 
6515 	/*
6516 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6517 	 * will be set to false.
6518 	 */
6519 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6520 		ill_index = ill->ill_phyint->phyint_ifindex;
6521 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6522 		if (mp == NULL) {
6523 			CONN_DEC_REF(connp);
6524 			if (mctl_present) {
6525 				freeb(first_mp);
6526 			}
6527 			return;
6528 		}
6529 	}
6530 
6531 	rq = connp->conn_rq;
6532 	if (!canputnext(rq)) {
6533 		if (flags & IP_FF_RAWIP) {
6534 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6535 		} else {
6536 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6537 		}
6538 
6539 		freemsg(first_mp);
6540 	} else {
6541 		if (IPCL_IS_IPTUN(connp)) {
6542 			/*
6543 			 * Tunneled packet.  We enforce policy in the tunnel
6544 			 * module itself.
6545 			 *
6546 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6547 			 * a policy check.
6548 			 * FIXME to use conn_recv for tun later.
6549 			 */
6550 			putnext(rq, first_mp);
6551 			CONN_DEC_REF(connp);
6552 			return;
6553 		}
6554 
6555 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6556 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6557 			    ipha, NULL, mctl_present);
6558 		}
6559 
6560 		if (first_mp != NULL) {
6561 			int in_flags = 0;
6562 
6563 			/*
6564 			 * ip_fanout_proto also gets called
6565 			 * from icmp_inbound_error_fanout, in
6566 			 * which case the msg type is M_CTL.
6567 			 * Don't add info in this case for time
6568 			 * being. In future when there is a
6569 			 * need for knowing the inbound iface
6570 			 * index for ICMP error msgs, then this
6571 			 * can be changed
6572 			 */
6573 			if (connp->conn_recvif)
6574 				in_flags = IPF_RECVIF;
6575 			if (connp->conn_ip_recvpktinfo) {
6576 				if (connp->conn_af_isv6) {
6577 					/*
6578 					 * V6 only needs index
6579 					 */
6580 					in_flags |= IPF_RECVIF;
6581 				} else {
6582 					/*
6583 					 * V4 needs index +
6584 					 * matching address.
6585 					 */
6586 					in_flags |= IPF_RECVADDR;
6587 				}
6588 			}
6589 			if ((in_flags != 0) &&
6590 			    (mp->b_datap->db_type != M_CTL)) {
6591 
6592 				/*
6593 				 * the actual data will be contained in
6594 				 * b_cont upon successful return
6595 				 * of the following call else original
6596 				 * mblk is returned
6597 				 */
6598 				ASSERT(recv_ill != NULL);
6599 				mp = ip_add_info(mp, recv_ill,
6600 				    in_flags, IPCL_ZONEID(connp), ipst);
6601 			}
6602 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6603 			(connp->conn_recv)(connp, mp, NULL);
6604 			if (mctl_present)
6605 				freeb(first_mp);
6606 		}
6607 	}
6608 	CONN_DEC_REF(connp);
6609 }
6610 
6611 /*
6612  * Fanout for TCP packets
6613  * The caller puts <fport, lport> in the ports parameter.
6614  *
6615  * IPQoS Notes
6616  * Before sending it to the client, invoke IPPF processing.
6617  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6618  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6619  * ip_policy is false.
6620  */
6621 static void
6622 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6623     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6624 {
6625 	mblk_t  *first_mp;
6626 	boolean_t secure;
6627 	uint32_t ill_index;
6628 	int	ip_hdr_len;
6629 	tcph_t	*tcph;
6630 	boolean_t syn_present = B_FALSE;
6631 	conn_t	*connp;
6632 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6633 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6634 
6635 	ASSERT(recv_ill != NULL);
6636 
6637 	first_mp = mp;
6638 	if (mctl_present) {
6639 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6640 		mp = first_mp->b_cont;
6641 		secure = ipsec_in_is_secure(first_mp);
6642 		ASSERT(mp != NULL);
6643 	} else {
6644 		secure = B_FALSE;
6645 	}
6646 
6647 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6648 
6649 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6650 	    zoneid, ipst)) == NULL) {
6651 		/*
6652 		 * No connected connection or listener. Send a
6653 		 * TH_RST via tcp_xmit_listeners_reset.
6654 		 */
6655 
6656 		/* Initiate IPPf processing, if needed. */
6657 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6658 			uint32_t ill_index;
6659 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6660 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6661 			if (first_mp == NULL)
6662 				return;
6663 		}
6664 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6665 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6666 		    zoneid));
6667 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6668 		    ipst->ips_netstack->netstack_tcp, NULL);
6669 		return;
6670 	}
6671 
6672 	/*
6673 	 * Allocate the SYN for the TCP connection here itself
6674 	 */
6675 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6676 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6677 		if (IPCL_IS_TCP(connp)) {
6678 			squeue_t *sqp;
6679 
6680 			/*
6681 			 * For fused tcp loopback, assign the eager's
6682 			 * squeue to be that of the active connect's.
6683 			 * Note that we don't check for IP_FF_LOOPBACK
6684 			 * here since this routine gets called only
6685 			 * for loopback (unlike the IPv6 counterpart).
6686 			 */
6687 			ASSERT(Q_TO_CONN(q) != NULL);
6688 			if (do_tcp_fusion &&
6689 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6690 			    !secure &&
6691 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6692 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6693 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6694 				sqp = Q_TO_CONN(q)->conn_sqp;
6695 			} else {
6696 				sqp = IP_SQUEUE_GET(lbolt);
6697 			}
6698 
6699 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6700 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6701 			syn_present = B_TRUE;
6702 		}
6703 	}
6704 
6705 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6706 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6707 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6708 		if ((flags & TH_RST) || (flags & TH_URG)) {
6709 			CONN_DEC_REF(connp);
6710 			freemsg(first_mp);
6711 			return;
6712 		}
6713 		if (flags & TH_ACK) {
6714 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6715 			    ipst->ips_netstack->netstack_tcp, connp);
6716 			CONN_DEC_REF(connp);
6717 			return;
6718 		}
6719 
6720 		CONN_DEC_REF(connp);
6721 		freemsg(first_mp);
6722 		return;
6723 	}
6724 
6725 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6726 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6727 		    NULL, mctl_present);
6728 		if (first_mp == NULL) {
6729 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6730 			CONN_DEC_REF(connp);
6731 			return;
6732 		}
6733 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6734 			ASSERT(syn_present);
6735 			if (mctl_present) {
6736 				ASSERT(first_mp != mp);
6737 				first_mp->b_datap->db_struioflag |=
6738 				    STRUIO_POLICY;
6739 			} else {
6740 				ASSERT(first_mp == mp);
6741 				mp->b_datap->db_struioflag &=
6742 				    ~STRUIO_EAGER;
6743 				mp->b_datap->db_struioflag |=
6744 				    STRUIO_POLICY;
6745 			}
6746 		} else {
6747 			/*
6748 			 * Discard first_mp early since we're dealing with a
6749 			 * fully-connected conn_t and tcp doesn't do policy in
6750 			 * this case.
6751 			 */
6752 			if (mctl_present) {
6753 				freeb(first_mp);
6754 				mctl_present = B_FALSE;
6755 			}
6756 			first_mp = mp;
6757 		}
6758 	}
6759 
6760 	/*
6761 	 * Initiate policy processing here if needed. If we get here from
6762 	 * icmp_inbound_error_fanout, ip_policy is false.
6763 	 */
6764 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6765 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6766 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6767 		if (mp == NULL) {
6768 			CONN_DEC_REF(connp);
6769 			if (mctl_present)
6770 				freeb(first_mp);
6771 			return;
6772 		} else if (mctl_present) {
6773 			ASSERT(first_mp != mp);
6774 			first_mp->b_cont = mp;
6775 		} else {
6776 			first_mp = mp;
6777 		}
6778 	}
6779 
6780 
6781 
6782 	/* Handle socket options. */
6783 	if (!syn_present &&
6784 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6785 		/* Add header */
6786 		ASSERT(recv_ill != NULL);
6787 		/*
6788 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6789 		 * IPF_RECVIF.
6790 		 */
6791 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6792 		    ipst);
6793 		if (mp == NULL) {
6794 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6795 			CONN_DEC_REF(connp);
6796 			if (mctl_present)
6797 				freeb(first_mp);
6798 			return;
6799 		} else if (mctl_present) {
6800 			/*
6801 			 * ip_add_info might return a new mp.
6802 			 */
6803 			ASSERT(first_mp != mp);
6804 			first_mp->b_cont = mp;
6805 		} else {
6806 			first_mp = mp;
6807 		}
6808 	}
6809 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6810 	if (IPCL_IS_TCP(connp)) {
6811 		/* do not drain, certain use cases can blow the stack */
6812 		squeue_enter_nodrain(connp->conn_sqp, first_mp,
6813 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6814 	} else {
6815 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
6816 		(connp->conn_recv)(connp, first_mp, NULL);
6817 		CONN_DEC_REF(connp);
6818 	}
6819 }
6820 
6821 /*
6822  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
6823  * pass it along to ESP if the SPI is non-zero.  Returns TRUE if the mblk
6824  * is not consumed.
6825  *
6826  * One of four things can happen, all of which affect the passed-in mblk:
6827  *
6828  * 1.) ICMP messages that go through here just get returned TRUE.
6829  *
6830  * 2.) The packet is stock UDP and gets its zero-SPI stripped.  Return TRUE.
6831  *
6832  * 3.) The packet is ESP-in-UDP, gets transformed into an equivalent
6833  *     ESP packet, and is passed along to ESP for consumption.  Return FALSE.
6834  *
6835  * 4.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
6836  */
6837 static boolean_t
6838 zero_spi_check(queue_t *q, mblk_t *mp, ire_t *ire, ill_t *recv_ill,
6839     ipsec_stack_t *ipss)
6840 {
6841 	int shift, plen, iph_len;
6842 	ipha_t *ipha;
6843 	udpha_t *udpha;
6844 	uint32_t *spi;
6845 	uint32_t esp_ports;
6846 	uint8_t *orptr;
6847 	boolean_t free_ire;
6848 
6849 	if (DB_TYPE(mp) == M_CTL) {
6850 		/*
6851 		 * ICMP message with UDP inside.  Don't bother stripping, just
6852 		 * send it up.
6853 		 *
6854 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
6855 		 * to ignore errors set by ICMP anyway ('cause they might be
6856 		 * forged), but that's the app's decision, not ours.
6857 		 */
6858 
6859 		/* Bunch of reality checks for DEBUG kernels... */
6860 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
6861 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
6862 
6863 		return (B_TRUE);
6864 	}
6865 
6866 	ipha = (ipha_t *)mp->b_rptr;
6867 	iph_len = IPH_HDR_LENGTH(ipha);
6868 	plen = ntohs(ipha->ipha_length);
6869 
6870 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
6871 		/*
6872 		 * Most likely a keepalive for the benefit of an intervening
6873 		 * NAT.  These aren't for us, per se, so drop it.
6874 		 *
6875 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
6876 		 * byte packets (keepalives are 1-byte), but we'll drop them
6877 		 * also.
6878 		 */
6879 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6880 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
6881 		return (B_FALSE);
6882 	}
6883 
6884 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
6885 		/* might as well pull it all up - it might be ESP. */
6886 		if (!pullupmsg(mp, -1)) {
6887 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6888 			    DROPPER(ipss, ipds_esp_nomem),
6889 			    &ipss->ipsec_dropper);
6890 			return (B_FALSE);
6891 		}
6892 
6893 		ipha = (ipha_t *)mp->b_rptr;
6894 	}
6895 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
6896 	if (*spi == 0) {
6897 		/* UDP packet - remove 0-spi. */
6898 		shift = sizeof (uint32_t);
6899 	} else {
6900 		/* ESP-in-UDP packet - reduce to ESP. */
6901 		ipha->ipha_protocol = IPPROTO_ESP;
6902 		shift = sizeof (udpha_t);
6903 	}
6904 
6905 	/* Fix IP header */
6906 	ipha->ipha_length = htons(plen - shift);
6907 	ipha->ipha_hdr_checksum = 0;
6908 
6909 	orptr = mp->b_rptr;
6910 	mp->b_rptr += shift;
6911 
6912 	udpha = (udpha_t *)(orptr + iph_len);
6913 	if (*spi == 0) {
6914 		ASSERT((uint8_t *)ipha == orptr);
6915 		udpha->uha_length = htons(plen - shift - iph_len);
6916 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
6917 		esp_ports = 0;
6918 	} else {
6919 		esp_ports = *((uint32_t *)udpha);
6920 		ASSERT(esp_ports != 0);
6921 	}
6922 	ovbcopy(orptr, orptr + shift, iph_len);
6923 	if (esp_ports != 0) /* Punt up for ESP processing. */ {
6924 		ipha = (ipha_t *)(orptr + shift);
6925 
6926 		free_ire = (ire == NULL);
6927 		if (free_ire) {
6928 			/* Re-acquire ire. */
6929 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
6930 			    ipss->ipsec_netstack->netstack_ip);
6931 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
6932 				if (ire != NULL)
6933 					ire_refrele(ire);
6934 				/*
6935 				 * Do a regular freemsg(), as this is an IP
6936 				 * error (no local route) not an IPsec one.
6937 				 */
6938 				freemsg(mp);
6939 			}
6940 		}
6941 
6942 		ip_proto_input(q, mp, ipha, ire, recv_ill, esp_ports);
6943 		if (free_ire)
6944 			ire_refrele(ire);
6945 	}
6946 
6947 	return (esp_ports == 0);
6948 }
6949 
6950 /*
6951  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6952  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6953  * Caller is responsible for dropping references to the conn, and freeing
6954  * first_mp.
6955  *
6956  * IPQoS Notes
6957  * Before sending it to the client, invoke IPPF processing. Policy processing
6958  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6959  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6960  * ip_wput_local, ip_policy is false.
6961  */
6962 static void
6963 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
6964     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
6965     boolean_t ip_policy)
6966 {
6967 	boolean_t	mctl_present = (first_mp != NULL);
6968 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
6969 	uint32_t	ill_index;
6970 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6971 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6972 
6973 	ASSERT(ill != NULL);
6974 
6975 	if (mctl_present)
6976 		first_mp->b_cont = mp;
6977 	else
6978 		first_mp = mp;
6979 
6980 	if (CONN_UDP_FLOWCTLD(connp)) {
6981 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
6982 		freemsg(first_mp);
6983 		return;
6984 	}
6985 
6986 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6987 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6988 		    NULL, mctl_present);
6989 		if (first_mp == NULL) {
6990 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
6991 			return;	/* Freed by ipsec_check_inbound_policy(). */
6992 		}
6993 	}
6994 	if (mctl_present)
6995 		freeb(first_mp);
6996 
6997 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
6998 	if (connp->conn_udp->udp_nat_t_endpoint) {
6999 		if (mctl_present) {
7000 			/* mctl_present *shouldn't* happen. */
7001 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
7002 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
7003 			    &ipss->ipsec_dropper);
7004 			return;
7005 		}
7006 
7007 		if (!zero_spi_check(ill->ill_rq, mp, NULL, recv_ill, ipss))
7008 			return;
7009 	}
7010 
7011 	/* Handle options. */
7012 	if (connp->conn_recvif)
7013 		in_flags = IPF_RECVIF;
7014 	/*
7015 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7016 	 * passed to ip_add_info is based on IP version of connp.
7017 	 */
7018 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7019 		if (connp->conn_af_isv6) {
7020 			/*
7021 			 * V6 only needs index
7022 			 */
7023 			in_flags |= IPF_RECVIF;
7024 		} else {
7025 			/*
7026 			 * V4 needs index + matching address.
7027 			 */
7028 			in_flags |= IPF_RECVADDR;
7029 		}
7030 	}
7031 
7032 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7033 		in_flags |= IPF_RECVSLLA;
7034 
7035 	/*
7036 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7037 	 * freed if the packet is dropped. The caller will do so.
7038 	 */
7039 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7040 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7041 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7042 		if (mp == NULL) {
7043 			return;
7044 		}
7045 	}
7046 	if ((in_flags != 0) &&
7047 	    (mp->b_datap->db_type != M_CTL)) {
7048 		/*
7049 		 * The actual data will be contained in b_cont
7050 		 * upon successful return of the following call
7051 		 * else original mblk is returned
7052 		 */
7053 		ASSERT(recv_ill != NULL);
7054 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7055 		    ipst);
7056 	}
7057 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7058 	/* Send it upstream */
7059 	(connp->conn_recv)(connp, mp, NULL);
7060 }
7061 
7062 /*
7063  * Fanout for UDP packets.
7064  * The caller puts <fport, lport> in the ports parameter.
7065  *
7066  * If SO_REUSEADDR is set all multicast and broadcast packets
7067  * will be delivered to all streams bound to the same port.
7068  *
7069  * Zones notes:
7070  * Multicast and broadcast packets will be distributed to streams in all zones.
7071  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7072  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7073  * packets. To maintain this behavior with multiple zones, the conns are grouped
7074  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7075  * each zone. If unset, all the following conns in the same zone are skipped.
7076  */
7077 static void
7078 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7079     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7080     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7081 {
7082 	uint32_t	dstport, srcport;
7083 	ipaddr_t	dst;
7084 	mblk_t		*first_mp;
7085 	boolean_t	secure;
7086 	in6_addr_t	v6src;
7087 	conn_t		*connp;
7088 	connf_t		*connfp;
7089 	conn_t		*first_connp;
7090 	conn_t		*next_connp;
7091 	mblk_t		*mp1, *first_mp1;
7092 	ipaddr_t	src;
7093 	zoneid_t	last_zoneid;
7094 	boolean_t	reuseaddr;
7095 	boolean_t	shared_addr;
7096 	boolean_t	unlabeled;
7097 	ip_stack_t	*ipst;
7098 
7099 	ASSERT(recv_ill != NULL);
7100 	ipst = recv_ill->ill_ipst;
7101 
7102 	first_mp = mp;
7103 	if (mctl_present) {
7104 		mp = first_mp->b_cont;
7105 		first_mp->b_cont = NULL;
7106 		secure = ipsec_in_is_secure(first_mp);
7107 		ASSERT(mp != NULL);
7108 	} else {
7109 		first_mp = NULL;
7110 		secure = B_FALSE;
7111 	}
7112 
7113 	/* Extract ports in net byte order */
7114 	dstport = htons(ntohl(ports) & 0xFFFF);
7115 	srcport = htons(ntohl(ports) >> 16);
7116 	dst = ipha->ipha_dst;
7117 	src = ipha->ipha_src;
7118 
7119 	unlabeled = B_FALSE;
7120 	if (is_system_labeled())
7121 		/* Cred cannot be null on IPv4 */
7122 		unlabeled = (crgetlabel(DB_CRED(mp))->tsl_flags &
7123 		    TSLF_UNLABELED) != 0;
7124 	shared_addr = (zoneid == ALL_ZONES);
7125 	if (shared_addr) {
7126 		/*
7127 		 * No need to handle exclusive-stack zones since ALL_ZONES
7128 		 * only applies to the shared stack.
7129 		 */
7130 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7131 		/*
7132 		 * If no shared MLP is found, tsol_mlp_findzone returns
7133 		 * ALL_ZONES.  In that case, we assume it's SLP, and
7134 		 * search for the zone based on the packet label.
7135 		 *
7136 		 * If there is such a zone, we prefer to find a
7137 		 * connection in it.  Otherwise, we look for a
7138 		 * MAC-exempt connection in any zone whose label
7139 		 * dominates the default label on the packet.
7140 		 */
7141 		if (zoneid == ALL_ZONES)
7142 			zoneid = tsol_packet_to_zoneid(mp);
7143 		else
7144 			unlabeled = B_FALSE;
7145 	}
7146 
7147 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7148 	mutex_enter(&connfp->connf_lock);
7149 	connp = connfp->connf_head;
7150 	if (!broadcast && !CLASSD(dst)) {
7151 		/*
7152 		 * Not broadcast or multicast. Send to the one (first)
7153 		 * client we find. No need to check conn_wantpacket()
7154 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7155 		 * IPv4 unicast packets.
7156 		 */
7157 		while ((connp != NULL) &&
7158 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7159 		    (!IPCL_ZONE_MATCH(connp, zoneid) &&
7160 		    !(unlabeled && connp->conn_mac_exempt)))) {
7161 			/*
7162 			 * We keep searching since the conn did not match,
7163 			 * or its zone did not match and it is not either
7164 			 * an allzones conn or a mac exempt conn (if the
7165 			 * sender is unlabeled.)
7166 			 */
7167 			connp = connp->conn_next;
7168 		}
7169 
7170 		if (connp == NULL || connp->conn_upq == NULL)
7171 			goto notfound;
7172 
7173 		if (is_system_labeled() &&
7174 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7175 		    connp))
7176 			goto notfound;
7177 
7178 		CONN_INC_REF(connp);
7179 		mutex_exit(&connfp->connf_lock);
7180 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7181 		    flags, recv_ill, ip_policy);
7182 		IP_STAT(ipst, ip_udp_fannorm);
7183 		CONN_DEC_REF(connp);
7184 		return;
7185 	}
7186 
7187 	/*
7188 	 * Broadcast and multicast case
7189 	 *
7190 	 * Need to check conn_wantpacket().
7191 	 * If SO_REUSEADDR has been set on the first we send the
7192 	 * packet to all clients that have joined the group and
7193 	 * match the port.
7194 	 */
7195 
7196 	while (connp != NULL) {
7197 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7198 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7199 		    (!is_system_labeled() ||
7200 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7201 		    connp)))
7202 			break;
7203 		connp = connp->conn_next;
7204 	}
7205 
7206 	if (connp == NULL || connp->conn_upq == NULL)
7207 		goto notfound;
7208 
7209 	first_connp = connp;
7210 	/*
7211 	 * When SO_REUSEADDR is not set, send the packet only to the first
7212 	 * matching connection in its zone by keeping track of the zoneid.
7213 	 */
7214 	reuseaddr = first_connp->conn_reuseaddr;
7215 	last_zoneid = first_connp->conn_zoneid;
7216 
7217 	CONN_INC_REF(connp);
7218 	connp = connp->conn_next;
7219 	for (;;) {
7220 		while (connp != NULL) {
7221 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7222 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7223 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7224 			    (!is_system_labeled() ||
7225 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7226 			    shared_addr, connp)))
7227 				break;
7228 			connp = connp->conn_next;
7229 		}
7230 		/*
7231 		 * Just copy the data part alone. The mctl part is
7232 		 * needed just for verifying policy and it is never
7233 		 * sent up.
7234 		 */
7235 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7236 		    ((mp1 = copymsg(mp)) == NULL))) {
7237 			/*
7238 			 * No more interested clients or memory
7239 			 * allocation failed
7240 			 */
7241 			connp = first_connp;
7242 			break;
7243 		}
7244 		if (connp->conn_zoneid != last_zoneid) {
7245 			/*
7246 			 * Update the zoneid so that the packet isn't sent to
7247 			 * any more conns in the same zone unless SO_REUSEADDR
7248 			 * is set.
7249 			 */
7250 			reuseaddr = connp->conn_reuseaddr;
7251 			last_zoneid = connp->conn_zoneid;
7252 		}
7253 		if (first_mp != NULL) {
7254 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7255 			    ipsec_info_type == IPSEC_IN);
7256 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7257 			    ipst->ips_netstack);
7258 			if (first_mp1 == NULL) {
7259 				freemsg(mp1);
7260 				connp = first_connp;
7261 				break;
7262 			}
7263 		} else {
7264 			first_mp1 = NULL;
7265 		}
7266 		CONN_INC_REF(connp);
7267 		mutex_exit(&connfp->connf_lock);
7268 		/*
7269 		 * IPQoS notes: We don't send the packet for policy
7270 		 * processing here, will do it for the last one (below).
7271 		 * i.e. we do it per-packet now, but if we do policy
7272 		 * processing per-conn, then we would need to do it
7273 		 * here too.
7274 		 */
7275 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7276 		    ipha, flags, recv_ill, B_FALSE);
7277 		mutex_enter(&connfp->connf_lock);
7278 		/* Follow the next pointer before releasing the conn. */
7279 		next_connp = connp->conn_next;
7280 		IP_STAT(ipst, ip_udp_fanmb);
7281 		CONN_DEC_REF(connp);
7282 		connp = next_connp;
7283 	}
7284 
7285 	/* Last one.  Send it upstream. */
7286 	mutex_exit(&connfp->connf_lock);
7287 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7288 	    recv_ill, ip_policy);
7289 	IP_STAT(ipst, ip_udp_fanmb);
7290 	CONN_DEC_REF(connp);
7291 	return;
7292 
7293 notfound:
7294 
7295 	mutex_exit(&connfp->connf_lock);
7296 	IP_STAT(ipst, ip_udp_fanothers);
7297 	/*
7298 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7299 	 * have already been matched above, since they live in the IPv4
7300 	 * fanout tables. This implies we only need to
7301 	 * check for IPv6 in6addr_any endpoints here.
7302 	 * Thus we compare using ipv6_all_zeros instead of the destination
7303 	 * address, except for the multicast group membership lookup which
7304 	 * uses the IPv4 destination.
7305 	 */
7306 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7307 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7308 	mutex_enter(&connfp->connf_lock);
7309 	connp = connfp->connf_head;
7310 	if (!broadcast && !CLASSD(dst)) {
7311 		while (connp != NULL) {
7312 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7313 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7314 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7315 			    !connp->conn_ipv6_v6only)
7316 				break;
7317 			connp = connp->conn_next;
7318 		}
7319 
7320 		if (connp != NULL && is_system_labeled() &&
7321 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7322 		    connp))
7323 			connp = NULL;
7324 
7325 		if (connp == NULL || connp->conn_upq == NULL) {
7326 			/*
7327 			 * No one bound to this port.  Is
7328 			 * there a client that wants all
7329 			 * unclaimed datagrams?
7330 			 */
7331 			mutex_exit(&connfp->connf_lock);
7332 
7333 			if (mctl_present)
7334 				first_mp->b_cont = mp;
7335 			else
7336 				first_mp = mp;
7337 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7338 			    connf_head != NULL) {
7339 				ip_fanout_proto(q, first_mp, ill, ipha,
7340 				    flags | IP_FF_RAWIP, mctl_present,
7341 				    ip_policy, recv_ill, zoneid);
7342 			} else {
7343 				if (ip_fanout_send_icmp(q, first_mp, flags,
7344 				    ICMP_DEST_UNREACHABLE,
7345 				    ICMP_PORT_UNREACHABLE,
7346 				    mctl_present, zoneid, ipst)) {
7347 					BUMP_MIB(ill->ill_ip_mib,
7348 					    udpIfStatsNoPorts);
7349 				}
7350 			}
7351 			return;
7352 		}
7353 
7354 		CONN_INC_REF(connp);
7355 		mutex_exit(&connfp->connf_lock);
7356 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7357 		    flags, recv_ill, ip_policy);
7358 		CONN_DEC_REF(connp);
7359 		return;
7360 	}
7361 	/*
7362 	 * IPv4 multicast packet being delivered to an AF_INET6
7363 	 * in6addr_any endpoint.
7364 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7365 	 * and not conn_wantpacket_v6() since any multicast membership is
7366 	 * for an IPv4-mapped multicast address.
7367 	 * The packet is sent to all clients in all zones that have joined the
7368 	 * group and match the port.
7369 	 */
7370 	while (connp != NULL) {
7371 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7372 		    srcport, v6src) &&
7373 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7374 		    (!is_system_labeled() ||
7375 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7376 		    connp)))
7377 			break;
7378 		connp = connp->conn_next;
7379 	}
7380 
7381 	if (connp == NULL || connp->conn_upq == NULL) {
7382 		/*
7383 		 * No one bound to this port.  Is
7384 		 * there a client that wants all
7385 		 * unclaimed datagrams?
7386 		 */
7387 		mutex_exit(&connfp->connf_lock);
7388 
7389 		if (mctl_present)
7390 			first_mp->b_cont = mp;
7391 		else
7392 			first_mp = mp;
7393 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7394 		    NULL) {
7395 			ip_fanout_proto(q, first_mp, ill, ipha,
7396 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7397 			    recv_ill, zoneid);
7398 		} else {
7399 			/*
7400 			 * We used to attempt to send an icmp error here, but
7401 			 * since this is known to be a multicast packet
7402 			 * and we don't send icmp errors in response to
7403 			 * multicast, just drop the packet and give up sooner.
7404 			 */
7405 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7406 			freemsg(first_mp);
7407 		}
7408 		return;
7409 	}
7410 
7411 	first_connp = connp;
7412 
7413 	CONN_INC_REF(connp);
7414 	connp = connp->conn_next;
7415 	for (;;) {
7416 		while (connp != NULL) {
7417 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7418 			    ipv6_all_zeros, srcport, v6src) &&
7419 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7420 			    (!is_system_labeled() ||
7421 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7422 			    shared_addr, connp)))
7423 				break;
7424 			connp = connp->conn_next;
7425 		}
7426 		/*
7427 		 * Just copy the data part alone. The mctl part is
7428 		 * needed just for verifying policy and it is never
7429 		 * sent up.
7430 		 */
7431 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7432 		    ((mp1 = copymsg(mp)) == NULL))) {
7433 			/*
7434 			 * No more intested clients or memory
7435 			 * allocation failed
7436 			 */
7437 			connp = first_connp;
7438 			break;
7439 		}
7440 		if (first_mp != NULL) {
7441 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7442 			    ipsec_info_type == IPSEC_IN);
7443 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7444 			    ipst->ips_netstack);
7445 			if (first_mp1 == NULL) {
7446 				freemsg(mp1);
7447 				connp = first_connp;
7448 				break;
7449 			}
7450 		} else {
7451 			first_mp1 = NULL;
7452 		}
7453 		CONN_INC_REF(connp);
7454 		mutex_exit(&connfp->connf_lock);
7455 		/*
7456 		 * IPQoS notes: We don't send the packet for policy
7457 		 * processing here, will do it for the last one (below).
7458 		 * i.e. we do it per-packet now, but if we do policy
7459 		 * processing per-conn, then we would need to do it
7460 		 * here too.
7461 		 */
7462 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7463 		    ipha, flags, recv_ill, B_FALSE);
7464 		mutex_enter(&connfp->connf_lock);
7465 		/* Follow the next pointer before releasing the conn. */
7466 		next_connp = connp->conn_next;
7467 		CONN_DEC_REF(connp);
7468 		connp = next_connp;
7469 	}
7470 
7471 	/* Last one.  Send it upstream. */
7472 	mutex_exit(&connfp->connf_lock);
7473 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7474 	    recv_ill, ip_policy);
7475 	CONN_DEC_REF(connp);
7476 }
7477 
7478 /*
7479  * Complete the ip_wput header so that it
7480  * is possible to generate ICMP
7481  * errors.
7482  */
7483 int
7484 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7485 {
7486 	ire_t *ire;
7487 
7488 	if (ipha->ipha_src == INADDR_ANY) {
7489 		ire = ire_lookup_local(zoneid, ipst);
7490 		if (ire == NULL) {
7491 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7492 			return (1);
7493 		}
7494 		ipha->ipha_src = ire->ire_addr;
7495 		ire_refrele(ire);
7496 	}
7497 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7498 	ipha->ipha_hdr_checksum = 0;
7499 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7500 	return (0);
7501 }
7502 
7503 /*
7504  * Nobody should be sending
7505  * packets up this stream
7506  */
7507 static void
7508 ip_lrput(queue_t *q, mblk_t *mp)
7509 {
7510 	mblk_t *mp1;
7511 
7512 	switch (mp->b_datap->db_type) {
7513 	case M_FLUSH:
7514 		/* Turn around */
7515 		if (*mp->b_rptr & FLUSHW) {
7516 			*mp->b_rptr &= ~FLUSHR;
7517 			qreply(q, mp);
7518 			return;
7519 		}
7520 		break;
7521 	}
7522 	/* Could receive messages that passed through ar_rput */
7523 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7524 		mp1->b_prev = mp1->b_next = NULL;
7525 	freemsg(mp);
7526 }
7527 
7528 /* Nobody should be sending packets down this stream */
7529 /* ARGSUSED */
7530 void
7531 ip_lwput(queue_t *q, mblk_t *mp)
7532 {
7533 	freemsg(mp);
7534 }
7535 
7536 /*
7537  * Move the first hop in any source route to ipha_dst and remove that part of
7538  * the source route.  Called by other protocols.  Errors in option formatting
7539  * are ignored - will be handled by ip_wput_options Return the final
7540  * destination (either ipha_dst or the last entry in a source route.)
7541  */
7542 ipaddr_t
7543 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7544 {
7545 	ipoptp_t	opts;
7546 	uchar_t		*opt;
7547 	uint8_t		optval;
7548 	uint8_t		optlen;
7549 	ipaddr_t	dst;
7550 	int		i;
7551 	ire_t		*ire;
7552 	ip_stack_t	*ipst = ns->netstack_ip;
7553 
7554 	ip2dbg(("ip_massage_options\n"));
7555 	dst = ipha->ipha_dst;
7556 	for (optval = ipoptp_first(&opts, ipha);
7557 	    optval != IPOPT_EOL;
7558 	    optval = ipoptp_next(&opts)) {
7559 		opt = opts.ipoptp_cur;
7560 		switch (optval) {
7561 			uint8_t off;
7562 		case IPOPT_SSRR:
7563 		case IPOPT_LSRR:
7564 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7565 				ip1dbg(("ip_massage_options: bad src route\n"));
7566 				break;
7567 			}
7568 			optlen = opts.ipoptp_len;
7569 			off = opt[IPOPT_OFFSET];
7570 			off--;
7571 		redo_srr:
7572 			if (optlen < IP_ADDR_LEN ||
7573 			    off > optlen - IP_ADDR_LEN) {
7574 				/* End of source route */
7575 				ip1dbg(("ip_massage_options: end of SR\n"));
7576 				break;
7577 			}
7578 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7579 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7580 			    ntohl(dst)));
7581 			/*
7582 			 * Check if our address is present more than
7583 			 * once as consecutive hops in source route.
7584 			 * XXX verify per-interface ip_forwarding
7585 			 * for source route?
7586 			 */
7587 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7588 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7589 			if (ire != NULL) {
7590 				ire_refrele(ire);
7591 				off += IP_ADDR_LEN;
7592 				goto redo_srr;
7593 			}
7594 			if (dst == htonl(INADDR_LOOPBACK)) {
7595 				ip1dbg(("ip_massage_options: loopback addr in "
7596 				    "source route!\n"));
7597 				break;
7598 			}
7599 			/*
7600 			 * Update ipha_dst to be the first hop and remove the
7601 			 * first hop from the source route (by overwriting
7602 			 * part of the option with NOP options).
7603 			 */
7604 			ipha->ipha_dst = dst;
7605 			/* Put the last entry in dst */
7606 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7607 			    3;
7608 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7609 
7610 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7611 			    ntohl(dst)));
7612 			/* Move down and overwrite */
7613 			opt[IP_ADDR_LEN] = opt[0];
7614 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7615 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7616 			for (i = 0; i < IP_ADDR_LEN; i++)
7617 				opt[i] = IPOPT_NOP;
7618 			break;
7619 		}
7620 	}
7621 	return (dst);
7622 }
7623 
7624 /*
7625  * Return the network mask
7626  * associated with the specified address.
7627  */
7628 ipaddr_t
7629 ip_net_mask(ipaddr_t addr)
7630 {
7631 	uchar_t	*up = (uchar_t *)&addr;
7632 	ipaddr_t mask = 0;
7633 	uchar_t	*maskp = (uchar_t *)&mask;
7634 
7635 #if defined(__i386) || defined(__amd64)
7636 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7637 #endif
7638 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7639 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7640 #endif
7641 	if (CLASSD(addr)) {
7642 		maskp[0] = 0xF0;
7643 		return (mask);
7644 	}
7645 
7646 	/* We assume Class E default netmask to be 32 */
7647 	if (CLASSE(addr))
7648 		return (0xffffffffU);
7649 
7650 	if (addr == 0)
7651 		return (0);
7652 	maskp[0] = 0xFF;
7653 	if ((up[0] & 0x80) == 0)
7654 		return (mask);
7655 
7656 	maskp[1] = 0xFF;
7657 	if ((up[0] & 0xC0) == 0x80)
7658 		return (mask);
7659 
7660 	maskp[2] = 0xFF;
7661 	if ((up[0] & 0xE0) == 0xC0)
7662 		return (mask);
7663 
7664 	/* Otherwise return no mask */
7665 	return ((ipaddr_t)0);
7666 }
7667 
7668 /*
7669  * Select an ill for the packet by considering load spreading across
7670  * a different ill in the group if dst_ill is part of some group.
7671  */
7672 ill_t *
7673 ip_newroute_get_dst_ill(ill_t *dst_ill)
7674 {
7675 	ill_t *ill;
7676 
7677 	/*
7678 	 * We schedule irrespective of whether the source address is
7679 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7680 	 */
7681 	ill = illgrp_scheduler(dst_ill);
7682 	if (ill == NULL)
7683 		return (NULL);
7684 
7685 	/*
7686 	 * For groups with names ip_sioctl_groupname ensures that all
7687 	 * ills are of same type. For groups without names, ifgrp_insert
7688 	 * ensures this.
7689 	 */
7690 	ASSERT(dst_ill->ill_type == ill->ill_type);
7691 
7692 	return (ill);
7693 }
7694 
7695 /*
7696  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7697  */
7698 ill_t *
7699 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6,
7700     ip_stack_t *ipst)
7701 {
7702 	ill_t *ret_ill;
7703 
7704 	ASSERT(ifindex != 0);
7705 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7706 	    ipst);
7707 	if (ret_ill == NULL ||
7708 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7709 		if (isv6) {
7710 			if (ill != NULL) {
7711 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7712 			} else {
7713 				BUMP_MIB(&ipst->ips_ip6_mib,
7714 				    ipIfStatsOutDiscards);
7715 			}
7716 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7717 			    "bad ifindex %d.\n", ifindex));
7718 		} else {
7719 			if (ill != NULL) {
7720 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7721 			} else {
7722 				BUMP_MIB(&ipst->ips_ip_mib,
7723 				    ipIfStatsOutDiscards);
7724 			}
7725 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7726 			    "bad ifindex %d.\n", ifindex));
7727 		}
7728 		if (ret_ill != NULL)
7729 			ill_refrele(ret_ill);
7730 		freemsg(first_mp);
7731 		return (NULL);
7732 	}
7733 
7734 	return (ret_ill);
7735 }
7736 
7737 /*
7738  * IPv4 -
7739  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7740  * out a packet to a destination address for which we do not have specific
7741  * (or sufficient) routing information.
7742  *
7743  * NOTE : These are the scopes of some of the variables that point at IRE,
7744  *	  which needs to be followed while making any future modifications
7745  *	  to avoid memory leaks.
7746  *
7747  *	- ire and sire are the entries looked up initially by
7748  *	  ire_ftable_lookup.
7749  *	- ipif_ire is used to hold the interface ire associated with
7750  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7751  *	  it before branching out to error paths.
7752  *	- save_ire is initialized before ire_create, so that ire returned
7753  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7754  *	  before breaking out of the switch.
7755  *
7756  *	Thus on failures, we have to REFRELE only ire and sire, if they
7757  *	are not NULL.
7758  */
7759 void
7760 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7761     zoneid_t zoneid, ip_stack_t *ipst)
7762 {
7763 	areq_t	*areq;
7764 	ipaddr_t gw = 0;
7765 	ire_t	*ire = NULL;
7766 	mblk_t	*res_mp;
7767 	ipaddr_t *addrp;
7768 	ipaddr_t nexthop_addr;
7769 	ipif_t  *src_ipif = NULL;
7770 	ill_t	*dst_ill = NULL;
7771 	ipha_t  *ipha;
7772 	ire_t	*sire = NULL;
7773 	mblk_t	*first_mp;
7774 	ire_t	*save_ire;
7775 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7776 	ushort_t ire_marks = 0;
7777 	boolean_t mctl_present;
7778 	ipsec_out_t *io;
7779 	mblk_t	*saved_mp;
7780 	ire_t	*first_sire = NULL;
7781 	mblk_t	*copy_mp = NULL;
7782 	mblk_t	*xmit_mp = NULL;
7783 	ipaddr_t save_dst;
7784 	uint32_t multirt_flags =
7785 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7786 	boolean_t multirt_is_resolvable;
7787 	boolean_t multirt_resolve_next;
7788 	boolean_t unspec_src;
7789 	boolean_t do_attach_ill = B_FALSE;
7790 	boolean_t ip_nexthop = B_FALSE;
7791 	tsol_ire_gw_secattr_t *attrp = NULL;
7792 	tsol_gcgrp_t *gcgrp = NULL;
7793 	tsol_gcgrp_addr_t ga;
7794 
7795 	if (ip_debug > 2) {
7796 		/* ip1dbg */
7797 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7798 	}
7799 
7800 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7801 	if (mctl_present) {
7802 		io = (ipsec_out_t *)first_mp->b_rptr;
7803 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7804 		ASSERT(zoneid == io->ipsec_out_zoneid);
7805 		ASSERT(zoneid != ALL_ZONES);
7806 	}
7807 
7808 	ipha = (ipha_t *)mp->b_rptr;
7809 
7810 	/* All multicast lookups come through ip_newroute_ipif() */
7811 	if (CLASSD(dst)) {
7812 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7813 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7814 		freemsg(first_mp);
7815 		return;
7816 	}
7817 
7818 	if (mctl_present && io->ipsec_out_attach_if) {
7819 		/* ip_grab_attach_ill returns a held ill */
7820 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7821 		    io->ipsec_out_ill_index, B_FALSE, ipst);
7822 
7823 		/* Failure case frees things for us. */
7824 		if (attach_ill == NULL)
7825 			return;
7826 
7827 		/*
7828 		 * Check if we need an ire that will not be
7829 		 * looked up by anybody else i.e. HIDDEN.
7830 		 */
7831 		if (ill_is_probeonly(attach_ill))
7832 			ire_marks = IRE_MARK_HIDDEN;
7833 	}
7834 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7835 		ip_nexthop = B_TRUE;
7836 		nexthop_addr = io->ipsec_out_nexthop_addr;
7837 	}
7838 	/*
7839 	 * If this IRE is created for forwarding or it is not for
7840 	 * traffic for congestion controlled protocols, mark it as temporary.
7841 	 */
7842 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7843 		ire_marks |= IRE_MARK_TEMPORARY;
7844 
7845 	/*
7846 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7847 	 * chain until it gets the most specific information available.
7848 	 * For example, we know that there is no IRE_CACHE for this dest,
7849 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7850 	 * ire_ftable_lookup will look up the gateway, etc.
7851 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7852 	 * to the destination, of equal netmask length in the forward table,
7853 	 * will be recursively explored. If no information is available
7854 	 * for the final gateway of that route, we force the returned ire
7855 	 * to be equal to sire using MATCH_IRE_PARENT.
7856 	 * At least, in this case we have a starting point (in the buckets)
7857 	 * to look for other routes to the destination in the forward table.
7858 	 * This is actually used only for multirouting, where a list
7859 	 * of routes has to be processed in sequence.
7860 	 *
7861 	 * In the process of coming up with the most specific information,
7862 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7863 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7864 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7865 	 * Two caveats when handling incomplete ire's in ip_newroute:
7866 	 * - we should be careful when accessing its ire_nce (specifically
7867 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7868 	 * - not all legacy code path callers are prepared to handle
7869 	 *   incomplete ire's, so we should not create/add incomplete
7870 	 *   ire_cache entries here. (See discussion about temporary solution
7871 	 *   further below).
7872 	 *
7873 	 * In order to minimize packet dropping, and to preserve existing
7874 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7875 	 * gateway, and instead use the IF_RESOLVER ire to send out
7876 	 * another request to ARP (this is achieved by passing the
7877 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7878 	 * arp response comes back in ip_wput_nondata, we will create
7879 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7880 	 *
7881 	 * Note that this is a temporary solution; the correct solution is
7882 	 * to create an incomplete  per-dst ire_cache entry, and send the
7883 	 * packet out when the gw's nce is resolved. In order to achieve this,
7884 	 * all packet processing must have been completed prior to calling
7885 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7886 	 * to be modified to accomodate this solution.
7887 	 */
7888 	if (ip_nexthop) {
7889 		/*
7890 		 * The first time we come here, we look for an IRE_INTERFACE
7891 		 * entry for the specified nexthop, set the dst to be the
7892 		 * nexthop address and create an IRE_CACHE entry for the
7893 		 * nexthop. The next time around, we are able to find an
7894 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7895 		 * nexthop address and create an IRE_CACHE entry for the
7896 		 * destination address via the specified nexthop.
7897 		 */
7898 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7899 		    MBLK_GETLABEL(mp), ipst);
7900 		if (ire != NULL) {
7901 			gw = nexthop_addr;
7902 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7903 		} else {
7904 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7905 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7906 			    MBLK_GETLABEL(mp),
7907 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
7908 			    ipst);
7909 			if (ire != NULL) {
7910 				dst = nexthop_addr;
7911 			}
7912 		}
7913 	} else if (attach_ill == NULL) {
7914 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7915 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
7916 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7917 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7918 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
7919 		    ipst);
7920 	} else {
7921 		/*
7922 		 * attach_ill is set only for communicating with
7923 		 * on-link hosts. So, don't look for DEFAULT.
7924 		 */
7925 		ipif_t	*attach_ipif;
7926 
7927 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
7928 		if (attach_ipif == NULL) {
7929 			ill_refrele(attach_ill);
7930 			goto icmp_err_ret;
7931 		}
7932 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
7933 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
7934 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
7935 		    MATCH_IRE_SECATTR, ipst);
7936 		ipif_refrele(attach_ipif);
7937 	}
7938 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7939 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7940 
7941 	/*
7942 	 * This loop is run only once in most cases.
7943 	 * We loop to resolve further routes only when the destination
7944 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7945 	 */
7946 	do {
7947 		/* Clear the previous iteration's values */
7948 		if (src_ipif != NULL) {
7949 			ipif_refrele(src_ipif);
7950 			src_ipif = NULL;
7951 		}
7952 		if (dst_ill != NULL) {
7953 			ill_refrele(dst_ill);
7954 			dst_ill = NULL;
7955 		}
7956 
7957 		multirt_resolve_next = B_FALSE;
7958 		/*
7959 		 * We check if packets have to be multirouted.
7960 		 * In this case, given the current <ire, sire> couple,
7961 		 * we look for the next suitable <ire, sire>.
7962 		 * This check is done in ire_multirt_lookup(),
7963 		 * which applies various criteria to find the next route
7964 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7965 		 * unchanged if it detects it has not been tried yet.
7966 		 */
7967 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7968 			ip3dbg(("ip_newroute: starting next_resolution "
7969 			    "with first_mp %p, tag %d\n",
7970 			    (void *)first_mp,
7971 			    MULTIRT_DEBUG_TAGGED(first_mp)));
7972 
7973 			ASSERT(sire != NULL);
7974 			multirt_is_resolvable =
7975 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
7976 			    MBLK_GETLABEL(mp), ipst);
7977 
7978 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
7979 			    "ire %p, sire %p\n",
7980 			    multirt_is_resolvable,
7981 			    (void *)ire, (void *)sire));
7982 
7983 			if (!multirt_is_resolvable) {
7984 				/*
7985 				 * No more multirt route to resolve; give up
7986 				 * (all routes resolved or no more
7987 				 * resolvable routes).
7988 				 */
7989 				if (ire != NULL) {
7990 					ire_refrele(ire);
7991 					ire = NULL;
7992 				}
7993 			} else {
7994 				ASSERT(sire != NULL);
7995 				ASSERT(ire != NULL);
7996 				/*
7997 				 * We simply use first_sire as a flag that
7998 				 * indicates if a resolvable multirt route
7999 				 * has already been found.
8000 				 * If it is not the case, we may have to send
8001 				 * an ICMP error to report that the
8002 				 * destination is unreachable.
8003 				 * We do not IRE_REFHOLD first_sire.
8004 				 */
8005 				if (first_sire == NULL) {
8006 					first_sire = sire;
8007 				}
8008 			}
8009 		}
8010 		if (ire == NULL) {
8011 			if (ip_debug > 3) {
8012 				/* ip2dbg */
8013 				pr_addr_dbg("ip_newroute: "
8014 				    "can't resolve %s\n", AF_INET, &dst);
8015 			}
8016 			ip3dbg(("ip_newroute: "
8017 			    "ire %p, sire %p, first_sire %p\n",
8018 			    (void *)ire, (void *)sire, (void *)first_sire));
8019 
8020 			if (sire != NULL) {
8021 				ire_refrele(sire);
8022 				sire = NULL;
8023 			}
8024 
8025 			if (first_sire != NULL) {
8026 				/*
8027 				 * At least one multirt route has been found
8028 				 * in the same call to ip_newroute();
8029 				 * there is no need to report an ICMP error.
8030 				 * first_sire was not IRE_REFHOLDed.
8031 				 */
8032 				MULTIRT_DEBUG_UNTAG(first_mp);
8033 				freemsg(first_mp);
8034 				return;
8035 			}
8036 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8037 			    RTA_DST, ipst);
8038 			if (attach_ill != NULL)
8039 				ill_refrele(attach_ill);
8040 			goto icmp_err_ret;
8041 		}
8042 
8043 		/*
8044 		 * Verify that the returned IRE does not have either
8045 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8046 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8047 		 */
8048 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8049 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8050 			if (attach_ill != NULL)
8051 				ill_refrele(attach_ill);
8052 			goto icmp_err_ret;
8053 		}
8054 		/*
8055 		 * Increment the ire_ob_pkt_count field for ire if it is an
8056 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8057 		 * increment the same for the parent IRE, sire, if it is some
8058 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8059 		 */
8060 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8061 			UPDATE_OB_PKT_COUNT(ire);
8062 			ire->ire_last_used_time = lbolt;
8063 		}
8064 
8065 		if (sire != NULL) {
8066 			gw = sire->ire_gateway_addr;
8067 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8068 			    IRE_INTERFACE)) == 0);
8069 			UPDATE_OB_PKT_COUNT(sire);
8070 			sire->ire_last_used_time = lbolt;
8071 		}
8072 		/*
8073 		 * We have a route to reach the destination.
8074 		 *
8075 		 * 1) If the interface is part of ill group, try to get a new
8076 		 *    ill taking load spreading into account.
8077 		 *
8078 		 * 2) After selecting the ill, get a source address that
8079 		 *    might create good inbound load spreading.
8080 		 *    ipif_select_source does this for us.
8081 		 *
8082 		 * If the application specified the ill (ifindex), we still
8083 		 * load spread. Only if the packets needs to go out
8084 		 * specifically on a given ill e.g. binding to
8085 		 * IPIF_NOFAILOVER address, then we don't try to use a
8086 		 * different ill for load spreading.
8087 		 */
8088 		if (attach_ill == NULL) {
8089 			/*
8090 			 * Don't perform outbound load spreading in the
8091 			 * case of an RTF_MULTIRT route, as we actually
8092 			 * typically want to replicate outgoing packets
8093 			 * through particular interfaces.
8094 			 */
8095 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8096 				dst_ill = ire->ire_ipif->ipif_ill;
8097 				/* for uniformity */
8098 				ill_refhold(dst_ill);
8099 			} else {
8100 				/*
8101 				 * If we are here trying to create an IRE_CACHE
8102 				 * for an offlink destination and have the
8103 				 * IRE_CACHE for the next hop and the latter is
8104 				 * using virtual IP source address selection i.e
8105 				 * it's ire->ire_ipif is pointing to a virtual
8106 				 * network interface (vni) then
8107 				 * ip_newroute_get_dst_ll() will return the vni
8108 				 * interface as the dst_ill. Since the vni is
8109 				 * virtual i.e not associated with any physical
8110 				 * interface, it cannot be the dst_ill, hence
8111 				 * in such a case call ip_newroute_get_dst_ll()
8112 				 * with the stq_ill instead of the ire_ipif ILL.
8113 				 * The function returns a refheld ill.
8114 				 */
8115 				if ((ire->ire_type == IRE_CACHE) &&
8116 				    IS_VNI(ire->ire_ipif->ipif_ill))
8117 					dst_ill = ip_newroute_get_dst_ill(
8118 					    ire->ire_stq->q_ptr);
8119 				else
8120 					dst_ill = ip_newroute_get_dst_ill(
8121 					    ire->ire_ipif->ipif_ill);
8122 			}
8123 			if (dst_ill == NULL) {
8124 				if (ip_debug > 2) {
8125 					pr_addr_dbg("ip_newroute: "
8126 					    "no dst ill for dst"
8127 					    " %s\n", AF_INET, &dst);
8128 				}
8129 				goto icmp_err_ret;
8130 			}
8131 		} else {
8132 			dst_ill = ire->ire_ipif->ipif_ill;
8133 			/* for uniformity */
8134 			ill_refhold(dst_ill);
8135 			/*
8136 			 * We should have found a route matching ill as we
8137 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
8138 			 * Rather than asserting, when there is a mismatch,
8139 			 * we just drop the packet.
8140 			 */
8141 			if (dst_ill != attach_ill) {
8142 				ip0dbg(("ip_newroute: Packet dropped as "
8143 				    "IPIF_NOFAILOVER ill is %s, "
8144 				    "ire->ire_ipif->ipif_ill is %s\n",
8145 				    attach_ill->ill_name,
8146 				    dst_ill->ill_name));
8147 				ill_refrele(attach_ill);
8148 				goto icmp_err_ret;
8149 			}
8150 		}
8151 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
8152 		if (attach_ill != NULL) {
8153 			ill_refrele(attach_ill);
8154 			attach_ill = NULL;
8155 			do_attach_ill = B_TRUE;
8156 		}
8157 		ASSERT(dst_ill != NULL);
8158 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8159 
8160 		/*
8161 		 * Pick the best source address from dst_ill.
8162 		 *
8163 		 * 1) If it is part of a multipathing group, we would
8164 		 *    like to spread the inbound packets across different
8165 		 *    interfaces. ipif_select_source picks a random source
8166 		 *    across the different ills in the group.
8167 		 *
8168 		 * 2) If it is not part of a multipathing group, we try
8169 		 *    to pick the source address from the destination
8170 		 *    route. Clustering assumes that when we have multiple
8171 		 *    prefixes hosted on an interface, the prefix of the
8172 		 *    source address matches the prefix of the destination
8173 		 *    route. We do this only if the address is not
8174 		 *    DEPRECATED.
8175 		 *
8176 		 * 3) If the conn is in a different zone than the ire, we
8177 		 *    need to pick a source address from the right zone.
8178 		 *
8179 		 * NOTE : If we hit case (1) above, the prefix of the source
8180 		 *	  address picked may not match the prefix of the
8181 		 *	  destination routes prefix as ipif_select_source
8182 		 *	  does not look at "dst" while picking a source
8183 		 *	  address.
8184 		 *	  If we want the same behavior as (2), we will need
8185 		 *	  to change the behavior of ipif_select_source.
8186 		 */
8187 		ASSERT(src_ipif == NULL);
8188 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8189 			/*
8190 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8191 			 * Check that the ipif matching the requested source
8192 			 * address still exists.
8193 			 */
8194 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8195 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8196 		}
8197 
8198 		unspec_src = (connp != NULL && connp->conn_unspec_src);
8199 
8200 		if (src_ipif == NULL &&
8201 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
8202 			ire_marks |= IRE_MARK_USESRC_CHECK;
8203 			if ((dst_ill->ill_group != NULL) ||
8204 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8205 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8206 			    ire->ire_zoneid != ALL_ZONES) ||
8207 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8208 				/*
8209 				 * If the destination is reachable via a
8210 				 * given gateway, the selected source address
8211 				 * should be in the same subnet as the gateway.
8212 				 * Otherwise, the destination is not reachable.
8213 				 *
8214 				 * If there are no interfaces on the same subnet
8215 				 * as the destination, ipif_select_source gives
8216 				 * first non-deprecated interface which might be
8217 				 * on a different subnet than the gateway.
8218 				 * This is not desirable. Hence pass the dst_ire
8219 				 * source address to ipif_select_source.
8220 				 * It is sure that the destination is reachable
8221 				 * with the dst_ire source address subnet.
8222 				 * So passing dst_ire source address to
8223 				 * ipif_select_source will make sure that the
8224 				 * selected source will be on the same subnet
8225 				 * as dst_ire source address.
8226 				 */
8227 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8228 				src_ipif = ipif_select_source(dst_ill, saddr,
8229 				    zoneid);
8230 				if (src_ipif == NULL) {
8231 					if (ip_debug > 2) {
8232 						pr_addr_dbg("ip_newroute: "
8233 						    "no src for dst %s ",
8234 						    AF_INET, &dst);
8235 						printf("through interface %s\n",
8236 						    dst_ill->ill_name);
8237 					}
8238 					goto icmp_err_ret;
8239 				}
8240 			} else {
8241 				src_ipif = ire->ire_ipif;
8242 				ASSERT(src_ipif != NULL);
8243 				/* hold src_ipif for uniformity */
8244 				ipif_refhold(src_ipif);
8245 			}
8246 		}
8247 
8248 		/*
8249 		 * Assign a source address while we have the conn.
8250 		 * We can't have ip_wput_ire pick a source address when the
8251 		 * packet returns from arp since we need to look at
8252 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8253 		 * going through arp.
8254 		 *
8255 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8256 		 *	  it uses ip6i to store this information.
8257 		 */
8258 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
8259 			ipha->ipha_src = src_ipif->ipif_src_addr;
8260 
8261 		if (ip_debug > 3) {
8262 			/* ip2dbg */
8263 			pr_addr_dbg("ip_newroute: first hop %s\n",
8264 			    AF_INET, &gw);
8265 		}
8266 		ip2dbg(("\tire type %s (%d)\n",
8267 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8268 
8269 		/*
8270 		 * The TTL of multirouted packets is bounded by the
8271 		 * ip_multirt_ttl ndd variable.
8272 		 */
8273 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8274 			/* Force TTL of multirouted packets */
8275 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8276 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8277 				ip2dbg(("ip_newroute: forcing multirt TTL "
8278 				    "to %d (was %d), dst 0x%08x\n",
8279 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8280 				    ntohl(sire->ire_addr)));
8281 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8282 			}
8283 		}
8284 		/*
8285 		 * At this point in ip_newroute(), ire is either the
8286 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8287 		 * destination or an IRE_INTERFACE type that should be used
8288 		 * to resolve an on-subnet destination or an on-subnet
8289 		 * next-hop gateway.
8290 		 *
8291 		 * In the IRE_CACHE case, we have the following :
8292 		 *
8293 		 * 1) src_ipif - used for getting a source address.
8294 		 *
8295 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8296 		 *    means packets using this IRE_CACHE will go out on
8297 		 *    dst_ill.
8298 		 *
8299 		 * 3) The IRE sire will point to the prefix that is the
8300 		 *    longest  matching route for the destination. These
8301 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8302 		 *
8303 		 *    The newly created IRE_CACHE entry for the off-subnet
8304 		 *    destination is tied to both the prefix route and the
8305 		 *    interface route used to resolve the next-hop gateway
8306 		 *    via the ire_phandle and ire_ihandle fields,
8307 		 *    respectively.
8308 		 *
8309 		 * In the IRE_INTERFACE case, we have the following :
8310 		 *
8311 		 * 1) src_ipif - used for getting a source address.
8312 		 *
8313 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8314 		 *    means packets using the IRE_CACHE that we will build
8315 		 *    here will go out on dst_ill.
8316 		 *
8317 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8318 		 *    to be created will only be tied to the IRE_INTERFACE
8319 		 *    that was derived from the ire_ihandle field.
8320 		 *
8321 		 *    If sire is non-NULL, it means the destination is
8322 		 *    off-link and we will first create the IRE_CACHE for the
8323 		 *    gateway. Next time through ip_newroute, we will create
8324 		 *    the IRE_CACHE for the final destination as described
8325 		 *    above.
8326 		 *
8327 		 * In both cases, after the current resolution has been
8328 		 * completed (or possibly initialised, in the IRE_INTERFACE
8329 		 * case), the loop may be re-entered to attempt the resolution
8330 		 * of another RTF_MULTIRT route.
8331 		 *
8332 		 * When an IRE_CACHE entry for the off-subnet destination is
8333 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8334 		 * for further processing in emission loops.
8335 		 */
8336 		save_ire = ire;
8337 		switch (ire->ire_type) {
8338 		case IRE_CACHE: {
8339 			ire_t	*ipif_ire;
8340 
8341 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8342 			if (gw == 0)
8343 				gw = ire->ire_gateway_addr;
8344 			/*
8345 			 * We need 3 ire's to create a new cache ire for an
8346 			 * off-link destination from the cache ire of the
8347 			 * gateway.
8348 			 *
8349 			 *	1. The prefix ire 'sire' (Note that this does
8350 			 *	   not apply to the conn_nexthop_set case)
8351 			 *	2. The cache ire of the gateway 'ire'
8352 			 *	3. The interface ire 'ipif_ire'
8353 			 *
8354 			 * We have (1) and (2). We lookup (3) below.
8355 			 *
8356 			 * If there is no interface route to the gateway,
8357 			 * it is a race condition, where we found the cache
8358 			 * but the interface route has been deleted.
8359 			 */
8360 			if (ip_nexthop) {
8361 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8362 			} else {
8363 				ipif_ire =
8364 				    ire_ihandle_lookup_offlink(ire, sire);
8365 			}
8366 			if (ipif_ire == NULL) {
8367 				ip1dbg(("ip_newroute: "
8368 				    "ire_ihandle_lookup_offlink failed\n"));
8369 				goto icmp_err_ret;
8370 			}
8371 
8372 			/*
8373 			 * Check cached gateway IRE for any security
8374 			 * attributes; if found, associate the gateway
8375 			 * credentials group to the destination IRE.
8376 			 */
8377 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8378 				mutex_enter(&attrp->igsa_lock);
8379 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8380 					GCGRP_REFHOLD(gcgrp);
8381 				mutex_exit(&attrp->igsa_lock);
8382 			}
8383 
8384 			/*
8385 			 * XXX For the source of the resolver mp,
8386 			 * we are using the same DL_UNITDATA_REQ
8387 			 * (from save_ire->ire_nce->nce_res_mp)
8388 			 * though the save_ire is not pointing at the same ill.
8389 			 * This is incorrect. We need to send it up to the
8390 			 * resolver to get the right res_mp. For ethernets
8391 			 * this may be okay (ill_type == DL_ETHER).
8392 			 */
8393 
8394 			ire = ire_create(
8395 			    (uchar_t *)&dst,		/* dest address */
8396 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8397 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8398 			    (uchar_t *)&gw,		/* gateway address */
8399 			    &save_ire->ire_max_frag,
8400 			    save_ire->ire_nce,		/* src nce */
8401 			    dst_ill->ill_rq,		/* recv-from queue */
8402 			    dst_ill->ill_wq,		/* send-to queue */
8403 			    IRE_CACHE,			/* IRE type */
8404 			    src_ipif,
8405 			    (sire != NULL) ?
8406 			    sire->ire_mask : 0, 	/* Parent mask */
8407 			    (sire != NULL) ?
8408 			    sire->ire_phandle : 0,	/* Parent handle */
8409 			    ipif_ire->ire_ihandle,	/* Interface handle */
8410 			    (sire != NULL) ? (sire->ire_flags &
8411 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8412 			    (sire != NULL) ?
8413 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8414 			    NULL,
8415 			    gcgrp,
8416 			    ipst);
8417 
8418 			if (ire == NULL) {
8419 				if (gcgrp != NULL) {
8420 					GCGRP_REFRELE(gcgrp);
8421 					gcgrp = NULL;
8422 				}
8423 				ire_refrele(ipif_ire);
8424 				ire_refrele(save_ire);
8425 				break;
8426 			}
8427 
8428 			/* reference now held by IRE */
8429 			gcgrp = NULL;
8430 
8431 			ire->ire_marks |= ire_marks;
8432 
8433 			/*
8434 			 * Prevent sire and ipif_ire from getting deleted.
8435 			 * The newly created ire is tied to both of them via
8436 			 * the phandle and ihandle respectively.
8437 			 */
8438 			if (sire != NULL) {
8439 				IRB_REFHOLD(sire->ire_bucket);
8440 				/* Has it been removed already ? */
8441 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8442 					IRB_REFRELE(sire->ire_bucket);
8443 					ire_refrele(ipif_ire);
8444 					ire_refrele(save_ire);
8445 					break;
8446 				}
8447 			}
8448 
8449 			IRB_REFHOLD(ipif_ire->ire_bucket);
8450 			/* Has it been removed already ? */
8451 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8452 				IRB_REFRELE(ipif_ire->ire_bucket);
8453 				if (sire != NULL)
8454 					IRB_REFRELE(sire->ire_bucket);
8455 				ire_refrele(ipif_ire);
8456 				ire_refrele(save_ire);
8457 				break;
8458 			}
8459 
8460 			xmit_mp = first_mp;
8461 			/*
8462 			 * In the case of multirouting, a copy
8463 			 * of the packet is done before its sending.
8464 			 * The copy is used to attempt another
8465 			 * route resolution, in a next loop.
8466 			 */
8467 			if (ire->ire_flags & RTF_MULTIRT) {
8468 				copy_mp = copymsg(first_mp);
8469 				if (copy_mp != NULL) {
8470 					xmit_mp = copy_mp;
8471 					MULTIRT_DEBUG_TAG(first_mp);
8472 				}
8473 			}
8474 			ire_add_then_send(q, ire, xmit_mp);
8475 			ire_refrele(save_ire);
8476 
8477 			/* Assert that sire is not deleted yet. */
8478 			if (sire != NULL) {
8479 				ASSERT(sire->ire_ptpn != NULL);
8480 				IRB_REFRELE(sire->ire_bucket);
8481 			}
8482 
8483 			/* Assert that ipif_ire is not deleted yet. */
8484 			ASSERT(ipif_ire->ire_ptpn != NULL);
8485 			IRB_REFRELE(ipif_ire->ire_bucket);
8486 			ire_refrele(ipif_ire);
8487 
8488 			/*
8489 			 * If copy_mp is not NULL, multirouting was
8490 			 * requested. We loop to initiate a next
8491 			 * route resolution attempt, starting from sire.
8492 			 */
8493 			if (copy_mp != NULL) {
8494 				/*
8495 				 * Search for the next unresolved
8496 				 * multirt route.
8497 				 */
8498 				copy_mp = NULL;
8499 				ipif_ire = NULL;
8500 				ire = NULL;
8501 				multirt_resolve_next = B_TRUE;
8502 				continue;
8503 			}
8504 			if (sire != NULL)
8505 				ire_refrele(sire);
8506 			ipif_refrele(src_ipif);
8507 			ill_refrele(dst_ill);
8508 			return;
8509 		}
8510 		case IRE_IF_NORESOLVER: {
8511 
8512 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8513 			    dst_ill->ill_resolver_mp == NULL) {
8514 				ip1dbg(("ip_newroute: dst_ill %p "
8515 				    "for IRE_IF_NORESOLVER ire %p has "
8516 				    "no ill_resolver_mp\n",
8517 				    (void *)dst_ill, (void *)ire));
8518 				break;
8519 			}
8520 
8521 			/*
8522 			 * TSol note: We are creating the ire cache for the
8523 			 * destination 'dst'. If 'dst' is offlink, going
8524 			 * through the first hop 'gw', the security attributes
8525 			 * of 'dst' must be set to point to the gateway
8526 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8527 			 * is possible that 'dst' is a potential gateway that is
8528 			 * referenced by some route that has some security
8529 			 * attributes. Thus in the former case, we need to do a
8530 			 * gcgrp_lookup of 'gw' while in the latter case we
8531 			 * need to do gcgrp_lookup of 'dst' itself.
8532 			 */
8533 			ga.ga_af = AF_INET;
8534 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8535 			    &ga.ga_addr);
8536 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8537 
8538 			ire = ire_create(
8539 			    (uchar_t *)&dst,		/* dest address */
8540 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8541 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8542 			    (uchar_t *)&gw,		/* gateway address */
8543 			    &save_ire->ire_max_frag,
8544 			    NULL,			/* no src nce */
8545 			    dst_ill->ill_rq,		/* recv-from queue */
8546 			    dst_ill->ill_wq,		/* send-to queue */
8547 			    IRE_CACHE,
8548 			    src_ipif,
8549 			    save_ire->ire_mask,		/* Parent mask */
8550 			    (sire != NULL) ?		/* Parent handle */
8551 			    sire->ire_phandle : 0,
8552 			    save_ire->ire_ihandle,	/* Interface handle */
8553 			    (sire != NULL) ? sire->ire_flags &
8554 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8555 			    &(save_ire->ire_uinfo),
8556 			    NULL,
8557 			    gcgrp,
8558 			    ipst);
8559 
8560 			if (ire == NULL) {
8561 				if (gcgrp != NULL) {
8562 					GCGRP_REFRELE(gcgrp);
8563 					gcgrp = NULL;
8564 				}
8565 				ire_refrele(save_ire);
8566 				break;
8567 			}
8568 
8569 			/* reference now held by IRE */
8570 			gcgrp = NULL;
8571 
8572 			ire->ire_marks |= ire_marks;
8573 
8574 			/* Prevent save_ire from getting deleted */
8575 			IRB_REFHOLD(save_ire->ire_bucket);
8576 			/* Has it been removed already ? */
8577 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8578 				IRB_REFRELE(save_ire->ire_bucket);
8579 				ire_refrele(save_ire);
8580 				break;
8581 			}
8582 
8583 			/*
8584 			 * In the case of multirouting, a copy
8585 			 * of the packet is made before it is sent.
8586 			 * The copy is used in the next
8587 			 * loop to attempt another resolution.
8588 			 */
8589 			xmit_mp = first_mp;
8590 			if ((sire != NULL) &&
8591 			    (sire->ire_flags & RTF_MULTIRT)) {
8592 				copy_mp = copymsg(first_mp);
8593 				if (copy_mp != NULL) {
8594 					xmit_mp = copy_mp;
8595 					MULTIRT_DEBUG_TAG(first_mp);
8596 				}
8597 			}
8598 			ire_add_then_send(q, ire, xmit_mp);
8599 
8600 			/* Assert that it is not deleted yet. */
8601 			ASSERT(save_ire->ire_ptpn != NULL);
8602 			IRB_REFRELE(save_ire->ire_bucket);
8603 			ire_refrele(save_ire);
8604 
8605 			if (copy_mp != NULL) {
8606 				/*
8607 				 * If we found a (no)resolver, we ignore any
8608 				 * trailing top priority IRE_CACHE in further
8609 				 * loops. This ensures that we do not omit any
8610 				 * (no)resolver.
8611 				 * This IRE_CACHE, if any, will be processed
8612 				 * by another thread entering ip_newroute().
8613 				 * IRE_CACHE entries, if any, will be processed
8614 				 * by another thread entering ip_newroute(),
8615 				 * (upon resolver response, for instance).
8616 				 * This aims to force parallel multirt
8617 				 * resolutions as soon as a packet must be sent.
8618 				 * In the best case, after the tx of only one
8619 				 * packet, all reachable routes are resolved.
8620 				 * Otherwise, the resolution of all RTF_MULTIRT
8621 				 * routes would require several emissions.
8622 				 */
8623 				multirt_flags &= ~MULTIRT_CACHEGW;
8624 
8625 				/*
8626 				 * Search for the next unresolved multirt
8627 				 * route.
8628 				 */
8629 				copy_mp = NULL;
8630 				save_ire = NULL;
8631 				ire = NULL;
8632 				multirt_resolve_next = B_TRUE;
8633 				continue;
8634 			}
8635 
8636 			/*
8637 			 * Don't need sire anymore
8638 			 */
8639 			if (sire != NULL)
8640 				ire_refrele(sire);
8641 
8642 			ipif_refrele(src_ipif);
8643 			ill_refrele(dst_ill);
8644 			return;
8645 		}
8646 		case IRE_IF_RESOLVER:
8647 			/*
8648 			 * We can't build an IRE_CACHE yet, but at least we
8649 			 * found a resolver that can help.
8650 			 */
8651 			res_mp = dst_ill->ill_resolver_mp;
8652 			if (!OK_RESOLVER_MP(res_mp))
8653 				break;
8654 
8655 			/*
8656 			 * To be at this point in the code with a non-zero gw
8657 			 * means that dst is reachable through a gateway that
8658 			 * we have never resolved.  By changing dst to the gw
8659 			 * addr we resolve the gateway first.
8660 			 * When ire_add_then_send() tries to put the IP dg
8661 			 * to dst, it will reenter ip_newroute() at which
8662 			 * time we will find the IRE_CACHE for the gw and
8663 			 * create another IRE_CACHE in case IRE_CACHE above.
8664 			 */
8665 			if (gw != INADDR_ANY) {
8666 				/*
8667 				 * The source ipif that was determined above was
8668 				 * relative to the destination address, not the
8669 				 * gateway's. If src_ipif was not taken out of
8670 				 * the IRE_IF_RESOLVER entry, we'll need to call
8671 				 * ipif_select_source() again.
8672 				 */
8673 				if (src_ipif != ire->ire_ipif) {
8674 					ipif_refrele(src_ipif);
8675 					src_ipif = ipif_select_source(dst_ill,
8676 					    gw, zoneid);
8677 					if (src_ipif == NULL) {
8678 						if (ip_debug > 2) {
8679 							pr_addr_dbg(
8680 							    "ip_newroute: no "
8681 							    "src for gw %s ",
8682 							    AF_INET, &gw);
8683 							printf("through "
8684 							    "interface %s\n",
8685 							    dst_ill->ill_name);
8686 						}
8687 						goto icmp_err_ret;
8688 					}
8689 				}
8690 				save_dst = dst;
8691 				dst = gw;
8692 				gw = INADDR_ANY;
8693 			}
8694 
8695 			/*
8696 			 * We obtain a partial IRE_CACHE which we will pass
8697 			 * along with the resolver query.  When the response
8698 			 * comes back it will be there ready for us to add.
8699 			 * The ire_max_frag is atomically set under the
8700 			 * irebucket lock in ire_add_v[46].
8701 			 */
8702 
8703 			ire = ire_create_mp(
8704 			    (uchar_t *)&dst,		/* dest address */
8705 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8706 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8707 			    (uchar_t *)&gw,		/* gateway address */
8708 			    NULL,			/* ire_max_frag */
8709 			    NULL,			/* no src nce */
8710 			    dst_ill->ill_rq,		/* recv-from queue */
8711 			    dst_ill->ill_wq,		/* send-to queue */
8712 			    IRE_CACHE,
8713 			    src_ipif,			/* Interface ipif */
8714 			    save_ire->ire_mask,		/* Parent mask */
8715 			    0,
8716 			    save_ire->ire_ihandle,	/* Interface handle */
8717 			    0,				/* flags if any */
8718 			    &(save_ire->ire_uinfo),
8719 			    NULL,
8720 			    NULL,
8721 			    ipst);
8722 
8723 			if (ire == NULL) {
8724 				ire_refrele(save_ire);
8725 				break;
8726 			}
8727 
8728 			if ((sire != NULL) &&
8729 			    (sire->ire_flags & RTF_MULTIRT)) {
8730 				copy_mp = copymsg(first_mp);
8731 				if (copy_mp != NULL)
8732 					MULTIRT_DEBUG_TAG(copy_mp);
8733 			}
8734 
8735 			ire->ire_marks |= ire_marks;
8736 
8737 			/*
8738 			 * Construct message chain for the resolver
8739 			 * of the form:
8740 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8741 			 * Packet could contain a IPSEC_OUT mp.
8742 			 *
8743 			 * NOTE : ire will be added later when the response
8744 			 * comes back from ARP. If the response does not
8745 			 * come back, ARP frees the packet. For this reason,
8746 			 * we can't REFHOLD the bucket of save_ire to prevent
8747 			 * deletions. We may not be able to REFRELE the bucket
8748 			 * if the response never comes back. Thus, before
8749 			 * adding the ire, ire_add_v4 will make sure that the
8750 			 * interface route does not get deleted. This is the
8751 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8752 			 * where we can always prevent deletions because of
8753 			 * the synchronous nature of adding IRES i.e
8754 			 * ire_add_then_send is called after creating the IRE.
8755 			 */
8756 			ASSERT(ire->ire_mp != NULL);
8757 			ire->ire_mp->b_cont = first_mp;
8758 			/* Have saved_mp handy, for cleanup if canput fails */
8759 			saved_mp = mp;
8760 			mp = copyb(res_mp);
8761 			if (mp == NULL) {
8762 				/* Prepare for cleanup */
8763 				mp = saved_mp; /* pkt */
8764 				ire_delete(ire); /* ire_mp */
8765 				ire = NULL;
8766 				ire_refrele(save_ire);
8767 				if (copy_mp != NULL) {
8768 					MULTIRT_DEBUG_UNTAG(copy_mp);
8769 					freemsg(copy_mp);
8770 					copy_mp = NULL;
8771 				}
8772 				break;
8773 			}
8774 			linkb(mp, ire->ire_mp);
8775 
8776 			/*
8777 			 * Fill in the source and dest addrs for the resolver.
8778 			 * NOTE: this depends on memory layouts imposed by
8779 			 * ill_init().
8780 			 */
8781 			areq = (areq_t *)mp->b_rptr;
8782 			addrp = (ipaddr_t *)((char *)areq +
8783 			    areq->areq_sender_addr_offset);
8784 			if (do_attach_ill) {
8785 				/*
8786 				 * This is bind to no failover case.
8787 				 * arp packet also must go out on attach_ill.
8788 				 */
8789 				ASSERT(ipha->ipha_src != NULL);
8790 				*addrp = ipha->ipha_src;
8791 			} else {
8792 				*addrp = save_ire->ire_src_addr;
8793 			}
8794 
8795 			ire_refrele(save_ire);
8796 			addrp = (ipaddr_t *)((char *)areq +
8797 			    areq->areq_target_addr_offset);
8798 			*addrp = dst;
8799 			/* Up to the resolver. */
8800 			if (canputnext(dst_ill->ill_rq) &&
8801 			    !(dst_ill->ill_arp_closing)) {
8802 				putnext(dst_ill->ill_rq, mp);
8803 				ire = NULL;
8804 				if (copy_mp != NULL) {
8805 					/*
8806 					 * If we found a resolver, we ignore
8807 					 * any trailing top priority IRE_CACHE
8808 					 * in the further loops. This ensures
8809 					 * that we do not omit any resolver.
8810 					 * IRE_CACHE entries, if any, will be
8811 					 * processed next time we enter
8812 					 * ip_newroute().
8813 					 */
8814 					multirt_flags &= ~MULTIRT_CACHEGW;
8815 					/*
8816 					 * Search for the next unresolved
8817 					 * multirt route.
8818 					 */
8819 					first_mp = copy_mp;
8820 					copy_mp = NULL;
8821 					/* Prepare the next resolution loop. */
8822 					mp = first_mp;
8823 					EXTRACT_PKT_MP(mp, first_mp,
8824 					    mctl_present);
8825 					if (mctl_present)
8826 						io = (ipsec_out_t *)
8827 						    first_mp->b_rptr;
8828 					ipha = (ipha_t *)mp->b_rptr;
8829 
8830 					ASSERT(sire != NULL);
8831 
8832 					dst = save_dst;
8833 					multirt_resolve_next = B_TRUE;
8834 					continue;
8835 				}
8836 
8837 				if (sire != NULL)
8838 					ire_refrele(sire);
8839 
8840 				/*
8841 				 * The response will come back in ip_wput
8842 				 * with db_type IRE_DB_TYPE.
8843 				 */
8844 				ipif_refrele(src_ipif);
8845 				ill_refrele(dst_ill);
8846 				return;
8847 			} else {
8848 				/* Prepare for cleanup */
8849 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8850 				    mp);
8851 				mp->b_cont = NULL;
8852 				freeb(mp); /* areq */
8853 				/*
8854 				 * this is an ire that is not added to the
8855 				 * cache. ire_freemblk will handle the release
8856 				 * of any resources associated with the ire.
8857 				 */
8858 				ire_delete(ire); /* ire_mp */
8859 				mp = saved_mp; /* pkt */
8860 				ire = NULL;
8861 				if (copy_mp != NULL) {
8862 					MULTIRT_DEBUG_UNTAG(copy_mp);
8863 					freemsg(copy_mp);
8864 					copy_mp = NULL;
8865 				}
8866 				break;
8867 			}
8868 		default:
8869 			break;
8870 		}
8871 	} while (multirt_resolve_next);
8872 
8873 	ip1dbg(("ip_newroute: dropped\n"));
8874 	/* Did this packet originate externally? */
8875 	if (mp->b_prev) {
8876 		mp->b_next = NULL;
8877 		mp->b_prev = NULL;
8878 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8879 	} else {
8880 		if (dst_ill != NULL) {
8881 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8882 		} else {
8883 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8884 		}
8885 	}
8886 	ASSERT(copy_mp == NULL);
8887 	MULTIRT_DEBUG_UNTAG(first_mp);
8888 	freemsg(first_mp);
8889 	if (ire != NULL)
8890 		ire_refrele(ire);
8891 	if (sire != NULL)
8892 		ire_refrele(sire);
8893 	if (src_ipif != NULL)
8894 		ipif_refrele(src_ipif);
8895 	if (dst_ill != NULL)
8896 		ill_refrele(dst_ill);
8897 	return;
8898 
8899 icmp_err_ret:
8900 	ip1dbg(("ip_newroute: no route\n"));
8901 	if (src_ipif != NULL)
8902 		ipif_refrele(src_ipif);
8903 	if (dst_ill != NULL)
8904 		ill_refrele(dst_ill);
8905 	if (sire != NULL)
8906 		ire_refrele(sire);
8907 	/* Did this packet originate externally? */
8908 	if (mp->b_prev) {
8909 		mp->b_next = NULL;
8910 		mp->b_prev = NULL;
8911 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8912 		q = WR(q);
8913 	} else {
8914 		/*
8915 		 * There is no outgoing ill, so just increment the
8916 		 * system MIB.
8917 		 */
8918 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
8919 		/*
8920 		 * Since ip_wput() isn't close to finished, we fill
8921 		 * in enough of the header for credible error reporting.
8922 		 */
8923 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
8924 			/* Failed */
8925 			MULTIRT_DEBUG_UNTAG(first_mp);
8926 			freemsg(first_mp);
8927 			if (ire != NULL)
8928 				ire_refrele(ire);
8929 			return;
8930 		}
8931 	}
8932 
8933 	/*
8934 	 * At this point we will have ire only if RTF_BLACKHOLE
8935 	 * or RTF_REJECT flags are set on the IRE. It will not
8936 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8937 	 */
8938 	if (ire != NULL) {
8939 		if (ire->ire_flags & RTF_BLACKHOLE) {
8940 			ire_refrele(ire);
8941 			MULTIRT_DEBUG_UNTAG(first_mp);
8942 			freemsg(first_mp);
8943 			return;
8944 		}
8945 		ire_refrele(ire);
8946 	}
8947 	if (ip_source_routed(ipha, ipst)) {
8948 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8949 		    zoneid, ipst);
8950 		return;
8951 	}
8952 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
8953 }
8954 
8955 ip_opt_info_t zero_info;
8956 
8957 /*
8958  * IPv4 -
8959  * ip_newroute_ipif is called by ip_wput_multicast and
8960  * ip_rput_forward_multicast whenever we need to send
8961  * out a packet to a destination address for which we do not have specific
8962  * routing information. It is used when the packet will be sent out
8963  * on a specific interface. It is also called by ip_wput() when IP_BOUND_IF
8964  * socket option is set or icmp error message wants to go out on a particular
8965  * interface for a unicast packet.
8966  *
8967  * In most cases, the destination address is resolved thanks to the ipif
8968  * intrinsic resolver. However, there are some cases where the call to
8969  * ip_newroute_ipif must take into account the potential presence of
8970  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8971  * that uses the interface. This is specified through flags,
8972  * which can be a combination of:
8973  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8974  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
8975  *   and flags. Additionally, the packet source address has to be set to
8976  *   the specified address. The caller is thus expected to set this flag
8977  *   if the packet has no specific source address yet.
8978  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
8979  *   flag, the resulting ire will inherit the flag. All unresolved routes
8980  *   to the destination must be explored in the same call to
8981  *   ip_newroute_ipif().
8982  */
8983 static void
8984 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
8985     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
8986 {
8987 	areq_t	*areq;
8988 	ire_t	*ire = NULL;
8989 	mblk_t	*res_mp;
8990 	ipaddr_t *addrp;
8991 	mblk_t *first_mp;
8992 	ire_t	*save_ire = NULL;
8993 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
8994 	ipif_t	*src_ipif = NULL;
8995 	ushort_t ire_marks = 0;
8996 	ill_t	*dst_ill = NULL;
8997 	boolean_t mctl_present;
8998 	ipsec_out_t *io;
8999 	ipha_t *ipha;
9000 	int	ihandle = 0;
9001 	mblk_t	*saved_mp;
9002 	ire_t   *fire = NULL;
9003 	mblk_t  *copy_mp = NULL;
9004 	boolean_t multirt_resolve_next;
9005 	boolean_t unspec_src;
9006 	ipaddr_t ipha_dst;
9007 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
9008 
9009 	/*
9010 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9011 	 * here for uniformity
9012 	 */
9013 	ipif_refhold(ipif);
9014 
9015 	/*
9016 	 * This loop is run only once in most cases.
9017 	 * We loop to resolve further routes only when the destination
9018 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9019 	 */
9020 	do {
9021 		if (dst_ill != NULL) {
9022 			ill_refrele(dst_ill);
9023 			dst_ill = NULL;
9024 		}
9025 		if (src_ipif != NULL) {
9026 			ipif_refrele(src_ipif);
9027 			src_ipif = NULL;
9028 		}
9029 		multirt_resolve_next = B_FALSE;
9030 
9031 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9032 		    ipif->ipif_ill->ill_name));
9033 
9034 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
9035 		if (mctl_present)
9036 			io = (ipsec_out_t *)first_mp->b_rptr;
9037 
9038 		ipha = (ipha_t *)mp->b_rptr;
9039 
9040 		/*
9041 		 * Save the packet destination address, we may need it after
9042 		 * the packet has been consumed.
9043 		 */
9044 		ipha_dst = ipha->ipha_dst;
9045 
9046 		/*
9047 		 * If the interface is a pt-pt interface we look for an
9048 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9049 		 * local_address and the pt-pt destination address. Otherwise
9050 		 * we just match the local address.
9051 		 * NOTE: dst could be different than ipha->ipha_dst in case
9052 		 * of sending igmp multicast packets over a point-to-point
9053 		 * connection.
9054 		 * Thus we must be careful enough to check ipha_dst to be a
9055 		 * multicast address, otherwise it will take xmit_if path for
9056 		 * multicast packets resulting into kernel stack overflow by
9057 		 * repeated calls to ip_newroute_ipif from ire_send().
9058 		 */
9059 		if (CLASSD(ipha_dst) &&
9060 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9061 			goto err_ret;
9062 		}
9063 
9064 		/*
9065 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9066 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9067 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9068 		 * propagate its flags to the new ire.
9069 		 */
9070 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9071 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9072 			ip2dbg(("ip_newroute_ipif: "
9073 			    "ipif_lookup_multi_ire("
9074 			    "ipif %p, dst %08x) = fire %p\n",
9075 			    (void *)ipif, ntohl(dst), (void *)fire));
9076 		}
9077 
9078 		if (mctl_present && io->ipsec_out_attach_if) {
9079 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
9080 			    io->ipsec_out_ill_index, B_FALSE, ipst);
9081 
9082 			/* Failure case frees things for us. */
9083 			if (attach_ill == NULL) {
9084 				ipif_refrele(ipif);
9085 				if (fire != NULL)
9086 					ire_refrele(fire);
9087 				return;
9088 			}
9089 
9090 			/*
9091 			 * Check if we need an ire that will not be
9092 			 * looked up by anybody else i.e. HIDDEN.
9093 			 */
9094 			if (ill_is_probeonly(attach_ill)) {
9095 				ire_marks = IRE_MARK_HIDDEN;
9096 			}
9097 			/*
9098 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
9099 			 * case.
9100 			 */
9101 			dst_ill = ipif->ipif_ill;
9102 			/* attach_ill has been refheld by ip_grab_attach_ill */
9103 			ASSERT(dst_ill == attach_ill);
9104 		} else {
9105 			/*
9106 			 * If the interface belongs to an interface group,
9107 			 * make sure the next possible interface in the group
9108 			 * is used.  This encourages load spreading among
9109 			 * peers in an interface group.
9110 			 * Note: load spreading is disabled for RTF_MULTIRT
9111 			 * routes.
9112 			 */
9113 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9114 			    (fire->ire_flags & RTF_MULTIRT)) {
9115 				/*
9116 				 * Don't perform outbound load spreading
9117 				 * in the case of an RTF_MULTIRT issued route,
9118 				 * we actually typically want to replicate
9119 				 * outgoing packets through particular
9120 				 * interfaces.
9121 				 */
9122 				dst_ill = ipif->ipif_ill;
9123 				ill_refhold(dst_ill);
9124 			} else {
9125 				dst_ill = ip_newroute_get_dst_ill(
9126 				    ipif->ipif_ill);
9127 			}
9128 			if (dst_ill == NULL) {
9129 				if (ip_debug > 2) {
9130 					pr_addr_dbg("ip_newroute_ipif: "
9131 					    "no dst ill for dst %s\n",
9132 					    AF_INET, &dst);
9133 				}
9134 				goto err_ret;
9135 			}
9136 		}
9137 
9138 		/*
9139 		 * Pick a source address preferring non-deprecated ones.
9140 		 * Unlike ip_newroute, we don't do any source address
9141 		 * selection here since for multicast it really does not help
9142 		 * in inbound load spreading as in the unicast case.
9143 		 */
9144 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9145 		    (fire->ire_flags & RTF_SETSRC)) {
9146 			/*
9147 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9148 			 * on that interface. This ire has RTF_SETSRC flag, so
9149 			 * the source address of the packet must be changed.
9150 			 * Check that the ipif matching the requested source
9151 			 * address still exists.
9152 			 */
9153 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9154 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9155 		}
9156 
9157 		unspec_src = (connp != NULL && connp->conn_unspec_src);
9158 
9159 		if (((!ipif->ipif_isv6 && ipif->ipif_lcl_addr == INADDR_ANY) ||
9160 		    (ipif->ipif_flags & (IPIF_DEPRECATED|IPIF_UP)) != IPIF_UP ||
9161 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9162 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9163 		    (src_ipif == NULL) &&
9164 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
9165 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9166 			if (src_ipif == NULL) {
9167 				if (ip_debug > 2) {
9168 					/* ip1dbg */
9169 					pr_addr_dbg("ip_newroute_ipif: "
9170 					    "no src for dst %s",
9171 					    AF_INET, &dst);
9172 				}
9173 				ip1dbg((" through interface %s\n",
9174 				    dst_ill->ill_name));
9175 				goto err_ret;
9176 			}
9177 			ipif_refrele(ipif);
9178 			ipif = src_ipif;
9179 			ipif_refhold(ipif);
9180 		}
9181 		if (src_ipif == NULL) {
9182 			src_ipif = ipif;
9183 			ipif_refhold(src_ipif);
9184 		}
9185 
9186 		/*
9187 		 * Assign a source address while we have the conn.
9188 		 * We can't have ip_wput_ire pick a source address when the
9189 		 * packet returns from arp since conn_unspec_src might be set
9190 		 * and we lose the conn when going through arp.
9191 		 */
9192 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
9193 			ipha->ipha_src = src_ipif->ipif_src_addr;
9194 
9195 		/*
9196 		 * In the case of IP_BOUND_IF and IP_PKTINFO, it is possible
9197 		 * that the outgoing interface does not have an interface ire.
9198 		 */
9199 		if (CLASSD(ipha_dst) && (connp == NULL ||
9200 		    connp->conn_outgoing_ill == NULL) &&
9201 		    infop->ip_opt_ill_index == 0) {
9202 			/* ipif_to_ire returns an held ire */
9203 			ire = ipif_to_ire(ipif);
9204 			if (ire == NULL)
9205 				goto err_ret;
9206 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9207 				goto err_ret;
9208 			/*
9209 			 * ihandle is needed when the ire is added to
9210 			 * cache table.
9211 			 */
9212 			save_ire = ire;
9213 			ihandle = save_ire->ire_ihandle;
9214 
9215 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9216 			    "flags %04x\n",
9217 			    (void *)ire, (void *)ipif, flags));
9218 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9219 			    (fire->ire_flags & RTF_MULTIRT)) {
9220 				/*
9221 				 * As requested by flags, an IRE_OFFSUBNET was
9222 				 * looked up on that interface. This ire has
9223 				 * RTF_MULTIRT flag, so the resolution loop will
9224 				 * be re-entered to resolve additional routes on
9225 				 * other interfaces. For that purpose, a copy of
9226 				 * the packet is performed at this point.
9227 				 */
9228 				fire->ire_last_used_time = lbolt;
9229 				copy_mp = copymsg(first_mp);
9230 				if (copy_mp) {
9231 					MULTIRT_DEBUG_TAG(copy_mp);
9232 				}
9233 			}
9234 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9235 			    (fire->ire_flags & RTF_SETSRC)) {
9236 				/*
9237 				 * As requested by flags, an IRE_OFFSUBET was
9238 				 * looked up on that interface. This ire has
9239 				 * RTF_SETSRC flag, so the source address of the
9240 				 * packet must be changed.
9241 				 */
9242 				ipha->ipha_src = fire->ire_src_addr;
9243 			}
9244 		} else {
9245 			ASSERT((connp == NULL) ||
9246 			    (connp->conn_outgoing_ill != NULL) ||
9247 			    (connp->conn_dontroute) ||
9248 			    infop->ip_opt_ill_index != 0);
9249 			/*
9250 			 * The only ways we can come here are:
9251 			 * 1) IP_BOUND_IF socket option is set
9252 			 * 2) SO_DONTROUTE socket option is set
9253 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9254 			 * In all cases, the new ire will not be added
9255 			 * into cache table.
9256 			 */
9257 			ire_marks |= IRE_MARK_NOADD;
9258 		}
9259 
9260 		switch (ipif->ipif_net_type) {
9261 		case IRE_IF_NORESOLVER: {
9262 			/* We have what we need to build an IRE_CACHE. */
9263 
9264 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9265 			    (dst_ill->ill_resolver_mp == NULL)) {
9266 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9267 				    "for IRE_IF_NORESOLVER ire %p has "
9268 				    "no ill_resolver_mp\n",
9269 				    (void *)dst_ill, (void *)ire));
9270 				break;
9271 			}
9272 
9273 			/*
9274 			 * The new ire inherits the IRE_OFFSUBNET flags
9275 			 * and source address, if this was requested.
9276 			 */
9277 			ire = ire_create(
9278 			    (uchar_t *)&dst,		/* dest address */
9279 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9280 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9281 			    NULL,			/* gateway address */
9282 			    &ipif->ipif_mtu,
9283 			    NULL,			/* no src nce */
9284 			    dst_ill->ill_rq,		/* recv-from queue */
9285 			    dst_ill->ill_wq,		/* send-to queue */
9286 			    IRE_CACHE,
9287 			    src_ipif,
9288 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9289 			    (fire != NULL) ?		/* Parent handle */
9290 			    fire->ire_phandle : 0,
9291 			    ihandle,			/* Interface handle */
9292 			    (fire != NULL) ?
9293 			    (fire->ire_flags &
9294 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9295 			    (save_ire == NULL ? &ire_uinfo_null :
9296 			    &save_ire->ire_uinfo),
9297 			    NULL,
9298 			    NULL,
9299 			    ipst);
9300 
9301 			if (ire == NULL) {
9302 				if (save_ire != NULL)
9303 					ire_refrele(save_ire);
9304 				break;
9305 			}
9306 
9307 			ire->ire_marks |= ire_marks;
9308 
9309 			/*
9310 			 * If IRE_MARK_NOADD is set then we need to convert
9311 			 * the max_fragp to a useable value now. This is
9312 			 * normally done in ire_add_v[46]. We also need to
9313 			 * associate the ire with an nce (normally would be
9314 			 * done in ip_wput_nondata()).
9315 			 *
9316 			 * Note that IRE_MARK_NOADD packets created here
9317 			 * do not have a non-null ire_mp pointer. The null
9318 			 * value of ire_bucket indicates that they were
9319 			 * never added.
9320 			 */
9321 			if (ire->ire_marks & IRE_MARK_NOADD) {
9322 				uint_t  max_frag;
9323 
9324 				max_frag = *ire->ire_max_fragp;
9325 				ire->ire_max_fragp = NULL;
9326 				ire->ire_max_frag = max_frag;
9327 
9328 				if ((ire->ire_nce = ndp_lookup_v4(
9329 				    ire_to_ill(ire),
9330 				    (ire->ire_gateway_addr != INADDR_ANY ?
9331 				    &ire->ire_gateway_addr : &ire->ire_addr),
9332 				    B_FALSE)) == NULL) {
9333 					if (save_ire != NULL)
9334 						ire_refrele(save_ire);
9335 					break;
9336 				}
9337 				ASSERT(ire->ire_nce->nce_state ==
9338 				    ND_REACHABLE);
9339 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9340 			}
9341 
9342 			/* Prevent save_ire from getting deleted */
9343 			if (save_ire != NULL) {
9344 				IRB_REFHOLD(save_ire->ire_bucket);
9345 				/* Has it been removed already ? */
9346 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9347 					IRB_REFRELE(save_ire->ire_bucket);
9348 					ire_refrele(save_ire);
9349 					break;
9350 				}
9351 			}
9352 
9353 			ire_add_then_send(q, ire, first_mp);
9354 
9355 			/* Assert that save_ire is not deleted yet. */
9356 			if (save_ire != NULL) {
9357 				ASSERT(save_ire->ire_ptpn != NULL);
9358 				IRB_REFRELE(save_ire->ire_bucket);
9359 				ire_refrele(save_ire);
9360 				save_ire = NULL;
9361 			}
9362 			if (fire != NULL) {
9363 				ire_refrele(fire);
9364 				fire = NULL;
9365 			}
9366 
9367 			/*
9368 			 * the resolution loop is re-entered if this
9369 			 * was requested through flags and if we
9370 			 * actually are in a multirouting case.
9371 			 */
9372 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9373 				boolean_t need_resolve =
9374 				    ire_multirt_need_resolve(ipha_dst,
9375 				    MBLK_GETLABEL(copy_mp), ipst);
9376 				if (!need_resolve) {
9377 					MULTIRT_DEBUG_UNTAG(copy_mp);
9378 					freemsg(copy_mp);
9379 					copy_mp = NULL;
9380 				} else {
9381 					/*
9382 					 * ipif_lookup_group() calls
9383 					 * ire_lookup_multi() that uses
9384 					 * ire_ftable_lookup() to find
9385 					 * an IRE_INTERFACE for the group.
9386 					 * In the multirt case,
9387 					 * ire_lookup_multi() then invokes
9388 					 * ire_multirt_lookup() to find
9389 					 * the next resolvable ire.
9390 					 * As a result, we obtain an new
9391 					 * interface, derived from the
9392 					 * next ire.
9393 					 */
9394 					ipif_refrele(ipif);
9395 					ipif = ipif_lookup_group(ipha_dst,
9396 					    zoneid, ipst);
9397 					ip2dbg(("ip_newroute_ipif: "
9398 					    "multirt dst %08x, ipif %p\n",
9399 					    htonl(dst), (void *)ipif));
9400 					if (ipif != NULL) {
9401 						mp = copy_mp;
9402 						copy_mp = NULL;
9403 						multirt_resolve_next = B_TRUE;
9404 						continue;
9405 					} else {
9406 						freemsg(copy_mp);
9407 					}
9408 				}
9409 			}
9410 			if (ipif != NULL)
9411 				ipif_refrele(ipif);
9412 			ill_refrele(dst_ill);
9413 			ipif_refrele(src_ipif);
9414 			return;
9415 		}
9416 		case IRE_IF_RESOLVER:
9417 			/*
9418 			 * We can't build an IRE_CACHE yet, but at least
9419 			 * we found a resolver that can help.
9420 			 */
9421 			res_mp = dst_ill->ill_resolver_mp;
9422 			if (!OK_RESOLVER_MP(res_mp))
9423 				break;
9424 
9425 			/*
9426 			 * We obtain a partial IRE_CACHE which we will pass
9427 			 * along with the resolver query.  When the response
9428 			 * comes back it will be there ready for us to add.
9429 			 * The new ire inherits the IRE_OFFSUBNET flags
9430 			 * and source address, if this was requested.
9431 			 * The ire_max_frag is atomically set under the
9432 			 * irebucket lock in ire_add_v[46]. Only in the
9433 			 * case of IRE_MARK_NOADD, we set it here itself.
9434 			 */
9435 			ire = ire_create_mp(
9436 			    (uchar_t *)&dst,		/* dest address */
9437 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9438 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9439 			    NULL,			/* gateway address */
9440 			    (ire_marks & IRE_MARK_NOADD) ?
9441 			    ipif->ipif_mtu : 0,		/* max_frag */
9442 			    NULL,			/* no src nce */
9443 			    dst_ill->ill_rq,		/* recv-from queue */
9444 			    dst_ill->ill_wq,		/* send-to queue */
9445 			    IRE_CACHE,
9446 			    src_ipif,
9447 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9448 			    (fire != NULL) ?		/* Parent handle */
9449 			    fire->ire_phandle : 0,
9450 			    ihandle,			/* Interface handle */
9451 			    (fire != NULL) ?		/* flags if any */
9452 			    (fire->ire_flags &
9453 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9454 			    (save_ire == NULL ? &ire_uinfo_null :
9455 			    &save_ire->ire_uinfo),
9456 			    NULL,
9457 			    NULL,
9458 			    ipst);
9459 
9460 			if (save_ire != NULL) {
9461 				ire_refrele(save_ire);
9462 				save_ire = NULL;
9463 			}
9464 			if (ire == NULL)
9465 				break;
9466 
9467 			ire->ire_marks |= ire_marks;
9468 			/*
9469 			 * Construct message chain for the resolver of the
9470 			 * form:
9471 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9472 			 *
9473 			 * NOTE : ire will be added later when the response
9474 			 * comes back from ARP. If the response does not
9475 			 * come back, ARP frees the packet. For this reason,
9476 			 * we can't REFHOLD the bucket of save_ire to prevent
9477 			 * deletions. We may not be able to REFRELE the
9478 			 * bucket if the response never comes back.
9479 			 * Thus, before adding the ire, ire_add_v4 will make
9480 			 * sure that the interface route does not get deleted.
9481 			 * This is the only case unlike ip_newroute_v6,
9482 			 * ip_newroute_ipif_v6 where we can always prevent
9483 			 * deletions because ire_add_then_send is called after
9484 			 * creating the IRE.
9485 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9486 			 * does not add this IRE into the IRE CACHE.
9487 			 */
9488 			ASSERT(ire->ire_mp != NULL);
9489 			ire->ire_mp->b_cont = first_mp;
9490 			/* Have saved_mp handy, for cleanup if canput fails */
9491 			saved_mp = mp;
9492 			mp = copyb(res_mp);
9493 			if (mp == NULL) {
9494 				/* Prepare for cleanup */
9495 				mp = saved_mp; /* pkt */
9496 				ire_delete(ire); /* ire_mp */
9497 				ire = NULL;
9498 				if (copy_mp != NULL) {
9499 					MULTIRT_DEBUG_UNTAG(copy_mp);
9500 					freemsg(copy_mp);
9501 					copy_mp = NULL;
9502 				}
9503 				break;
9504 			}
9505 			linkb(mp, ire->ire_mp);
9506 
9507 			/*
9508 			 * Fill in the source and dest addrs for the resolver.
9509 			 * NOTE: this depends on memory layouts imposed by
9510 			 * ill_init().
9511 			 */
9512 			areq = (areq_t *)mp->b_rptr;
9513 			addrp = (ipaddr_t *)((char *)areq +
9514 			    areq->areq_sender_addr_offset);
9515 			*addrp = ire->ire_src_addr;
9516 			addrp = (ipaddr_t *)((char *)areq +
9517 			    areq->areq_target_addr_offset);
9518 			*addrp = dst;
9519 			/* Up to the resolver. */
9520 			if (canputnext(dst_ill->ill_rq) &&
9521 			    !(dst_ill->ill_arp_closing)) {
9522 				putnext(dst_ill->ill_rq, mp);
9523 				/*
9524 				 * The response will come back in ip_wput
9525 				 * with db_type IRE_DB_TYPE.
9526 				 */
9527 			} else {
9528 				mp->b_cont = NULL;
9529 				freeb(mp); /* areq */
9530 				ire_delete(ire); /* ire_mp */
9531 				saved_mp->b_next = NULL;
9532 				saved_mp->b_prev = NULL;
9533 				freemsg(first_mp); /* pkt */
9534 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9535 			}
9536 
9537 			if (fire != NULL) {
9538 				ire_refrele(fire);
9539 				fire = NULL;
9540 			}
9541 
9542 
9543 			/*
9544 			 * The resolution loop is re-entered if this was
9545 			 * requested through flags and we actually are
9546 			 * in a multirouting case.
9547 			 */
9548 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9549 				boolean_t need_resolve =
9550 				    ire_multirt_need_resolve(ipha_dst,
9551 				    MBLK_GETLABEL(copy_mp), ipst);
9552 				if (!need_resolve) {
9553 					MULTIRT_DEBUG_UNTAG(copy_mp);
9554 					freemsg(copy_mp);
9555 					copy_mp = NULL;
9556 				} else {
9557 					/*
9558 					 * ipif_lookup_group() calls
9559 					 * ire_lookup_multi() that uses
9560 					 * ire_ftable_lookup() to find
9561 					 * an IRE_INTERFACE for the group.
9562 					 * In the multirt case,
9563 					 * ire_lookup_multi() then invokes
9564 					 * ire_multirt_lookup() to find
9565 					 * the next resolvable ire.
9566 					 * As a result, we obtain an new
9567 					 * interface, derived from the
9568 					 * next ire.
9569 					 */
9570 					ipif_refrele(ipif);
9571 					ipif = ipif_lookup_group(ipha_dst,
9572 					    zoneid, ipst);
9573 					if (ipif != NULL) {
9574 						mp = copy_mp;
9575 						copy_mp = NULL;
9576 						multirt_resolve_next = B_TRUE;
9577 						continue;
9578 					} else {
9579 						freemsg(copy_mp);
9580 					}
9581 				}
9582 			}
9583 			if (ipif != NULL)
9584 				ipif_refrele(ipif);
9585 			ill_refrele(dst_ill);
9586 			ipif_refrele(src_ipif);
9587 			return;
9588 		default:
9589 			break;
9590 		}
9591 	} while (multirt_resolve_next);
9592 
9593 err_ret:
9594 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9595 	if (fire != NULL)
9596 		ire_refrele(fire);
9597 	ipif_refrele(ipif);
9598 	/* Did this packet originate externally? */
9599 	if (dst_ill != NULL)
9600 		ill_refrele(dst_ill);
9601 	if (src_ipif != NULL)
9602 		ipif_refrele(src_ipif);
9603 	if (mp->b_prev || mp->b_next) {
9604 		mp->b_next = NULL;
9605 		mp->b_prev = NULL;
9606 	} else {
9607 		/*
9608 		 * Since ip_wput() isn't close to finished, we fill
9609 		 * in enough of the header for credible error reporting.
9610 		 */
9611 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9612 			/* Failed */
9613 			freemsg(first_mp);
9614 			if (ire != NULL)
9615 				ire_refrele(ire);
9616 			return;
9617 		}
9618 	}
9619 	/*
9620 	 * At this point we will have ire only if RTF_BLACKHOLE
9621 	 * or RTF_REJECT flags are set on the IRE. It will not
9622 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9623 	 */
9624 	if (ire != NULL) {
9625 		if (ire->ire_flags & RTF_BLACKHOLE) {
9626 			ire_refrele(ire);
9627 			freemsg(first_mp);
9628 			return;
9629 		}
9630 		ire_refrele(ire);
9631 	}
9632 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9633 }
9634 
9635 /* Name/Value Table Lookup Routine */
9636 char *
9637 ip_nv_lookup(nv_t *nv, int value)
9638 {
9639 	if (!nv)
9640 		return (NULL);
9641 	for (; nv->nv_name; nv++) {
9642 		if (nv->nv_value == value)
9643 			return (nv->nv_name);
9644 	}
9645 	return ("unknown");
9646 }
9647 
9648 /*
9649  * This is a module open, i.e. this is a control stream for access
9650  * to a DLPI device.  We allocate an ill_t as the instance data in
9651  * this case.
9652  */
9653 int
9654 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9655 {
9656 	ill_t	*ill;
9657 	int	err;
9658 	zoneid_t zoneid;
9659 	netstack_t *ns;
9660 	ip_stack_t *ipst;
9661 
9662 	/*
9663 	 * Prevent unprivileged processes from pushing IP so that
9664 	 * they can't send raw IP.
9665 	 */
9666 	if (secpolicy_net_rawaccess(credp) != 0)
9667 		return (EPERM);
9668 
9669 	ns = netstack_find_by_cred(credp);
9670 	ASSERT(ns != NULL);
9671 	ipst = ns->netstack_ip;
9672 	ASSERT(ipst != NULL);
9673 
9674 	/*
9675 	 * For exclusive stacks we set the zoneid to zero
9676 	 * to make IP operate as if in the global zone.
9677 	 */
9678 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9679 		zoneid = GLOBAL_ZONEID;
9680 	else
9681 		zoneid = crgetzoneid(credp);
9682 
9683 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9684 	q->q_ptr = WR(q)->q_ptr = ill;
9685 	ill->ill_ipst = ipst;
9686 	ill->ill_zoneid = zoneid;
9687 
9688 	/*
9689 	 * ill_init initializes the ill fields and then sends down
9690 	 * down a DL_INFO_REQ after calling qprocson.
9691 	 */
9692 	err = ill_init(q, ill);
9693 	if (err != 0) {
9694 		mi_free(ill);
9695 		netstack_rele(ipst->ips_netstack);
9696 		q->q_ptr = NULL;
9697 		WR(q)->q_ptr = NULL;
9698 		return (err);
9699 	}
9700 
9701 	/* ill_init initializes the ipsq marking this thread as writer */
9702 	ipsq_exit(ill->ill_phyint->phyint_ipsq);
9703 	/* Wait for the DL_INFO_ACK */
9704 	mutex_enter(&ill->ill_lock);
9705 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9706 		/*
9707 		 * Return value of 0 indicates a pending signal.
9708 		 */
9709 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9710 		if (err == 0) {
9711 			mutex_exit(&ill->ill_lock);
9712 			(void) ip_close(q, 0);
9713 			return (EINTR);
9714 		}
9715 	}
9716 	mutex_exit(&ill->ill_lock);
9717 
9718 	/*
9719 	 * ip_rput_other could have set an error  in ill_error on
9720 	 * receipt of M_ERROR.
9721 	 */
9722 
9723 	err = ill->ill_error;
9724 	if (err != 0) {
9725 		(void) ip_close(q, 0);
9726 		return (err);
9727 	}
9728 
9729 	ill->ill_credp = credp;
9730 	crhold(credp);
9731 
9732 	mutex_enter(&ipst->ips_ip_mi_lock);
9733 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9734 	    credp);
9735 	mutex_exit(&ipst->ips_ip_mi_lock);
9736 	if (err) {
9737 		(void) ip_close(q, 0);
9738 		return (err);
9739 	}
9740 	return (0);
9741 }
9742 
9743 /* For /dev/ip aka AF_INET open */
9744 int
9745 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9746 {
9747 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
9748 }
9749 
9750 /* For /dev/ip6 aka AF_INET6 open */
9751 int
9752 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9753 {
9754 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
9755 }
9756 
9757 /* IP open routine. */
9758 int
9759 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9760     boolean_t isv6)
9761 {
9762 	conn_t 		*connp;
9763 	major_t		maj;
9764 	zoneid_t	zoneid;
9765 	netstack_t	*ns;
9766 	ip_stack_t	*ipst;
9767 
9768 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9769 
9770 	/* Allow reopen. */
9771 	if (q->q_ptr != NULL)
9772 		return (0);
9773 
9774 	if (sflag & MODOPEN) {
9775 		/* This is a module open */
9776 		return (ip_modopen(q, devp, flag, sflag, credp));
9777 	}
9778 
9779 	ns = netstack_find_by_cred(credp);
9780 	ASSERT(ns != NULL);
9781 	ipst = ns->netstack_ip;
9782 	ASSERT(ipst != NULL);
9783 
9784 	/*
9785 	 * For exclusive stacks we set the zoneid to zero
9786 	 * to make IP operate as if in the global zone.
9787 	 */
9788 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9789 		zoneid = GLOBAL_ZONEID;
9790 	else
9791 		zoneid = crgetzoneid(credp);
9792 
9793 	/*
9794 	 * We are opening as a device. This is an IP client stream, and we
9795 	 * allocate an conn_t as the instance data.
9796 	 */
9797 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9798 
9799 	/*
9800 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9801 	 * done by netstack_find_by_cred()
9802 	 */
9803 	netstack_rele(ipst->ips_netstack);
9804 
9805 	connp->conn_zoneid = zoneid;
9806 
9807 	connp->conn_upq = q;
9808 	q->q_ptr = WR(q)->q_ptr = connp;
9809 
9810 	if (flag & SO_SOCKSTR)
9811 		connp->conn_flags |= IPCL_SOCKET;
9812 
9813 	/* Minor tells us which /dev entry was opened */
9814 	if (isv6) {
9815 		connp->conn_flags |= IPCL_ISV6;
9816 		connp->conn_af_isv6 = B_TRUE;
9817 		ip_setpktversion(connp, isv6, B_FALSE, ipst);
9818 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9819 	} else {
9820 		connp->conn_af_isv6 = B_FALSE;
9821 		connp->conn_pkt_isv6 = B_FALSE;
9822 	}
9823 
9824 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9825 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9826 		connp->conn_minor_arena = ip_minor_arena_la;
9827 	} else {
9828 		/*
9829 		 * Either minor numbers in the large arena were exhausted
9830 		 * or a non socket application is doing the open.
9831 		 * Try to allocate from the small arena.
9832 		 */
9833 		if ((connp->conn_dev =
9834 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9835 			/* CONN_DEC_REF takes care of netstack_rele() */
9836 			q->q_ptr = WR(q)->q_ptr = NULL;
9837 			CONN_DEC_REF(connp);
9838 			return (EBUSY);
9839 		}
9840 		connp->conn_minor_arena = ip_minor_arena_sa;
9841 	}
9842 
9843 	maj = getemajor(*devp);
9844 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9845 
9846 	/*
9847 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9848 	 */
9849 	connp->conn_cred = credp;
9850 
9851 	/*
9852 	 * Handle IP_RTS_REQUEST and other ioctls which use conn_recv
9853 	 */
9854 	connp->conn_recv = ip_conn_input;
9855 
9856 	crhold(connp->conn_cred);
9857 
9858 	/*
9859 	 * If the caller has the process-wide flag set, then default to MAC
9860 	 * exempt mode.  This allows read-down to unlabeled hosts.
9861 	 */
9862 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9863 		connp->conn_mac_exempt = B_TRUE;
9864 
9865 	connp->conn_rq = q;
9866 	connp->conn_wq = WR(q);
9867 
9868 	/* Non-zero default values */
9869 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9870 
9871 	/*
9872 	 * Make the conn globally visible to walkers
9873 	 */
9874 	ASSERT(connp->conn_ref == 1);
9875 	mutex_enter(&connp->conn_lock);
9876 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9877 	mutex_exit(&connp->conn_lock);
9878 
9879 	qprocson(q);
9880 
9881 	return (0);
9882 }
9883 
9884 /*
9885  * Change the output format (IPv4 vs. IPv6) for a conn_t.
9886  * Note that there is no race since either ip_output function works - it
9887  * is just an optimization to enter the best ip_output routine directly.
9888  */
9889 void
9890 ip_setpktversion(conn_t *connp, boolean_t isv6, boolean_t bump_mib,
9891     ip_stack_t *ipst)
9892 {
9893 	if (isv6)  {
9894 		if (bump_mib) {
9895 			BUMP_MIB(&ipst->ips_ip6_mib,
9896 			    ipIfStatsOutSwitchIPVersion);
9897 		}
9898 		connp->conn_send = ip_output_v6;
9899 		connp->conn_pkt_isv6 = B_TRUE;
9900 	} else {
9901 		if (bump_mib) {
9902 			BUMP_MIB(&ipst->ips_ip_mib,
9903 			    ipIfStatsOutSwitchIPVersion);
9904 		}
9905 		connp->conn_send = ip_output;
9906 		connp->conn_pkt_isv6 = B_FALSE;
9907 	}
9908 
9909 }
9910 
9911 /*
9912  * See if IPsec needs loading because of the options in mp.
9913  */
9914 static boolean_t
9915 ipsec_opt_present(mblk_t *mp)
9916 {
9917 	uint8_t *optcp, *next_optcp, *opt_endcp;
9918 	struct opthdr *opt;
9919 	struct T_opthdr *topt;
9920 	int opthdr_len;
9921 	t_uscalar_t optname, optlevel;
9922 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9923 	ipsec_req_t *ipsr;
9924 
9925 	/*
9926 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9927 	 * return TRUE.
9928 	 */
9929 
9930 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9931 	opt_endcp = optcp + tor->OPT_length;
9932 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9933 		opthdr_len = sizeof (struct T_opthdr);
9934 	} else {		/* O_OPTMGMT_REQ */
9935 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9936 		opthdr_len = sizeof (struct opthdr);
9937 	}
9938 	for (; optcp < opt_endcp; optcp = next_optcp) {
9939 		if (optcp + opthdr_len > opt_endcp)
9940 			return (B_FALSE);	/* Not enough option header. */
9941 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9942 			topt = (struct T_opthdr *)optcp;
9943 			optlevel = topt->level;
9944 			optname = topt->name;
9945 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9946 		} else {
9947 			opt = (struct opthdr *)optcp;
9948 			optlevel = opt->level;
9949 			optname = opt->name;
9950 			next_optcp = optcp + opthdr_len +
9951 			    _TPI_ALIGN_OPT(opt->len);
9952 		}
9953 		if ((next_optcp < optcp) || /* wraparound pointer space */
9954 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9955 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9956 			return (B_FALSE); /* bad option buffer */
9957 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9958 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9959 			/*
9960 			 * Check to see if it's an all-bypass or all-zeroes
9961 			 * IPsec request.  Don't bother loading IPsec if
9962 			 * the socket doesn't want to use it.  (A good example
9963 			 * is a bypass request.)
9964 			 *
9965 			 * Basically, if any of the non-NEVER bits are set,
9966 			 * load IPsec.
9967 			 */
9968 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9969 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9970 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9971 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9972 			    != 0)
9973 				return (B_TRUE);
9974 		}
9975 	}
9976 	return (B_FALSE);
9977 }
9978 
9979 /*
9980  * If conn is is waiting for ipsec to finish loading, kick it.
9981  */
9982 /* ARGSUSED */
9983 static void
9984 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9985 {
9986 	t_scalar_t	optreq_prim;
9987 	mblk_t		*mp;
9988 	cred_t		*cr;
9989 	int		err = 0;
9990 
9991 	/*
9992 	 * This function is called, after ipsec loading is complete.
9993 	 * Since IP checks exclusively and atomically (i.e it prevents
9994 	 * ipsec load from completing until ip_optcom_req completes)
9995 	 * whether ipsec load is complete, there cannot be a race with IP
9996 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
9997 	 */
9998 	mutex_enter(&connp->conn_lock);
9999 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
10000 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
10001 		mp = connp->conn_ipsec_opt_mp;
10002 		connp->conn_ipsec_opt_mp = NULL;
10003 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
10004 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
10005 		mutex_exit(&connp->conn_lock);
10006 
10007 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
10008 
10009 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
10010 		if (optreq_prim == T_OPTMGMT_REQ) {
10011 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10012 			    &ip_opt_obj, B_FALSE);
10013 		} else {
10014 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10015 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10016 			    &ip_opt_obj, B_FALSE);
10017 		}
10018 		if (err != EINPROGRESS)
10019 			CONN_OPER_PENDING_DONE(connp);
10020 		return;
10021 	}
10022 	mutex_exit(&connp->conn_lock);
10023 }
10024 
10025 /*
10026  * Called from the ipsec_loader thread, outside any perimeter, to tell
10027  * ip qenable any of the queues waiting for the ipsec loader to
10028  * complete.
10029  */
10030 void
10031 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10032 {
10033 	netstack_t *ns = ipss->ipsec_netstack;
10034 
10035 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10036 }
10037 
10038 /*
10039  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10040  * determines the grp on which it has to become exclusive, queues the mp
10041  * and sq draining restarts the optmgmt
10042  */
10043 static boolean_t
10044 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10045 {
10046 	conn_t *connp = Q_TO_CONN(q);
10047 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10048 
10049 	/*
10050 	 * Take IPsec requests and treat them special.
10051 	 */
10052 	if (ipsec_opt_present(mp)) {
10053 		/* First check if IPsec is loaded. */
10054 		mutex_enter(&ipss->ipsec_loader_lock);
10055 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10056 			mutex_exit(&ipss->ipsec_loader_lock);
10057 			return (B_FALSE);
10058 		}
10059 		mutex_enter(&connp->conn_lock);
10060 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10061 
10062 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10063 		connp->conn_ipsec_opt_mp = mp;
10064 		mutex_exit(&connp->conn_lock);
10065 		mutex_exit(&ipss->ipsec_loader_lock);
10066 
10067 		ipsec_loader_loadnow(ipss);
10068 		return (B_TRUE);
10069 	}
10070 	return (B_FALSE);
10071 }
10072 
10073 /*
10074  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10075  * all of them are copied to the conn_t. If the req is "zero", the policy is
10076  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10077  * fields.
10078  * We keep only the latest setting of the policy and thus policy setting
10079  * is not incremental/cumulative.
10080  *
10081  * Requests to set policies with multiple alternative actions will
10082  * go through a different API.
10083  */
10084 int
10085 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10086 {
10087 	uint_t ah_req = 0;
10088 	uint_t esp_req = 0;
10089 	uint_t se_req = 0;
10090 	ipsec_selkey_t sel;
10091 	ipsec_act_t *actp = NULL;
10092 	uint_t nact;
10093 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10094 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10095 	ipsec_policy_root_t *pr;
10096 	ipsec_policy_head_t *ph;
10097 	int fam;
10098 	boolean_t is_pol_reset;
10099 	int error = 0;
10100 	netstack_t	*ns = connp->conn_netstack;
10101 	ip_stack_t	*ipst = ns->netstack_ip;
10102 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10103 
10104 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10105 
10106 	/*
10107 	 * The IP_SEC_OPT option does not allow variable length parameters,
10108 	 * hence a request cannot be NULL.
10109 	 */
10110 	if (req == NULL)
10111 		return (EINVAL);
10112 
10113 	ah_req = req->ipsr_ah_req;
10114 	esp_req = req->ipsr_esp_req;
10115 	se_req = req->ipsr_self_encap_req;
10116 
10117 	/* Don't allow setting self-encap without one or more of AH/ESP. */
10118 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
10119 		return (EINVAL);
10120 
10121 	/*
10122 	 * Are we dealing with a request to reset the policy (i.e.
10123 	 * zero requests).
10124 	 */
10125 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10126 	    (esp_req & REQ_MASK) == 0 &&
10127 	    (se_req & REQ_MASK) == 0);
10128 
10129 	if (!is_pol_reset) {
10130 		/*
10131 		 * If we couldn't load IPsec, fail with "protocol
10132 		 * not supported".
10133 		 * IPsec may not have been loaded for a request with zero
10134 		 * policies, so we don't fail in this case.
10135 		 */
10136 		mutex_enter(&ipss->ipsec_loader_lock);
10137 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10138 			mutex_exit(&ipss->ipsec_loader_lock);
10139 			return (EPROTONOSUPPORT);
10140 		}
10141 		mutex_exit(&ipss->ipsec_loader_lock);
10142 
10143 		/*
10144 		 * Test for valid requests. Invalid algorithms
10145 		 * need to be tested by IPsec code because new
10146 		 * algorithms can be added dynamically.
10147 		 */
10148 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10149 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10150 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10151 			return (EINVAL);
10152 		}
10153 
10154 		/*
10155 		 * Only privileged users can issue these
10156 		 * requests.
10157 		 */
10158 		if (((ah_req & IPSEC_PREF_NEVER) ||
10159 		    (esp_req & IPSEC_PREF_NEVER) ||
10160 		    (se_req & IPSEC_PREF_NEVER)) &&
10161 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10162 			return (EPERM);
10163 		}
10164 
10165 		/*
10166 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10167 		 * are mutually exclusive.
10168 		 */
10169 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10170 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10171 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10172 			/* Both of them are set */
10173 			return (EINVAL);
10174 		}
10175 	}
10176 
10177 	mutex_enter(&connp->conn_lock);
10178 
10179 	/*
10180 	 * If we have already cached policies in ip_bind_connected*(), don't
10181 	 * let them change now. We cache policies for connections
10182 	 * whose src,dst [addr, port] is known.
10183 	 */
10184 	if (connp->conn_policy_cached) {
10185 		mutex_exit(&connp->conn_lock);
10186 		return (EINVAL);
10187 	}
10188 
10189 	/*
10190 	 * We have a zero policies, reset the connection policy if already
10191 	 * set. This will cause the connection to inherit the
10192 	 * global policy, if any.
10193 	 */
10194 	if (is_pol_reset) {
10195 		if (connp->conn_policy != NULL) {
10196 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10197 			connp->conn_policy = NULL;
10198 		}
10199 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10200 		connp->conn_in_enforce_policy = B_FALSE;
10201 		connp->conn_out_enforce_policy = B_FALSE;
10202 		mutex_exit(&connp->conn_lock);
10203 		return (0);
10204 	}
10205 
10206 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10207 	    ipst->ips_netstack);
10208 	if (ph == NULL)
10209 		goto enomem;
10210 
10211 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10212 	if (actp == NULL)
10213 		goto enomem;
10214 
10215 	/*
10216 	 * Always allocate IPv4 policy entries, since they can also
10217 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10218 	 */
10219 	bzero(&sel, sizeof (sel));
10220 	sel.ipsl_valid = IPSL_IPV4;
10221 
10222 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10223 	    ipst->ips_netstack);
10224 	if (pin4 == NULL)
10225 		goto enomem;
10226 
10227 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10228 	    ipst->ips_netstack);
10229 	if (pout4 == NULL)
10230 		goto enomem;
10231 
10232 	if (connp->conn_af_isv6) {
10233 		/*
10234 		 * We're looking at a v6 socket, also allocate the
10235 		 * v6-specific entries...
10236 		 */
10237 		sel.ipsl_valid = IPSL_IPV6;
10238 		pin6 = ipsec_policy_create(&sel, actp, nact,
10239 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10240 		if (pin6 == NULL)
10241 			goto enomem;
10242 
10243 		pout6 = ipsec_policy_create(&sel, actp, nact,
10244 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10245 		if (pout6 == NULL)
10246 			goto enomem;
10247 
10248 		/*
10249 		 * .. and file them away in the right place.
10250 		 */
10251 		fam = IPSEC_AF_V6;
10252 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10253 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10254 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10255 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10256 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10257 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10258 	}
10259 
10260 	ipsec_actvec_free(actp, nact);
10261 
10262 	/*
10263 	 * File the v4 policies.
10264 	 */
10265 	fam = IPSEC_AF_V4;
10266 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10267 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10268 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10269 
10270 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10271 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10272 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10273 
10274 	/*
10275 	 * If the requests need security, set enforce_policy.
10276 	 * If the requests are IPSEC_PREF_NEVER, one should
10277 	 * still set conn_out_enforce_policy so that an ipsec_out
10278 	 * gets attached in ip_wput. This is needed so that
10279 	 * for connections that we don't cache policy in ip_bind,
10280 	 * if global policy matches in ip_wput_attach_policy, we
10281 	 * don't wrongly inherit global policy. Similarly, we need
10282 	 * to set conn_in_enforce_policy also so that we don't verify
10283 	 * policy wrongly.
10284 	 */
10285 	if ((ah_req & REQ_MASK) != 0 ||
10286 	    (esp_req & REQ_MASK) != 0 ||
10287 	    (se_req & REQ_MASK) != 0) {
10288 		connp->conn_in_enforce_policy = B_TRUE;
10289 		connp->conn_out_enforce_policy = B_TRUE;
10290 		connp->conn_flags |= IPCL_CHECK_POLICY;
10291 	}
10292 
10293 	mutex_exit(&connp->conn_lock);
10294 	return (error);
10295 #undef REQ_MASK
10296 
10297 	/*
10298 	 * Common memory-allocation-failure exit path.
10299 	 */
10300 enomem:
10301 	mutex_exit(&connp->conn_lock);
10302 	if (actp != NULL)
10303 		ipsec_actvec_free(actp, nact);
10304 	if (pin4 != NULL)
10305 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10306 	if (pout4 != NULL)
10307 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10308 	if (pin6 != NULL)
10309 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10310 	if (pout6 != NULL)
10311 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10312 	return (ENOMEM);
10313 }
10314 
10315 /*
10316  * Only for options that pass in an IP addr. Currently only V4 options
10317  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10318  * So this function assumes level is IPPROTO_IP
10319  */
10320 int
10321 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10322     mblk_t *first_mp)
10323 {
10324 	ipif_t *ipif = NULL;
10325 	int error;
10326 	ill_t *ill;
10327 	int zoneid;
10328 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10329 
10330 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10331 
10332 	if (addr != INADDR_ANY || checkonly) {
10333 		ASSERT(connp != NULL);
10334 		zoneid = IPCL_ZONEID(connp);
10335 		if (option == IP_NEXTHOP) {
10336 			ipif = ipif_lookup_onlink_addr(addr,
10337 			    connp->conn_zoneid, ipst);
10338 		} else {
10339 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10340 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10341 			    &error, ipst);
10342 		}
10343 		if (ipif == NULL) {
10344 			if (error == EINPROGRESS)
10345 				return (error);
10346 			else if ((option == IP_MULTICAST_IF) ||
10347 			    (option == IP_NEXTHOP))
10348 				return (EHOSTUNREACH);
10349 			else
10350 				return (EINVAL);
10351 		} else if (checkonly) {
10352 			if (option == IP_MULTICAST_IF) {
10353 				ill = ipif->ipif_ill;
10354 				/* not supported by the virtual network iface */
10355 				if (IS_VNI(ill)) {
10356 					ipif_refrele(ipif);
10357 					return (EINVAL);
10358 				}
10359 			}
10360 			ipif_refrele(ipif);
10361 			return (0);
10362 		}
10363 		ill = ipif->ipif_ill;
10364 		mutex_enter(&connp->conn_lock);
10365 		mutex_enter(&ill->ill_lock);
10366 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10367 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10368 			mutex_exit(&ill->ill_lock);
10369 			mutex_exit(&connp->conn_lock);
10370 			ipif_refrele(ipif);
10371 			return (option == IP_MULTICAST_IF ?
10372 			    EHOSTUNREACH : EINVAL);
10373 		}
10374 	} else {
10375 		mutex_enter(&connp->conn_lock);
10376 	}
10377 
10378 	/* None of the options below are supported on the VNI */
10379 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10380 		mutex_exit(&ill->ill_lock);
10381 		mutex_exit(&connp->conn_lock);
10382 		ipif_refrele(ipif);
10383 		return (EINVAL);
10384 	}
10385 
10386 	switch (option) {
10387 	case IP_DONTFAILOVER_IF:
10388 		/*
10389 		 * This option is used by in.mpathd to ensure
10390 		 * that IPMP probe packets only go out on the
10391 		 * test interfaces. in.mpathd sets this option
10392 		 * on the non-failover interfaces.
10393 		 * For backward compatibility, this option
10394 		 * implicitly sets IP_MULTICAST_IF, as used
10395 		 * be done in bind(), so that ip_wput gets
10396 		 * this ipif to send mcast packets.
10397 		 */
10398 		if (ipif != NULL) {
10399 			ASSERT(addr != INADDR_ANY);
10400 			connp->conn_nofailover_ill = ipif->ipif_ill;
10401 			connp->conn_multicast_ipif = ipif;
10402 		} else {
10403 			ASSERT(addr == INADDR_ANY);
10404 			connp->conn_nofailover_ill = NULL;
10405 			connp->conn_multicast_ipif = NULL;
10406 		}
10407 		break;
10408 
10409 	case IP_MULTICAST_IF:
10410 		connp->conn_multicast_ipif = ipif;
10411 		break;
10412 	case IP_NEXTHOP:
10413 		connp->conn_nexthop_v4 = addr;
10414 		connp->conn_nexthop_set = B_TRUE;
10415 		break;
10416 	}
10417 
10418 	if (ipif != NULL) {
10419 		mutex_exit(&ill->ill_lock);
10420 		mutex_exit(&connp->conn_lock);
10421 		ipif_refrele(ipif);
10422 		return (0);
10423 	}
10424 	mutex_exit(&connp->conn_lock);
10425 	/* We succeded in cleared the option */
10426 	return (0);
10427 }
10428 
10429 /*
10430  * For options that pass in an ifindex specifying the ill. V6 options always
10431  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10432  */
10433 int
10434 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10435     int level, int option, mblk_t *first_mp)
10436 {
10437 	ill_t *ill = NULL;
10438 	int error = 0;
10439 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10440 
10441 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10442 	if (ifindex != 0) {
10443 		ASSERT(connp != NULL);
10444 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10445 		    first_mp, ip_restart_optmgmt, &error, ipst);
10446 		if (ill != NULL) {
10447 			if (checkonly) {
10448 				/* not supported by the virtual network iface */
10449 				if (IS_VNI(ill)) {
10450 					ill_refrele(ill);
10451 					return (EINVAL);
10452 				}
10453 				ill_refrele(ill);
10454 				return (0);
10455 			}
10456 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10457 			    0, NULL)) {
10458 				ill_refrele(ill);
10459 				ill = NULL;
10460 				mutex_enter(&connp->conn_lock);
10461 				goto setit;
10462 			}
10463 			mutex_enter(&connp->conn_lock);
10464 			mutex_enter(&ill->ill_lock);
10465 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10466 				mutex_exit(&ill->ill_lock);
10467 				mutex_exit(&connp->conn_lock);
10468 				ill_refrele(ill);
10469 				ill = NULL;
10470 				mutex_enter(&connp->conn_lock);
10471 			}
10472 			goto setit;
10473 		} else if (error == EINPROGRESS) {
10474 			return (error);
10475 		} else {
10476 			error = 0;
10477 		}
10478 	}
10479 	mutex_enter(&connp->conn_lock);
10480 setit:
10481 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10482 
10483 	/*
10484 	 * The options below assume that the ILL (if any) transmits and/or
10485 	 * receives traffic. Neither of which is true for the virtual network
10486 	 * interface, so fail setting these on a VNI.
10487 	 */
10488 	if (IS_VNI(ill)) {
10489 		ASSERT(ill != NULL);
10490 		mutex_exit(&ill->ill_lock);
10491 		mutex_exit(&connp->conn_lock);
10492 		ill_refrele(ill);
10493 		return (EINVAL);
10494 	}
10495 
10496 	if (level == IPPROTO_IP) {
10497 		switch (option) {
10498 		case IP_BOUND_IF:
10499 			connp->conn_incoming_ill = ill;
10500 			connp->conn_outgoing_ill = ill;
10501 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10502 			    0 : ifindex;
10503 			break;
10504 
10505 		case IP_MULTICAST_IF:
10506 			/*
10507 			 * This option is an internal special. The socket
10508 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10509 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10510 			 * specifies an ifindex and we try first on V6 ill's.
10511 			 * If we don't find one, we they try using on v4 ill's
10512 			 * intenally and we come here.
10513 			 */
10514 			if (!checkonly && ill != NULL) {
10515 				ipif_t	*ipif;
10516 				ipif = ill->ill_ipif;
10517 
10518 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10519 					mutex_exit(&ill->ill_lock);
10520 					mutex_exit(&connp->conn_lock);
10521 					ill_refrele(ill);
10522 					ill = NULL;
10523 					mutex_enter(&connp->conn_lock);
10524 				} else {
10525 					connp->conn_multicast_ipif = ipif;
10526 				}
10527 			}
10528 			break;
10529 
10530 		case IP_DHCPINIT_IF:
10531 			if (connp->conn_dhcpinit_ill != NULL) {
10532 				/*
10533 				 * We've locked the conn so conn_cleanup_ill()
10534 				 * cannot clear conn_dhcpinit_ill -- so it's
10535 				 * safe to access the ill.
10536 				 */
10537 				ill_t *oill = connp->conn_dhcpinit_ill;
10538 
10539 				ASSERT(oill->ill_dhcpinit != 0);
10540 				atomic_dec_32(&oill->ill_dhcpinit);
10541 				connp->conn_dhcpinit_ill = NULL;
10542 			}
10543 
10544 			if (ill != NULL) {
10545 				connp->conn_dhcpinit_ill = ill;
10546 				atomic_inc_32(&ill->ill_dhcpinit);
10547 			}
10548 			break;
10549 		}
10550 	} else {
10551 		switch (option) {
10552 		case IPV6_BOUND_IF:
10553 			connp->conn_incoming_ill = ill;
10554 			connp->conn_outgoing_ill = ill;
10555 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10556 			    0 : ifindex;
10557 			break;
10558 
10559 		case IPV6_BOUND_PIF:
10560 			/*
10561 			 * Limit all transmit to this ill.
10562 			 * Unlike IPV6_BOUND_IF, using this option
10563 			 * prevents load spreading and failover from
10564 			 * happening when the interface is part of the
10565 			 * group. That's why we don't need to remember
10566 			 * the ifindex in orig_bound_ifindex as in
10567 			 * IPV6_BOUND_IF.
10568 			 */
10569 			connp->conn_outgoing_pill = ill;
10570 			break;
10571 
10572 		case IPV6_DONTFAILOVER_IF:
10573 			/*
10574 			 * This option is used by in.mpathd to ensure
10575 			 * that IPMP probe packets only go out on the
10576 			 * test interfaces. in.mpathd sets this option
10577 			 * on the non-failover interfaces.
10578 			 */
10579 			connp->conn_nofailover_ill = ill;
10580 			/*
10581 			 * For backward compatibility, this option
10582 			 * implicitly sets ip_multicast_ill as used in
10583 			 * IPV6_MULTICAST_IF so that ip_wput gets
10584 			 * this ill to send mcast packets.
10585 			 */
10586 			connp->conn_multicast_ill = ill;
10587 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10588 			    0 : ifindex;
10589 			break;
10590 
10591 		case IPV6_MULTICAST_IF:
10592 			/*
10593 			 * Set conn_multicast_ill to be the IPv6 ill.
10594 			 * Set conn_multicast_ipif to be an IPv4 ipif
10595 			 * for ifindex to make IPv4 mapped addresses
10596 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10597 			 * Even if no IPv6 ill exists for the ifindex
10598 			 * we need to check for an IPv4 ifindex in order
10599 			 * for this to work with mapped addresses. In that
10600 			 * case only set conn_multicast_ipif.
10601 			 */
10602 			if (!checkonly) {
10603 				if (ifindex == 0) {
10604 					connp->conn_multicast_ill = NULL;
10605 					connp->conn_orig_multicast_ifindex = 0;
10606 					connp->conn_multicast_ipif = NULL;
10607 				} else if (ill != NULL) {
10608 					connp->conn_multicast_ill = ill;
10609 					connp->conn_orig_multicast_ifindex =
10610 					    ifindex;
10611 				}
10612 			}
10613 			break;
10614 		}
10615 	}
10616 
10617 	if (ill != NULL) {
10618 		mutex_exit(&ill->ill_lock);
10619 		mutex_exit(&connp->conn_lock);
10620 		ill_refrele(ill);
10621 		return (0);
10622 	}
10623 	mutex_exit(&connp->conn_lock);
10624 	/*
10625 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10626 	 * locate the ill and could not set the option (ifindex != 0)
10627 	 */
10628 	return (ifindex == 0 ? 0 : EINVAL);
10629 }
10630 
10631 /* This routine sets socket options. */
10632 /* ARGSUSED */
10633 int
10634 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10635     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10636     void *dummy, cred_t *cr, mblk_t *first_mp)
10637 {
10638 	int		*i1 = (int *)invalp;
10639 	conn_t		*connp = Q_TO_CONN(q);
10640 	int		error = 0;
10641 	boolean_t	checkonly;
10642 	ire_t		*ire;
10643 	boolean_t	found;
10644 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10645 
10646 	switch (optset_context) {
10647 
10648 	case SETFN_OPTCOM_CHECKONLY:
10649 		checkonly = B_TRUE;
10650 		/*
10651 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10652 		 * inlen != 0 implies value supplied and
10653 		 * 	we have to "pretend" to set it.
10654 		 * inlen == 0 implies that there is no
10655 		 * 	value part in T_CHECK request and just validation
10656 		 * done elsewhere should be enough, we just return here.
10657 		 */
10658 		if (inlen == 0) {
10659 			*outlenp = 0;
10660 			return (0);
10661 		}
10662 		break;
10663 	case SETFN_OPTCOM_NEGOTIATE:
10664 	case SETFN_UD_NEGOTIATE:
10665 	case SETFN_CONN_NEGOTIATE:
10666 		checkonly = B_FALSE;
10667 		break;
10668 	default:
10669 		/*
10670 		 * We should never get here
10671 		 */
10672 		*outlenp = 0;
10673 		return (EINVAL);
10674 	}
10675 
10676 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10677 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10678 
10679 	/*
10680 	 * For fixed length options, no sanity check
10681 	 * of passed in length is done. It is assumed *_optcom_req()
10682 	 * routines do the right thing.
10683 	 */
10684 
10685 	switch (level) {
10686 	case SOL_SOCKET:
10687 		/*
10688 		 * conn_lock protects the bitfields, and is used to
10689 		 * set the fields atomically.
10690 		 */
10691 		switch (name) {
10692 		case SO_BROADCAST:
10693 			if (!checkonly) {
10694 				/* TODO: use value someplace? */
10695 				mutex_enter(&connp->conn_lock);
10696 				connp->conn_broadcast = *i1 ? 1 : 0;
10697 				mutex_exit(&connp->conn_lock);
10698 			}
10699 			break;	/* goto sizeof (int) option return */
10700 		case SO_USELOOPBACK:
10701 			if (!checkonly) {
10702 				/* TODO: use value someplace? */
10703 				mutex_enter(&connp->conn_lock);
10704 				connp->conn_loopback = *i1 ? 1 : 0;
10705 				mutex_exit(&connp->conn_lock);
10706 			}
10707 			break;	/* goto sizeof (int) option return */
10708 		case SO_DONTROUTE:
10709 			if (!checkonly) {
10710 				mutex_enter(&connp->conn_lock);
10711 				connp->conn_dontroute = *i1 ? 1 : 0;
10712 				mutex_exit(&connp->conn_lock);
10713 			}
10714 			break;	/* goto sizeof (int) option return */
10715 		case SO_REUSEADDR:
10716 			if (!checkonly) {
10717 				mutex_enter(&connp->conn_lock);
10718 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10719 				mutex_exit(&connp->conn_lock);
10720 			}
10721 			break;	/* goto sizeof (int) option return */
10722 		case SO_PROTOTYPE:
10723 			if (!checkonly) {
10724 				mutex_enter(&connp->conn_lock);
10725 				connp->conn_proto = *i1;
10726 				mutex_exit(&connp->conn_lock);
10727 			}
10728 			break;	/* goto sizeof (int) option return */
10729 		case SO_ALLZONES:
10730 			if (!checkonly) {
10731 				mutex_enter(&connp->conn_lock);
10732 				if (IPCL_IS_BOUND(connp)) {
10733 					mutex_exit(&connp->conn_lock);
10734 					return (EINVAL);
10735 				}
10736 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10737 				mutex_exit(&connp->conn_lock);
10738 			}
10739 			break;	/* goto sizeof (int) option return */
10740 		case SO_ANON_MLP:
10741 			if (!checkonly) {
10742 				mutex_enter(&connp->conn_lock);
10743 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10744 				mutex_exit(&connp->conn_lock);
10745 			}
10746 			break;	/* goto sizeof (int) option return */
10747 		case SO_MAC_EXEMPT:
10748 			if (secpolicy_net_mac_aware(cr) != 0 ||
10749 			    IPCL_IS_BOUND(connp))
10750 				return (EACCES);
10751 			if (!checkonly) {
10752 				mutex_enter(&connp->conn_lock);
10753 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10754 				mutex_exit(&connp->conn_lock);
10755 			}
10756 			break;	/* goto sizeof (int) option return */
10757 		default:
10758 			/*
10759 			 * "soft" error (negative)
10760 			 * option not handled at this level
10761 			 * Note: Do not modify *outlenp
10762 			 */
10763 			return (-EINVAL);
10764 		}
10765 		break;
10766 	case IPPROTO_IP:
10767 		switch (name) {
10768 		case IP_NEXTHOP:
10769 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10770 				return (EPERM);
10771 			/* FALLTHRU */
10772 		case IP_MULTICAST_IF:
10773 		case IP_DONTFAILOVER_IF: {
10774 			ipaddr_t addr = *i1;
10775 
10776 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10777 			    first_mp);
10778 			if (error != 0)
10779 				return (error);
10780 			break;	/* goto sizeof (int) option return */
10781 		}
10782 
10783 		case IP_MULTICAST_TTL:
10784 			/* Recorded in transport above IP */
10785 			*outvalp = *invalp;
10786 			*outlenp = sizeof (uchar_t);
10787 			return (0);
10788 		case IP_MULTICAST_LOOP:
10789 			if (!checkonly) {
10790 				mutex_enter(&connp->conn_lock);
10791 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10792 				mutex_exit(&connp->conn_lock);
10793 			}
10794 			*outvalp = *invalp;
10795 			*outlenp = sizeof (uchar_t);
10796 			return (0);
10797 		case IP_ADD_MEMBERSHIP:
10798 		case MCAST_JOIN_GROUP:
10799 		case IP_DROP_MEMBERSHIP:
10800 		case MCAST_LEAVE_GROUP: {
10801 			struct ip_mreq *mreqp;
10802 			struct group_req *greqp;
10803 			ire_t *ire;
10804 			boolean_t done = B_FALSE;
10805 			ipaddr_t group, ifaddr;
10806 			struct sockaddr_in *sin;
10807 			uint32_t *ifindexp;
10808 			boolean_t mcast_opt = B_TRUE;
10809 			mcast_record_t fmode;
10810 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10811 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10812 
10813 			switch (name) {
10814 			case IP_ADD_MEMBERSHIP:
10815 				mcast_opt = B_FALSE;
10816 				/* FALLTHRU */
10817 			case MCAST_JOIN_GROUP:
10818 				fmode = MODE_IS_EXCLUDE;
10819 				optfn = ip_opt_add_group;
10820 				break;
10821 
10822 			case IP_DROP_MEMBERSHIP:
10823 				mcast_opt = B_FALSE;
10824 				/* FALLTHRU */
10825 			case MCAST_LEAVE_GROUP:
10826 				fmode = MODE_IS_INCLUDE;
10827 				optfn = ip_opt_delete_group;
10828 				break;
10829 			}
10830 
10831 			if (mcast_opt) {
10832 				greqp = (struct group_req *)i1;
10833 				sin = (struct sockaddr_in *)&greqp->gr_group;
10834 				if (sin->sin_family != AF_INET) {
10835 					*outlenp = 0;
10836 					return (ENOPROTOOPT);
10837 				}
10838 				group = (ipaddr_t)sin->sin_addr.s_addr;
10839 				ifaddr = INADDR_ANY;
10840 				ifindexp = &greqp->gr_interface;
10841 			} else {
10842 				mreqp = (struct ip_mreq *)i1;
10843 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10844 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10845 				ifindexp = NULL;
10846 			}
10847 
10848 			/*
10849 			 * In the multirouting case, we need to replicate
10850 			 * the request on all interfaces that will take part
10851 			 * in replication.  We do so because multirouting is
10852 			 * reflective, thus we will probably receive multi-
10853 			 * casts on those interfaces.
10854 			 * The ip_multirt_apply_membership() succeeds if the
10855 			 * operation succeeds on at least one interface.
10856 			 */
10857 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10858 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10859 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10860 			if (ire != NULL) {
10861 				if (ire->ire_flags & RTF_MULTIRT) {
10862 					error = ip_multirt_apply_membership(
10863 					    optfn, ire, connp, checkonly, group,
10864 					    fmode, INADDR_ANY, first_mp);
10865 					done = B_TRUE;
10866 				}
10867 				ire_refrele(ire);
10868 			}
10869 			if (!done) {
10870 				error = optfn(connp, checkonly, group, ifaddr,
10871 				    ifindexp, fmode, INADDR_ANY, first_mp);
10872 			}
10873 			if (error) {
10874 				/*
10875 				 * EINPROGRESS is a soft error, needs retry
10876 				 * so don't make *outlenp zero.
10877 				 */
10878 				if (error != EINPROGRESS)
10879 					*outlenp = 0;
10880 				return (error);
10881 			}
10882 			/* OK return - copy input buffer into output buffer */
10883 			if (invalp != outvalp) {
10884 				/* don't trust bcopy for identical src/dst */
10885 				bcopy(invalp, outvalp, inlen);
10886 			}
10887 			*outlenp = inlen;
10888 			return (0);
10889 		}
10890 		case IP_BLOCK_SOURCE:
10891 		case IP_UNBLOCK_SOURCE:
10892 		case IP_ADD_SOURCE_MEMBERSHIP:
10893 		case IP_DROP_SOURCE_MEMBERSHIP:
10894 		case MCAST_BLOCK_SOURCE:
10895 		case MCAST_UNBLOCK_SOURCE:
10896 		case MCAST_JOIN_SOURCE_GROUP:
10897 		case MCAST_LEAVE_SOURCE_GROUP: {
10898 			struct ip_mreq_source *imreqp;
10899 			struct group_source_req *gsreqp;
10900 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10901 			uint32_t ifindex = 0;
10902 			mcast_record_t fmode;
10903 			struct sockaddr_in *sin;
10904 			ire_t *ire;
10905 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10906 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10907 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10908 
10909 			switch (name) {
10910 			case IP_BLOCK_SOURCE:
10911 				mcast_opt = B_FALSE;
10912 				/* FALLTHRU */
10913 			case MCAST_BLOCK_SOURCE:
10914 				fmode = MODE_IS_EXCLUDE;
10915 				optfn = ip_opt_add_group;
10916 				break;
10917 
10918 			case IP_UNBLOCK_SOURCE:
10919 				mcast_opt = B_FALSE;
10920 				/* FALLTHRU */
10921 			case MCAST_UNBLOCK_SOURCE:
10922 				fmode = MODE_IS_EXCLUDE;
10923 				optfn = ip_opt_delete_group;
10924 				break;
10925 
10926 			case IP_ADD_SOURCE_MEMBERSHIP:
10927 				mcast_opt = B_FALSE;
10928 				/* FALLTHRU */
10929 			case MCAST_JOIN_SOURCE_GROUP:
10930 				fmode = MODE_IS_INCLUDE;
10931 				optfn = ip_opt_add_group;
10932 				break;
10933 
10934 			case IP_DROP_SOURCE_MEMBERSHIP:
10935 				mcast_opt = B_FALSE;
10936 				/* FALLTHRU */
10937 			case MCAST_LEAVE_SOURCE_GROUP:
10938 				fmode = MODE_IS_INCLUDE;
10939 				optfn = ip_opt_delete_group;
10940 				break;
10941 			}
10942 
10943 			if (mcast_opt) {
10944 				gsreqp = (struct group_source_req *)i1;
10945 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10946 					*outlenp = 0;
10947 					return (ENOPROTOOPT);
10948 				}
10949 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10950 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10951 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10952 				src = (ipaddr_t)sin->sin_addr.s_addr;
10953 				ifindex = gsreqp->gsr_interface;
10954 			} else {
10955 				imreqp = (struct ip_mreq_source *)i1;
10956 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10957 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10958 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10959 			}
10960 
10961 			/*
10962 			 * In the multirouting case, we need to replicate
10963 			 * the request as noted in the mcast cases above.
10964 			 */
10965 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10966 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10967 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10968 			if (ire != NULL) {
10969 				if (ire->ire_flags & RTF_MULTIRT) {
10970 					error = ip_multirt_apply_membership(
10971 					    optfn, ire, connp, checkonly, grp,
10972 					    fmode, src, first_mp);
10973 					done = B_TRUE;
10974 				}
10975 				ire_refrele(ire);
10976 			}
10977 			if (!done) {
10978 				error = optfn(connp, checkonly, grp, ifaddr,
10979 				    &ifindex, fmode, src, first_mp);
10980 			}
10981 			if (error != 0) {
10982 				/*
10983 				 * EINPROGRESS is a soft error, needs retry
10984 				 * so don't make *outlenp zero.
10985 				 */
10986 				if (error != EINPROGRESS)
10987 					*outlenp = 0;
10988 				return (error);
10989 			}
10990 			/* OK return - copy input buffer into output buffer */
10991 			if (invalp != outvalp) {
10992 				bcopy(invalp, outvalp, inlen);
10993 			}
10994 			*outlenp = inlen;
10995 			return (0);
10996 		}
10997 		case IP_SEC_OPT:
10998 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10999 			if (error != 0) {
11000 				*outlenp = 0;
11001 				return (error);
11002 			}
11003 			break;
11004 		case IP_HDRINCL:
11005 		case IP_OPTIONS:
11006 		case T_IP_OPTIONS:
11007 		case IP_TOS:
11008 		case T_IP_TOS:
11009 		case IP_TTL:
11010 		case IP_RECVDSTADDR:
11011 		case IP_RECVOPTS:
11012 			/* OK return - copy input buffer into output buffer */
11013 			if (invalp != outvalp) {
11014 				/* don't trust bcopy for identical src/dst */
11015 				bcopy(invalp, outvalp, inlen);
11016 			}
11017 			*outlenp = inlen;
11018 			return (0);
11019 		case IP_RECVIF:
11020 			/* Retrieve the inbound interface index */
11021 			if (!checkonly) {
11022 				mutex_enter(&connp->conn_lock);
11023 				connp->conn_recvif = *i1 ? 1 : 0;
11024 				mutex_exit(&connp->conn_lock);
11025 			}
11026 			break;	/* goto sizeof (int) option return */
11027 		case IP_RECVPKTINFO:
11028 			if (!checkonly) {
11029 				mutex_enter(&connp->conn_lock);
11030 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11031 				mutex_exit(&connp->conn_lock);
11032 			}
11033 			break;	/* goto sizeof (int) option return */
11034 		case IP_RECVSLLA:
11035 			/* Retrieve the source link layer address */
11036 			if (!checkonly) {
11037 				mutex_enter(&connp->conn_lock);
11038 				connp->conn_recvslla = *i1 ? 1 : 0;
11039 				mutex_exit(&connp->conn_lock);
11040 			}
11041 			break;	/* goto sizeof (int) option return */
11042 		case MRT_INIT:
11043 		case MRT_DONE:
11044 		case MRT_ADD_VIF:
11045 		case MRT_DEL_VIF:
11046 		case MRT_ADD_MFC:
11047 		case MRT_DEL_MFC:
11048 		case MRT_ASSERT:
11049 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11050 				*outlenp = 0;
11051 				return (error);
11052 			}
11053 			error = ip_mrouter_set((int)name, q, checkonly,
11054 			    (uchar_t *)invalp, inlen, first_mp);
11055 			if (error) {
11056 				*outlenp = 0;
11057 				return (error);
11058 			}
11059 			/* OK return - copy input buffer into output buffer */
11060 			if (invalp != outvalp) {
11061 				/* don't trust bcopy for identical src/dst */
11062 				bcopy(invalp, outvalp, inlen);
11063 			}
11064 			*outlenp = inlen;
11065 			return (0);
11066 		case IP_BOUND_IF:
11067 		case IP_DHCPINIT_IF:
11068 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11069 			    level, name, first_mp);
11070 			if (error != 0)
11071 				return (error);
11072 			break; 		/* goto sizeof (int) option return */
11073 
11074 		case IP_UNSPEC_SRC:
11075 			/* Allow sending with a zero source address */
11076 			if (!checkonly) {
11077 				mutex_enter(&connp->conn_lock);
11078 				connp->conn_unspec_src = *i1 ? 1 : 0;
11079 				mutex_exit(&connp->conn_lock);
11080 			}
11081 			break;	/* goto sizeof (int) option return */
11082 		default:
11083 			/*
11084 			 * "soft" error (negative)
11085 			 * option not handled at this level
11086 			 * Note: Do not modify *outlenp
11087 			 */
11088 			return (-EINVAL);
11089 		}
11090 		break;
11091 	case IPPROTO_IPV6:
11092 		switch (name) {
11093 		case IPV6_BOUND_IF:
11094 		case IPV6_BOUND_PIF:
11095 		case IPV6_DONTFAILOVER_IF:
11096 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11097 			    level, name, first_mp);
11098 			if (error != 0)
11099 				return (error);
11100 			break; 		/* goto sizeof (int) option return */
11101 
11102 		case IPV6_MULTICAST_IF:
11103 			/*
11104 			 * The only possible errors are EINPROGRESS and
11105 			 * EINVAL. EINPROGRESS will be restarted and is not
11106 			 * a hard error. We call this option on both V4 and V6
11107 			 * If both return EINVAL, then this call returns
11108 			 * EINVAL. If at least one of them succeeds we
11109 			 * return success.
11110 			 */
11111 			found = B_FALSE;
11112 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11113 			    level, name, first_mp);
11114 			if (error == EINPROGRESS)
11115 				return (error);
11116 			if (error == 0)
11117 				found = B_TRUE;
11118 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11119 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11120 			if (error == 0)
11121 				found = B_TRUE;
11122 			if (!found)
11123 				return (error);
11124 			break; 		/* goto sizeof (int) option return */
11125 
11126 		case IPV6_MULTICAST_HOPS:
11127 			/* Recorded in transport above IP */
11128 			break;	/* goto sizeof (int) option return */
11129 		case IPV6_MULTICAST_LOOP:
11130 			if (!checkonly) {
11131 				mutex_enter(&connp->conn_lock);
11132 				connp->conn_multicast_loop = *i1;
11133 				mutex_exit(&connp->conn_lock);
11134 			}
11135 			break;	/* goto sizeof (int) option return */
11136 		case IPV6_JOIN_GROUP:
11137 		case MCAST_JOIN_GROUP:
11138 		case IPV6_LEAVE_GROUP:
11139 		case MCAST_LEAVE_GROUP: {
11140 			struct ipv6_mreq *ip_mreqp;
11141 			struct group_req *greqp;
11142 			ire_t *ire;
11143 			boolean_t done = B_FALSE;
11144 			in6_addr_t groupv6;
11145 			uint32_t ifindex;
11146 			boolean_t mcast_opt = B_TRUE;
11147 			mcast_record_t fmode;
11148 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11149 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11150 
11151 			switch (name) {
11152 			case IPV6_JOIN_GROUP:
11153 				mcast_opt = B_FALSE;
11154 				/* FALLTHRU */
11155 			case MCAST_JOIN_GROUP:
11156 				fmode = MODE_IS_EXCLUDE;
11157 				optfn = ip_opt_add_group_v6;
11158 				break;
11159 
11160 			case IPV6_LEAVE_GROUP:
11161 				mcast_opt = B_FALSE;
11162 				/* FALLTHRU */
11163 			case MCAST_LEAVE_GROUP:
11164 				fmode = MODE_IS_INCLUDE;
11165 				optfn = ip_opt_delete_group_v6;
11166 				break;
11167 			}
11168 
11169 			if (mcast_opt) {
11170 				struct sockaddr_in *sin;
11171 				struct sockaddr_in6 *sin6;
11172 				greqp = (struct group_req *)i1;
11173 				if (greqp->gr_group.ss_family == AF_INET) {
11174 					sin = (struct sockaddr_in *)
11175 					    &(greqp->gr_group);
11176 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11177 					    &groupv6);
11178 				} else {
11179 					sin6 = (struct sockaddr_in6 *)
11180 					    &(greqp->gr_group);
11181 					groupv6 = sin6->sin6_addr;
11182 				}
11183 				ifindex = greqp->gr_interface;
11184 			} else {
11185 				ip_mreqp = (struct ipv6_mreq *)i1;
11186 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11187 				ifindex = ip_mreqp->ipv6mr_interface;
11188 			}
11189 			/*
11190 			 * In the multirouting case, we need to replicate
11191 			 * the request on all interfaces that will take part
11192 			 * in replication.  We do so because multirouting is
11193 			 * reflective, thus we will probably receive multi-
11194 			 * casts on those interfaces.
11195 			 * The ip_multirt_apply_membership_v6() succeeds if
11196 			 * the operation succeeds on at least one interface.
11197 			 */
11198 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11199 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11200 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11201 			if (ire != NULL) {
11202 				if (ire->ire_flags & RTF_MULTIRT) {
11203 					error = ip_multirt_apply_membership_v6(
11204 					    optfn, ire, connp, checkonly,
11205 					    &groupv6, fmode, &ipv6_all_zeros,
11206 					    first_mp);
11207 					done = B_TRUE;
11208 				}
11209 				ire_refrele(ire);
11210 			}
11211 			if (!done) {
11212 				error = optfn(connp, checkonly, &groupv6,
11213 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11214 			}
11215 			if (error) {
11216 				/*
11217 				 * EINPROGRESS is a soft error, needs retry
11218 				 * so don't make *outlenp zero.
11219 				 */
11220 				if (error != EINPROGRESS)
11221 					*outlenp = 0;
11222 				return (error);
11223 			}
11224 			/* OK return - copy input buffer into output buffer */
11225 			if (invalp != outvalp) {
11226 				/* don't trust bcopy for identical src/dst */
11227 				bcopy(invalp, outvalp, inlen);
11228 			}
11229 			*outlenp = inlen;
11230 			return (0);
11231 		}
11232 		case MCAST_BLOCK_SOURCE:
11233 		case MCAST_UNBLOCK_SOURCE:
11234 		case MCAST_JOIN_SOURCE_GROUP:
11235 		case MCAST_LEAVE_SOURCE_GROUP: {
11236 			struct group_source_req *gsreqp;
11237 			in6_addr_t v6grp, v6src;
11238 			uint32_t ifindex;
11239 			mcast_record_t fmode;
11240 			ire_t *ire;
11241 			boolean_t done = B_FALSE;
11242 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11243 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11244 
11245 			switch (name) {
11246 			case MCAST_BLOCK_SOURCE:
11247 				fmode = MODE_IS_EXCLUDE;
11248 				optfn = ip_opt_add_group_v6;
11249 				break;
11250 			case MCAST_UNBLOCK_SOURCE:
11251 				fmode = MODE_IS_EXCLUDE;
11252 				optfn = ip_opt_delete_group_v6;
11253 				break;
11254 			case MCAST_JOIN_SOURCE_GROUP:
11255 				fmode = MODE_IS_INCLUDE;
11256 				optfn = ip_opt_add_group_v6;
11257 				break;
11258 			case MCAST_LEAVE_SOURCE_GROUP:
11259 				fmode = MODE_IS_INCLUDE;
11260 				optfn = ip_opt_delete_group_v6;
11261 				break;
11262 			}
11263 
11264 			gsreqp = (struct group_source_req *)i1;
11265 			ifindex = gsreqp->gsr_interface;
11266 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11267 				struct sockaddr_in *s;
11268 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11269 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11270 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11271 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11272 			} else {
11273 				struct sockaddr_in6 *s6;
11274 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11275 				v6grp = s6->sin6_addr;
11276 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11277 				v6src = s6->sin6_addr;
11278 			}
11279 
11280 			/*
11281 			 * In the multirouting case, we need to replicate
11282 			 * the request as noted in the mcast cases above.
11283 			 */
11284 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11285 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11286 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11287 			if (ire != NULL) {
11288 				if (ire->ire_flags & RTF_MULTIRT) {
11289 					error = ip_multirt_apply_membership_v6(
11290 					    optfn, ire, connp, checkonly,
11291 					    &v6grp, fmode, &v6src, first_mp);
11292 					done = B_TRUE;
11293 				}
11294 				ire_refrele(ire);
11295 			}
11296 			if (!done) {
11297 				error = optfn(connp, checkonly, &v6grp,
11298 				    ifindex, fmode, &v6src, first_mp);
11299 			}
11300 			if (error != 0) {
11301 				/*
11302 				 * EINPROGRESS is a soft error, needs retry
11303 				 * so don't make *outlenp zero.
11304 				 */
11305 				if (error != EINPROGRESS)
11306 					*outlenp = 0;
11307 				return (error);
11308 			}
11309 			/* OK return - copy input buffer into output buffer */
11310 			if (invalp != outvalp) {
11311 				bcopy(invalp, outvalp, inlen);
11312 			}
11313 			*outlenp = inlen;
11314 			return (0);
11315 		}
11316 		case IPV6_UNICAST_HOPS:
11317 			/* Recorded in transport above IP */
11318 			break;	/* goto sizeof (int) option return */
11319 		case IPV6_UNSPEC_SRC:
11320 			/* Allow sending with a zero source address */
11321 			if (!checkonly) {
11322 				mutex_enter(&connp->conn_lock);
11323 				connp->conn_unspec_src = *i1 ? 1 : 0;
11324 				mutex_exit(&connp->conn_lock);
11325 			}
11326 			break;	/* goto sizeof (int) option return */
11327 		case IPV6_RECVPKTINFO:
11328 			if (!checkonly) {
11329 				mutex_enter(&connp->conn_lock);
11330 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11331 				mutex_exit(&connp->conn_lock);
11332 			}
11333 			break;	/* goto sizeof (int) option return */
11334 		case IPV6_RECVTCLASS:
11335 			if (!checkonly) {
11336 				if (*i1 < 0 || *i1 > 1) {
11337 					return (EINVAL);
11338 				}
11339 				mutex_enter(&connp->conn_lock);
11340 				connp->conn_ipv6_recvtclass = *i1;
11341 				mutex_exit(&connp->conn_lock);
11342 			}
11343 			break;
11344 		case IPV6_RECVPATHMTU:
11345 			if (!checkonly) {
11346 				if (*i1 < 0 || *i1 > 1) {
11347 					return (EINVAL);
11348 				}
11349 				mutex_enter(&connp->conn_lock);
11350 				connp->conn_ipv6_recvpathmtu = *i1;
11351 				mutex_exit(&connp->conn_lock);
11352 			}
11353 			break;
11354 		case IPV6_RECVHOPLIMIT:
11355 			if (!checkonly) {
11356 				mutex_enter(&connp->conn_lock);
11357 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11358 				mutex_exit(&connp->conn_lock);
11359 			}
11360 			break;	/* goto sizeof (int) option return */
11361 		case IPV6_RECVHOPOPTS:
11362 			if (!checkonly) {
11363 				mutex_enter(&connp->conn_lock);
11364 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11365 				mutex_exit(&connp->conn_lock);
11366 			}
11367 			break;	/* goto sizeof (int) option return */
11368 		case IPV6_RECVDSTOPTS:
11369 			if (!checkonly) {
11370 				mutex_enter(&connp->conn_lock);
11371 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11372 				mutex_exit(&connp->conn_lock);
11373 			}
11374 			break;	/* goto sizeof (int) option return */
11375 		case IPV6_RECVRTHDR:
11376 			if (!checkonly) {
11377 				mutex_enter(&connp->conn_lock);
11378 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11379 				mutex_exit(&connp->conn_lock);
11380 			}
11381 			break;	/* goto sizeof (int) option return */
11382 		case IPV6_RECVRTHDRDSTOPTS:
11383 			if (!checkonly) {
11384 				mutex_enter(&connp->conn_lock);
11385 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11386 				mutex_exit(&connp->conn_lock);
11387 			}
11388 			break;	/* goto sizeof (int) option return */
11389 		case IPV6_PKTINFO:
11390 			if (inlen == 0)
11391 				return (-EINVAL);	/* clearing option */
11392 			error = ip6_set_pktinfo(cr, connp,
11393 			    (struct in6_pktinfo *)invalp, first_mp);
11394 			if (error != 0)
11395 				*outlenp = 0;
11396 			else
11397 				*outlenp = inlen;
11398 			return (error);
11399 		case IPV6_NEXTHOP: {
11400 			struct sockaddr_in6 *sin6;
11401 
11402 			/* Verify that the nexthop is reachable */
11403 			if (inlen == 0)
11404 				return (-EINVAL);	/* clearing option */
11405 
11406 			sin6 = (struct sockaddr_in6 *)invalp;
11407 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11408 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11409 			    NULL, MATCH_IRE_DEFAULT, ipst);
11410 
11411 			if (ire == NULL) {
11412 				*outlenp = 0;
11413 				return (EHOSTUNREACH);
11414 			}
11415 			ire_refrele(ire);
11416 			return (-EINVAL);
11417 		}
11418 		case IPV6_SEC_OPT:
11419 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11420 			if (error != 0) {
11421 				*outlenp = 0;
11422 				return (error);
11423 			}
11424 			break;
11425 		case IPV6_SRC_PREFERENCES: {
11426 			/*
11427 			 * This is implemented strictly in the ip module
11428 			 * (here and in tcp_opt_*() to accomodate tcp
11429 			 * sockets).  Modules above ip pass this option
11430 			 * down here since ip is the only one that needs to
11431 			 * be aware of source address preferences.
11432 			 *
11433 			 * This socket option only affects connected
11434 			 * sockets that haven't already bound to a specific
11435 			 * IPv6 address.  In other words, sockets that
11436 			 * don't call bind() with an address other than the
11437 			 * unspecified address and that call connect().
11438 			 * ip_bind_connected_v6() passes these preferences
11439 			 * to the ipif_select_source_v6() function.
11440 			 */
11441 			if (inlen != sizeof (uint32_t))
11442 				return (EINVAL);
11443 			error = ip6_set_src_preferences(connp,
11444 			    *(uint32_t *)invalp);
11445 			if (error != 0) {
11446 				*outlenp = 0;
11447 				return (error);
11448 			} else {
11449 				*outlenp = sizeof (uint32_t);
11450 			}
11451 			break;
11452 		}
11453 		case IPV6_V6ONLY:
11454 			if (*i1 < 0 || *i1 > 1) {
11455 				return (EINVAL);
11456 			}
11457 			mutex_enter(&connp->conn_lock);
11458 			connp->conn_ipv6_v6only = *i1;
11459 			mutex_exit(&connp->conn_lock);
11460 			break;
11461 		default:
11462 			return (-EINVAL);
11463 		}
11464 		break;
11465 	default:
11466 		/*
11467 		 * "soft" error (negative)
11468 		 * option not handled at this level
11469 		 * Note: Do not modify *outlenp
11470 		 */
11471 		return (-EINVAL);
11472 	}
11473 	/*
11474 	 * Common case of return from an option that is sizeof (int)
11475 	 */
11476 	*(int *)outvalp = *i1;
11477 	*outlenp = sizeof (int);
11478 	return (0);
11479 }
11480 
11481 /*
11482  * This routine gets default values of certain options whose default
11483  * values are maintained by protocol specific code
11484  */
11485 /* ARGSUSED */
11486 int
11487 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11488 {
11489 	int *i1 = (int *)ptr;
11490 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11491 
11492 	switch (level) {
11493 	case IPPROTO_IP:
11494 		switch (name) {
11495 		case IP_MULTICAST_TTL:
11496 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11497 			return (sizeof (uchar_t));
11498 		case IP_MULTICAST_LOOP:
11499 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11500 			return (sizeof (uchar_t));
11501 		default:
11502 			return (-1);
11503 		}
11504 	case IPPROTO_IPV6:
11505 		switch (name) {
11506 		case IPV6_UNICAST_HOPS:
11507 			*i1 = ipst->ips_ipv6_def_hops;
11508 			return (sizeof (int));
11509 		case IPV6_MULTICAST_HOPS:
11510 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11511 			return (sizeof (int));
11512 		case IPV6_MULTICAST_LOOP:
11513 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11514 			return (sizeof (int));
11515 		case IPV6_V6ONLY:
11516 			*i1 = 1;
11517 			return (sizeof (int));
11518 		default:
11519 			return (-1);
11520 		}
11521 	default:
11522 		return (-1);
11523 	}
11524 	/* NOTREACHED */
11525 }
11526 
11527 /*
11528  * Given a destination address and a pointer to where to put the information
11529  * this routine fills in the mtuinfo.
11530  */
11531 int
11532 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11533     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11534 {
11535 	ire_t *ire;
11536 	ip_stack_t	*ipst = ns->netstack_ip;
11537 
11538 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11539 		return (-1);
11540 
11541 	bzero(mtuinfo, sizeof (*mtuinfo));
11542 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11543 	mtuinfo->ip6m_addr.sin6_port = port;
11544 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11545 
11546 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11547 	if (ire != NULL) {
11548 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11549 		ire_refrele(ire);
11550 	} else {
11551 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11552 	}
11553 	return (sizeof (struct ip6_mtuinfo));
11554 }
11555 
11556 /*
11557  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11558  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11559  * isn't.  This doesn't matter as the error checking is done properly for the
11560  * other MRT options coming in through ip_opt_set.
11561  */
11562 int
11563 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11564 {
11565 	conn_t		*connp = Q_TO_CONN(q);
11566 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11567 
11568 	switch (level) {
11569 	case IPPROTO_IP:
11570 		switch (name) {
11571 		case MRT_VERSION:
11572 		case MRT_ASSERT:
11573 			(void) ip_mrouter_get(name, q, ptr);
11574 			return (sizeof (int));
11575 		case IP_SEC_OPT:
11576 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11577 		case IP_NEXTHOP:
11578 			if (connp->conn_nexthop_set) {
11579 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11580 				return (sizeof (ipaddr_t));
11581 			} else
11582 				return (0);
11583 		case IP_RECVPKTINFO:
11584 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11585 			return (sizeof (int));
11586 		default:
11587 			break;
11588 		}
11589 		break;
11590 	case IPPROTO_IPV6:
11591 		switch (name) {
11592 		case IPV6_SEC_OPT:
11593 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11594 		case IPV6_SRC_PREFERENCES: {
11595 			return (ip6_get_src_preferences(connp,
11596 			    (uint32_t *)ptr));
11597 		}
11598 		case IPV6_V6ONLY:
11599 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11600 			return (sizeof (int));
11601 		case IPV6_PATHMTU:
11602 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11603 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11604 		default:
11605 			break;
11606 		}
11607 		break;
11608 	default:
11609 		break;
11610 	}
11611 	return (-1);
11612 }
11613 
11614 /* Named Dispatch routine to get a current value out of our parameter table. */
11615 /* ARGSUSED */
11616 static int
11617 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11618 {
11619 	ipparam_t *ippa = (ipparam_t *)cp;
11620 
11621 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11622 	return (0);
11623 }
11624 
11625 /* ARGSUSED */
11626 static int
11627 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11628 {
11629 
11630 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11631 	return (0);
11632 }
11633 
11634 /*
11635  * Set ip{,6}_forwarding values.  This means walking through all of the
11636  * ill's and toggling their forwarding values.
11637  */
11638 /* ARGSUSED */
11639 static int
11640 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11641 {
11642 	long new_value;
11643 	int *forwarding_value = (int *)cp;
11644 	ill_t *ill;
11645 	boolean_t isv6;
11646 	ill_walk_context_t ctx;
11647 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11648 
11649 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11650 
11651 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11652 	    new_value < 0 || new_value > 1) {
11653 		return (EINVAL);
11654 	}
11655 
11656 	*forwarding_value = new_value;
11657 
11658 	/*
11659 	 * Regardless of the current value of ip_forwarding, set all per-ill
11660 	 * values of ip_forwarding to the value being set.
11661 	 *
11662 	 * Bring all the ill's up to date with the new global value.
11663 	 */
11664 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11665 
11666 	if (isv6)
11667 		ill = ILL_START_WALK_V6(&ctx, ipst);
11668 	else
11669 		ill = ILL_START_WALK_V4(&ctx, ipst);
11670 
11671 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11672 		(void) ill_forward_set(ill, new_value != 0);
11673 
11674 	rw_exit(&ipst->ips_ill_g_lock);
11675 	return (0);
11676 }
11677 
11678 /*
11679  * Walk through the param array specified registering each element with the
11680  * Named Dispatch handler. This is called only during init. So it is ok
11681  * not to acquire any locks
11682  */
11683 static boolean_t
11684 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11685     ipndp_t *ipnd, size_t ipnd_cnt)
11686 {
11687 	for (; ippa_cnt-- > 0; ippa++) {
11688 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11689 			if (!nd_load(ndp, ippa->ip_param_name,
11690 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11691 				nd_free(ndp);
11692 				return (B_FALSE);
11693 			}
11694 		}
11695 	}
11696 
11697 	for (; ipnd_cnt-- > 0; ipnd++) {
11698 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11699 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11700 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11701 			    ipnd->ip_ndp_data)) {
11702 				nd_free(ndp);
11703 				return (B_FALSE);
11704 			}
11705 		}
11706 	}
11707 
11708 	return (B_TRUE);
11709 }
11710 
11711 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11712 /* ARGSUSED */
11713 static int
11714 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11715 {
11716 	long		new_value;
11717 	ipparam_t	*ippa = (ipparam_t *)cp;
11718 
11719 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11720 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11721 		return (EINVAL);
11722 	}
11723 	ippa->ip_param_value = new_value;
11724 	return (0);
11725 }
11726 
11727 /*
11728  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11729  * When an ipf is passed here for the first time, if
11730  * we already have in-order fragments on the queue, we convert from the fast-
11731  * path reassembly scheme to the hard-case scheme.  From then on, additional
11732  * fragments are reassembled here.  We keep track of the start and end offsets
11733  * of each piece, and the number of holes in the chain.  When the hole count
11734  * goes to zero, we are done!
11735  *
11736  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11737  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11738  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11739  * after the call to ip_reassemble().
11740  */
11741 int
11742 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11743     size_t msg_len)
11744 {
11745 	uint_t	end;
11746 	mblk_t	*next_mp;
11747 	mblk_t	*mp1;
11748 	uint_t	offset;
11749 	boolean_t incr_dups = B_TRUE;
11750 	boolean_t offset_zero_seen = B_FALSE;
11751 	boolean_t pkt_boundary_checked = B_FALSE;
11752 
11753 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11754 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11755 
11756 	/* Add in byte count */
11757 	ipf->ipf_count += msg_len;
11758 	if (ipf->ipf_end) {
11759 		/*
11760 		 * We were part way through in-order reassembly, but now there
11761 		 * is a hole.  We walk through messages already queued, and
11762 		 * mark them for hard case reassembly.  We know that up till
11763 		 * now they were in order starting from offset zero.
11764 		 */
11765 		offset = 0;
11766 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11767 			IP_REASS_SET_START(mp1, offset);
11768 			if (offset == 0) {
11769 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11770 				offset = -ipf->ipf_nf_hdr_len;
11771 			}
11772 			offset += mp1->b_wptr - mp1->b_rptr;
11773 			IP_REASS_SET_END(mp1, offset);
11774 		}
11775 		/* One hole at the end. */
11776 		ipf->ipf_hole_cnt = 1;
11777 		/* Brand it as a hard case, forever. */
11778 		ipf->ipf_end = 0;
11779 	}
11780 	/* Walk through all the new pieces. */
11781 	do {
11782 		end = start + (mp->b_wptr - mp->b_rptr);
11783 		/*
11784 		 * If start is 0, decrease 'end' only for the first mblk of
11785 		 * the fragment. Otherwise 'end' can get wrong value in the
11786 		 * second pass of the loop if first mblk is exactly the
11787 		 * size of ipf_nf_hdr_len.
11788 		 */
11789 		if (start == 0 && !offset_zero_seen) {
11790 			/* First segment */
11791 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11792 			end -= ipf->ipf_nf_hdr_len;
11793 			offset_zero_seen = B_TRUE;
11794 		}
11795 		next_mp = mp->b_cont;
11796 		/*
11797 		 * We are checking to see if there is any interesing data
11798 		 * to process.  If there isn't and the mblk isn't the
11799 		 * one which carries the unfragmentable header then we
11800 		 * drop it.  It's possible to have just the unfragmentable
11801 		 * header come through without any data.  That needs to be
11802 		 * saved.
11803 		 *
11804 		 * If the assert at the top of this function holds then the
11805 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11806 		 * is infrequently traveled enough that the test is left in
11807 		 * to protect against future code changes which break that
11808 		 * invariant.
11809 		 */
11810 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11811 			/* Empty.  Blast it. */
11812 			IP_REASS_SET_START(mp, 0);
11813 			IP_REASS_SET_END(mp, 0);
11814 			/*
11815 			 * If the ipf points to the mblk we are about to free,
11816 			 * update ipf to point to the next mblk (or NULL
11817 			 * if none).
11818 			 */
11819 			if (ipf->ipf_mp->b_cont == mp)
11820 				ipf->ipf_mp->b_cont = next_mp;
11821 			freeb(mp);
11822 			continue;
11823 		}
11824 		mp->b_cont = NULL;
11825 		IP_REASS_SET_START(mp, start);
11826 		IP_REASS_SET_END(mp, end);
11827 		if (!ipf->ipf_tail_mp) {
11828 			ipf->ipf_tail_mp = mp;
11829 			ipf->ipf_mp->b_cont = mp;
11830 			if (start == 0 || !more) {
11831 				ipf->ipf_hole_cnt = 1;
11832 				/*
11833 				 * if the first fragment comes in more than one
11834 				 * mblk, this loop will be executed for each
11835 				 * mblk. Need to adjust hole count so exiting
11836 				 * this routine will leave hole count at 1.
11837 				 */
11838 				if (next_mp)
11839 					ipf->ipf_hole_cnt++;
11840 			} else
11841 				ipf->ipf_hole_cnt = 2;
11842 			continue;
11843 		} else if (ipf->ipf_last_frag_seen && !more &&
11844 		    !pkt_boundary_checked) {
11845 			/*
11846 			 * We check datagram boundary only if this fragment
11847 			 * claims to be the last fragment and we have seen a
11848 			 * last fragment in the past too. We do this only
11849 			 * once for a given fragment.
11850 			 *
11851 			 * start cannot be 0 here as fragments with start=0
11852 			 * and MF=0 gets handled as a complete packet. These
11853 			 * fragments should not reach here.
11854 			 */
11855 
11856 			if (start + msgdsize(mp) !=
11857 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11858 				/*
11859 				 * We have two fragments both of which claim
11860 				 * to be the last fragment but gives conflicting
11861 				 * information about the whole datagram size.
11862 				 * Something fishy is going on. Drop the
11863 				 * fragment and free up the reassembly list.
11864 				 */
11865 				return (IP_REASS_FAILED);
11866 			}
11867 
11868 			/*
11869 			 * We shouldn't come to this code block again for this
11870 			 * particular fragment.
11871 			 */
11872 			pkt_boundary_checked = B_TRUE;
11873 		}
11874 
11875 		/* New stuff at or beyond tail? */
11876 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11877 		if (start >= offset) {
11878 			if (ipf->ipf_last_frag_seen) {
11879 				/* current fragment is beyond last fragment */
11880 				return (IP_REASS_FAILED);
11881 			}
11882 			/* Link it on end. */
11883 			ipf->ipf_tail_mp->b_cont = mp;
11884 			ipf->ipf_tail_mp = mp;
11885 			if (more) {
11886 				if (start != offset)
11887 					ipf->ipf_hole_cnt++;
11888 			} else if (start == offset && next_mp == NULL)
11889 					ipf->ipf_hole_cnt--;
11890 			continue;
11891 		}
11892 		mp1 = ipf->ipf_mp->b_cont;
11893 		offset = IP_REASS_START(mp1);
11894 		/* New stuff at the front? */
11895 		if (start < offset) {
11896 			if (start == 0) {
11897 				if (end >= offset) {
11898 					/* Nailed the hole at the begining. */
11899 					ipf->ipf_hole_cnt--;
11900 				}
11901 			} else if (end < offset) {
11902 				/*
11903 				 * A hole, stuff, and a hole where there used
11904 				 * to be just a hole.
11905 				 */
11906 				ipf->ipf_hole_cnt++;
11907 			}
11908 			mp->b_cont = mp1;
11909 			/* Check for overlap. */
11910 			while (end > offset) {
11911 				if (end < IP_REASS_END(mp1)) {
11912 					mp->b_wptr -= end - offset;
11913 					IP_REASS_SET_END(mp, offset);
11914 					BUMP_MIB(ill->ill_ip_mib,
11915 					    ipIfStatsReasmPartDups);
11916 					break;
11917 				}
11918 				/* Did we cover another hole? */
11919 				if ((mp1->b_cont &&
11920 				    IP_REASS_END(mp1) !=
11921 				    IP_REASS_START(mp1->b_cont) &&
11922 				    end >= IP_REASS_START(mp1->b_cont)) ||
11923 				    (!ipf->ipf_last_frag_seen && !more)) {
11924 					ipf->ipf_hole_cnt--;
11925 				}
11926 				/* Clip out mp1. */
11927 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11928 					/*
11929 					 * After clipping out mp1, this guy
11930 					 * is now hanging off the end.
11931 					 */
11932 					ipf->ipf_tail_mp = mp;
11933 				}
11934 				IP_REASS_SET_START(mp1, 0);
11935 				IP_REASS_SET_END(mp1, 0);
11936 				/* Subtract byte count */
11937 				ipf->ipf_count -= mp1->b_datap->db_lim -
11938 				    mp1->b_datap->db_base;
11939 				freeb(mp1);
11940 				BUMP_MIB(ill->ill_ip_mib,
11941 				    ipIfStatsReasmPartDups);
11942 				mp1 = mp->b_cont;
11943 				if (!mp1)
11944 					break;
11945 				offset = IP_REASS_START(mp1);
11946 			}
11947 			ipf->ipf_mp->b_cont = mp;
11948 			continue;
11949 		}
11950 		/*
11951 		 * The new piece starts somewhere between the start of the head
11952 		 * and before the end of the tail.
11953 		 */
11954 		for (; mp1; mp1 = mp1->b_cont) {
11955 			offset = IP_REASS_END(mp1);
11956 			if (start < offset) {
11957 				if (end <= offset) {
11958 					/* Nothing new. */
11959 					IP_REASS_SET_START(mp, 0);
11960 					IP_REASS_SET_END(mp, 0);
11961 					/* Subtract byte count */
11962 					ipf->ipf_count -= mp->b_datap->db_lim -
11963 					    mp->b_datap->db_base;
11964 					if (incr_dups) {
11965 						ipf->ipf_num_dups++;
11966 						incr_dups = B_FALSE;
11967 					}
11968 					freeb(mp);
11969 					BUMP_MIB(ill->ill_ip_mib,
11970 					    ipIfStatsReasmDuplicates);
11971 					break;
11972 				}
11973 				/*
11974 				 * Trim redundant stuff off beginning of new
11975 				 * piece.
11976 				 */
11977 				IP_REASS_SET_START(mp, offset);
11978 				mp->b_rptr += offset - start;
11979 				BUMP_MIB(ill->ill_ip_mib,
11980 				    ipIfStatsReasmPartDups);
11981 				start = offset;
11982 				if (!mp1->b_cont) {
11983 					/*
11984 					 * After trimming, this guy is now
11985 					 * hanging off the end.
11986 					 */
11987 					mp1->b_cont = mp;
11988 					ipf->ipf_tail_mp = mp;
11989 					if (!more) {
11990 						ipf->ipf_hole_cnt--;
11991 					}
11992 					break;
11993 				}
11994 			}
11995 			if (start >= IP_REASS_START(mp1->b_cont))
11996 				continue;
11997 			/* Fill a hole */
11998 			if (start > offset)
11999 				ipf->ipf_hole_cnt++;
12000 			mp->b_cont = mp1->b_cont;
12001 			mp1->b_cont = mp;
12002 			mp1 = mp->b_cont;
12003 			offset = IP_REASS_START(mp1);
12004 			if (end >= offset) {
12005 				ipf->ipf_hole_cnt--;
12006 				/* Check for overlap. */
12007 				while (end > offset) {
12008 					if (end < IP_REASS_END(mp1)) {
12009 						mp->b_wptr -= end - offset;
12010 						IP_REASS_SET_END(mp, offset);
12011 						/*
12012 						 * TODO we might bump
12013 						 * this up twice if there is
12014 						 * overlap at both ends.
12015 						 */
12016 						BUMP_MIB(ill->ill_ip_mib,
12017 						    ipIfStatsReasmPartDups);
12018 						break;
12019 					}
12020 					/* Did we cover another hole? */
12021 					if ((mp1->b_cont &&
12022 					    IP_REASS_END(mp1)
12023 					    != IP_REASS_START(mp1->b_cont) &&
12024 					    end >=
12025 					    IP_REASS_START(mp1->b_cont)) ||
12026 					    (!ipf->ipf_last_frag_seen &&
12027 					    !more)) {
12028 						ipf->ipf_hole_cnt--;
12029 					}
12030 					/* Clip out mp1. */
12031 					if ((mp->b_cont = mp1->b_cont) ==
12032 					    NULL) {
12033 						/*
12034 						 * After clipping out mp1,
12035 						 * this guy is now hanging
12036 						 * off the end.
12037 						 */
12038 						ipf->ipf_tail_mp = mp;
12039 					}
12040 					IP_REASS_SET_START(mp1, 0);
12041 					IP_REASS_SET_END(mp1, 0);
12042 					/* Subtract byte count */
12043 					ipf->ipf_count -=
12044 					    mp1->b_datap->db_lim -
12045 					    mp1->b_datap->db_base;
12046 					freeb(mp1);
12047 					BUMP_MIB(ill->ill_ip_mib,
12048 					    ipIfStatsReasmPartDups);
12049 					mp1 = mp->b_cont;
12050 					if (!mp1)
12051 						break;
12052 					offset = IP_REASS_START(mp1);
12053 				}
12054 			}
12055 			break;
12056 		}
12057 	} while (start = end, mp = next_mp);
12058 
12059 	/* Fragment just processed could be the last one. Remember this fact */
12060 	if (!more)
12061 		ipf->ipf_last_frag_seen = B_TRUE;
12062 
12063 	/* Still got holes? */
12064 	if (ipf->ipf_hole_cnt)
12065 		return (IP_REASS_PARTIAL);
12066 	/* Clean up overloaded fields to avoid upstream disasters. */
12067 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12068 		IP_REASS_SET_START(mp1, 0);
12069 		IP_REASS_SET_END(mp1, 0);
12070 	}
12071 	return (IP_REASS_COMPLETE);
12072 }
12073 
12074 /*
12075  * ipsec processing for the fast path, used for input UDP Packets
12076  * Returns true if ready for passup to UDP.
12077  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
12078  * was an ESP-in-UDP packet, etc.).
12079  */
12080 static boolean_t
12081 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12082     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
12083 {
12084 	uint32_t	ill_index;
12085 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12086 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12087 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12088 	udp_t		*udp = connp->conn_udp;
12089 
12090 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12091 	/* The ill_index of the incoming ILL */
12092 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12093 
12094 	/* pass packet up to the transport */
12095 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12096 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12097 		    NULL, mctl_present);
12098 		if (*first_mpp == NULL) {
12099 			return (B_FALSE);
12100 		}
12101 	}
12102 
12103 	/* Initiate IPPF processing for fastpath UDP */
12104 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12105 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12106 		if (*mpp == NULL) {
12107 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12108 			    "deferred/dropped during IPPF processing\n"));
12109 			return (B_FALSE);
12110 		}
12111 	}
12112 	/*
12113 	 * Remove 0-spi if it's 0, or move everything behind
12114 	 * the UDP header over it and forward to ESP via
12115 	 * ip_proto_input().
12116 	 */
12117 	if (udp->udp_nat_t_endpoint) {
12118 		if (mctl_present) {
12119 			/* mctl_present *shouldn't* happen. */
12120 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
12121 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
12122 			    &ipss->ipsec_dropper);
12123 			*first_mpp = NULL;
12124 			return (B_FALSE);
12125 		}
12126 
12127 		/* "ill" is "recv_ill" in actuality. */
12128 		if (!zero_spi_check(q, *mpp, ire, ill, ipss))
12129 			return (B_FALSE);
12130 
12131 		/* Else continue like a normal UDP packet. */
12132 	}
12133 
12134 	/*
12135 	 * We make the checks as below since we are in the fast path
12136 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12137 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12138 	 */
12139 	if (connp->conn_recvif || connp->conn_recvslla ||
12140 	    connp->conn_ip_recvpktinfo) {
12141 		if (connp->conn_recvif) {
12142 			in_flags = IPF_RECVIF;
12143 		}
12144 		/*
12145 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12146 		 * so the flag passed to ip_add_info is based on IP version
12147 		 * of connp.
12148 		 */
12149 		if (connp->conn_ip_recvpktinfo) {
12150 			if (connp->conn_af_isv6) {
12151 				/*
12152 				 * V6 only needs index
12153 				 */
12154 				in_flags |= IPF_RECVIF;
12155 			} else {
12156 				/*
12157 				 * V4 needs index + matching address.
12158 				 */
12159 				in_flags |= IPF_RECVADDR;
12160 			}
12161 		}
12162 		if (connp->conn_recvslla) {
12163 			in_flags |= IPF_RECVSLLA;
12164 		}
12165 		/*
12166 		 * since in_flags are being set ill will be
12167 		 * referenced in ip_add_info, so it better not
12168 		 * be NULL.
12169 		 */
12170 		/*
12171 		 * the actual data will be contained in b_cont
12172 		 * upon successful return of the following call.
12173 		 * If the call fails then the original mblk is
12174 		 * returned.
12175 		 */
12176 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12177 		    ipst);
12178 	}
12179 
12180 	return (B_TRUE);
12181 }
12182 
12183 /*
12184  * Fragmentation reassembly.  Each ILL has a hash table for
12185  * queuing packets undergoing reassembly for all IPIFs
12186  * associated with the ILL.  The hash is based on the packet
12187  * IP ident field.  The ILL frag hash table was allocated
12188  * as a timer block at the time the ILL was created.  Whenever
12189  * there is anything on the reassembly queue, the timer will
12190  * be running.  Returns B_TRUE if successful else B_FALSE;
12191  * frees mp on failure.
12192  */
12193 static boolean_t
12194 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12195     uint32_t *cksum_val, uint16_t *cksum_flags)
12196 {
12197 	uint32_t	frag_offset_flags;
12198 	ill_t		*ill = (ill_t *)q->q_ptr;
12199 	mblk_t		*mp = *mpp;
12200 	mblk_t		*t_mp;
12201 	ipaddr_t	dst;
12202 	uint8_t		proto = ipha->ipha_protocol;
12203 	uint32_t	sum_val;
12204 	uint16_t	sum_flags;
12205 	ipf_t		*ipf;
12206 	ipf_t		**ipfp;
12207 	ipfb_t		*ipfb;
12208 	uint16_t	ident;
12209 	uint32_t	offset;
12210 	ipaddr_t	src;
12211 	uint_t		hdr_length;
12212 	uint32_t	end;
12213 	mblk_t		*mp1;
12214 	mblk_t		*tail_mp;
12215 	size_t		count;
12216 	size_t		msg_len;
12217 	uint8_t		ecn_info = 0;
12218 	uint32_t	packet_size;
12219 	boolean_t	pruned = B_FALSE;
12220 	ip_stack_t *ipst = ill->ill_ipst;
12221 
12222 	if (cksum_val != NULL)
12223 		*cksum_val = 0;
12224 	if (cksum_flags != NULL)
12225 		*cksum_flags = 0;
12226 
12227 	/*
12228 	 * Drop the fragmented as early as possible, if
12229 	 * we don't have resource(s) to re-assemble.
12230 	 */
12231 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12232 		freemsg(mp);
12233 		return (B_FALSE);
12234 	}
12235 
12236 	/* Check for fragmentation offset; return if there's none */
12237 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12238 	    (IPH_MF | IPH_OFFSET)) == 0)
12239 		return (B_TRUE);
12240 
12241 	/*
12242 	 * We utilize hardware computed checksum info only for UDP since
12243 	 * IP fragmentation is a normal occurence for the protocol.  In
12244 	 * addition, checksum offload support for IP fragments carrying
12245 	 * UDP payload is commonly implemented across network adapters.
12246 	 */
12247 	ASSERT(ill != NULL);
12248 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12249 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12250 		mblk_t *mp1 = mp->b_cont;
12251 		int32_t len;
12252 
12253 		/* Record checksum information from the packet */
12254 		sum_val = (uint32_t)DB_CKSUM16(mp);
12255 		sum_flags = DB_CKSUMFLAGS(mp);
12256 
12257 		/* IP payload offset from beginning of mblk */
12258 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12259 
12260 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12261 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12262 		    offset >= DB_CKSUMSTART(mp) &&
12263 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12264 			uint32_t adj;
12265 			/*
12266 			 * Partial checksum has been calculated by hardware
12267 			 * and attached to the packet; in addition, any
12268 			 * prepended extraneous data is even byte aligned.
12269 			 * If any such data exists, we adjust the checksum;
12270 			 * this would also handle any postpended data.
12271 			 */
12272 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12273 			    mp, mp1, len, adj);
12274 
12275 			/* One's complement subtract extraneous checksum */
12276 			if (adj >= sum_val)
12277 				sum_val = ~(adj - sum_val) & 0xFFFF;
12278 			else
12279 				sum_val -= adj;
12280 		}
12281 	} else {
12282 		sum_val = 0;
12283 		sum_flags = 0;
12284 	}
12285 
12286 	/* Clear hardware checksumming flag */
12287 	DB_CKSUMFLAGS(mp) = 0;
12288 
12289 	ident = ipha->ipha_ident;
12290 	offset = (frag_offset_flags << 3) & 0xFFFF;
12291 	src = ipha->ipha_src;
12292 	dst = ipha->ipha_dst;
12293 	hdr_length = IPH_HDR_LENGTH(ipha);
12294 	end = ntohs(ipha->ipha_length) - hdr_length;
12295 
12296 	/* If end == 0 then we have a packet with no data, so just free it */
12297 	if (end == 0) {
12298 		freemsg(mp);
12299 		return (B_FALSE);
12300 	}
12301 
12302 	/* Record the ECN field info. */
12303 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12304 	if (offset != 0) {
12305 		/*
12306 		 * If this isn't the first piece, strip the header, and
12307 		 * add the offset to the end value.
12308 		 */
12309 		mp->b_rptr += hdr_length;
12310 		end += offset;
12311 	}
12312 
12313 	msg_len = MBLKSIZE(mp);
12314 	tail_mp = mp;
12315 	while (tail_mp->b_cont != NULL) {
12316 		tail_mp = tail_mp->b_cont;
12317 		msg_len += MBLKSIZE(tail_mp);
12318 	}
12319 
12320 	/* If the reassembly list for this ILL will get too big, prune it */
12321 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12322 	    ipst->ips_ip_reass_queue_bytes) {
12323 		ill_frag_prune(ill,
12324 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12325 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12326 		pruned = B_TRUE;
12327 	}
12328 
12329 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12330 	mutex_enter(&ipfb->ipfb_lock);
12331 
12332 	ipfp = &ipfb->ipfb_ipf;
12333 	/* Try to find an existing fragment queue for this packet. */
12334 	for (;;) {
12335 		ipf = ipfp[0];
12336 		if (ipf != NULL) {
12337 			/*
12338 			 * It has to match on ident and src/dst address.
12339 			 */
12340 			if (ipf->ipf_ident == ident &&
12341 			    ipf->ipf_src == src &&
12342 			    ipf->ipf_dst == dst &&
12343 			    ipf->ipf_protocol == proto) {
12344 				/*
12345 				 * If we have received too many
12346 				 * duplicate fragments for this packet
12347 				 * free it.
12348 				 */
12349 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12350 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12351 					freemsg(mp);
12352 					mutex_exit(&ipfb->ipfb_lock);
12353 					return (B_FALSE);
12354 				}
12355 				/* Found it. */
12356 				break;
12357 			}
12358 			ipfp = &ipf->ipf_hash_next;
12359 			continue;
12360 		}
12361 
12362 		/*
12363 		 * If we pruned the list, do we want to store this new
12364 		 * fragment?. We apply an optimization here based on the
12365 		 * fact that most fragments will be received in order.
12366 		 * So if the offset of this incoming fragment is zero,
12367 		 * it is the first fragment of a new packet. We will
12368 		 * keep it.  Otherwise drop the fragment, as we have
12369 		 * probably pruned the packet already (since the
12370 		 * packet cannot be found).
12371 		 */
12372 		if (pruned && offset != 0) {
12373 			mutex_exit(&ipfb->ipfb_lock);
12374 			freemsg(mp);
12375 			return (B_FALSE);
12376 		}
12377 
12378 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12379 			/*
12380 			 * Too many fragmented packets in this hash
12381 			 * bucket. Free the oldest.
12382 			 */
12383 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12384 		}
12385 
12386 		/* New guy.  Allocate a frag message. */
12387 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12388 		if (mp1 == NULL) {
12389 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12390 			freemsg(mp);
12391 reass_done:
12392 			mutex_exit(&ipfb->ipfb_lock);
12393 			return (B_FALSE);
12394 		}
12395 
12396 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12397 		mp1->b_cont = mp;
12398 
12399 		/* Initialize the fragment header. */
12400 		ipf = (ipf_t *)mp1->b_rptr;
12401 		ipf->ipf_mp = mp1;
12402 		ipf->ipf_ptphn = ipfp;
12403 		ipfp[0] = ipf;
12404 		ipf->ipf_hash_next = NULL;
12405 		ipf->ipf_ident = ident;
12406 		ipf->ipf_protocol = proto;
12407 		ipf->ipf_src = src;
12408 		ipf->ipf_dst = dst;
12409 		ipf->ipf_nf_hdr_len = 0;
12410 		/* Record reassembly start time. */
12411 		ipf->ipf_timestamp = gethrestime_sec();
12412 		/* Record ipf generation and account for frag header */
12413 		ipf->ipf_gen = ill->ill_ipf_gen++;
12414 		ipf->ipf_count = MBLKSIZE(mp1);
12415 		ipf->ipf_last_frag_seen = B_FALSE;
12416 		ipf->ipf_ecn = ecn_info;
12417 		ipf->ipf_num_dups = 0;
12418 		ipfb->ipfb_frag_pkts++;
12419 		ipf->ipf_checksum = 0;
12420 		ipf->ipf_checksum_flags = 0;
12421 
12422 		/* Store checksum value in fragment header */
12423 		if (sum_flags != 0) {
12424 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12425 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12426 			ipf->ipf_checksum = sum_val;
12427 			ipf->ipf_checksum_flags = sum_flags;
12428 		}
12429 
12430 		/*
12431 		 * We handle reassembly two ways.  In the easy case,
12432 		 * where all the fragments show up in order, we do
12433 		 * minimal bookkeeping, and just clip new pieces on
12434 		 * the end.  If we ever see a hole, then we go off
12435 		 * to ip_reassemble which has to mark the pieces and
12436 		 * keep track of the number of holes, etc.  Obviously,
12437 		 * the point of having both mechanisms is so we can
12438 		 * handle the easy case as efficiently as possible.
12439 		 */
12440 		if (offset == 0) {
12441 			/* Easy case, in-order reassembly so far. */
12442 			ipf->ipf_count += msg_len;
12443 			ipf->ipf_tail_mp = tail_mp;
12444 			/*
12445 			 * Keep track of next expected offset in
12446 			 * ipf_end.
12447 			 */
12448 			ipf->ipf_end = end;
12449 			ipf->ipf_nf_hdr_len = hdr_length;
12450 		} else {
12451 			/* Hard case, hole at the beginning. */
12452 			ipf->ipf_tail_mp = NULL;
12453 			/*
12454 			 * ipf_end == 0 means that we have given up
12455 			 * on easy reassembly.
12456 			 */
12457 			ipf->ipf_end = 0;
12458 
12459 			/* Forget checksum offload from now on */
12460 			ipf->ipf_checksum_flags = 0;
12461 
12462 			/*
12463 			 * ipf_hole_cnt is set by ip_reassemble.
12464 			 * ipf_count is updated by ip_reassemble.
12465 			 * No need to check for return value here
12466 			 * as we don't expect reassembly to complete
12467 			 * or fail for the first fragment itself.
12468 			 */
12469 			(void) ip_reassemble(mp, ipf,
12470 			    (frag_offset_flags & IPH_OFFSET) << 3,
12471 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12472 		}
12473 		/* Update per ipfb and ill byte counts */
12474 		ipfb->ipfb_count += ipf->ipf_count;
12475 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12476 		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
12477 		/* If the frag timer wasn't already going, start it. */
12478 		mutex_enter(&ill->ill_lock);
12479 		ill_frag_timer_start(ill);
12480 		mutex_exit(&ill->ill_lock);
12481 		goto reass_done;
12482 	}
12483 
12484 	/*
12485 	 * If the packet's flag has changed (it could be coming up
12486 	 * from an interface different than the previous, therefore
12487 	 * possibly different checksum capability), then forget about
12488 	 * any stored checksum states.  Otherwise add the value to
12489 	 * the existing one stored in the fragment header.
12490 	 */
12491 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12492 		sum_val += ipf->ipf_checksum;
12493 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12494 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12495 		ipf->ipf_checksum = sum_val;
12496 	} else if (ipf->ipf_checksum_flags != 0) {
12497 		/* Forget checksum offload from now on */
12498 		ipf->ipf_checksum_flags = 0;
12499 	}
12500 
12501 	/*
12502 	 * We have a new piece of a datagram which is already being
12503 	 * reassembled.  Update the ECN info if all IP fragments
12504 	 * are ECN capable.  If there is one which is not, clear
12505 	 * all the info.  If there is at least one which has CE
12506 	 * code point, IP needs to report that up to transport.
12507 	 */
12508 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12509 		if (ecn_info == IPH_ECN_CE)
12510 			ipf->ipf_ecn = IPH_ECN_CE;
12511 	} else {
12512 		ipf->ipf_ecn = IPH_ECN_NECT;
12513 	}
12514 	if (offset && ipf->ipf_end == offset) {
12515 		/* The new fragment fits at the end */
12516 		ipf->ipf_tail_mp->b_cont = mp;
12517 		/* Update the byte count */
12518 		ipf->ipf_count += msg_len;
12519 		/* Update per ipfb and ill byte counts */
12520 		ipfb->ipfb_count += msg_len;
12521 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12522 		atomic_add_32(&ill->ill_frag_count, msg_len);
12523 		if (frag_offset_flags & IPH_MF) {
12524 			/* More to come. */
12525 			ipf->ipf_end = end;
12526 			ipf->ipf_tail_mp = tail_mp;
12527 			goto reass_done;
12528 		}
12529 	} else {
12530 		/* Go do the hard cases. */
12531 		int ret;
12532 
12533 		if (offset == 0)
12534 			ipf->ipf_nf_hdr_len = hdr_length;
12535 
12536 		/* Save current byte count */
12537 		count = ipf->ipf_count;
12538 		ret = ip_reassemble(mp, ipf,
12539 		    (frag_offset_flags & IPH_OFFSET) << 3,
12540 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12541 		/* Count of bytes added and subtracted (freeb()ed) */
12542 		count = ipf->ipf_count - count;
12543 		if (count) {
12544 			/* Update per ipfb and ill byte counts */
12545 			ipfb->ipfb_count += count;
12546 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12547 			atomic_add_32(&ill->ill_frag_count, count);
12548 		}
12549 		if (ret == IP_REASS_PARTIAL) {
12550 			goto reass_done;
12551 		} else if (ret == IP_REASS_FAILED) {
12552 			/* Reassembly failed. Free up all resources */
12553 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12554 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12555 				IP_REASS_SET_START(t_mp, 0);
12556 				IP_REASS_SET_END(t_mp, 0);
12557 			}
12558 			freemsg(mp);
12559 			goto reass_done;
12560 		}
12561 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12562 	}
12563 	/*
12564 	 * We have completed reassembly.  Unhook the frag header from
12565 	 * the reassembly list.
12566 	 *
12567 	 * Before we free the frag header, record the ECN info
12568 	 * to report back to the transport.
12569 	 */
12570 	ecn_info = ipf->ipf_ecn;
12571 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12572 	ipfp = ipf->ipf_ptphn;
12573 
12574 	/* We need to supply these to caller */
12575 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12576 		sum_val = ipf->ipf_checksum;
12577 	else
12578 		sum_val = 0;
12579 
12580 	mp1 = ipf->ipf_mp;
12581 	count = ipf->ipf_count;
12582 	ipf = ipf->ipf_hash_next;
12583 	if (ipf != NULL)
12584 		ipf->ipf_ptphn = ipfp;
12585 	ipfp[0] = ipf;
12586 	atomic_add_32(&ill->ill_frag_count, -count);
12587 	ASSERT(ipfb->ipfb_count >= count);
12588 	ipfb->ipfb_count -= count;
12589 	ipfb->ipfb_frag_pkts--;
12590 	mutex_exit(&ipfb->ipfb_lock);
12591 	/* Ditch the frag header. */
12592 	mp = mp1->b_cont;
12593 
12594 	freeb(mp1);
12595 
12596 	/* Restore original IP length in header. */
12597 	packet_size = (uint32_t)msgdsize(mp);
12598 	if (packet_size > IP_MAXPACKET) {
12599 		freemsg(mp);
12600 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12601 		return (B_FALSE);
12602 	}
12603 
12604 	if (DB_REF(mp) > 1) {
12605 		mblk_t *mp2 = copymsg(mp);
12606 
12607 		freemsg(mp);
12608 		if (mp2 == NULL) {
12609 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12610 			return (B_FALSE);
12611 		}
12612 		mp = mp2;
12613 	}
12614 	ipha = (ipha_t *)mp->b_rptr;
12615 
12616 	ipha->ipha_length = htons((uint16_t)packet_size);
12617 	/* We're now complete, zip the frag state */
12618 	ipha->ipha_fragment_offset_and_flags = 0;
12619 	/* Record the ECN info. */
12620 	ipha->ipha_type_of_service &= 0xFC;
12621 	ipha->ipha_type_of_service |= ecn_info;
12622 	*mpp = mp;
12623 
12624 	/* Reassembly is successful; return checksum information if needed */
12625 	if (cksum_val != NULL)
12626 		*cksum_val = sum_val;
12627 	if (cksum_flags != NULL)
12628 		*cksum_flags = sum_flags;
12629 
12630 	return (B_TRUE);
12631 }
12632 
12633 /*
12634  * Perform ip header check sum update local options.
12635  * return B_TRUE if all is well, else return B_FALSE and release
12636  * the mp. caller is responsible for decrementing ire ref cnt.
12637  */
12638 static boolean_t
12639 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12640     ip_stack_t *ipst)
12641 {
12642 	mblk_t		*first_mp;
12643 	boolean_t	mctl_present;
12644 	uint16_t	sum;
12645 
12646 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12647 	/*
12648 	 * Don't do the checksum if it has gone through AH/ESP
12649 	 * processing.
12650 	 */
12651 	if (!mctl_present) {
12652 		sum = ip_csum_hdr(ipha);
12653 		if (sum != 0) {
12654 			if (ill != NULL) {
12655 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12656 			} else {
12657 				BUMP_MIB(&ipst->ips_ip_mib,
12658 				    ipIfStatsInCksumErrs);
12659 			}
12660 			freemsg(first_mp);
12661 			return (B_FALSE);
12662 		}
12663 	}
12664 
12665 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12666 		if (mctl_present)
12667 			freeb(first_mp);
12668 		return (B_FALSE);
12669 	}
12670 
12671 	return (B_TRUE);
12672 }
12673 
12674 /*
12675  * All udp packet are delivered to the local host via this routine.
12676  */
12677 void
12678 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12679     ill_t *recv_ill)
12680 {
12681 	uint32_t	sum;
12682 	uint32_t	u1;
12683 	boolean_t	mctl_present;
12684 	conn_t		*connp;
12685 	mblk_t		*first_mp;
12686 	uint16_t	*up;
12687 	ill_t		*ill = (ill_t *)q->q_ptr;
12688 	uint16_t	reass_hck_flags = 0;
12689 	ip_stack_t	*ipst;
12690 
12691 	ASSERT(recv_ill != NULL);
12692 	ipst = recv_ill->ill_ipst;
12693 
12694 #define	rptr    ((uchar_t *)ipha)
12695 
12696 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12697 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12698 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12699 	ASSERT(ill != NULL);
12700 
12701 	/*
12702 	 * FAST PATH for udp packets
12703 	 */
12704 
12705 	/* u1 is # words of IP options */
12706 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12707 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12708 
12709 	/* IP options present */
12710 	if (u1 != 0)
12711 		goto ipoptions;
12712 
12713 	/* Check the IP header checksum.  */
12714 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12715 		/* Clear the IP header h/w cksum flag */
12716 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12717 	} else if (!mctl_present) {
12718 		/*
12719 		 * Don't verify header checksum if this packet is coming
12720 		 * back from AH/ESP as we already did it.
12721 		 */
12722 #define	uph	((uint16_t *)ipha)
12723 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12724 		    uph[6] + uph[7] + uph[8] + uph[9];
12725 #undef	uph
12726 		/* finish doing IP checksum */
12727 		sum = (sum & 0xFFFF) + (sum >> 16);
12728 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12729 		if (sum != 0 && sum != 0xFFFF) {
12730 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12731 			freemsg(first_mp);
12732 			return;
12733 		}
12734 	}
12735 
12736 	/*
12737 	 * Count for SNMP of inbound packets for ire.
12738 	 * if mctl is present this might be a secure packet and
12739 	 * has already been counted for in ip_proto_input().
12740 	 */
12741 	if (!mctl_present) {
12742 		UPDATE_IB_PKT_COUNT(ire);
12743 		ire->ire_last_used_time = lbolt;
12744 	}
12745 
12746 	/* packet part of fragmented IP packet? */
12747 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12748 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12749 		goto fragmented;
12750 	}
12751 
12752 	/* u1 = IP header length (20 bytes) */
12753 	u1 = IP_SIMPLE_HDR_LENGTH;
12754 
12755 	/* packet does not contain complete IP & UDP headers */
12756 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12757 		goto udppullup;
12758 
12759 	/* up points to UDP header */
12760 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12761 #define	iphs    ((uint16_t *)ipha)
12762 
12763 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12764 	if (up[3] != 0) {
12765 		mblk_t *mp1 = mp->b_cont;
12766 		boolean_t cksum_err;
12767 		uint16_t hck_flags = 0;
12768 
12769 		/* Pseudo-header checksum */
12770 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12771 		    iphs[9] + up[2];
12772 
12773 		/*
12774 		 * Revert to software checksum calculation if the interface
12775 		 * isn't capable of checksum offload or if IPsec is present.
12776 		 */
12777 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12778 			hck_flags = DB_CKSUMFLAGS(mp);
12779 
12780 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12781 			IP_STAT(ipst, ip_in_sw_cksum);
12782 
12783 		IP_CKSUM_RECV(hck_flags, u1,
12784 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12785 		    (int32_t)((uchar_t *)up - rptr),
12786 		    mp, mp1, cksum_err);
12787 
12788 		if (cksum_err) {
12789 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12790 			if (hck_flags & HCK_FULLCKSUM)
12791 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12792 			else if (hck_flags & HCK_PARTIALCKSUM)
12793 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12794 			else
12795 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12796 
12797 			freemsg(first_mp);
12798 			return;
12799 		}
12800 	}
12801 
12802 	/* Non-fragmented broadcast or multicast packet? */
12803 	if (ire->ire_type == IRE_BROADCAST)
12804 		goto udpslowpath;
12805 
12806 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12807 	    ire->ire_zoneid, ipst)) != NULL) {
12808 		ASSERT(connp->conn_upq != NULL);
12809 		IP_STAT(ipst, ip_udp_fast_path);
12810 
12811 		if (CONN_UDP_FLOWCTLD(connp)) {
12812 			freemsg(mp);
12813 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12814 		} else {
12815 			if (!mctl_present) {
12816 				BUMP_MIB(ill->ill_ip_mib,
12817 				    ipIfStatsHCInDelivers);
12818 			}
12819 			/*
12820 			 * mp and first_mp can change.
12821 			 */
12822 			if (ip_udp_check(q, connp, recv_ill,
12823 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12824 				/* Send it upstream */
12825 				(connp->conn_recv)(connp, mp, NULL);
12826 			}
12827 		}
12828 		/*
12829 		 * freeb() cannot deal with null mblk being passed
12830 		 * in and first_mp can be set to null in the call
12831 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12832 		 */
12833 		if (mctl_present && first_mp != NULL) {
12834 			freeb(first_mp);
12835 		}
12836 		CONN_DEC_REF(connp);
12837 		return;
12838 	}
12839 
12840 	/*
12841 	 * if we got here we know the packet is not fragmented and
12842 	 * has no options. The classifier could not find a conn_t and
12843 	 * most likely its an icmp packet so send it through slow path.
12844 	 */
12845 
12846 	goto udpslowpath;
12847 
12848 ipoptions:
12849 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12850 		goto slow_done;
12851 	}
12852 
12853 	UPDATE_IB_PKT_COUNT(ire);
12854 	ire->ire_last_used_time = lbolt;
12855 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12856 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12857 fragmented:
12858 		/*
12859 		 * "sum" and "reass_hck_flags" are non-zero if the
12860 		 * reassembled packet has a valid hardware computed
12861 		 * checksum information associated with it.
12862 		 */
12863 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12864 			goto slow_done;
12865 		/*
12866 		 * Make sure that first_mp points back to mp as
12867 		 * the mp we came in with could have changed in
12868 		 * ip_rput_fragment().
12869 		 */
12870 		ASSERT(!mctl_present);
12871 		ipha = (ipha_t *)mp->b_rptr;
12872 		first_mp = mp;
12873 	}
12874 
12875 	/* Now we have a complete datagram, destined for this machine. */
12876 	u1 = IPH_HDR_LENGTH(ipha);
12877 	/* Pull up the UDP header, if necessary. */
12878 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12879 udppullup:
12880 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12881 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12882 			freemsg(first_mp);
12883 			goto slow_done;
12884 		}
12885 		ipha = (ipha_t *)mp->b_rptr;
12886 	}
12887 
12888 	/*
12889 	 * Validate the checksum for the reassembled packet; for the
12890 	 * pullup case we calculate the payload checksum in software.
12891 	 */
12892 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12893 	if (up[3] != 0) {
12894 		boolean_t cksum_err;
12895 
12896 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12897 			IP_STAT(ipst, ip_in_sw_cksum);
12898 
12899 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12900 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12901 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12902 		    iphs[9] + up[2], sum, cksum_err);
12903 
12904 		if (cksum_err) {
12905 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12906 
12907 			if (reass_hck_flags & HCK_FULLCKSUM)
12908 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12909 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12910 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12911 			else
12912 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12913 
12914 			freemsg(first_mp);
12915 			goto slow_done;
12916 		}
12917 	}
12918 udpslowpath:
12919 
12920 	/* Clear hardware checksum flag to be safe */
12921 	DB_CKSUMFLAGS(mp) = 0;
12922 
12923 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12924 	    (ire->ire_type == IRE_BROADCAST),
12925 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12926 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12927 
12928 slow_done:
12929 	IP_STAT(ipst, ip_udp_slow_path);
12930 	return;
12931 
12932 #undef  iphs
12933 #undef  rptr
12934 }
12935 
12936 /* ARGSUSED */
12937 static mblk_t *
12938 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12939     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12940     ill_rx_ring_t *ill_ring)
12941 {
12942 	conn_t		*connp;
12943 	uint32_t	sum;
12944 	uint32_t	u1;
12945 	uint16_t	*up;
12946 	int		offset;
12947 	ssize_t		len;
12948 	mblk_t		*mp1;
12949 	boolean_t	syn_present = B_FALSE;
12950 	tcph_t		*tcph;
12951 	uint_t		ip_hdr_len;
12952 	ill_t		*ill = (ill_t *)q->q_ptr;
12953 	zoneid_t	zoneid = ire->ire_zoneid;
12954 	boolean_t	cksum_err;
12955 	uint16_t	hck_flags = 0;
12956 	ip_stack_t	*ipst = recv_ill->ill_ipst;
12957 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12958 
12959 #define	rptr	((uchar_t *)ipha)
12960 
12961 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12962 	ASSERT(ill != NULL);
12963 
12964 	/*
12965 	 * FAST PATH for tcp packets
12966 	 */
12967 
12968 	/* u1 is # words of IP options */
12969 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12970 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12971 
12972 	/* IP options present */
12973 	if (u1) {
12974 		goto ipoptions;
12975 	} else if (!mctl_present) {
12976 		/* Check the IP header checksum.  */
12977 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12978 			/* Clear the IP header h/w cksum flag */
12979 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12980 		} else if (!mctl_present) {
12981 			/*
12982 			 * Don't verify header checksum if this packet
12983 			 * is coming back from AH/ESP as we already did it.
12984 			 */
12985 #define	uph	((uint16_t *)ipha)
12986 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12987 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12988 #undef	uph
12989 			/* finish doing IP checksum */
12990 			sum = (sum & 0xFFFF) + (sum >> 16);
12991 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12992 			if (sum != 0 && sum != 0xFFFF) {
12993 				BUMP_MIB(ill->ill_ip_mib,
12994 				    ipIfStatsInCksumErrs);
12995 				goto error;
12996 			}
12997 		}
12998 	}
12999 
13000 	if (!mctl_present) {
13001 		UPDATE_IB_PKT_COUNT(ire);
13002 		ire->ire_last_used_time = lbolt;
13003 	}
13004 
13005 	/* packet part of fragmented IP packet? */
13006 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13007 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13008 		goto fragmented;
13009 	}
13010 
13011 	/* u1 = IP header length (20 bytes) */
13012 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
13013 
13014 	/* does packet contain IP+TCP headers? */
13015 	len = mp->b_wptr - rptr;
13016 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
13017 		IP_STAT(ipst, ip_tcppullup);
13018 		goto tcppullup;
13019 	}
13020 
13021 	/* TCP options present? */
13022 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
13023 
13024 	/*
13025 	 * If options need to be pulled up, then goto tcpoptions.
13026 	 * otherwise we are still in the fast path
13027 	 */
13028 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
13029 		IP_STAT(ipst, ip_tcpoptions);
13030 		goto tcpoptions;
13031 	}
13032 
13033 	/* multiple mblks of tcp data? */
13034 	if ((mp1 = mp->b_cont) != NULL) {
13035 		/* more then two? */
13036 		if (mp1->b_cont != NULL) {
13037 			IP_STAT(ipst, ip_multipkttcp);
13038 			goto multipkttcp;
13039 		}
13040 		len += mp1->b_wptr - mp1->b_rptr;
13041 	}
13042 
13043 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13044 
13045 	/* part of pseudo checksum */
13046 
13047 	/* TCP datagram length */
13048 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13049 
13050 #define	iphs    ((uint16_t *)ipha)
13051 
13052 #ifdef	_BIG_ENDIAN
13053 	u1 += IPPROTO_TCP;
13054 #else
13055 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13056 #endif
13057 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13058 
13059 	/*
13060 	 * Revert to software checksum calculation if the interface
13061 	 * isn't capable of checksum offload or if IPsec is present.
13062 	 */
13063 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
13064 		hck_flags = DB_CKSUMFLAGS(mp);
13065 
13066 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13067 		IP_STAT(ipst, ip_in_sw_cksum);
13068 
13069 	IP_CKSUM_RECV(hck_flags, u1,
13070 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13071 	    (int32_t)((uchar_t *)up - rptr),
13072 	    mp, mp1, cksum_err);
13073 
13074 	if (cksum_err) {
13075 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13076 
13077 		if (hck_flags & HCK_FULLCKSUM)
13078 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13079 		else if (hck_flags & HCK_PARTIALCKSUM)
13080 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13081 		else
13082 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13083 
13084 		goto error;
13085 	}
13086 
13087 try_again:
13088 
13089 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13090 	    zoneid, ipst)) == NULL) {
13091 		/* Send the TH_RST */
13092 		goto no_conn;
13093 	}
13094 
13095 	/*
13096 	 * TCP FAST PATH for AF_INET socket.
13097 	 *
13098 	 * TCP fast path to avoid extra work. An AF_INET socket type
13099 	 * does not have facility to receive extra information via
13100 	 * ip_process or ip_add_info. Also, when the connection was
13101 	 * established, we made a check if this connection is impacted
13102 	 * by any global IPsec policy or per connection policy (a
13103 	 * policy that comes in effect later will not apply to this
13104 	 * connection). Since all this can be determined at the
13105 	 * connection establishment time, a quick check of flags
13106 	 * can avoid extra work.
13107 	 */
13108 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13109 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13110 		ASSERT(first_mp == mp);
13111 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13112 		SET_SQUEUE(mp, tcp_rput_data, connp);
13113 		return (mp);
13114 	}
13115 
13116 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13117 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
13118 		if (IPCL_IS_TCP(connp)) {
13119 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13120 			DB_CKSUMSTART(mp) =
13121 			    (intptr_t)ip_squeue_get(ill_ring);
13122 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13123 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13124 				BUMP_MIB(ill->ill_ip_mib,
13125 				    ipIfStatsHCInDelivers);
13126 				SET_SQUEUE(mp, connp->conn_recv, connp);
13127 				return (mp);
13128 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13129 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13130 				BUMP_MIB(ill->ill_ip_mib,
13131 				    ipIfStatsHCInDelivers);
13132 				ip_squeue_enter_unbound++;
13133 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13134 				    connp);
13135 				return (mp);
13136 			}
13137 			syn_present = B_TRUE;
13138 		}
13139 
13140 	}
13141 
13142 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13143 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13144 
13145 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13146 		/* No need to send this packet to TCP */
13147 		if ((flags & TH_RST) || (flags & TH_URG)) {
13148 			CONN_DEC_REF(connp);
13149 			freemsg(first_mp);
13150 			return (NULL);
13151 		}
13152 		if (flags & TH_ACK) {
13153 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
13154 			    ipst->ips_netstack->netstack_tcp, connp);
13155 			CONN_DEC_REF(connp);
13156 			return (NULL);
13157 		}
13158 
13159 		CONN_DEC_REF(connp);
13160 		freemsg(first_mp);
13161 		return (NULL);
13162 	}
13163 
13164 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13165 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13166 		    ipha, NULL, mctl_present);
13167 		if (first_mp == NULL) {
13168 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13169 			CONN_DEC_REF(connp);
13170 			return (NULL);
13171 		}
13172 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13173 			ASSERT(syn_present);
13174 			if (mctl_present) {
13175 				ASSERT(first_mp != mp);
13176 				first_mp->b_datap->db_struioflag |=
13177 				    STRUIO_POLICY;
13178 			} else {
13179 				ASSERT(first_mp == mp);
13180 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13181 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13182 			}
13183 		} else {
13184 			/*
13185 			 * Discard first_mp early since we're dealing with a
13186 			 * fully-connected conn_t and tcp doesn't do policy in
13187 			 * this case.
13188 			 */
13189 			if (mctl_present) {
13190 				freeb(first_mp);
13191 				mctl_present = B_FALSE;
13192 			}
13193 			first_mp = mp;
13194 		}
13195 	}
13196 
13197 	/* Initiate IPPF processing for fastpath */
13198 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13199 		uint32_t	ill_index;
13200 
13201 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13202 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13203 		if (mp == NULL) {
13204 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13205 			    "deferred/dropped during IPPF processing\n"));
13206 			CONN_DEC_REF(connp);
13207 			if (mctl_present)
13208 				freeb(first_mp);
13209 			return (NULL);
13210 		} else if (mctl_present) {
13211 			/*
13212 			 * ip_process might return a new mp.
13213 			 */
13214 			ASSERT(first_mp != mp);
13215 			first_mp->b_cont = mp;
13216 		} else {
13217 			first_mp = mp;
13218 		}
13219 
13220 	}
13221 
13222 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13223 		/*
13224 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13225 		 * make sure IPF_RECVIF is passed to ip_add_info.
13226 		 */
13227 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13228 		    IPCL_ZONEID(connp), ipst);
13229 		if (mp == NULL) {
13230 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13231 			CONN_DEC_REF(connp);
13232 			if (mctl_present)
13233 				freeb(first_mp);
13234 			return (NULL);
13235 		} else if (mctl_present) {
13236 			/*
13237 			 * ip_add_info might return a new mp.
13238 			 */
13239 			ASSERT(first_mp != mp);
13240 			first_mp->b_cont = mp;
13241 		} else {
13242 			first_mp = mp;
13243 		}
13244 	}
13245 
13246 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13247 	if (IPCL_IS_TCP(connp)) {
13248 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13249 		return (first_mp);
13250 	} else {
13251 		/* SOCK_RAW, IPPROTO_TCP case */
13252 		(connp->conn_recv)(connp, first_mp, NULL);
13253 		CONN_DEC_REF(connp);
13254 		return (NULL);
13255 	}
13256 
13257 no_conn:
13258 	/* Initiate IPPf processing, if needed. */
13259 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13260 		uint32_t ill_index;
13261 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13262 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13263 		if (first_mp == NULL) {
13264 			return (NULL);
13265 		}
13266 	}
13267 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13268 
13269 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13270 	    ipst->ips_netstack->netstack_tcp, NULL);
13271 	return (NULL);
13272 ipoptions:
13273 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13274 		goto slow_done;
13275 	}
13276 
13277 	UPDATE_IB_PKT_COUNT(ire);
13278 	ire->ire_last_used_time = lbolt;
13279 
13280 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13281 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13282 fragmented:
13283 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13284 			if (mctl_present)
13285 				freeb(first_mp);
13286 			goto slow_done;
13287 		}
13288 		/*
13289 		 * Make sure that first_mp points back to mp as
13290 		 * the mp we came in with could have changed in
13291 		 * ip_rput_fragment().
13292 		 */
13293 		ASSERT(!mctl_present);
13294 		ipha = (ipha_t *)mp->b_rptr;
13295 		first_mp = mp;
13296 	}
13297 
13298 	/* Now we have a complete datagram, destined for this machine. */
13299 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13300 
13301 	len = mp->b_wptr - mp->b_rptr;
13302 	/* Pull up a minimal TCP header, if necessary. */
13303 	if (len < (u1 + 20)) {
13304 tcppullup:
13305 		if (!pullupmsg(mp, u1 + 20)) {
13306 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13307 			goto error;
13308 		}
13309 		ipha = (ipha_t *)mp->b_rptr;
13310 		len = mp->b_wptr - mp->b_rptr;
13311 	}
13312 
13313 	/*
13314 	 * Extract the offset field from the TCP header.  As usual, we
13315 	 * try to help the compiler more than the reader.
13316 	 */
13317 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13318 	if (offset != 5) {
13319 tcpoptions:
13320 		if (offset < 5) {
13321 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13322 			goto error;
13323 		}
13324 		/*
13325 		 * There must be TCP options.
13326 		 * Make sure we can grab them.
13327 		 */
13328 		offset <<= 2;
13329 		offset += u1;
13330 		if (len < offset) {
13331 			if (!pullupmsg(mp, offset)) {
13332 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13333 				goto error;
13334 			}
13335 			ipha = (ipha_t *)mp->b_rptr;
13336 			len = mp->b_wptr - rptr;
13337 		}
13338 	}
13339 
13340 	/* Get the total packet length in len, including headers. */
13341 	if (mp->b_cont) {
13342 multipkttcp:
13343 		len = msgdsize(mp);
13344 	}
13345 
13346 	/*
13347 	 * Check the TCP checksum by pulling together the pseudo-
13348 	 * header checksum, and passing it to ip_csum to be added in
13349 	 * with the TCP datagram.
13350 	 *
13351 	 * Since we are not using the hwcksum if available we must
13352 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13353 	 * If either of these fails along the way the mblk is freed.
13354 	 * If this logic ever changes and mblk is reused to say send
13355 	 * ICMP's back, then this flag may need to be cleared in
13356 	 * other places as well.
13357 	 */
13358 	DB_CKSUMFLAGS(mp) = 0;
13359 
13360 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13361 
13362 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13363 #ifdef	_BIG_ENDIAN
13364 	u1 += IPPROTO_TCP;
13365 #else
13366 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13367 #endif
13368 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13369 	/*
13370 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13371 	 */
13372 	IP_STAT(ipst, ip_in_sw_cksum);
13373 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13374 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13375 		goto error;
13376 	}
13377 
13378 	IP_STAT(ipst, ip_tcp_slow_path);
13379 	goto try_again;
13380 #undef  iphs
13381 #undef  rptr
13382 
13383 error:
13384 	freemsg(first_mp);
13385 slow_done:
13386 	return (NULL);
13387 }
13388 
13389 /* ARGSUSED */
13390 static void
13391 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13392     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13393 {
13394 	conn_t		*connp;
13395 	uint32_t	sum;
13396 	uint32_t	u1;
13397 	ssize_t		len;
13398 	sctp_hdr_t	*sctph;
13399 	zoneid_t	zoneid = ire->ire_zoneid;
13400 	uint32_t	pktsum;
13401 	uint32_t	calcsum;
13402 	uint32_t	ports;
13403 	in6_addr_t	map_src, map_dst;
13404 	ill_t		*ill = (ill_t *)q->q_ptr;
13405 	ip_stack_t	*ipst;
13406 	sctp_stack_t	*sctps;
13407 	boolean_t	sctp_csum_err = B_FALSE;
13408 
13409 	ASSERT(recv_ill != NULL);
13410 	ipst = recv_ill->ill_ipst;
13411 	sctps = ipst->ips_netstack->netstack_sctp;
13412 
13413 #define	rptr	((uchar_t *)ipha)
13414 
13415 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13416 	ASSERT(ill != NULL);
13417 
13418 	/* u1 is # words of IP options */
13419 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13420 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13421 
13422 	/* IP options present */
13423 	if (u1 > 0) {
13424 		goto ipoptions;
13425 	} else {
13426 		/* Check the IP header checksum.  */
13427 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill) &&
13428 		    !mctl_present) {
13429 #define	uph	((uint16_t *)ipha)
13430 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13431 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13432 #undef	uph
13433 			/* finish doing IP checksum */
13434 			sum = (sum & 0xFFFF) + (sum >> 16);
13435 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13436 			/*
13437 			 * Don't verify header checksum if this packet
13438 			 * is coming back from AH/ESP as we already did it.
13439 			 */
13440 			if (sum != 0 && sum != 0xFFFF) {
13441 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13442 				goto error;
13443 			}
13444 		}
13445 		/*
13446 		 * Since there is no SCTP h/w cksum support yet, just
13447 		 * clear the flag.
13448 		 */
13449 		DB_CKSUMFLAGS(mp) = 0;
13450 	}
13451 
13452 	/*
13453 	 * Don't verify header checksum if this packet is coming
13454 	 * back from AH/ESP as we already did it.
13455 	 */
13456 	if (!mctl_present) {
13457 		UPDATE_IB_PKT_COUNT(ire);
13458 		ire->ire_last_used_time = lbolt;
13459 	}
13460 
13461 	/* packet part of fragmented IP packet? */
13462 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13463 	if (u1 & (IPH_MF | IPH_OFFSET))
13464 		goto fragmented;
13465 
13466 	/* u1 = IP header length (20 bytes) */
13467 	u1 = IP_SIMPLE_HDR_LENGTH;
13468 
13469 find_sctp_client:
13470 	/* Pullup if we don't have the sctp common header. */
13471 	len = MBLKL(mp);
13472 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13473 		if (mp->b_cont == NULL ||
13474 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13475 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13476 			goto error;
13477 		}
13478 		ipha = (ipha_t *)mp->b_rptr;
13479 		len = MBLKL(mp);
13480 	}
13481 
13482 	sctph = (sctp_hdr_t *)(rptr + u1);
13483 #ifdef	DEBUG
13484 	if (!skip_sctp_cksum) {
13485 #endif
13486 		pktsum = sctph->sh_chksum;
13487 		sctph->sh_chksum = 0;
13488 		calcsum = sctp_cksum(mp, u1);
13489 		sctph->sh_chksum = pktsum;
13490 		if (calcsum != pktsum)
13491 			sctp_csum_err = B_TRUE;
13492 #ifdef	DEBUG	/* skip_sctp_cksum */
13493 	}
13494 #endif
13495 	/* get the ports */
13496 	ports = *(uint32_t *)&sctph->sh_sport;
13497 
13498 	IRE_REFRELE(ire);
13499 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13500 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13501 	if (sctp_csum_err) {
13502 		/*
13503 		 * No potential sctp checksum errors go to the Sun
13504 		 * sctp stack however they might be Adler-32 summed
13505 		 * packets a userland stack bound to a raw IP socket
13506 		 * could reasonably use. Note though that Adler-32 is
13507 		 * a long deprecated algorithm and customer sctp
13508 		 * networks should eventually migrate to CRC-32 at
13509 		 * which time this facility should be removed.
13510 		 */
13511 		flags |= IP_FF_SCTP_CSUM_ERR;
13512 		goto no_conn;
13513 	}
13514 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13515 	    sctps)) == NULL) {
13516 		/* Check for raw socket or OOTB handling */
13517 		goto no_conn;
13518 	}
13519 
13520 	/* Found a client; up it goes */
13521 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13522 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13523 	return;
13524 
13525 no_conn:
13526 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13527 	    ports, mctl_present, flags, B_TRUE, zoneid);
13528 	return;
13529 
13530 ipoptions:
13531 	DB_CKSUMFLAGS(mp) = 0;
13532 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13533 		goto slow_done;
13534 
13535 	UPDATE_IB_PKT_COUNT(ire);
13536 	ire->ire_last_used_time = lbolt;
13537 
13538 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13539 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13540 fragmented:
13541 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13542 			goto slow_done;
13543 		/*
13544 		 * Make sure that first_mp points back to mp as
13545 		 * the mp we came in with could have changed in
13546 		 * ip_rput_fragment().
13547 		 */
13548 		ASSERT(!mctl_present);
13549 		ipha = (ipha_t *)mp->b_rptr;
13550 		first_mp = mp;
13551 	}
13552 
13553 	/* Now we have a complete datagram, destined for this machine. */
13554 	u1 = IPH_HDR_LENGTH(ipha);
13555 	goto find_sctp_client;
13556 #undef  iphs
13557 #undef  rptr
13558 
13559 error:
13560 	freemsg(first_mp);
13561 slow_done:
13562 	IRE_REFRELE(ire);
13563 }
13564 
13565 #define	VER_BITS	0xF0
13566 #define	VERSION_6	0x60
13567 
13568 static boolean_t
13569 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13570     ipaddr_t *dstp, ip_stack_t *ipst)
13571 {
13572 	uint_t	opt_len;
13573 	ipha_t *ipha;
13574 	ssize_t len;
13575 	uint_t	pkt_len;
13576 
13577 	ASSERT(ill != NULL);
13578 	IP_STAT(ipst, ip_ipoptions);
13579 	ipha = *iphapp;
13580 
13581 #define	rptr    ((uchar_t *)ipha)
13582 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13583 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13584 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13585 		freemsg(mp);
13586 		return (B_FALSE);
13587 	}
13588 
13589 	/* multiple mblk or too short */
13590 	pkt_len = ntohs(ipha->ipha_length);
13591 
13592 	/* Get the number of words of IP options in the IP header. */
13593 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13594 	if (opt_len) {
13595 		/* IP Options present!  Validate and process. */
13596 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13597 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13598 			goto done;
13599 		}
13600 		/*
13601 		 * Recompute complete header length and make sure we
13602 		 * have access to all of it.
13603 		 */
13604 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13605 		if (len > (mp->b_wptr - rptr)) {
13606 			if (len > pkt_len) {
13607 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13608 				goto done;
13609 			}
13610 			if (!pullupmsg(mp, len)) {
13611 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13612 				goto done;
13613 			}
13614 			ipha = (ipha_t *)mp->b_rptr;
13615 		}
13616 		/*
13617 		 * Go off to ip_rput_options which returns the next hop
13618 		 * destination address, which may have been affected
13619 		 * by source routing.
13620 		 */
13621 		IP_STAT(ipst, ip_opt);
13622 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13623 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13624 			return (B_FALSE);
13625 		}
13626 	}
13627 	*iphapp = ipha;
13628 	return (B_TRUE);
13629 done:
13630 	/* clear b_prev - used by ip_mroute_decap */
13631 	mp->b_prev = NULL;
13632 	freemsg(mp);
13633 	return (B_FALSE);
13634 #undef  rptr
13635 }
13636 
13637 /*
13638  * Deal with the fact that there is no ire for the destination.
13639  */
13640 static ire_t *
13641 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13642 {
13643 	ipha_t	*ipha;
13644 	ill_t	*ill;
13645 	ire_t	*ire;
13646 	ip_stack_t *ipst;
13647 	enum	ire_forward_action ret_action;
13648 
13649 	ipha = (ipha_t *)mp->b_rptr;
13650 	ill = (ill_t *)q->q_ptr;
13651 
13652 	ASSERT(ill != NULL);
13653 	ipst = ill->ill_ipst;
13654 
13655 	/*
13656 	 * No IRE for this destination, so it can't be for us.
13657 	 * Unless we are forwarding, drop the packet.
13658 	 * We have to let source routed packets through
13659 	 * since we don't yet know if they are 'ping -l'
13660 	 * packets i.e. if they will go out over the
13661 	 * same interface as they came in on.
13662 	 */
13663 	if (ll_multicast) {
13664 		freemsg(mp);
13665 		return (NULL);
13666 	}
13667 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13668 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13669 		freemsg(mp);
13670 		return (NULL);
13671 	}
13672 
13673 	/*
13674 	 * Mark this packet as having originated externally.
13675 	 *
13676 	 * For non-forwarding code path, ire_send later double
13677 	 * checks this interface to see if it is still exists
13678 	 * post-ARP resolution.
13679 	 *
13680 	 * Also, IPQOS uses this to differentiate between
13681 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13682 	 * QOS packet processing in ip_wput_attach_llhdr().
13683 	 * The QoS module can mark the b_band for a fastpath message
13684 	 * or the dl_priority field in a unitdata_req header for
13685 	 * CoS marking. This info can only be found in
13686 	 * ip_wput_attach_llhdr().
13687 	 */
13688 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13689 	/*
13690 	 * Clear the indication that this may have a hardware checksum
13691 	 * as we are not using it
13692 	 */
13693 	DB_CKSUMFLAGS(mp) = 0;
13694 
13695 	ire = ire_forward(dst, &ret_action, NULL, NULL,
13696 	    MBLK_GETLABEL(mp), ipst);
13697 
13698 	if (ire == NULL && ret_action == Forward_check_multirt) {
13699 		/* Let ip_newroute handle CGTP  */
13700 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13701 		return (NULL);
13702 	}
13703 
13704 	if (ire != NULL)
13705 		return (ire);
13706 
13707 	mp->b_prev = mp->b_next = 0;
13708 
13709 	if (ret_action == Forward_blackhole) {
13710 		freemsg(mp);
13711 		return (NULL);
13712 	}
13713 	/* send icmp unreachable */
13714 	q = WR(q);
13715 	/* Sent by forwarding path, and router is global zone */
13716 	if (ip_source_routed(ipha, ipst)) {
13717 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13718 		    GLOBAL_ZONEID, ipst);
13719 	} else {
13720 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13721 		    ipst);
13722 	}
13723 
13724 	return (NULL);
13725 
13726 }
13727 
13728 /*
13729  * check ip header length and align it.
13730  */
13731 static boolean_t
13732 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13733 {
13734 	ssize_t len;
13735 	ill_t *ill;
13736 	ipha_t	*ipha;
13737 
13738 	len = MBLKL(mp);
13739 
13740 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13741 		ill = (ill_t *)q->q_ptr;
13742 
13743 		if (!OK_32PTR(mp->b_rptr))
13744 			IP_STAT(ipst, ip_notaligned1);
13745 		else
13746 			IP_STAT(ipst, ip_notaligned2);
13747 		/* Guard against bogus device drivers */
13748 		if (len < 0) {
13749 			/* clear b_prev - used by ip_mroute_decap */
13750 			mp->b_prev = NULL;
13751 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13752 			freemsg(mp);
13753 			return (B_FALSE);
13754 		}
13755 
13756 		if (ip_rput_pullups++ == 0) {
13757 			ipha = (ipha_t *)mp->b_rptr;
13758 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13759 			    "ip_check_and_align_header: %s forced us to "
13760 			    " pullup pkt, hdr len %ld, hdr addr %p",
13761 			    ill->ill_name, len, ipha);
13762 		}
13763 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13764 			/* clear b_prev - used by ip_mroute_decap */
13765 			mp->b_prev = NULL;
13766 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13767 			freemsg(mp);
13768 			return (B_FALSE);
13769 		}
13770 	}
13771 	return (B_TRUE);
13772 }
13773 
13774 ire_t *
13775 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13776 {
13777 	ire_t		*new_ire;
13778 	ill_t		*ire_ill;
13779 	uint_t		ifindex;
13780 	ip_stack_t	*ipst = ill->ill_ipst;
13781 	boolean_t	strict_check = B_FALSE;
13782 
13783 	/*
13784 	 * This packet came in on an interface other than the one associated
13785 	 * with the first ire we found for the destination address. We do
13786 	 * another ire lookup here, using the ingress ill, to see if the
13787 	 * interface is in an interface group.
13788 	 * As long as the ills belong to the same group, we don't consider
13789 	 * them to be arriving on the wrong interface. Thus, if the switch
13790 	 * is doing inbound load spreading, we won't drop packets when the
13791 	 * ip*_strict_dst_multihoming switch is on. Note, the same holds true
13792 	 * for 'usesrc groups' where the destination address may belong to
13793 	 * another interface to allow multipathing to happen.
13794 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13795 	 * where the local address may not be unique. In this case we were
13796 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13797 	 * actually returned. The new lookup, which is more specific, should
13798 	 * only find the IRE_LOCAL associated with the ingress ill if one
13799 	 * exists.
13800 	 */
13801 
13802 	if (ire->ire_ipversion == IPV4_VERSION) {
13803 		if (ipst->ips_ip_strict_dst_multihoming)
13804 			strict_check = B_TRUE;
13805 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13806 		    ill->ill_ipif, ALL_ZONES, NULL,
13807 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13808 	} else {
13809 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13810 		if (ipst->ips_ipv6_strict_dst_multihoming)
13811 			strict_check = B_TRUE;
13812 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13813 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13814 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13815 	}
13816 	/*
13817 	 * If the same ire that was returned in ip_input() is found then this
13818 	 * is an indication that interface groups are in use. The packet
13819 	 * arrived on a different ill in the group than the one associated with
13820 	 * the destination address.  If a different ire was found then the same
13821 	 * IP address must be hosted on multiple ills. This is possible with
13822 	 * unnumbered point2point interfaces. We switch to use this new ire in
13823 	 * order to have accurate interface statistics.
13824 	 */
13825 	if (new_ire != NULL) {
13826 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13827 			ire_refrele(ire);
13828 			ire = new_ire;
13829 		} else {
13830 			ire_refrele(new_ire);
13831 		}
13832 		return (ire);
13833 	} else if ((ire->ire_rfq == NULL) &&
13834 	    (ire->ire_ipversion == IPV4_VERSION)) {
13835 		/*
13836 		 * The best match could have been the original ire which
13837 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13838 		 * the strict multihoming checks are irrelevant as we consider
13839 		 * local addresses hosted on lo0 to be interface agnostic. We
13840 		 * only expect a null ire_rfq on IREs which are associated with
13841 		 * lo0 hence we can return now.
13842 		 */
13843 		return (ire);
13844 	}
13845 
13846 	/*
13847 	 * Chase pointers once and store locally.
13848 	 */
13849 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13850 	    (ill_t *)(ire->ire_rfq->q_ptr);
13851 	ifindex = ill->ill_usesrc_ifindex;
13852 
13853 	/*
13854 	 * Check if it's a legal address on the 'usesrc' interface.
13855 	 */
13856 	if ((ifindex != 0) && (ire_ill != NULL) &&
13857 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13858 		return (ire);
13859 	}
13860 
13861 	/*
13862 	 * If the ip*_strict_dst_multihoming switch is on then we can
13863 	 * only accept this packet if the interface is marked as routing.
13864 	 */
13865 	if (!(strict_check))
13866 		return (ire);
13867 
13868 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13869 	    ILLF_ROUTER) != 0) {
13870 		return (ire);
13871 	}
13872 
13873 	ire_refrele(ire);
13874 	return (NULL);
13875 }
13876 
13877 ire_t *
13878 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13879 {
13880 	ipha_t	*ipha;
13881 	ire_t	*src_ire;
13882 	ill_t	*stq_ill;
13883 	uint_t	hlen;
13884 	uint_t	pkt_len;
13885 	uint32_t sum;
13886 	queue_t	*dev_q;
13887 	ip_stack_t *ipst = ill->ill_ipst;
13888 	mblk_t *fpmp;
13889 	enum	ire_forward_action ret_action;
13890 
13891 	ipha = (ipha_t *)mp->b_rptr;
13892 
13893 	if (ire != NULL &&
13894 	    ire->ire_zoneid != GLOBAL_ZONEID &&
13895 	    ire->ire_zoneid != ALL_ZONES) {
13896 		/*
13897 		 * Should only use IREs that are visible to the global
13898 		 * zone for forwarding.
13899 		 */
13900 		ire_refrele(ire);
13901 		ire = ire_cache_lookup(dst, GLOBAL_ZONEID, NULL, ipst);
13902 	}
13903 
13904 	/*
13905 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13906 	 * The loopback address check for both src and dst has already
13907 	 * been checked in ip_input
13908 	 */
13909 
13910 	if (dst == INADDR_ANY || CLASSD(ipha->ipha_src)) {
13911 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13912 		goto drop;
13913 	}
13914 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13915 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13916 
13917 	if (src_ire != NULL) {
13918 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13919 		ire_refrele(src_ire);
13920 		goto drop;
13921 	}
13922 
13923 	/* No ire cache of nexthop. So first create one  */
13924 	if (ire == NULL) {
13925 
13926 		ire = ire_forward(dst, &ret_action, NULL, NULL,
13927 		    NULL, ipst);
13928 		/*
13929 		 * We only come to ip_fast_forward if ip_cgtp_filter
13930 		 * is not set. So ire_forward() should not return with
13931 		 * Forward_check_multirt as the next action.
13932 		 */
13933 		ASSERT(ret_action != Forward_check_multirt);
13934 		if (ire == NULL) {
13935 			/* An attempt was made to forward the packet */
13936 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13937 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13938 			mp->b_prev = mp->b_next = 0;
13939 			/* send icmp unreachable */
13940 			/* Sent by forwarding path, and router is global zone */
13941 			if (ret_action == Forward_ret_icmp_err) {
13942 				if (ip_source_routed(ipha, ipst)) {
13943 					icmp_unreachable(ill->ill_wq, mp,
13944 					    ICMP_SOURCE_ROUTE_FAILED,
13945 					    GLOBAL_ZONEID, ipst);
13946 				} else {
13947 					icmp_unreachable(ill->ill_wq, mp,
13948 					    ICMP_HOST_UNREACHABLE,
13949 					    GLOBAL_ZONEID, ipst);
13950 				}
13951 			} else {
13952 				freemsg(mp);
13953 			}
13954 			return (NULL);
13955 		}
13956 	}
13957 
13958 	/*
13959 	 * Forwarding fastpath exception case:
13960 	 * If either of the follwoing case is true, we take
13961 	 * the slowpath
13962 	 *	o forwarding is not enabled
13963 	 *	o incoming and outgoing interface are the same, or the same
13964 	 *	  IPMP group
13965 	 *	o corresponding ire is in incomplete state
13966 	 *	o packet needs fragmentation
13967 	 *	o ARP cache is not resolved
13968 	 *
13969 	 * The codeflow from here on is thus:
13970 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13971 	 */
13972 	pkt_len = ntohs(ipha->ipha_length);
13973 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13974 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13975 	    !(ill->ill_flags & ILLF_ROUTER) ||
13976 	    (ill == stq_ill) ||
13977 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
13978 	    (ire->ire_nce == NULL) ||
13979 	    (pkt_len > ire->ire_max_frag) ||
13980 	    ((fpmp = ire->ire_nce->nce_fp_mp) == NULL) ||
13981 	    ((hlen = MBLKL(fpmp)) > MBLKHEAD(mp)) ||
13982 	    ipha->ipha_ttl <= 1) {
13983 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13984 		    ipha, ill, B_FALSE);
13985 		return (ire);
13986 	}
13987 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13988 
13989 	DTRACE_PROBE4(ip4__forwarding__start,
13990 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13991 
13992 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
13993 	    ipst->ips_ipv4firewall_forwarding,
13994 	    ill, stq_ill, ipha, mp, mp, 0, ipst);
13995 
13996 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13997 
13998 	if (mp == NULL)
13999 		goto drop;
14000 
14001 	mp->b_datap->db_struioun.cksum.flags = 0;
14002 	/* Adjust the checksum to reflect the ttl decrement. */
14003 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
14004 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
14005 	ipha->ipha_ttl--;
14006 
14007 	/*
14008 	 * Write the link layer header.  We can do this safely here,
14009 	 * because we have already tested to make sure that the IP
14010 	 * policy is not set, and that we have a fast path destination
14011 	 * header.
14012 	 */
14013 	mp->b_rptr -= hlen;
14014 	bcopy(fpmp->b_rptr, mp->b_rptr, hlen);
14015 
14016 	UPDATE_IB_PKT_COUNT(ire);
14017 	ire->ire_last_used_time = lbolt;
14018 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
14019 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14020 	UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets, pkt_len);
14021 
14022 	dev_q = ire->ire_stq->q_next;
14023 	if ((dev_q->q_next != NULL || dev_q->q_first != NULL) &&
14024 	    !canputnext(ire->ire_stq)) {
14025 		goto indiscard;
14026 	}
14027 	if (ILL_DLS_CAPABLE(stq_ill)) {
14028 		/*
14029 		 * Send the packet directly to DLD, where it
14030 		 * may be queued depending on the availability
14031 		 * of transmit resources at the media layer.
14032 		 */
14033 		IP_DLS_ILL_TX(stq_ill, ipha, mp, ipst);
14034 	} else {
14035 		DTRACE_PROBE4(ip4__physical__out__start,
14036 		    ill_t *, NULL, ill_t *, stq_ill,
14037 		    ipha_t *, ipha, mblk_t *, mp);
14038 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
14039 		    ipst->ips_ipv4firewall_physical_out,
14040 		    NULL, stq_ill, ipha, mp, mp, 0, ipst);
14041 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
14042 		if (mp == NULL)
14043 			goto drop;
14044 
14045 		DTRACE_IP7(send, mblk_t *, mp, conn_t *, NULL, void_ip_t *,
14046 		    ipha, __dtrace_ipsr_ill_t *, stq_ill, ipha_t *, ipha,
14047 		    ip6_t *, NULL, int, 0);
14048 
14049 		putnext(ire->ire_stq, mp);
14050 	}
14051 	return (ire);
14052 
14053 indiscard:
14054 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14055 drop:
14056 	if (mp != NULL)
14057 		freemsg(mp);
14058 	return (ire);
14059 
14060 }
14061 
14062 /*
14063  * This function is called in the forwarding slowpath, when
14064  * either the ire lacks the link-layer address, or the packet needs
14065  * further processing(eg. fragmentation), before transmission.
14066  */
14067 
14068 static void
14069 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14070     ill_t *ill, boolean_t ll_multicast)
14071 {
14072 	ill_group_t	*ill_group;
14073 	ill_group_t	*ire_group;
14074 	queue_t		*dev_q;
14075 	ire_t		*src_ire;
14076 	ip_stack_t	*ipst = ill->ill_ipst;
14077 
14078 	ASSERT(ire->ire_stq != NULL);
14079 
14080 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14081 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14082 
14083 	if (ll_multicast != 0) {
14084 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14085 		goto drop_pkt;
14086 	}
14087 
14088 	/*
14089 	 * check if ipha_src is a broadcast address. Note that this
14090 	 * check is redundant when we get here from ip_fast_forward()
14091 	 * which has already done this check. However, since we can
14092 	 * also get here from ip_rput_process_broadcast() or, for
14093 	 * for the slow path through ip_fast_forward(), we perform
14094 	 * the check again for code-reusability
14095 	 */
14096 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14097 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14098 	if (src_ire != NULL || ipha->ipha_dst == INADDR_ANY) {
14099 		if (src_ire != NULL)
14100 			ire_refrele(src_ire);
14101 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14102 		ip2dbg(("ip_rput_process_forward: Received packet with"
14103 		    " bad src/dst address on %s\n", ill->ill_name));
14104 		goto drop_pkt;
14105 	}
14106 
14107 	ill_group = ill->ill_group;
14108 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
14109 	/*
14110 	 * Check if we want to forward this one at this time.
14111 	 * We allow source routed packets on a host provided that
14112 	 * they go out the same interface or same interface group
14113 	 * as they came in on.
14114 	 *
14115 	 * XXX To be quicker, we may wish to not chase pointers to
14116 	 * get the ILLF_ROUTER flag and instead store the
14117 	 * forwarding policy in the ire.  An unfortunate
14118 	 * side-effect of that would be requiring an ire flush
14119 	 * whenever the ILLF_ROUTER flag changes.
14120 	 */
14121 	if (((ill->ill_flags &
14122 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
14123 	    ILLF_ROUTER) == 0) &&
14124 	    !(ip_source_routed(ipha, ipst) && (ire->ire_rfq == q ||
14125 	    (ill_group != NULL && ill_group == ire_group)))) {
14126 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14127 		if (ip_source_routed(ipha, ipst)) {
14128 			q = WR(q);
14129 			/*
14130 			 * Clear the indication that this may have
14131 			 * hardware checksum as we are not using it.
14132 			 */
14133 			DB_CKSUMFLAGS(mp) = 0;
14134 			/* Sent by forwarding path, and router is global zone */
14135 			icmp_unreachable(q, mp,
14136 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14137 			return;
14138 		}
14139 		goto drop_pkt;
14140 	}
14141 
14142 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14143 
14144 	/* Packet is being forwarded. Turning off hwcksum flag. */
14145 	DB_CKSUMFLAGS(mp) = 0;
14146 	if (ipst->ips_ip_g_send_redirects) {
14147 		/*
14148 		 * Check whether the incoming interface and outgoing
14149 		 * interface is part of the same group. If so,
14150 		 * send redirects.
14151 		 *
14152 		 * Check the source address to see if it originated
14153 		 * on the same logical subnet it is going back out on.
14154 		 * If so, we should be able to send it a redirect.
14155 		 * Avoid sending a redirect if the destination
14156 		 * is directly connected (i.e., ipha_dst is the same
14157 		 * as ire_gateway_addr or the ire_addr of the
14158 		 * nexthop IRE_CACHE ), or if the packet was source
14159 		 * routed out this interface.
14160 		 */
14161 		ipaddr_t src, nhop;
14162 		mblk_t	*mp1;
14163 		ire_t	*nhop_ire = NULL;
14164 
14165 		/*
14166 		 * Check whether ire_rfq and q are from the same ill
14167 		 * or if they are not same, they at least belong
14168 		 * to the same group. If so, send redirects.
14169 		 */
14170 		if ((ire->ire_rfq == q ||
14171 		    (ill_group != NULL && ill_group == ire_group)) &&
14172 		    !ip_source_routed(ipha, ipst)) {
14173 
14174 			nhop = (ire->ire_gateway_addr != 0 ?
14175 			    ire->ire_gateway_addr : ire->ire_addr);
14176 
14177 			if (ipha->ipha_dst == nhop) {
14178 				/*
14179 				 * We avoid sending a redirect if the
14180 				 * destination is directly connected
14181 				 * because it is possible that multiple
14182 				 * IP subnets may have been configured on
14183 				 * the link, and the source may not
14184 				 * be on the same subnet as ip destination,
14185 				 * even though they are on the same
14186 				 * physical link.
14187 				 */
14188 				goto sendit;
14189 			}
14190 
14191 			src = ipha->ipha_src;
14192 
14193 			/*
14194 			 * We look up the interface ire for the nexthop,
14195 			 * to see if ipha_src is in the same subnet
14196 			 * as the nexthop.
14197 			 *
14198 			 * Note that, if, in the future, IRE_CACHE entries
14199 			 * are obsoleted,  this lookup will not be needed,
14200 			 * as the ire passed to this function will be the
14201 			 * same as the nhop_ire computed below.
14202 			 */
14203 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14204 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14205 			    0, NULL, MATCH_IRE_TYPE, ipst);
14206 
14207 			if (nhop_ire != NULL) {
14208 				if ((src & nhop_ire->ire_mask) ==
14209 				    (nhop & nhop_ire->ire_mask)) {
14210 					/*
14211 					 * The source is directly connected.
14212 					 * Just copy the ip header (which is
14213 					 * in the first mblk)
14214 					 */
14215 					mp1 = copyb(mp);
14216 					if (mp1 != NULL) {
14217 						icmp_send_redirect(WR(q), mp1,
14218 						    nhop, ipst);
14219 					}
14220 				}
14221 				ire_refrele(nhop_ire);
14222 			}
14223 		}
14224 	}
14225 sendit:
14226 	dev_q = ire->ire_stq->q_next;
14227 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
14228 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14229 		freemsg(mp);
14230 		return;
14231 	}
14232 
14233 	ip_rput_forward(ire, ipha, mp, ill);
14234 	return;
14235 
14236 drop_pkt:
14237 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14238 	freemsg(mp);
14239 }
14240 
14241 ire_t *
14242 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14243     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14244 {
14245 	queue_t		*q;
14246 	uint16_t	hcksumflags;
14247 	ip_stack_t	*ipst = ill->ill_ipst;
14248 
14249 	q = *qp;
14250 
14251 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14252 
14253 	/*
14254 	 * Clear the indication that this may have hardware
14255 	 * checksum as we are not using it for forwarding.
14256 	 */
14257 	hcksumflags = DB_CKSUMFLAGS(mp);
14258 	DB_CKSUMFLAGS(mp) = 0;
14259 
14260 	/*
14261 	 * Directed broadcast forwarding: if the packet came in over a
14262 	 * different interface then it is routed out over we can forward it.
14263 	 */
14264 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14265 		ire_refrele(ire);
14266 		freemsg(mp);
14267 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14268 		return (NULL);
14269 	}
14270 	/*
14271 	 * For multicast we have set dst to be INADDR_BROADCAST
14272 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
14273 	 * only for broadcast packets.
14274 	 */
14275 	if (!CLASSD(ipha->ipha_dst)) {
14276 		ire_t *new_ire;
14277 		ipif_t *ipif;
14278 		/*
14279 		 * For ill groups, as the switch duplicates broadcasts
14280 		 * across all the ports, we need to filter out and
14281 		 * send up only one copy. There is one copy for every
14282 		 * broadcast address on each ill. Thus, we look for a
14283 		 * specific IRE on this ill and look at IRE_MARK_NORECV
14284 		 * later to see whether this ill is eligible to receive
14285 		 * them or not. ill_nominate_bcast_rcv() nominates only
14286 		 * one set of IREs for receiving.
14287 		 */
14288 
14289 		ipif = ipif_get_next_ipif(NULL, ill);
14290 		if (ipif == NULL) {
14291 			ire_refrele(ire);
14292 			freemsg(mp);
14293 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14294 			return (NULL);
14295 		}
14296 		new_ire = ire_ctable_lookup(dst, 0, 0,
14297 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14298 		ipif_refrele(ipif);
14299 
14300 		if (new_ire != NULL) {
14301 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
14302 				ire_refrele(ire);
14303 				ire_refrele(new_ire);
14304 				freemsg(mp);
14305 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14306 				return (NULL);
14307 			}
14308 			/*
14309 			 * In the special case of multirouted broadcast
14310 			 * packets, we unconditionally need to "gateway"
14311 			 * them to the appropriate interface here.
14312 			 * In the normal case, this cannot happen, because
14313 			 * there is no broadcast IRE tagged with the
14314 			 * RTF_MULTIRT flag.
14315 			 */
14316 			if (new_ire->ire_flags & RTF_MULTIRT) {
14317 				ire_refrele(new_ire);
14318 				if (ire->ire_rfq != NULL) {
14319 					q = ire->ire_rfq;
14320 					*qp = q;
14321 				}
14322 			} else {
14323 				ire_refrele(ire);
14324 				ire = new_ire;
14325 			}
14326 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14327 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14328 				/*
14329 				 * Free the message if
14330 				 * ip_g_forward_directed_bcast is turned
14331 				 * off for non-local broadcast.
14332 				 */
14333 				ire_refrele(ire);
14334 				freemsg(mp);
14335 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14336 				return (NULL);
14337 			}
14338 		} else {
14339 			/*
14340 			 * This CGTP packet successfully passed the
14341 			 * CGTP filter, but the related CGTP
14342 			 * broadcast IRE has not been found,
14343 			 * meaning that the redundant ipif is
14344 			 * probably down. However, if we discarded
14345 			 * this packet, its duplicate would be
14346 			 * filtered out by the CGTP filter so none
14347 			 * of them would get through. So we keep
14348 			 * going with this one.
14349 			 */
14350 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14351 			if (ire->ire_rfq != NULL) {
14352 				q = ire->ire_rfq;
14353 				*qp = q;
14354 			}
14355 		}
14356 	}
14357 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14358 		/*
14359 		 * Verify that there are not more then one
14360 		 * IRE_BROADCAST with this broadcast address which
14361 		 * has ire_stq set.
14362 		 * TODO: simplify, loop over all IRE's
14363 		 */
14364 		ire_t	*ire1;
14365 		int	num_stq = 0;
14366 		mblk_t	*mp1;
14367 
14368 		/* Find the first one with ire_stq set */
14369 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14370 		for (ire1 = ire; ire1 &&
14371 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14372 		    ire1 = ire1->ire_next)
14373 			;
14374 		if (ire1) {
14375 			ire_refrele(ire);
14376 			ire = ire1;
14377 			IRE_REFHOLD(ire);
14378 		}
14379 
14380 		/* Check if there are additional ones with stq set */
14381 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14382 			if (ire->ire_addr != ire1->ire_addr)
14383 				break;
14384 			if (ire1->ire_stq) {
14385 				num_stq++;
14386 				break;
14387 			}
14388 		}
14389 		rw_exit(&ire->ire_bucket->irb_lock);
14390 		if (num_stq == 1 && ire->ire_stq != NULL) {
14391 			ip1dbg(("ip_rput_process_broadcast: directed "
14392 			    "broadcast to 0x%x\n",
14393 			    ntohl(ire->ire_addr)));
14394 			mp1 = copymsg(mp);
14395 			if (mp1) {
14396 				switch (ipha->ipha_protocol) {
14397 				case IPPROTO_UDP:
14398 					ip_udp_input(q, mp1, ipha, ire, ill);
14399 					break;
14400 				default:
14401 					ip_proto_input(q, mp1, ipha, ire, ill,
14402 					    0);
14403 					break;
14404 				}
14405 			}
14406 			/*
14407 			 * Adjust ttl to 2 (1+1 - the forward engine
14408 			 * will decrement it by one.
14409 			 */
14410 			if (ip_csum_hdr(ipha)) {
14411 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14412 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14413 				freemsg(mp);
14414 				ire_refrele(ire);
14415 				return (NULL);
14416 			}
14417 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14418 			ipha->ipha_hdr_checksum = 0;
14419 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14420 			ip_rput_process_forward(q, mp, ire, ipha,
14421 			    ill, ll_multicast);
14422 			ire_refrele(ire);
14423 			return (NULL);
14424 		}
14425 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14426 		    ntohl(ire->ire_addr)));
14427 	}
14428 
14429 
14430 	/* Restore any hardware checksum flags */
14431 	DB_CKSUMFLAGS(mp) = hcksumflags;
14432 	return (ire);
14433 }
14434 
14435 /* ARGSUSED */
14436 static boolean_t
14437 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14438     int *ll_multicast, ipaddr_t *dstp)
14439 {
14440 	ip_stack_t	*ipst = ill->ill_ipst;
14441 
14442 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14443 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14444 	    ntohs(ipha->ipha_length));
14445 
14446 	/*
14447 	 * Forward packets only if we have joined the allmulti
14448 	 * group on this interface.
14449 	 */
14450 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14451 		int retval;
14452 
14453 		/*
14454 		 * Clear the indication that this may have hardware
14455 		 * checksum as we are not using it.
14456 		 */
14457 		DB_CKSUMFLAGS(mp) = 0;
14458 		retval = ip_mforward(ill, ipha, mp);
14459 		/* ip_mforward updates mib variables if needed */
14460 		/* clear b_prev - used by ip_mroute_decap */
14461 		mp->b_prev = NULL;
14462 
14463 		switch (retval) {
14464 		case 0:
14465 			/*
14466 			 * pkt is okay and arrived on phyint.
14467 			 *
14468 			 * If we are running as a multicast router
14469 			 * we need to see all IGMP and/or PIM packets.
14470 			 */
14471 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14472 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14473 				goto done;
14474 			}
14475 			break;
14476 		case -1:
14477 			/* pkt is mal-formed, toss it */
14478 			goto drop_pkt;
14479 		case 1:
14480 			/* pkt is okay and arrived on a tunnel */
14481 			/*
14482 			 * If we are running a multicast router
14483 			 *  we need to see all igmp packets.
14484 			 */
14485 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14486 				*dstp = INADDR_BROADCAST;
14487 				*ll_multicast = 1;
14488 				return (B_FALSE);
14489 			}
14490 
14491 			goto drop_pkt;
14492 		}
14493 	}
14494 
14495 	ILM_WALKER_HOLD(ill);
14496 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14497 		/*
14498 		 * This might just be caused by the fact that
14499 		 * multiple IP Multicast addresses map to the same
14500 		 * link layer multicast - no need to increment counter!
14501 		 */
14502 		ILM_WALKER_RELE(ill);
14503 		freemsg(mp);
14504 		return (B_TRUE);
14505 	}
14506 	ILM_WALKER_RELE(ill);
14507 done:
14508 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14509 	/*
14510 	 * This assumes the we deliver to all streams for multicast
14511 	 * and broadcast packets.
14512 	 */
14513 	*dstp = INADDR_BROADCAST;
14514 	*ll_multicast = 1;
14515 	return (B_FALSE);
14516 drop_pkt:
14517 	ip2dbg(("ip_rput: drop pkt\n"));
14518 	freemsg(mp);
14519 	return (B_TRUE);
14520 }
14521 
14522 /*
14523  * This function is used to both return an indication of whether or not
14524  * the packet received is a non-unicast packet (by way of the DL_UNITDATA_IND)
14525  * and in doing so, determine whether or not it is broadcast vs multicast.
14526  * For it to be a broadcast packet, we must have the appropriate mblk_t
14527  * hanging off the ill_t.  If this is either not present or doesn't match
14528  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
14529  * to be multicast.  Thus NICs that have no broadcast address (or no
14530  * capability for one, such as point to point links) cannot return as
14531  * the packet being broadcast.  The use of HPE_BROADCAST/HPE_MULTICAST as
14532  * the return values simplifies the current use of the return value of this
14533  * function, which is to pass through the multicast/broadcast characteristic
14534  * to consumers of the netinfo/pfhooks API.  While this is not cast in stone,
14535  * changing the return value to some other symbol demands the appropriate
14536  * "translation" when hpe_flags is set prior to calling hook_run() for
14537  * packet events.
14538  */
14539 int
14540 ip_get_dlpi_mbcast(ill_t *ill, mblk_t *mb)
14541 {
14542 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
14543 	mblk_t *bmp;
14544 
14545 	if (ind->dl_group_address) {
14546 		if (ind->dl_dest_addr_offset > sizeof (*ind) &&
14547 		    ind->dl_dest_addr_offset + ind->dl_dest_addr_length <
14548 		    MBLKL(mb) &&
14549 		    (bmp = ill->ill_bcast_mp) != NULL) {
14550 			dl_unitdata_req_t *dlur;
14551 			uint8_t *bphys_addr;
14552 
14553 			dlur = (dl_unitdata_req_t *)bmp->b_rptr;
14554 			if (ill->ill_sap_length < 0)
14555 				bphys_addr = (uchar_t *)dlur +
14556 				    dlur->dl_dest_addr_offset;
14557 			else
14558 				bphys_addr = (uchar_t *)dlur +
14559 				    dlur->dl_dest_addr_offset +
14560 				    ill->ill_sap_length;
14561 
14562 			if (bcmp(mb->b_rptr + ind->dl_dest_addr_offset,
14563 			    bphys_addr, ind->dl_dest_addr_length) == 0) {
14564 				return (HPE_BROADCAST);
14565 			}
14566 			return (HPE_MULTICAST);
14567 		}
14568 		return (HPE_MULTICAST);
14569 	}
14570 	return (0);
14571 }
14572 
14573 static boolean_t
14574 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14575     int *ll_multicast, mblk_t **mpp)
14576 {
14577 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14578 	boolean_t must_copy = B_FALSE;
14579 	struct iocblk   *iocp;
14580 	ipha_t		*ipha;
14581 	ip_stack_t	*ipst = ill->ill_ipst;
14582 
14583 #define	rptr    ((uchar_t *)ipha)
14584 
14585 	first_mp = *first_mpp;
14586 	mp = *mpp;
14587 
14588 	ASSERT(first_mp == mp);
14589 
14590 	/*
14591 	 * if db_ref > 1 then copymsg and free original. Packet may be
14592 	 * changed and do not want other entity who has a reference to this
14593 	 * message to trip over the changes. This is a blind change because
14594 	 * trying to catch all places that might change packet is too
14595 	 * difficult (since it may be a module above this one)
14596 	 *
14597 	 * This corresponds to the non-fast path case. We walk down the full
14598 	 * chain in this case, and check the db_ref count of all the dblks,
14599 	 * and do a copymsg if required. It is possible that the db_ref counts
14600 	 * of the data blocks in the mblk chain can be different.
14601 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14602 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14603 	 * 'snoop' is running.
14604 	 */
14605 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14606 		if (mp1->b_datap->db_ref > 1) {
14607 			must_copy = B_TRUE;
14608 			break;
14609 		}
14610 	}
14611 
14612 	if (must_copy) {
14613 		mp1 = copymsg(mp);
14614 		if (mp1 == NULL) {
14615 			for (mp1 = mp; mp1 != NULL;
14616 			    mp1 = mp1->b_cont) {
14617 				mp1->b_next = NULL;
14618 				mp1->b_prev = NULL;
14619 			}
14620 			freemsg(mp);
14621 			if (ill != NULL) {
14622 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14623 			} else {
14624 				BUMP_MIB(&ipst->ips_ip_mib,
14625 				    ipIfStatsInDiscards);
14626 			}
14627 			return (B_TRUE);
14628 		}
14629 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14630 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14631 			/* Copy b_prev - used by ip_mroute_decap */
14632 			to_mp->b_prev = from_mp->b_prev;
14633 			from_mp->b_prev = NULL;
14634 		}
14635 		*first_mpp = first_mp = mp1;
14636 		freemsg(mp);
14637 		mp = mp1;
14638 		*mpp = mp1;
14639 	}
14640 
14641 	ipha = (ipha_t *)mp->b_rptr;
14642 
14643 	/*
14644 	 * previous code has a case for M_DATA.
14645 	 * We want to check how that happens.
14646 	 */
14647 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14648 	switch (first_mp->b_datap->db_type) {
14649 	case M_PROTO:
14650 	case M_PCPROTO:
14651 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14652 		    DL_UNITDATA_IND) {
14653 			/* Go handle anything other than data elsewhere. */
14654 			ip_rput_dlpi(q, mp);
14655 			return (B_TRUE);
14656 		}
14657 
14658 		*ll_multicast = ip_get_dlpi_mbcast(ill, mp);
14659 		/* Ditch the DLPI header. */
14660 		mp1 = mp->b_cont;
14661 		ASSERT(first_mp == mp);
14662 		*first_mpp = mp1;
14663 		freeb(mp);
14664 		*mpp = mp1;
14665 		return (B_FALSE);
14666 	case M_IOCACK:
14667 		ip1dbg(("got iocack "));
14668 		iocp = (struct iocblk *)mp->b_rptr;
14669 		switch (iocp->ioc_cmd) {
14670 		case DL_IOC_HDR_INFO:
14671 			ill = (ill_t *)q->q_ptr;
14672 			ill_fastpath_ack(ill, mp);
14673 			return (B_TRUE);
14674 		case SIOCSTUNPARAM:
14675 		case OSIOCSTUNPARAM:
14676 			/* Go through qwriter_ip */
14677 			break;
14678 		case SIOCGTUNPARAM:
14679 		case OSIOCGTUNPARAM:
14680 			ip_rput_other(NULL, q, mp, NULL);
14681 			return (B_TRUE);
14682 		default:
14683 			putnext(q, mp);
14684 			return (B_TRUE);
14685 		}
14686 		/* FALLTHRU */
14687 	case M_ERROR:
14688 	case M_HANGUP:
14689 		/*
14690 		 * Since this is on the ill stream we unconditionally
14691 		 * bump up the refcount
14692 		 */
14693 		ill_refhold(ill);
14694 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14695 		return (B_TRUE);
14696 	case M_CTL:
14697 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14698 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14699 		    IPHADA_M_CTL)) {
14700 			/*
14701 			 * It's an IPsec accelerated packet.
14702 			 * Make sure that the ill from which we received the
14703 			 * packet has enabled IPsec hardware acceleration.
14704 			 */
14705 			if (!(ill->ill_capabilities &
14706 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14707 				/* IPsec kstats: bean counter */
14708 				freemsg(mp);
14709 				return (B_TRUE);
14710 			}
14711 
14712 			/*
14713 			 * Make mp point to the mblk following the M_CTL,
14714 			 * then process according to type of mp.
14715 			 * After this processing, first_mp will point to
14716 			 * the data-attributes and mp to the pkt following
14717 			 * the M_CTL.
14718 			 */
14719 			mp = first_mp->b_cont;
14720 			if (mp == NULL) {
14721 				freemsg(first_mp);
14722 				return (B_TRUE);
14723 			}
14724 			/*
14725 			 * A Hardware Accelerated packet can only be M_DATA
14726 			 * ESP or AH packet.
14727 			 */
14728 			if (mp->b_datap->db_type != M_DATA) {
14729 				/* non-M_DATA IPsec accelerated packet */
14730 				IPSECHW_DEBUG(IPSECHW_PKT,
14731 				    ("non-M_DATA IPsec accelerated pkt\n"));
14732 				freemsg(first_mp);
14733 				return (B_TRUE);
14734 			}
14735 			ipha = (ipha_t *)mp->b_rptr;
14736 			if (ipha->ipha_protocol != IPPROTO_AH &&
14737 			    ipha->ipha_protocol != IPPROTO_ESP) {
14738 				IPSECHW_DEBUG(IPSECHW_PKT,
14739 				    ("non-M_DATA IPsec accelerated pkt\n"));
14740 				freemsg(first_mp);
14741 				return (B_TRUE);
14742 			}
14743 			*mpp = mp;
14744 			return (B_FALSE);
14745 		}
14746 		putnext(q, mp);
14747 		return (B_TRUE);
14748 	case M_IOCNAK:
14749 		ip1dbg(("got iocnak "));
14750 		iocp = (struct iocblk *)mp->b_rptr;
14751 		switch (iocp->ioc_cmd) {
14752 		case SIOCSTUNPARAM:
14753 		case OSIOCSTUNPARAM:
14754 			/*
14755 			 * Since this is on the ill stream we unconditionally
14756 			 * bump up the refcount
14757 			 */
14758 			ill_refhold(ill);
14759 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14760 			return (B_TRUE);
14761 		case DL_IOC_HDR_INFO:
14762 		case SIOCGTUNPARAM:
14763 		case OSIOCGTUNPARAM:
14764 			ip_rput_other(NULL, q, mp, NULL);
14765 			return (B_TRUE);
14766 		default:
14767 			break;
14768 		}
14769 		/* FALLTHRU */
14770 	default:
14771 		putnext(q, mp);
14772 		return (B_TRUE);
14773 	}
14774 }
14775 
14776 /* Read side put procedure.  Packets coming from the wire arrive here. */
14777 void
14778 ip_rput(queue_t *q, mblk_t *mp)
14779 {
14780 	ill_t	*ill;
14781 	union DL_primitives *dl;
14782 
14783 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14784 
14785 	ill = (ill_t *)q->q_ptr;
14786 
14787 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14788 		/*
14789 		 * If things are opening or closing, only accept high-priority
14790 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14791 		 * created; on close, things hanging off the ill may have been
14792 		 * freed already.)
14793 		 */
14794 		dl = (union DL_primitives *)mp->b_rptr;
14795 		if (DB_TYPE(mp) != M_PCPROTO ||
14796 		    dl->dl_primitive == DL_UNITDATA_IND) {
14797 			/*
14798 			 * SIOC[GS]TUNPARAM ioctls can come here.
14799 			 */
14800 			inet_freemsg(mp);
14801 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14802 			    "ip_rput_end: q %p (%S)", q, "uninit");
14803 			return;
14804 		}
14805 	}
14806 
14807 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14808 	    "ip_rput_end: q %p (%S)", q, "end");
14809 
14810 	ip_input(ill, NULL, mp, NULL);
14811 }
14812 
14813 static mblk_t *
14814 ip_fix_dbref(ill_t *ill, mblk_t *mp)
14815 {
14816 	mblk_t *mp1;
14817 	boolean_t adjusted = B_FALSE;
14818 	ip_stack_t *ipst = ill->ill_ipst;
14819 
14820 	IP_STAT(ipst, ip_db_ref);
14821 	/*
14822 	 * The IP_RECVSLLA option depends on having the
14823 	 * link layer header. First check that:
14824 	 * a> the underlying device is of type ether,
14825 	 * since this option is currently supported only
14826 	 * over ethernet.
14827 	 * b> there is enough room to copy over the link
14828 	 * layer header.
14829 	 *
14830 	 * Once the checks are done, adjust rptr so that
14831 	 * the link layer header will be copied via
14832 	 * copymsg. Note that, IFT_ETHER may be returned
14833 	 * by some non-ethernet drivers but in this case
14834 	 * the second check will fail.
14835 	 */
14836 	if (ill->ill_type == IFT_ETHER &&
14837 	    (mp->b_rptr - mp->b_datap->db_base) >=
14838 	    sizeof (struct ether_header)) {
14839 		mp->b_rptr -= sizeof (struct ether_header);
14840 		adjusted = B_TRUE;
14841 	}
14842 	mp1 = copymsg(mp);
14843 
14844 	if (mp1 == NULL) {
14845 		mp->b_next = NULL;
14846 		/* clear b_prev - used by ip_mroute_decap */
14847 		mp->b_prev = NULL;
14848 		freemsg(mp);
14849 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14850 		return (NULL);
14851 	}
14852 
14853 	if (adjusted) {
14854 		/*
14855 		 * Copy is done. Restore the pointer in
14856 		 * the _new_ mblk
14857 		 */
14858 		mp1->b_rptr += sizeof (struct ether_header);
14859 	}
14860 
14861 	/* Copy b_prev - used by ip_mroute_decap */
14862 	mp1->b_prev = mp->b_prev;
14863 	mp->b_prev = NULL;
14864 
14865 	/* preserve the hardware checksum flags and data, if present */
14866 	if (DB_CKSUMFLAGS(mp) != 0) {
14867 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
14868 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
14869 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
14870 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
14871 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
14872 	}
14873 
14874 	freemsg(mp);
14875 	return (mp1);
14876 }
14877 
14878 /*
14879  * Direct read side procedure capable of dealing with chains. GLDv3 based
14880  * drivers call this function directly with mblk chains while STREAMS
14881  * read side procedure ip_rput() calls this for single packet with ip_ring
14882  * set to NULL to process one packet at a time.
14883  *
14884  * The ill will always be valid if this function is called directly from
14885  * the driver.
14886  *
14887  * If ip_input() is called from GLDv3:
14888  *
14889  *   - This must be a non-VLAN IP stream.
14890  *   - 'mp' is either an untagged or a special priority-tagged packet.
14891  *   - Any VLAN tag that was in the MAC header has been stripped.
14892  *
14893  * If the IP header in packet is not 32-bit aligned, every message in the
14894  * chain will be aligned before further operations. This is required on SPARC
14895  * platform.
14896  */
14897 /* ARGSUSED */
14898 void
14899 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14900     struct mac_header_info_s *mhip)
14901 {
14902 	ipaddr_t		dst = NULL;
14903 	ipaddr_t		prev_dst;
14904 	ire_t			*ire = NULL;
14905 	ipha_t			*ipha;
14906 	uint_t			pkt_len;
14907 	ssize_t			len;
14908 	uint_t			opt_len;
14909 	int			ll_multicast;
14910 	int			cgtp_flt_pkt;
14911 	queue_t			*q = ill->ill_rq;
14912 	squeue_t		*curr_sqp = NULL;
14913 	mblk_t 			*head = NULL;
14914 	mblk_t			*tail = NULL;
14915 	mblk_t			*first_mp;
14916 	mblk_t 			*mp;
14917 	mblk_t			*dmp;
14918 	int			cnt = 0;
14919 	ip_stack_t		*ipst = ill->ill_ipst;
14920 
14921 	ASSERT(mp_chain != NULL);
14922 	ASSERT(ill != NULL);
14923 
14924 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14925 
14926 #define	rptr	((uchar_t *)ipha)
14927 
14928 	while (mp_chain != NULL) {
14929 		first_mp = mp = mp_chain;
14930 		mp_chain = mp_chain->b_next;
14931 		mp->b_next = NULL;
14932 		ll_multicast = 0;
14933 
14934 		/*
14935 		 * We do ire caching from one iteration to
14936 		 * another. In the event the packet chain contains
14937 		 * all packets from the same dst, this caching saves
14938 		 * an ire_cache_lookup for each of the succeeding
14939 		 * packets in a packet chain.
14940 		 */
14941 		prev_dst = dst;
14942 
14943 		/*
14944 		 * if db_ref > 1 then copymsg and free original. Packet
14945 		 * may be changed and we do not want the other entity
14946 		 * who has a reference to this message to trip over the
14947 		 * changes. This is a blind change because trying to
14948 		 * catch all places that might change the packet is too
14949 		 * difficult.
14950 		 *
14951 		 * This corresponds to the fast path case, where we have
14952 		 * a chain of M_DATA mblks.  We check the db_ref count
14953 		 * of only the 1st data block in the mblk chain. There
14954 		 * doesn't seem to be a reason why a device driver would
14955 		 * send up data with varying db_ref counts in the mblk
14956 		 * chain. In any case the Fast path is a private
14957 		 * interface, and our drivers don't do such a thing.
14958 		 * Given the above assumption, there is no need to walk
14959 		 * down the entire mblk chain (which could have a
14960 		 * potential performance problem)
14961 		 */
14962 
14963 		if (DB_REF(mp) > 1) {
14964 			if ((mp = ip_fix_dbref(ill, mp)) == NULL)
14965 				continue;
14966 		}
14967 
14968 		/*
14969 		 * Check and align the IP header.
14970 		 */
14971 		first_mp = mp;
14972 		if (DB_TYPE(mp) == M_DATA) {
14973 			dmp = mp;
14974 		} else if (DB_TYPE(mp) == M_PROTO &&
14975 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14976 			dmp = mp->b_cont;
14977 		} else {
14978 			dmp = NULL;
14979 		}
14980 		if (dmp != NULL) {
14981 			/*
14982 			 * IP header ptr not aligned?
14983 			 * OR IP header not complete in first mblk
14984 			 */
14985 			if (!OK_32PTR(dmp->b_rptr) ||
14986 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
14987 				if (!ip_check_and_align_header(q, dmp, ipst))
14988 					continue;
14989 			}
14990 		}
14991 
14992 		/*
14993 		 * ip_input fast path
14994 		 */
14995 
14996 		/* mblk type is not M_DATA */
14997 		if (DB_TYPE(mp) != M_DATA) {
14998 			if (ip_rput_process_notdata(q, &first_mp, ill,
14999 			    &ll_multicast, &mp))
15000 				continue;
15001 
15002 			/*
15003 			 * The only way we can get here is if we had a
15004 			 * packet that was either a DL_UNITDATA_IND or
15005 			 * an M_CTL for an IPsec accelerated packet.
15006 			 *
15007 			 * In either case, the first_mp will point to
15008 			 * the leading M_PROTO or M_CTL.
15009 			 */
15010 			ASSERT(first_mp != NULL);
15011 		} else if (mhip != NULL) {
15012 			/*
15013 			 * ll_multicast is set here so that it is ready
15014 			 * for easy use with FW_HOOKS().  ip_get_dlpi_mbcast
15015 			 * manipulates ll_multicast in the same fashion when
15016 			 * called from ip_rput_process_notdata.
15017 			 */
15018 			switch (mhip->mhi_dsttype) {
15019 			case MAC_ADDRTYPE_MULTICAST :
15020 				ll_multicast = HPE_MULTICAST;
15021 				break;
15022 			case MAC_ADDRTYPE_BROADCAST :
15023 				ll_multicast = HPE_BROADCAST;
15024 				break;
15025 			default :
15026 				break;
15027 			}
15028 		}
15029 
15030 		/* Make sure its an M_DATA and that its aligned */
15031 		ASSERT(DB_TYPE(mp) == M_DATA);
15032 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
15033 
15034 		ipha = (ipha_t *)mp->b_rptr;
15035 		len = mp->b_wptr - rptr;
15036 		pkt_len = ntohs(ipha->ipha_length);
15037 
15038 		/*
15039 		 * We must count all incoming packets, even if they end
15040 		 * up being dropped later on.
15041 		 */
15042 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15043 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15044 
15045 		/* multiple mblk or too short */
15046 		len -= pkt_len;
15047 		if (len != 0) {
15048 			/*
15049 			 * Make sure we have data length consistent
15050 			 * with the IP header.
15051 			 */
15052 			if (mp->b_cont == NULL) {
15053 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15054 					BUMP_MIB(ill->ill_ip_mib,
15055 					    ipIfStatsInHdrErrors);
15056 					ip2dbg(("ip_input: drop pkt\n"));
15057 					freemsg(mp);
15058 					continue;
15059 				}
15060 				mp->b_wptr = rptr + pkt_len;
15061 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
15062 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15063 					BUMP_MIB(ill->ill_ip_mib,
15064 					    ipIfStatsInHdrErrors);
15065 					ip2dbg(("ip_input: drop pkt\n"));
15066 					freemsg(mp);
15067 					continue;
15068 				}
15069 				(void) adjmsg(mp, -len);
15070 				IP_STAT(ipst, ip_multimblk3);
15071 			}
15072 		}
15073 
15074 		/* Obtain the dst of the current packet */
15075 		dst = ipha->ipha_dst;
15076 
15077 		DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL,
15078 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *,
15079 		    ipha, ip6_t *, NULL, int, 0);
15080 
15081 		/*
15082 		 * The following test for loopback is faster than
15083 		 * IP_LOOPBACK_ADDR(), because it avoids any bitwise
15084 		 * operations.
15085 		 * Note that these addresses are always in network byte order
15086 		 */
15087 		if (((*(uchar_t *)&ipha->ipha_dst) == 127) ||
15088 		    ((*(uchar_t *)&ipha->ipha_src) == 127)) {
15089 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
15090 			freemsg(mp);
15091 			continue;
15092 		}
15093 
15094 		/*
15095 		 * The event for packets being received from a 'physical'
15096 		 * interface is placed after validation of the source and/or
15097 		 * destination address as being local so that packets can be
15098 		 * redirected to loopback addresses using ipnat.
15099 		 */
15100 		DTRACE_PROBE4(ip4__physical__in__start,
15101 		    ill_t *, ill, ill_t *, NULL,
15102 		    ipha_t *, ipha, mblk_t *, first_mp);
15103 
15104 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15105 		    ipst->ips_ipv4firewall_physical_in,
15106 		    ill, NULL, ipha, first_mp, mp, ll_multicast, ipst);
15107 
15108 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15109 
15110 		if (first_mp == NULL) {
15111 			continue;
15112 		}
15113 		dst = ipha->ipha_dst;
15114 
15115 		/*
15116 		 * Attach any necessary label information to
15117 		 * this packet
15118 		 */
15119 		if (is_system_labeled() &&
15120 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15121 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15122 			freemsg(mp);
15123 			continue;
15124 		}
15125 
15126 		/*
15127 		 * Reuse the cached ire only if the ipha_dst of the previous
15128 		 * packet is the same as the current packet AND it is not
15129 		 * INADDR_ANY.
15130 		 */
15131 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15132 		    (ire != NULL)) {
15133 			ire_refrele(ire);
15134 			ire = NULL;
15135 		}
15136 		opt_len = ipha->ipha_version_and_hdr_length -
15137 		    IP_SIMPLE_HDR_VERSION;
15138 
15139 		/*
15140 		 * Check to see if we can take the fastpath.
15141 		 * That is possible if the following conditions are met
15142 		 *	o Tsol disabled
15143 		 *	o CGTP disabled
15144 		 *	o ipp_action_count is 0
15145 		 *	o no options in the packet
15146 		 *	o not a RSVP packet
15147 		 * 	o not a multicast packet
15148 		 *	o ill not in IP_DHCPINIT_IF mode
15149 		 */
15150 		if (!is_system_labeled() &&
15151 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
15152 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15153 		    !ll_multicast && !CLASSD(dst) && ill->ill_dhcpinit == 0) {
15154 			if (ire == NULL)
15155 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL,
15156 				    ipst);
15157 
15158 			/* incoming packet is for forwarding */
15159 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
15160 				ire = ip_fast_forward(ire, dst, ill, mp);
15161 				continue;
15162 			}
15163 			/* incoming packet is for local consumption */
15164 			if (ire->ire_type & IRE_LOCAL)
15165 				goto local;
15166 		}
15167 
15168 		/*
15169 		 * Disable ire caching for anything more complex
15170 		 * than the simple fast path case we checked for above.
15171 		 */
15172 		if (ire != NULL) {
15173 			ire_refrele(ire);
15174 			ire = NULL;
15175 		}
15176 
15177 		/*
15178 		 * Brutal hack for DHCPv4 unicast: RFC2131 allows a DHCP
15179 		 * server to unicast DHCP packets to a DHCP client using the
15180 		 * IP address it is offering to the client.  This can be
15181 		 * disabled through the "broadcast bit", but not all DHCP
15182 		 * servers honor that bit.  Therefore, to interoperate with as
15183 		 * many DHCP servers as possible, the DHCP client allows the
15184 		 * server to unicast, but we treat those packets as broadcast
15185 		 * here.  Note that we don't rewrite the packet itself since
15186 		 * (a) that would mess up the checksums and (b) the DHCP
15187 		 * client conn is bound to INADDR_ANY so ip_fanout_udp() will
15188 		 * hand it the packet regardless.
15189 		 */
15190 		if (ill->ill_dhcpinit != 0 &&
15191 		    IS_SIMPLE_IPH(ipha) && ipha->ipha_protocol == IPPROTO_UDP &&
15192 		    pullupmsg(mp, sizeof (ipha_t) + sizeof (udpha_t)) == 1) {
15193 			udpha_t *udpha;
15194 
15195 			/*
15196 			 * Reload ipha since pullupmsg() can change b_rptr.
15197 			 */
15198 			ipha = (ipha_t *)mp->b_rptr;
15199 			udpha = (udpha_t *)&ipha[1];
15200 
15201 			if (ntohs(udpha->uha_dst_port) == IPPORT_BOOTPC) {
15202 				DTRACE_PROBE2(ip4__dhcpinit__pkt, ill_t *, ill,
15203 				    mblk_t *, mp);
15204 				dst = INADDR_BROADCAST;
15205 			}
15206 		}
15207 
15208 		/* Full-blown slow path */
15209 		if (opt_len != 0) {
15210 			if (len != 0)
15211 				IP_STAT(ipst, ip_multimblk4);
15212 			else
15213 				IP_STAT(ipst, ip_ipoptions);
15214 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15215 			    &dst, ipst))
15216 				continue;
15217 		}
15218 
15219 		/*
15220 		 * Invoke the CGTP (multirouting) filtering module to process
15221 		 * the incoming packet. Packets identified as duplicates
15222 		 * must be discarded. Filtering is active only if the
15223 		 * the ip_cgtp_filter ndd variable is non-zero.
15224 		 */
15225 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15226 		if (ipst->ips_ip_cgtp_filter &&
15227 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15228 			netstackid_t stackid;
15229 
15230 			stackid = ipst->ips_netstack->netstack_stackid;
15231 			cgtp_flt_pkt =
15232 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15233 			    ill->ill_phyint->phyint_ifindex, mp);
15234 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15235 				freemsg(first_mp);
15236 				continue;
15237 			}
15238 		}
15239 
15240 		/*
15241 		 * If rsvpd is running, let RSVP daemon handle its processing
15242 		 * and forwarding of RSVP multicast/unicast packets.
15243 		 * If rsvpd is not running but mrouted is running, RSVP
15244 		 * multicast packets are forwarded as multicast traffic
15245 		 * and RSVP unicast packets are forwarded by unicast router.
15246 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15247 		 * packets are not forwarded, but the unicast packets are
15248 		 * forwarded like unicast traffic.
15249 		 */
15250 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15251 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15252 		    NULL) {
15253 			/* RSVP packet and rsvpd running. Treat as ours */
15254 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15255 			/*
15256 			 * This assumes that we deliver to all streams for
15257 			 * multicast and broadcast packets.
15258 			 * We have to force ll_multicast to 1 to handle the
15259 			 * M_DATA messages passed in from ip_mroute_decap.
15260 			 */
15261 			dst = INADDR_BROADCAST;
15262 			ll_multicast = 1;
15263 		} else if (CLASSD(dst)) {
15264 			/* packet is multicast */
15265 			mp->b_next = NULL;
15266 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15267 			    &ll_multicast, &dst))
15268 				continue;
15269 		}
15270 
15271 		if (ire == NULL) {
15272 			ire = ire_cache_lookup(dst, ALL_ZONES,
15273 			    MBLK_GETLABEL(mp), ipst);
15274 		}
15275 
15276 		if (ire != NULL && ire->ire_stq != NULL &&
15277 		    ire->ire_zoneid != GLOBAL_ZONEID &&
15278 		    ire->ire_zoneid != ALL_ZONES) {
15279 			/*
15280 			 * Should only use IREs that are visible from the
15281 			 * global zone for forwarding.
15282 			 */
15283 			ire_refrele(ire);
15284 			ire = ire_cache_lookup(dst, GLOBAL_ZONEID,
15285 			    MBLK_GETLABEL(mp), ipst);
15286 		}
15287 
15288 		if (ire == NULL) {
15289 			/*
15290 			 * No IRE for this destination, so it can't be for us.
15291 			 * Unless we are forwarding, drop the packet.
15292 			 * We have to let source routed packets through
15293 			 * since we don't yet know if they are 'ping -l'
15294 			 * packets i.e. if they will go out over the
15295 			 * same interface as they came in on.
15296 			 */
15297 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15298 			if (ire == NULL)
15299 				continue;
15300 		}
15301 
15302 		/*
15303 		 * Broadcast IRE may indicate either broadcast or
15304 		 * multicast packet
15305 		 */
15306 		if (ire->ire_type == IRE_BROADCAST) {
15307 			/*
15308 			 * Skip broadcast checks if packet is UDP multicast;
15309 			 * we'd rather not enter ip_rput_process_broadcast()
15310 			 * unless the packet is broadcast for real, since
15311 			 * that routine is a no-op for multicast.
15312 			 */
15313 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15314 			    !CLASSD(ipha->ipha_dst)) {
15315 				ire = ip_rput_process_broadcast(&q, mp,
15316 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15317 				    ll_multicast);
15318 				if (ire == NULL)
15319 					continue;
15320 			}
15321 		} else if (ire->ire_stq != NULL) {
15322 			/* fowarding? */
15323 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15324 			    ll_multicast);
15325 			/* ip_rput_process_forward consumed the packet */
15326 			continue;
15327 		}
15328 
15329 local:
15330 		/*
15331 		 * If the queue in the ire is different to the ingress queue
15332 		 * then we need to check to see if we can accept the packet.
15333 		 * Note that for multicast packets and broadcast packets sent
15334 		 * to a broadcast address which is shared between multiple
15335 		 * interfaces we should not do this since we just got a random
15336 		 * broadcast ire.
15337 		 */
15338 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15339 			if ((ire = ip_check_multihome(&ipha->ipha_dst, ire,
15340 			    ill)) == NULL) {
15341 				/* Drop packet */
15342 				BUMP_MIB(ill->ill_ip_mib,
15343 				    ipIfStatsForwProhibits);
15344 				freemsg(mp);
15345 				continue;
15346 			}
15347 			if (ire->ire_rfq != NULL)
15348 				q = ire->ire_rfq;
15349 		}
15350 
15351 		switch (ipha->ipha_protocol) {
15352 		case IPPROTO_TCP:
15353 			ASSERT(first_mp == mp);
15354 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15355 			    mp, 0, q, ip_ring)) != NULL) {
15356 				if (curr_sqp == NULL) {
15357 					curr_sqp = GET_SQUEUE(mp);
15358 					ASSERT(cnt == 0);
15359 					cnt++;
15360 					head = tail = mp;
15361 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15362 					ASSERT(tail != NULL);
15363 					cnt++;
15364 					tail->b_next = mp;
15365 					tail = mp;
15366 				} else {
15367 					/*
15368 					 * A different squeue. Send the
15369 					 * chain for the previous squeue on
15370 					 * its way. This shouldn't happen
15371 					 * often unless interrupt binding
15372 					 * changes.
15373 					 */
15374 					IP_STAT(ipst, ip_input_multi_squeue);
15375 					squeue_enter_chain(curr_sqp, head,
15376 					    tail, cnt, SQTAG_IP_INPUT);
15377 					curr_sqp = GET_SQUEUE(mp);
15378 					head = mp;
15379 					tail = mp;
15380 					cnt = 1;
15381 				}
15382 			}
15383 			continue;
15384 		case IPPROTO_UDP:
15385 			ASSERT(first_mp == mp);
15386 			ip_udp_input(q, mp, ipha, ire, ill);
15387 			continue;
15388 		case IPPROTO_SCTP:
15389 			ASSERT(first_mp == mp);
15390 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15391 			    q, dst);
15392 			/* ire has been released by ip_sctp_input */
15393 			ire = NULL;
15394 			continue;
15395 		default:
15396 			ip_proto_input(q, first_mp, ipha, ire, ill, 0);
15397 			continue;
15398 		}
15399 	}
15400 
15401 	if (ire != NULL)
15402 		ire_refrele(ire);
15403 
15404 	if (head != NULL)
15405 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
15406 
15407 	/*
15408 	 * This code is there just to make netperf/ttcp look good.
15409 	 *
15410 	 * Its possible that after being in polling mode (and having cleared
15411 	 * the backlog), squeues have turned the interrupt frequency higher
15412 	 * to improve latency at the expense of more CPU utilization (less
15413 	 * packets per interrupts or more number of interrupts). Workloads
15414 	 * like ttcp/netperf do manage to tickle polling once in a while
15415 	 * but for the remaining time, stay in higher interrupt mode since
15416 	 * their packet arrival rate is pretty uniform and this shows up
15417 	 * as higher CPU utilization. Since people care about CPU utilization
15418 	 * while running netperf/ttcp, turn the interrupt frequency back to
15419 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
15420 	 */
15421 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
15422 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
15423 			ip_ring->rr_poll_state &= ~ILL_POLLING;
15424 			ip_ring->rr_blank(ip_ring->rr_handle,
15425 			    ip_ring->rr_normal_blank_time,
15426 			    ip_ring->rr_normal_pkt_cnt);
15427 		}
15428 		}
15429 
15430 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15431 	    "ip_input_end: q %p (%S)", q, "end");
15432 #undef  rptr
15433 }
15434 
15435 static void
15436 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15437     t_uscalar_t err)
15438 {
15439 	if (dl_err == DL_SYSERR) {
15440 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15441 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15442 		    ill->ill_name, dl_primstr(prim), err);
15443 		return;
15444 	}
15445 
15446 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15447 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
15448 	    dl_errstr(dl_err));
15449 }
15450 
15451 /*
15452  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15453  * than DL_UNITDATA_IND messages. If we need to process this message
15454  * exclusively, we call qwriter_ip, in which case we also need to call
15455  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15456  */
15457 void
15458 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15459 {
15460 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15461 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15462 	ill_t		*ill = q->q_ptr;
15463 	t_uscalar_t	prim = dloa->dl_primitive;
15464 	t_uscalar_t	reqprim = DL_PRIM_INVAL;
15465 
15466 	ip1dbg(("ip_rput_dlpi"));
15467 
15468 	/*
15469 	 * If we received an ACK but didn't send a request for it, then it
15470 	 * can't be part of any pending operation; discard up-front.
15471 	 */
15472 	switch (prim) {
15473 	case DL_ERROR_ACK:
15474 		reqprim = dlea->dl_error_primitive;
15475 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
15476 		    "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
15477 		    reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
15478 		    dlea->dl_unix_errno));
15479 		break;
15480 	case DL_OK_ACK:
15481 		reqprim = dloa->dl_correct_primitive;
15482 		break;
15483 	case DL_INFO_ACK:
15484 		reqprim = DL_INFO_REQ;
15485 		break;
15486 	case DL_BIND_ACK:
15487 		reqprim = DL_BIND_REQ;
15488 		break;
15489 	case DL_PHYS_ADDR_ACK:
15490 		reqprim = DL_PHYS_ADDR_REQ;
15491 		break;
15492 	case DL_NOTIFY_ACK:
15493 		reqprim = DL_NOTIFY_REQ;
15494 		break;
15495 	case DL_CONTROL_ACK:
15496 		reqprim = DL_CONTROL_REQ;
15497 		break;
15498 	case DL_CAPABILITY_ACK:
15499 		reqprim = DL_CAPABILITY_REQ;
15500 		break;
15501 	}
15502 
15503 	if (prim != DL_NOTIFY_IND) {
15504 		if (reqprim == DL_PRIM_INVAL ||
15505 		    !ill_dlpi_pending(ill, reqprim)) {
15506 			/* Not a DLPI message we support or expected */
15507 			freemsg(mp);
15508 			return;
15509 		}
15510 		ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
15511 		    dl_primstr(reqprim)));
15512 	}
15513 
15514 	switch (reqprim) {
15515 	case DL_UNBIND_REQ:
15516 		/*
15517 		 * NOTE: we mark the unbind as complete even if we got a
15518 		 * DL_ERROR_ACK, since there's not much else we can do.
15519 		 */
15520 		mutex_enter(&ill->ill_lock);
15521 		ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15522 		cv_signal(&ill->ill_cv);
15523 		mutex_exit(&ill->ill_lock);
15524 		break;
15525 
15526 	case DL_ENABMULTI_REQ:
15527 		if (prim == DL_OK_ACK) {
15528 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15529 				ill->ill_dlpi_multicast_state = IDS_OK;
15530 		}
15531 		break;
15532 	}
15533 
15534 	/*
15535 	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
15536 	 * need to become writer to continue to process it.  Because an
15537 	 * exclusive operation doesn't complete until replies to all queued
15538 	 * DLPI messages have been received, we know we're in the middle of an
15539 	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
15540 	 *
15541 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15542 	 * Since this is on the ill stream we unconditionally bump up the
15543 	 * refcount without doing ILL_CAN_LOOKUP().
15544 	 */
15545 	ill_refhold(ill);
15546 	if (prim == DL_NOTIFY_IND)
15547 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15548 	else
15549 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15550 }
15551 
15552 /*
15553  * Handling of DLPI messages that require exclusive access to the ipsq.
15554  *
15555  * Need to do ill_pending_mp_release on ioctl completion, which could
15556  * happen here. (along with mi_copy_done)
15557  */
15558 /* ARGSUSED */
15559 static void
15560 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15561 {
15562 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15563 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15564 	int		err = 0;
15565 	ill_t		*ill;
15566 	ipif_t		*ipif = NULL;
15567 	mblk_t		*mp1 = NULL;
15568 	conn_t		*connp = NULL;
15569 	t_uscalar_t	paddrreq;
15570 	mblk_t		*mp_hw;
15571 	boolean_t	success;
15572 	boolean_t	ioctl_aborted = B_FALSE;
15573 	boolean_t	log = B_TRUE;
15574 	ip_stack_t		*ipst;
15575 
15576 	ip1dbg(("ip_rput_dlpi_writer .."));
15577 	ill = (ill_t *)q->q_ptr;
15578 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15579 
15580 	ASSERT(IAM_WRITER_ILL(ill));
15581 
15582 	ipst = ill->ill_ipst;
15583 
15584 	/*
15585 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15586 	 * both are null or non-null. However we can assert that only
15587 	 * after grabbing the ipsq_lock. So we don't make any assertion
15588 	 * here and in other places in the code.
15589 	 */
15590 	ipif = ipsq->ipsq_pending_ipif;
15591 	/*
15592 	 * The current ioctl could have been aborted by the user and a new
15593 	 * ioctl to bring up another ill could have started. We could still
15594 	 * get a response from the driver later.
15595 	 */
15596 	if (ipif != NULL && ipif->ipif_ill != ill)
15597 		ioctl_aborted = B_TRUE;
15598 
15599 	switch (dloa->dl_primitive) {
15600 	case DL_ERROR_ACK:
15601 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15602 		    dl_primstr(dlea->dl_error_primitive)));
15603 
15604 		switch (dlea->dl_error_primitive) {
15605 		case DL_DISABMULTI_REQ:
15606 			if (!ill->ill_isv6)
15607 				ipsq_current_finish(ipsq);
15608 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15609 			break;
15610 		case DL_PROMISCON_REQ:
15611 		case DL_PROMISCOFF_REQ:
15612 		case DL_UNBIND_REQ:
15613 		case DL_ATTACH_REQ:
15614 		case DL_INFO_REQ:
15615 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15616 			break;
15617 		case DL_NOTIFY_REQ:
15618 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15619 			log = B_FALSE;
15620 			break;
15621 		case DL_PHYS_ADDR_REQ:
15622 			/*
15623 			 * For IPv6 only, there are two additional
15624 			 * phys_addr_req's sent to the driver to get the
15625 			 * IPv6 token and lla. This allows IP to acquire
15626 			 * the hardware address format for a given interface
15627 			 * without having built in knowledge of the hardware
15628 			 * address. ill_phys_addr_pend keeps track of the last
15629 			 * DL_PAR sent so we know which response we are
15630 			 * dealing with. ill_dlpi_done will update
15631 			 * ill_phys_addr_pend when it sends the next req.
15632 			 * We don't complete the IOCTL until all three DL_PARs
15633 			 * have been attempted, so set *_len to 0 and break.
15634 			 */
15635 			paddrreq = ill->ill_phys_addr_pend;
15636 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15637 			if (paddrreq == DL_IPV6_TOKEN) {
15638 				ill->ill_token_length = 0;
15639 				log = B_FALSE;
15640 				break;
15641 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15642 				ill->ill_nd_lla_len = 0;
15643 				log = B_FALSE;
15644 				break;
15645 			}
15646 			/*
15647 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15648 			 * We presumably have an IOCTL hanging out waiting
15649 			 * for completion. Find it and complete the IOCTL
15650 			 * with the error noted.
15651 			 * However, ill_dl_phys was called on an ill queue
15652 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15653 			 * set. But the ioctl is known to be pending on ill_wq.
15654 			 */
15655 			if (!ill->ill_ifname_pending)
15656 				break;
15657 			ill->ill_ifname_pending = 0;
15658 			if (!ioctl_aborted)
15659 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15660 			if (mp1 != NULL) {
15661 				/*
15662 				 * This operation (SIOCSLIFNAME) must have
15663 				 * happened on the ill. Assert there is no conn
15664 				 */
15665 				ASSERT(connp == NULL);
15666 				q = ill->ill_wq;
15667 			}
15668 			break;
15669 		case DL_BIND_REQ:
15670 			ill_dlpi_done(ill, DL_BIND_REQ);
15671 			if (ill->ill_ifname_pending)
15672 				break;
15673 			/*
15674 			 * Something went wrong with the bind.  We presumably
15675 			 * have an IOCTL hanging out waiting for completion.
15676 			 * Find it, take down the interface that was coming
15677 			 * up, and complete the IOCTL with the error noted.
15678 			 */
15679 			if (!ioctl_aborted)
15680 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15681 			if (mp1 != NULL) {
15682 				/*
15683 				 * This operation (SIOCSLIFFLAGS) must have
15684 				 * happened from a conn.
15685 				 */
15686 				ASSERT(connp != NULL);
15687 				q = CONNP_TO_WQ(connp);
15688 				if (ill->ill_move_in_progress) {
15689 					ILL_CLEAR_MOVE(ill);
15690 				}
15691 				(void) ipif_down(ipif, NULL, NULL);
15692 				/* error is set below the switch */
15693 			}
15694 			break;
15695 		case DL_ENABMULTI_REQ:
15696 			if (!ill->ill_isv6)
15697 				ipsq_current_finish(ipsq);
15698 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15699 
15700 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15701 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15702 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15703 				ipif_t *ipif;
15704 
15705 				printf("ip: joining multicasts failed (%d)"
15706 				    " on %s - will use link layer "
15707 				    "broadcasts for multicast\n",
15708 				    dlea->dl_errno, ill->ill_name);
15709 
15710 				/*
15711 				 * Set up the multicast mapping alone.
15712 				 * writer, so ok to access ill->ill_ipif
15713 				 * without any lock.
15714 				 */
15715 				ipif = ill->ill_ipif;
15716 				mutex_enter(&ill->ill_phyint->phyint_lock);
15717 				ill->ill_phyint->phyint_flags |=
15718 				    PHYI_MULTI_BCAST;
15719 				mutex_exit(&ill->ill_phyint->phyint_lock);
15720 
15721 				if (!ill->ill_isv6) {
15722 					(void) ipif_arp_setup_multicast(ipif,
15723 					    NULL);
15724 				} else {
15725 					(void) ipif_ndp_setup_multicast(ipif,
15726 					    NULL);
15727 				}
15728 			}
15729 			freemsg(mp);	/* Don't want to pass this up */
15730 			return;
15731 
15732 		case DL_CAPABILITY_REQ:
15733 		case DL_CONTROL_REQ:
15734 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15735 			ill->ill_dlpi_capab_state = IDS_FAILED;
15736 			freemsg(mp);
15737 			return;
15738 		}
15739 		/*
15740 		 * Note the error for IOCTL completion (mp1 is set when
15741 		 * ready to complete ioctl). If ill_ifname_pending_err is
15742 		 * set, an error occured during plumbing (ill_ifname_pending),
15743 		 * so we want to report that error.
15744 		 *
15745 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15746 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15747 		 * expected to get errack'd if the driver doesn't support
15748 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15749 		 * if these error conditions are encountered.
15750 		 */
15751 		if (mp1 != NULL) {
15752 			if (ill->ill_ifname_pending_err != 0)  {
15753 				err = ill->ill_ifname_pending_err;
15754 				ill->ill_ifname_pending_err = 0;
15755 			} else {
15756 				err = dlea->dl_unix_errno ?
15757 				    dlea->dl_unix_errno : ENXIO;
15758 			}
15759 		/*
15760 		 * If we're plumbing an interface and an error hasn't already
15761 		 * been saved, set ill_ifname_pending_err to the error passed
15762 		 * up. Ignore the error if log is B_FALSE (see comment above).
15763 		 */
15764 		} else if (log && ill->ill_ifname_pending &&
15765 		    ill->ill_ifname_pending_err == 0) {
15766 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15767 			    dlea->dl_unix_errno : ENXIO;
15768 		}
15769 
15770 		if (log)
15771 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15772 			    dlea->dl_errno, dlea->dl_unix_errno);
15773 		break;
15774 	case DL_CAPABILITY_ACK:
15775 		/* Call a routine to handle this one. */
15776 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15777 		ill_capability_ack(ill, mp);
15778 
15779 		/*
15780 		 * If the ack is due to renegotiation, we will need to send
15781 		 * a new CAPABILITY_REQ to start the renegotiation.
15782 		 */
15783 		if (ill->ill_capab_reneg) {
15784 			ill->ill_capab_reneg = B_FALSE;
15785 			ill_capability_probe(ill);
15786 		}
15787 		break;
15788 	case DL_CONTROL_ACK:
15789 		/* We treat all of these as "fire and forget" */
15790 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15791 		break;
15792 	case DL_INFO_ACK:
15793 		/* Call a routine to handle this one. */
15794 		ill_dlpi_done(ill, DL_INFO_REQ);
15795 		ip_ll_subnet_defaults(ill, mp);
15796 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15797 		return;
15798 	case DL_BIND_ACK:
15799 		/*
15800 		 * We should have an IOCTL waiting on this unless
15801 		 * sent by ill_dl_phys, in which case just return
15802 		 */
15803 		ill_dlpi_done(ill, DL_BIND_REQ);
15804 		if (ill->ill_ifname_pending)
15805 			break;
15806 
15807 		if (!ioctl_aborted)
15808 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15809 		if (mp1 == NULL)
15810 			break;
15811 		/*
15812 		 * Because mp1 was added by ill_dl_up(), and it always
15813 		 * passes a valid connp, connp must be valid here.
15814 		 */
15815 		ASSERT(connp != NULL);
15816 		q = CONNP_TO_WQ(connp);
15817 
15818 		/*
15819 		 * We are exclusive. So nothing can change even after
15820 		 * we get the pending mp. If need be we can put it back
15821 		 * and restart, as in calling ipif_arp_up()  below.
15822 		 */
15823 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15824 
15825 		mutex_enter(&ill->ill_lock);
15826 		ill->ill_dl_up = 1;
15827 		(void) ill_hook_event_create(ill, 0, NE_UP, NULL, 0);
15828 		mutex_exit(&ill->ill_lock);
15829 
15830 		/*
15831 		 * Now bring up the resolver; when that is complete, we'll
15832 		 * create IREs.  Note that we intentionally mirror what
15833 		 * ipif_up() would have done, because we got here by way of
15834 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15835 		 */
15836 		if (ill->ill_isv6) {
15837 			/*
15838 			 * v6 interfaces.
15839 			 * Unlike ARP which has to do another bind
15840 			 * and attach, once we get here we are
15841 			 * done with NDP. Except in the case of
15842 			 * ILLF_XRESOLV, in which case we send an
15843 			 * AR_INTERFACE_UP to the external resolver.
15844 			 * If all goes well, the ioctl will complete
15845 			 * in ip_rput(). If there's an error, we
15846 			 * complete it here.
15847 			 */
15848 			if ((err = ipif_ndp_up(ipif)) == 0) {
15849 				if (ill->ill_flags & ILLF_XRESOLV) {
15850 					mutex_enter(&connp->conn_lock);
15851 					mutex_enter(&ill->ill_lock);
15852 					success = ipsq_pending_mp_add(
15853 					    connp, ipif, q, mp1, 0);
15854 					mutex_exit(&ill->ill_lock);
15855 					mutex_exit(&connp->conn_lock);
15856 					if (success) {
15857 						err = ipif_resolver_up(ipif,
15858 						    Res_act_initial);
15859 						if (err == EINPROGRESS) {
15860 							freemsg(mp);
15861 							return;
15862 						}
15863 						ASSERT(err != 0);
15864 						mp1 = ipsq_pending_mp_get(ipsq,
15865 						    &connp);
15866 						ASSERT(mp1 != NULL);
15867 					} else {
15868 						/* conn has started closing */
15869 						err = EINTR;
15870 					}
15871 				} else { /* Non XRESOLV interface */
15872 					(void) ipif_resolver_up(ipif,
15873 					    Res_act_initial);
15874 					err = ipif_up_done_v6(ipif);
15875 				}
15876 			}
15877 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
15878 			/*
15879 			 * ARP and other v4 external resolvers.
15880 			 * Leave the pending mblk intact so that
15881 			 * the ioctl completes in ip_rput().
15882 			 */
15883 			mutex_enter(&connp->conn_lock);
15884 			mutex_enter(&ill->ill_lock);
15885 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
15886 			mutex_exit(&ill->ill_lock);
15887 			mutex_exit(&connp->conn_lock);
15888 			if (success) {
15889 				err = ipif_resolver_up(ipif, Res_act_initial);
15890 				if (err == EINPROGRESS) {
15891 					freemsg(mp);
15892 					return;
15893 				}
15894 				ASSERT(err != 0);
15895 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15896 			} else {
15897 				/* The conn has started closing */
15898 				err = EINTR;
15899 			}
15900 		} else {
15901 			/*
15902 			 * This one is complete. Reply to pending ioctl.
15903 			 */
15904 			(void) ipif_resolver_up(ipif, Res_act_initial);
15905 			err = ipif_up_done(ipif);
15906 		}
15907 
15908 		if ((err == 0) && (ill->ill_up_ipifs)) {
15909 			err = ill_up_ipifs(ill, q, mp1);
15910 			if (err == EINPROGRESS) {
15911 				freemsg(mp);
15912 				return;
15913 			}
15914 		}
15915 
15916 		if (ill->ill_up_ipifs) {
15917 			ill_group_cleanup(ill);
15918 		}
15919 
15920 		break;
15921 	case DL_NOTIFY_IND: {
15922 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
15923 		ire_t *ire;
15924 		boolean_t need_ire_walk_v4 = B_FALSE;
15925 		boolean_t need_ire_walk_v6 = B_FALSE;
15926 
15927 		switch (notify->dl_notification) {
15928 		case DL_NOTE_PHYS_ADDR:
15929 			err = ill_set_phys_addr(ill, mp);
15930 			break;
15931 
15932 		case DL_NOTE_FASTPATH_FLUSH:
15933 			ill_fastpath_flush(ill);
15934 			break;
15935 
15936 		case DL_NOTE_SDU_SIZE:
15937 			/*
15938 			 * Change the MTU size of the interface, of all
15939 			 * attached ipif's, and of all relevant ire's.  The
15940 			 * new value's a uint32_t at notify->dl_data.
15941 			 * Mtu change Vs. new ire creation - protocol below.
15942 			 *
15943 			 * a Mark the ipif as IPIF_CHANGING.
15944 			 * b Set the new mtu in the ipif.
15945 			 * c Change the ire_max_frag on all affected ires
15946 			 * d Unmark the IPIF_CHANGING
15947 			 *
15948 			 * To see how the protocol works, assume an interface
15949 			 * route is also being added simultaneously by
15950 			 * ip_rt_add and let 'ipif' be the ipif referenced by
15951 			 * the ire. If the ire is created before step a,
15952 			 * it will be cleaned up by step c. If the ire is
15953 			 * created after step d, it will see the new value of
15954 			 * ipif_mtu. Any attempt to create the ire between
15955 			 * steps a to d will fail because of the IPIF_CHANGING
15956 			 * flag. Note that ire_create() is passed a pointer to
15957 			 * the ipif_mtu, and not the value. During ire_add
15958 			 * under the bucket lock, the ire_max_frag of the
15959 			 * new ire being created is set from the ipif/ire from
15960 			 * which it is being derived.
15961 			 */
15962 			mutex_enter(&ill->ill_lock);
15963 			ill->ill_max_frag = (uint_t)notify->dl_data;
15964 
15965 			/*
15966 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
15967 			 * leave it alone
15968 			 */
15969 			if (ill->ill_mtu_userspecified) {
15970 				mutex_exit(&ill->ill_lock);
15971 				break;
15972 			}
15973 			ill->ill_max_mtu = ill->ill_max_frag;
15974 			if (ill->ill_isv6) {
15975 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
15976 					ill->ill_max_mtu = IPV6_MIN_MTU;
15977 			} else {
15978 				if (ill->ill_max_mtu < IP_MIN_MTU)
15979 					ill->ill_max_mtu = IP_MIN_MTU;
15980 			}
15981 			for (ipif = ill->ill_ipif; ipif != NULL;
15982 			    ipif = ipif->ipif_next) {
15983 				/*
15984 				 * Don't override the mtu if the user
15985 				 * has explicitly set it.
15986 				 */
15987 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
15988 					continue;
15989 				ipif->ipif_mtu = (uint_t)notify->dl_data;
15990 				if (ipif->ipif_isv6)
15991 					ire = ipif_to_ire_v6(ipif);
15992 				else
15993 					ire = ipif_to_ire(ipif);
15994 				if (ire != NULL) {
15995 					ire->ire_max_frag = ipif->ipif_mtu;
15996 					ire_refrele(ire);
15997 				}
15998 				if (ipif->ipif_flags & IPIF_UP) {
15999 					if (ill->ill_isv6)
16000 						need_ire_walk_v6 = B_TRUE;
16001 					else
16002 						need_ire_walk_v4 = B_TRUE;
16003 				}
16004 			}
16005 			mutex_exit(&ill->ill_lock);
16006 			if (need_ire_walk_v4)
16007 				ire_walk_v4(ill_mtu_change, (char *)ill,
16008 				    ALL_ZONES, ipst);
16009 			if (need_ire_walk_v6)
16010 				ire_walk_v6(ill_mtu_change, (char *)ill,
16011 				    ALL_ZONES, ipst);
16012 			break;
16013 		case DL_NOTE_LINK_UP:
16014 		case DL_NOTE_LINK_DOWN: {
16015 			/*
16016 			 * We are writer. ill / phyint / ipsq assocs stable.
16017 			 * The RUNNING flag reflects the state of the link.
16018 			 */
16019 			phyint_t *phyint = ill->ill_phyint;
16020 			uint64_t new_phyint_flags;
16021 			boolean_t changed = B_FALSE;
16022 			boolean_t went_up;
16023 
16024 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
16025 			mutex_enter(&phyint->phyint_lock);
16026 			new_phyint_flags = went_up ?
16027 			    phyint->phyint_flags | PHYI_RUNNING :
16028 			    phyint->phyint_flags & ~PHYI_RUNNING;
16029 			if (new_phyint_flags != phyint->phyint_flags) {
16030 				phyint->phyint_flags = new_phyint_flags;
16031 				changed = B_TRUE;
16032 			}
16033 			mutex_exit(&phyint->phyint_lock);
16034 			/*
16035 			 * ill_restart_dad handles the DAD restart and routing
16036 			 * socket notification logic.
16037 			 */
16038 			if (changed) {
16039 				ill_restart_dad(phyint->phyint_illv4, went_up);
16040 				ill_restart_dad(phyint->phyint_illv6, went_up);
16041 			}
16042 			break;
16043 		}
16044 		case DL_NOTE_PROMISC_ON_PHYS:
16045 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16046 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
16047 			mutex_enter(&ill->ill_lock);
16048 			ill->ill_promisc_on_phys = B_TRUE;
16049 			mutex_exit(&ill->ill_lock);
16050 			break;
16051 		case DL_NOTE_PROMISC_OFF_PHYS:
16052 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16053 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16054 			mutex_enter(&ill->ill_lock);
16055 			ill->ill_promisc_on_phys = B_FALSE;
16056 			mutex_exit(&ill->ill_lock);
16057 			break;
16058 		case DL_NOTE_CAPAB_RENEG:
16059 			/*
16060 			 * Something changed on the driver side.
16061 			 * It wants us to renegotiate the capabilities
16062 			 * on this ill. One possible cause is the aggregation
16063 			 * interface under us where a port got added or
16064 			 * went away.
16065 			 *
16066 			 * If the capability negotiation is already done
16067 			 * or is in progress, reset the capabilities and
16068 			 * mark the ill's ill_capab_reneg to be B_TRUE,
16069 			 * so that when the ack comes back, we can start
16070 			 * the renegotiation process.
16071 			 *
16072 			 * Note that if ill_capab_reneg is already B_TRUE
16073 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
16074 			 * the capability resetting request has been sent
16075 			 * and the renegotiation has not been started yet;
16076 			 * nothing needs to be done in this case.
16077 			 */
16078 			if (ill->ill_dlpi_capab_state != IDS_UNKNOWN) {
16079 				ill_capability_reset(ill);
16080 				ill->ill_capab_reneg = B_TRUE;
16081 			}
16082 			break;
16083 		default:
16084 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16085 			    "type 0x%x for DL_NOTIFY_IND\n",
16086 			    notify->dl_notification));
16087 			break;
16088 		}
16089 
16090 		/*
16091 		 * As this is an asynchronous operation, we
16092 		 * should not call ill_dlpi_done
16093 		 */
16094 		break;
16095 	}
16096 	case DL_NOTIFY_ACK: {
16097 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16098 
16099 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16100 			ill->ill_note_link = 1;
16101 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16102 		break;
16103 	}
16104 	case DL_PHYS_ADDR_ACK: {
16105 		/*
16106 		 * As part of plumbing the interface via SIOCSLIFNAME,
16107 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16108 		 * whose answers we receive here.  As each answer is received,
16109 		 * we call ill_dlpi_done() to dispatch the next request as
16110 		 * we're processing the current one.  Once all answers have
16111 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16112 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16113 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16114 		 * available, but we know the ioctl is pending on ill_wq.)
16115 		 */
16116 		uint_t paddrlen, paddroff;
16117 
16118 		paddrreq = ill->ill_phys_addr_pend;
16119 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16120 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16121 
16122 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16123 		if (paddrreq == DL_IPV6_TOKEN) {
16124 			/*
16125 			 * bcopy to low-order bits of ill_token
16126 			 *
16127 			 * XXX Temporary hack - currently, all known tokens
16128 			 * are 64 bits, so I'll cheat for the moment.
16129 			 */
16130 			bcopy(mp->b_rptr + paddroff,
16131 			    &ill->ill_token.s6_addr32[2], paddrlen);
16132 			ill->ill_token_length = paddrlen;
16133 			break;
16134 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16135 			ASSERT(ill->ill_nd_lla_mp == NULL);
16136 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16137 			mp = NULL;
16138 			break;
16139 		}
16140 
16141 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16142 		ASSERT(ill->ill_phys_addr_mp == NULL);
16143 		if (!ill->ill_ifname_pending)
16144 			break;
16145 		ill->ill_ifname_pending = 0;
16146 		if (!ioctl_aborted)
16147 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16148 		if (mp1 != NULL) {
16149 			ASSERT(connp == NULL);
16150 			q = ill->ill_wq;
16151 		}
16152 		/*
16153 		 * If any error acks received during the plumbing sequence,
16154 		 * ill_ifname_pending_err will be set. Break out and send up
16155 		 * the error to the pending ioctl.
16156 		 */
16157 		if (ill->ill_ifname_pending_err != 0) {
16158 			err = ill->ill_ifname_pending_err;
16159 			ill->ill_ifname_pending_err = 0;
16160 			break;
16161 		}
16162 
16163 		ill->ill_phys_addr_mp = mp;
16164 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16165 		mp = NULL;
16166 
16167 		/*
16168 		 * If paddrlen is zero, the DLPI provider doesn't support
16169 		 * physical addresses.  The other two tests were historical
16170 		 * workarounds for bugs in our former PPP implementation, but
16171 		 * now other things have grown dependencies on them -- e.g.,
16172 		 * the tun module specifies a dl_addr_length of zero in its
16173 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16174 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16175 		 * but only after careful testing ensures that all dependent
16176 		 * broken DLPI providers have been fixed.
16177 		 */
16178 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16179 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16180 			ill->ill_phys_addr = NULL;
16181 		} else if (paddrlen != ill->ill_phys_addr_length) {
16182 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16183 			    paddrlen, ill->ill_phys_addr_length));
16184 			err = EINVAL;
16185 			break;
16186 		}
16187 
16188 		if (ill->ill_nd_lla_mp == NULL) {
16189 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16190 				err = ENOMEM;
16191 				break;
16192 			}
16193 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16194 		}
16195 
16196 		/*
16197 		 * Set the interface token.  If the zeroth interface address
16198 		 * is unspecified, then set it to the link local address.
16199 		 */
16200 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16201 			(void) ill_setdefaulttoken(ill);
16202 
16203 		ASSERT(ill->ill_ipif->ipif_id == 0);
16204 		if (ipif != NULL &&
16205 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16206 			(void) ipif_setlinklocal(ipif);
16207 		}
16208 		break;
16209 	}
16210 	case DL_OK_ACK:
16211 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16212 		    dl_primstr((int)dloa->dl_correct_primitive),
16213 		    dloa->dl_correct_primitive));
16214 		switch (dloa->dl_correct_primitive) {
16215 		case DL_ENABMULTI_REQ:
16216 		case DL_DISABMULTI_REQ:
16217 			if (!ill->ill_isv6)
16218 				ipsq_current_finish(ipsq);
16219 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16220 			break;
16221 		case DL_PROMISCON_REQ:
16222 		case DL_PROMISCOFF_REQ:
16223 		case DL_UNBIND_REQ:
16224 		case DL_ATTACH_REQ:
16225 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16226 			break;
16227 		}
16228 		break;
16229 	default:
16230 		break;
16231 	}
16232 
16233 	freemsg(mp);
16234 	if (mp1 != NULL) {
16235 		/*
16236 		 * The operation must complete without EINPROGRESS
16237 		 * since ipsq_pending_mp_get() has removed the mblk
16238 		 * from ipsq_pending_mp.  Otherwise, the operation
16239 		 * will be stuck forever in the ipsq.
16240 		 */
16241 		ASSERT(err != EINPROGRESS);
16242 
16243 		switch (ipsq->ipsq_current_ioctl) {
16244 		case 0:
16245 			ipsq_current_finish(ipsq);
16246 			break;
16247 
16248 		case SIOCLIFADDIF:
16249 		case SIOCSLIFNAME:
16250 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16251 			break;
16252 
16253 		default:
16254 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16255 			break;
16256 		}
16257 	}
16258 }
16259 
16260 /*
16261  * ip_rput_other is called by ip_rput to handle messages modifying the global
16262  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16263  */
16264 /* ARGSUSED */
16265 void
16266 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16267 {
16268 	ill_t		*ill;
16269 	struct iocblk	*iocp;
16270 	mblk_t		*mp1;
16271 	conn_t		*connp = NULL;
16272 
16273 	ip1dbg(("ip_rput_other "));
16274 	ill = (ill_t *)q->q_ptr;
16275 	/*
16276 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16277 	 * in which case ipsq is NULL.
16278 	 */
16279 	if (ipsq != NULL) {
16280 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16281 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16282 	}
16283 
16284 	switch (mp->b_datap->db_type) {
16285 	case M_ERROR:
16286 	case M_HANGUP:
16287 		/*
16288 		 * The device has a problem.  We force the ILL down.  It can
16289 		 * be brought up again manually using SIOCSIFFLAGS (via
16290 		 * ifconfig or equivalent).
16291 		 */
16292 		ASSERT(ipsq != NULL);
16293 		if (mp->b_rptr < mp->b_wptr)
16294 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16295 		if (ill->ill_error == 0)
16296 			ill->ill_error = ENXIO;
16297 		if (!ill_down_start(q, mp))
16298 			return;
16299 		ipif_all_down_tail(ipsq, q, mp, NULL);
16300 		break;
16301 	case M_IOCACK:
16302 		iocp = (struct iocblk *)mp->b_rptr;
16303 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16304 		switch (iocp->ioc_cmd) {
16305 		case SIOCSTUNPARAM:
16306 		case OSIOCSTUNPARAM:
16307 			ASSERT(ipsq != NULL);
16308 			/*
16309 			 * Finish socket ioctl passed through to tun.
16310 			 * We should have an IOCTL waiting on this.
16311 			 */
16312 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16313 			if (ill->ill_isv6) {
16314 				struct iftun_req *ta;
16315 
16316 				/*
16317 				 * if a source or destination is
16318 				 * being set, try and set the link
16319 				 * local address for the tunnel
16320 				 */
16321 				ta = (struct iftun_req *)mp->b_cont->
16322 				    b_cont->b_rptr;
16323 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16324 					ipif_set_tun_llink(ill, ta);
16325 				}
16326 
16327 			}
16328 			if (mp1 != NULL) {
16329 				/*
16330 				 * Now copy back the b_next/b_prev used by
16331 				 * mi code for the mi_copy* functions.
16332 				 * See ip_sioctl_tunparam() for the reason.
16333 				 * Also protect against missing b_cont.
16334 				 */
16335 				if (mp->b_cont != NULL) {
16336 					mp->b_cont->b_next =
16337 					    mp1->b_cont->b_next;
16338 					mp->b_cont->b_prev =
16339 					    mp1->b_cont->b_prev;
16340 				}
16341 				inet_freemsg(mp1);
16342 				ASSERT(connp != NULL);
16343 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16344 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16345 			} else {
16346 				ASSERT(connp == NULL);
16347 				putnext(q, mp);
16348 			}
16349 			break;
16350 		case SIOCGTUNPARAM:
16351 		case OSIOCGTUNPARAM:
16352 			/*
16353 			 * This is really M_IOCDATA from the tunnel driver.
16354 			 * convert back and complete the ioctl.
16355 			 * We should have an IOCTL waiting on this.
16356 			 */
16357 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16358 			if (mp1) {
16359 				/*
16360 				 * Now copy back the b_next/b_prev used by
16361 				 * mi code for the mi_copy* functions.
16362 				 * See ip_sioctl_tunparam() for the reason.
16363 				 * Also protect against missing b_cont.
16364 				 */
16365 				if (mp->b_cont != NULL) {
16366 					mp->b_cont->b_next =
16367 					    mp1->b_cont->b_next;
16368 					mp->b_cont->b_prev =
16369 					    mp1->b_cont->b_prev;
16370 				}
16371 				inet_freemsg(mp1);
16372 				if (iocp->ioc_error == 0)
16373 					mp->b_datap->db_type = M_IOCDATA;
16374 				ASSERT(connp != NULL);
16375 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16376 				    iocp->ioc_error, COPYOUT, NULL);
16377 			} else {
16378 				ASSERT(connp == NULL);
16379 				putnext(q, mp);
16380 			}
16381 			break;
16382 		default:
16383 			break;
16384 		}
16385 		break;
16386 	case M_IOCNAK:
16387 		iocp = (struct iocblk *)mp->b_rptr;
16388 
16389 		switch (iocp->ioc_cmd) {
16390 		int mode;
16391 
16392 		case DL_IOC_HDR_INFO:
16393 			/*
16394 			 * If this was the first attempt turn of the
16395 			 * fastpath probing.
16396 			 */
16397 			mutex_enter(&ill->ill_lock);
16398 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16399 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16400 				mutex_exit(&ill->ill_lock);
16401 				ill_fastpath_nack(ill);
16402 				ip1dbg(("ip_rput: DLPI fastpath off on "
16403 				    "interface %s\n",
16404 				    ill->ill_name));
16405 			} else {
16406 				mutex_exit(&ill->ill_lock);
16407 			}
16408 			freemsg(mp);
16409 			break;
16410 		case SIOCSTUNPARAM:
16411 		case OSIOCSTUNPARAM:
16412 			ASSERT(ipsq != NULL);
16413 			/*
16414 			 * Finish socket ioctl passed through to tun
16415 			 * We should have an IOCTL waiting on this.
16416 			 */
16417 			/* FALLTHRU */
16418 		case SIOCGTUNPARAM:
16419 		case OSIOCGTUNPARAM:
16420 			/*
16421 			 * This is really M_IOCDATA from the tunnel driver.
16422 			 * convert back and complete the ioctl.
16423 			 * We should have an IOCTL waiting on this.
16424 			 */
16425 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16426 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16427 				mp1 = ill_pending_mp_get(ill, &connp,
16428 				    iocp->ioc_id);
16429 				mode = COPYOUT;
16430 				ipsq = NULL;
16431 			} else {
16432 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16433 				mode = NO_COPYOUT;
16434 			}
16435 			if (mp1 != NULL) {
16436 				/*
16437 				 * Now copy back the b_next/b_prev used by
16438 				 * mi code for the mi_copy* functions.
16439 				 * See ip_sioctl_tunparam() for the reason.
16440 				 * Also protect against missing b_cont.
16441 				 */
16442 				if (mp->b_cont != NULL) {
16443 					mp->b_cont->b_next =
16444 					    mp1->b_cont->b_next;
16445 					mp->b_cont->b_prev =
16446 					    mp1->b_cont->b_prev;
16447 				}
16448 				inet_freemsg(mp1);
16449 				if (iocp->ioc_error == 0)
16450 					iocp->ioc_error = EINVAL;
16451 				ASSERT(connp != NULL);
16452 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16453 				    iocp->ioc_error, mode, ipsq);
16454 			} else {
16455 				ASSERT(connp == NULL);
16456 				putnext(q, mp);
16457 			}
16458 			break;
16459 		default:
16460 			break;
16461 		}
16462 	default:
16463 		break;
16464 	}
16465 }
16466 
16467 /*
16468  * NOTE : This function does not ire_refrele the ire argument passed in.
16469  *
16470  * IPQoS notes
16471  * IP policy is invoked twice for a forwarded packet, once on the read side
16472  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16473  * enabled. An additional parameter, in_ill, has been added for this purpose.
16474  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16475  * because ip_mroute drops this information.
16476  *
16477  */
16478 void
16479 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16480 {
16481 	uint32_t	old_pkt_len;
16482 	uint32_t	pkt_len;
16483 	queue_t	*q;
16484 	uint32_t	sum;
16485 #define	rptr	((uchar_t *)ipha)
16486 	uint32_t	max_frag;
16487 	uint32_t	ill_index;
16488 	ill_t		*out_ill;
16489 	mib2_ipIfStatsEntry_t *mibptr;
16490 	ip_stack_t	*ipst = ((ill_t *)(ire->ire_stq->q_ptr))->ill_ipst;
16491 
16492 	/* Get the ill_index of the incoming ILL */
16493 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16494 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16495 
16496 	/* Initiate Read side IPPF processing */
16497 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16498 		ip_process(IPP_FWD_IN, &mp, ill_index);
16499 		if (mp == NULL) {
16500 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16501 			    "during IPPF processing\n"));
16502 			return;
16503 		}
16504 	}
16505 
16506 	/* Adjust the checksum to reflect the ttl decrement. */
16507 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16508 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16509 
16510 	if (ipha->ipha_ttl-- <= 1) {
16511 		if (ip_csum_hdr(ipha)) {
16512 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16513 			goto drop_pkt;
16514 		}
16515 		/*
16516 		 * Note: ire_stq this will be NULL for multicast
16517 		 * datagrams using the long path through arp (the IRE
16518 		 * is not an IRE_CACHE). This should not cause
16519 		 * problems since we don't generate ICMP errors for
16520 		 * multicast packets.
16521 		 */
16522 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16523 		q = ire->ire_stq;
16524 		if (q != NULL) {
16525 			/* Sent by forwarding path, and router is global zone */
16526 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16527 			    GLOBAL_ZONEID, ipst);
16528 		} else
16529 			freemsg(mp);
16530 		return;
16531 	}
16532 
16533 	/*
16534 	 * Don't forward if the interface is down
16535 	 */
16536 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16537 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16538 		ip2dbg(("ip_rput_forward:interface is down\n"));
16539 		goto drop_pkt;
16540 	}
16541 
16542 	/* Get the ill_index of the outgoing ILL */
16543 	out_ill = ire_to_ill(ire);
16544 	ill_index = out_ill->ill_phyint->phyint_ifindex;
16545 
16546 	DTRACE_PROBE4(ip4__forwarding__start,
16547 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16548 
16549 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16550 	    ipst->ips_ipv4firewall_forwarding,
16551 	    in_ill, out_ill, ipha, mp, mp, 0, ipst);
16552 
16553 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16554 
16555 	if (mp == NULL)
16556 		return;
16557 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16558 
16559 	if (is_system_labeled()) {
16560 		mblk_t *mp1;
16561 
16562 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16563 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16564 			goto drop_pkt;
16565 		}
16566 		/* Size may have changed */
16567 		mp = mp1;
16568 		ipha = (ipha_t *)mp->b_rptr;
16569 		pkt_len = ntohs(ipha->ipha_length);
16570 	}
16571 
16572 	/* Check if there are options to update */
16573 	if (!IS_SIMPLE_IPH(ipha)) {
16574 		if (ip_csum_hdr(ipha)) {
16575 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16576 			goto drop_pkt;
16577 		}
16578 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16579 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16580 			return;
16581 		}
16582 
16583 		ipha->ipha_hdr_checksum = 0;
16584 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16585 	}
16586 	max_frag = ire->ire_max_frag;
16587 	if (pkt_len > max_frag) {
16588 		/*
16589 		 * It needs fragging on its way out.  We haven't
16590 		 * verified the header checksum yet.  Since we
16591 		 * are going to put a surely good checksum in the
16592 		 * outgoing header, we have to make sure that it
16593 		 * was good coming in.
16594 		 */
16595 		if (ip_csum_hdr(ipha)) {
16596 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16597 			goto drop_pkt;
16598 		}
16599 		/* Initiate Write side IPPF processing */
16600 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16601 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16602 			if (mp == NULL) {
16603 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16604 				    " during IPPF processing\n"));
16605 				return;
16606 			}
16607 		}
16608 		/*
16609 		 * Handle labeled packet resizing.
16610 		 *
16611 		 * If we have added a label, inform ip_wput_frag() of its
16612 		 * effect on the MTU for ICMP messages.
16613 		 */
16614 		if (pkt_len > old_pkt_len) {
16615 			uint32_t secopt_size;
16616 
16617 			secopt_size = pkt_len - old_pkt_len;
16618 			if (secopt_size < max_frag)
16619 				max_frag -= secopt_size;
16620 		}
16621 
16622 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
16623 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16624 		return;
16625 	}
16626 
16627 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16628 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16629 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16630 	    ipst->ips_ipv4firewall_physical_out,
16631 	    NULL, out_ill, ipha, mp, mp, 0, ipst);
16632 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16633 	if (mp == NULL)
16634 		return;
16635 
16636 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16637 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16638 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16639 	/* ip_xmit_v4 always consumes the packet */
16640 	return;
16641 
16642 drop_pkt:;
16643 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16644 	freemsg(mp);
16645 #undef	rptr
16646 }
16647 
16648 void
16649 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16650 {
16651 	ire_t	*ire;
16652 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16653 
16654 	ASSERT(!ipif->ipif_isv6);
16655 	/*
16656 	 * Find an IRE which matches the destination and the outgoing
16657 	 * queue in the cache table. All we need is an IRE_CACHE which
16658 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16659 	 * then it is enough to have some IRE_CACHE in the group.
16660 	 */
16661 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16662 		dst = ipif->ipif_pp_dst_addr;
16663 
16664 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16665 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR, ipst);
16666 	if (ire == NULL) {
16667 		/*
16668 		 * Mark this packet to make it be delivered to
16669 		 * ip_rput_forward after the new ire has been
16670 		 * created.
16671 		 */
16672 		mp->b_prev = NULL;
16673 		mp->b_next = mp;
16674 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16675 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16676 	} else {
16677 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16678 		IRE_REFRELE(ire);
16679 	}
16680 }
16681 
16682 /* Update any source route, record route or timestamp options */
16683 static int
16684 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16685 {
16686 	ipoptp_t	opts;
16687 	uchar_t		*opt;
16688 	uint8_t		optval;
16689 	uint8_t		optlen;
16690 	ipaddr_t	dst;
16691 	uint32_t	ts;
16692 	ire_t		*dst_ire = NULL;
16693 	ire_t		*tmp_ire = NULL;
16694 	timestruc_t	now;
16695 
16696 	ip2dbg(("ip_rput_forward_options\n"));
16697 	dst = ipha->ipha_dst;
16698 	for (optval = ipoptp_first(&opts, ipha);
16699 	    optval != IPOPT_EOL;
16700 	    optval = ipoptp_next(&opts)) {
16701 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16702 		opt = opts.ipoptp_cur;
16703 		optlen = opts.ipoptp_len;
16704 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16705 		    optval, opts.ipoptp_len));
16706 		switch (optval) {
16707 			uint32_t off;
16708 		case IPOPT_SSRR:
16709 		case IPOPT_LSRR:
16710 			/* Check if adminstratively disabled */
16711 			if (!ipst->ips_ip_forward_src_routed) {
16712 				if (ire->ire_stq != NULL) {
16713 					/*
16714 					 * Sent by forwarding path, and router
16715 					 * is global zone
16716 					 */
16717 					icmp_unreachable(ire->ire_stq, mp,
16718 					    ICMP_SOURCE_ROUTE_FAILED,
16719 					    GLOBAL_ZONEID, ipst);
16720 				} else {
16721 					ip0dbg(("ip_rput_forward_options: "
16722 					    "unable to send unreach\n"));
16723 					freemsg(mp);
16724 				}
16725 				return (-1);
16726 			}
16727 
16728 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16729 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16730 			if (dst_ire == NULL) {
16731 				/*
16732 				 * Must be partial since ip_rput_options
16733 				 * checked for strict.
16734 				 */
16735 				break;
16736 			}
16737 			off = opt[IPOPT_OFFSET];
16738 			off--;
16739 		redo_srr:
16740 			if (optlen < IP_ADDR_LEN ||
16741 			    off > optlen - IP_ADDR_LEN) {
16742 				/* End of source route */
16743 				ip1dbg((
16744 				    "ip_rput_forward_options: end of SR\n"));
16745 				ire_refrele(dst_ire);
16746 				break;
16747 			}
16748 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16749 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16750 			    IP_ADDR_LEN);
16751 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16752 			    ntohl(dst)));
16753 
16754 			/*
16755 			 * Check if our address is present more than
16756 			 * once as consecutive hops in source route.
16757 			 */
16758 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16759 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16760 			if (tmp_ire != NULL) {
16761 				ire_refrele(tmp_ire);
16762 				off += IP_ADDR_LEN;
16763 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16764 				goto redo_srr;
16765 			}
16766 			ipha->ipha_dst = dst;
16767 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16768 			ire_refrele(dst_ire);
16769 			break;
16770 		case IPOPT_RR:
16771 			off = opt[IPOPT_OFFSET];
16772 			off--;
16773 			if (optlen < IP_ADDR_LEN ||
16774 			    off > optlen - IP_ADDR_LEN) {
16775 				/* No more room - ignore */
16776 				ip1dbg((
16777 				    "ip_rput_forward_options: end of RR\n"));
16778 				break;
16779 			}
16780 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16781 			    IP_ADDR_LEN);
16782 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16783 			break;
16784 		case IPOPT_TS:
16785 			/* Insert timestamp if there is room */
16786 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16787 			case IPOPT_TS_TSONLY:
16788 				off = IPOPT_TS_TIMELEN;
16789 				break;
16790 			case IPOPT_TS_PRESPEC:
16791 			case IPOPT_TS_PRESPEC_RFC791:
16792 				/* Verify that the address matched */
16793 				off = opt[IPOPT_OFFSET] - 1;
16794 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16795 				dst_ire = ire_ctable_lookup(dst, 0,
16796 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16797 				    MATCH_IRE_TYPE, ipst);
16798 				if (dst_ire == NULL) {
16799 					/* Not for us */
16800 					break;
16801 				}
16802 				ire_refrele(dst_ire);
16803 				/* FALLTHRU */
16804 			case IPOPT_TS_TSANDADDR:
16805 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16806 				break;
16807 			default:
16808 				/*
16809 				 * ip_*put_options should have already
16810 				 * dropped this packet.
16811 				 */
16812 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16813 				    "unknown IT - bug in ip_rput_options?\n");
16814 				return (0);	/* Keep "lint" happy */
16815 			}
16816 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16817 				/* Increase overflow counter */
16818 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16819 				opt[IPOPT_POS_OV_FLG] =
16820 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16821 				    (off << 4));
16822 				break;
16823 			}
16824 			off = opt[IPOPT_OFFSET] - 1;
16825 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16826 			case IPOPT_TS_PRESPEC:
16827 			case IPOPT_TS_PRESPEC_RFC791:
16828 			case IPOPT_TS_TSANDADDR:
16829 				bcopy(&ire->ire_src_addr,
16830 				    (char *)opt + off, IP_ADDR_LEN);
16831 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16832 				/* FALLTHRU */
16833 			case IPOPT_TS_TSONLY:
16834 				off = opt[IPOPT_OFFSET] - 1;
16835 				/* Compute # of milliseconds since midnight */
16836 				gethrestime(&now);
16837 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16838 				    now.tv_nsec / (NANOSEC / MILLISEC);
16839 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16840 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16841 				break;
16842 			}
16843 			break;
16844 		}
16845 	}
16846 	return (0);
16847 }
16848 
16849 /*
16850  * This is called after processing at least one of AH/ESP headers.
16851  *
16852  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16853  * the actual, physical interface on which the packet was received,
16854  * but, when ip_strict_dst_multihoming is set to 1, could be the
16855  * interface which had the ipha_dst configured when the packet went
16856  * through ip_rput. The ill_index corresponding to the recv_ill
16857  * is saved in ipsec_in_rill_index
16858  *
16859  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
16860  * cannot assume "ire" points to valid data for any IPv6 cases.
16861  */
16862 void
16863 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16864 {
16865 	mblk_t *mp;
16866 	ipaddr_t dst;
16867 	in6_addr_t *v6dstp;
16868 	ipha_t *ipha;
16869 	ip6_t *ip6h;
16870 	ipsec_in_t *ii;
16871 	boolean_t ill_need_rele = B_FALSE;
16872 	boolean_t rill_need_rele = B_FALSE;
16873 	boolean_t ire_need_rele = B_FALSE;
16874 	netstack_t	*ns;
16875 	ip_stack_t	*ipst;
16876 
16877 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16878 	ASSERT(ii->ipsec_in_ill_index != 0);
16879 	ns = ii->ipsec_in_ns;
16880 	ASSERT(ii->ipsec_in_ns != NULL);
16881 	ipst = ns->netstack_ip;
16882 
16883 	mp = ipsec_mp->b_cont;
16884 	ASSERT(mp != NULL);
16885 
16886 
16887 	if (ill == NULL) {
16888 		ASSERT(recv_ill == NULL);
16889 		/*
16890 		 * We need to get the original queue on which ip_rput_local
16891 		 * or ip_rput_data_v6 was called.
16892 		 */
16893 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16894 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
16895 		ill_need_rele = B_TRUE;
16896 
16897 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16898 			recv_ill = ill_lookup_on_ifindex(
16899 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16900 			    NULL, NULL, NULL, NULL, ipst);
16901 			rill_need_rele = B_TRUE;
16902 		} else {
16903 			recv_ill = ill;
16904 		}
16905 
16906 		if ((ill == NULL) || (recv_ill == NULL)) {
16907 			ip0dbg(("ip_fanout_proto_again: interface "
16908 			    "disappeared\n"));
16909 			if (ill != NULL)
16910 				ill_refrele(ill);
16911 			if (recv_ill != NULL)
16912 				ill_refrele(recv_ill);
16913 			freemsg(ipsec_mp);
16914 			return;
16915 		}
16916 	}
16917 
16918 	ASSERT(ill != NULL && recv_ill != NULL);
16919 
16920 	if (mp->b_datap->db_type == M_CTL) {
16921 		/*
16922 		 * AH/ESP is returning the ICMP message after
16923 		 * removing their headers. Fanout again till
16924 		 * it gets to the right protocol.
16925 		 */
16926 		if (ii->ipsec_in_v4) {
16927 			icmph_t *icmph;
16928 			int iph_hdr_length;
16929 			int hdr_length;
16930 
16931 			ipha = (ipha_t *)mp->b_rptr;
16932 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
16933 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
16934 			ipha = (ipha_t *)&icmph[1];
16935 			hdr_length = IPH_HDR_LENGTH(ipha);
16936 			/*
16937 			 * icmp_inbound_error_fanout may need to do pullupmsg.
16938 			 * Reset the type to M_DATA.
16939 			 */
16940 			mp->b_datap->db_type = M_DATA;
16941 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
16942 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
16943 			    B_FALSE, ill, ii->ipsec_in_zoneid);
16944 		} else {
16945 			icmp6_t *icmp6;
16946 			int hdr_length;
16947 
16948 			ip6h = (ip6_t *)mp->b_rptr;
16949 			/* Don't call hdr_length_v6() unless you have to. */
16950 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
16951 				hdr_length = ip_hdr_length_v6(mp, ip6h);
16952 			else
16953 				hdr_length = IPV6_HDR_LEN;
16954 
16955 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
16956 			/*
16957 			 * icmp_inbound_error_fanout_v6 may need to do
16958 			 * pullupmsg.  Reset the type to M_DATA.
16959 			 */
16960 			mp->b_datap->db_type = M_DATA;
16961 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
16962 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
16963 		}
16964 		if (ill_need_rele)
16965 			ill_refrele(ill);
16966 		if (rill_need_rele)
16967 			ill_refrele(recv_ill);
16968 		return;
16969 	}
16970 
16971 	if (ii->ipsec_in_v4) {
16972 		ipha = (ipha_t *)mp->b_rptr;
16973 		dst = ipha->ipha_dst;
16974 		if (CLASSD(dst)) {
16975 			/*
16976 			 * Multicast has to be delivered to all streams.
16977 			 */
16978 			dst = INADDR_BROADCAST;
16979 		}
16980 
16981 		if (ire == NULL) {
16982 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
16983 			    MBLK_GETLABEL(mp), ipst);
16984 			if (ire == NULL) {
16985 				if (ill_need_rele)
16986 					ill_refrele(ill);
16987 				if (rill_need_rele)
16988 					ill_refrele(recv_ill);
16989 				ip1dbg(("ip_fanout_proto_again: "
16990 				    "IRE not found"));
16991 				freemsg(ipsec_mp);
16992 				return;
16993 			}
16994 			ire_need_rele = B_TRUE;
16995 		}
16996 
16997 		switch (ipha->ipha_protocol) {
16998 			case IPPROTO_UDP:
16999 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
17000 				    recv_ill);
17001 				if (ire_need_rele)
17002 					ire_refrele(ire);
17003 				break;
17004 			case IPPROTO_TCP:
17005 				if (!ire_need_rele)
17006 					IRE_REFHOLD(ire);
17007 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
17008 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
17009 				IRE_REFRELE(ire);
17010 				if (mp != NULL)
17011 					squeue_enter_chain(GET_SQUEUE(mp), mp,
17012 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
17013 				break;
17014 			case IPPROTO_SCTP:
17015 				if (!ire_need_rele)
17016 					IRE_REFHOLD(ire);
17017 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
17018 				    ipsec_mp, 0, ill->ill_rq, dst);
17019 				break;
17020 			default:
17021 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
17022 				    recv_ill, 0);
17023 				if (ire_need_rele)
17024 					ire_refrele(ire);
17025 				break;
17026 		}
17027 	} else {
17028 		uint32_t rput_flags = 0;
17029 
17030 		ip6h = (ip6_t *)mp->b_rptr;
17031 		v6dstp = &ip6h->ip6_dst;
17032 		/*
17033 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
17034 		 * address.
17035 		 *
17036 		 * Currently, we don't store that state in the IPSEC_IN
17037 		 * message, and we may need to.
17038 		 */
17039 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
17040 		    IP6_IN_LLMCAST : 0);
17041 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
17042 		    NULL, NULL);
17043 	}
17044 	if (ill_need_rele)
17045 		ill_refrele(ill);
17046 	if (rill_need_rele)
17047 		ill_refrele(recv_ill);
17048 }
17049 
17050 /*
17051  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
17052  * returns 'true' if there are still fragments left on the queue, in
17053  * which case we restart the timer.
17054  */
17055 void
17056 ill_frag_timer(void *arg)
17057 {
17058 	ill_t	*ill = (ill_t *)arg;
17059 	boolean_t frag_pending;
17060 	ip_stack_t	*ipst = ill->ill_ipst;
17061 
17062 	mutex_enter(&ill->ill_lock);
17063 	ASSERT(!ill->ill_fragtimer_executing);
17064 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17065 		ill->ill_frag_timer_id = 0;
17066 		mutex_exit(&ill->ill_lock);
17067 		return;
17068 	}
17069 	ill->ill_fragtimer_executing = 1;
17070 	mutex_exit(&ill->ill_lock);
17071 
17072 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
17073 
17074 	/*
17075 	 * Restart the timer, if we have fragments pending or if someone
17076 	 * wanted us to be scheduled again.
17077 	 */
17078 	mutex_enter(&ill->ill_lock);
17079 	ill->ill_fragtimer_executing = 0;
17080 	ill->ill_frag_timer_id = 0;
17081 	if (frag_pending || ill->ill_fragtimer_needrestart)
17082 		ill_frag_timer_start(ill);
17083 	mutex_exit(&ill->ill_lock);
17084 }
17085 
17086 void
17087 ill_frag_timer_start(ill_t *ill)
17088 {
17089 	ip_stack_t	*ipst = ill->ill_ipst;
17090 
17091 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17092 
17093 	/* If the ill is closing or opening don't proceed */
17094 	if (ill->ill_state_flags & ILL_CONDEMNED)
17095 		return;
17096 
17097 	if (ill->ill_fragtimer_executing) {
17098 		/*
17099 		 * ill_frag_timer is currently executing. Just record the
17100 		 * the fact that we want the timer to be restarted.
17101 		 * ill_frag_timer will post a timeout before it returns,
17102 		 * ensuring it will be called again.
17103 		 */
17104 		ill->ill_fragtimer_needrestart = 1;
17105 		return;
17106 	}
17107 
17108 	if (ill->ill_frag_timer_id == 0) {
17109 		/*
17110 		 * The timer is neither running nor is the timeout handler
17111 		 * executing. Post a timeout so that ill_frag_timer will be
17112 		 * called
17113 		 */
17114 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17115 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
17116 		ill->ill_fragtimer_needrestart = 0;
17117 	}
17118 }
17119 
17120 /*
17121  * This routine is needed for loopback when forwarding multicasts.
17122  *
17123  * IPQoS Notes:
17124  * IPPF processing is done in fanout routines.
17125  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17126  * processing for IPsec packets is done when it comes back in clear.
17127  * NOTE : The callers of this function need to do the ire_refrele for the
17128  *	  ire that is being passed in.
17129  */
17130 void
17131 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17132     ill_t *recv_ill, uint32_t esp_udp_ports)
17133 {
17134 	boolean_t esp_in_udp_packet = (esp_udp_ports != 0);
17135 	ill_t	*ill = (ill_t *)q->q_ptr;
17136 	uint32_t	sum;
17137 	uint32_t	u1;
17138 	uint32_t	u2;
17139 	int		hdr_length;
17140 	boolean_t	mctl_present;
17141 	mblk_t		*first_mp = mp;
17142 	mblk_t		*hada_mp = NULL;
17143 	ipha_t		*inner_ipha;
17144 	ip_stack_t	*ipst;
17145 
17146 	ASSERT(recv_ill != NULL);
17147 	ipst = recv_ill->ill_ipst;
17148 
17149 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17150 	    "ip_rput_locl_start: q %p", q);
17151 
17152 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17153 	ASSERT(ill != NULL);
17154 
17155 
17156 #define	rptr	((uchar_t *)ipha)
17157 #define	iphs	((uint16_t *)ipha)
17158 
17159 	/*
17160 	 * no UDP or TCP packet should come here anymore.
17161 	 */
17162 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
17163 	    ipha->ipha_protocol != IPPROTO_UDP);
17164 
17165 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17166 	if (mctl_present &&
17167 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17168 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17169 
17170 		/*
17171 		 * It's an IPsec accelerated packet.
17172 		 * Keep a pointer to the data attributes around until
17173 		 * we allocate the ipsec_info_t.
17174 		 */
17175 		IPSECHW_DEBUG(IPSECHW_PKT,
17176 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17177 		hada_mp = first_mp;
17178 		hada_mp->b_cont = NULL;
17179 		/*
17180 		 * Since it is accelerated, it comes directly from
17181 		 * the ill and the data attributes is followed by
17182 		 * the packet data.
17183 		 */
17184 		ASSERT(mp->b_datap->db_type != M_CTL);
17185 		first_mp = mp;
17186 		mctl_present = B_FALSE;
17187 	}
17188 
17189 	/*
17190 	 * IF M_CTL is not present, then ipsec_in_is_secure
17191 	 * should return B_TRUE. There is a case where loopback
17192 	 * packets has an M_CTL in the front with all the
17193 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17194 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17195 	 * packets never comes here, it is safe to ASSERT the
17196 	 * following.
17197 	 */
17198 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17199 
17200 	/*
17201 	 * Also, we should never have an mctl_present if this is an
17202 	 * ESP-in-UDP packet.
17203 	 */
17204 	ASSERT(!mctl_present || !esp_in_udp_packet);
17205 
17206 
17207 	/* u1 is # words of IP options */
17208 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17209 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17210 
17211 	/*
17212 	 * Don't verify header checksum if we just removed UDP header or
17213 	 * packet is coming back from AH/ESP.
17214 	 */
17215 	if (!esp_in_udp_packet && !mctl_present) {
17216 		if (u1) {
17217 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17218 				if (hada_mp != NULL)
17219 					freemsg(hada_mp);
17220 				return;
17221 			}
17222 		} else {
17223 			/* Check the IP header checksum.  */
17224 #define	uph	((uint16_t *)ipha)
17225 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17226 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17227 #undef  uph
17228 			/* finish doing IP checksum */
17229 			sum = (sum & 0xFFFF) + (sum >> 16);
17230 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17231 			if (sum && sum != 0xFFFF) {
17232 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17233 				goto drop_pkt;
17234 			}
17235 		}
17236 	}
17237 
17238 	/*
17239 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17240 	 * might be called more than once for secure packets, count only
17241 	 * the first time.
17242 	 */
17243 	if (!mctl_present) {
17244 		UPDATE_IB_PKT_COUNT(ire);
17245 		ire->ire_last_used_time = lbolt;
17246 	}
17247 
17248 	/* Check for fragmentation offset. */
17249 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17250 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17251 	if (u1) {
17252 		/*
17253 		 * We re-assemble fragments before we do the AH/ESP
17254 		 * processing. Thus, M_CTL should not be present
17255 		 * while we are re-assembling.
17256 		 */
17257 		ASSERT(!mctl_present);
17258 		ASSERT(first_mp == mp);
17259 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
17260 			return;
17261 		}
17262 		/*
17263 		 * Make sure that first_mp points back to mp as
17264 		 * the mp we came in with could have changed in
17265 		 * ip_rput_fragment().
17266 		 */
17267 		ipha = (ipha_t *)mp->b_rptr;
17268 		first_mp = mp;
17269 	}
17270 
17271 	/*
17272 	 * Clear hardware checksumming flag as it is currently only
17273 	 * used by TCP and UDP.
17274 	 */
17275 	DB_CKSUMFLAGS(mp) = 0;
17276 
17277 	/* Now we have a complete datagram, destined for this machine. */
17278 	u1 = IPH_HDR_LENGTH(ipha);
17279 	switch (ipha->ipha_protocol) {
17280 	case IPPROTO_ICMP: {
17281 		ire_t		*ire_zone;
17282 		ilm_t		*ilm;
17283 		mblk_t		*mp1;
17284 		zoneid_t	last_zoneid;
17285 
17286 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17287 			ASSERT(ire->ire_type == IRE_BROADCAST);
17288 			/*
17289 			 * In the multicast case, applications may have joined
17290 			 * the group from different zones, so we need to deliver
17291 			 * the packet to each of them. Loop through the
17292 			 * multicast memberships structures (ilm) on the receive
17293 			 * ill and send a copy of the packet up each matching
17294 			 * one. However, we don't do this for multicasts sent on
17295 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17296 			 * they must stay in the sender's zone.
17297 			 *
17298 			 * ilm_add_v6() ensures that ilms in the same zone are
17299 			 * contiguous in the ill_ilm list. We use this property
17300 			 * to avoid sending duplicates needed when two
17301 			 * applications in the same zone join the same group on
17302 			 * different logical interfaces: we ignore the ilm if
17303 			 * its zoneid is the same as the last matching one.
17304 			 * In addition, the sending of the packet for
17305 			 * ire_zoneid is delayed until all of the other ilms
17306 			 * have been exhausted.
17307 			 */
17308 			last_zoneid = -1;
17309 			ILM_WALKER_HOLD(recv_ill);
17310 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17311 			    ilm = ilm->ilm_next) {
17312 				if ((ilm->ilm_flags & ILM_DELETED) ||
17313 				    ipha->ipha_dst != ilm->ilm_addr ||
17314 				    ilm->ilm_zoneid == last_zoneid ||
17315 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17316 				    ilm->ilm_zoneid == ALL_ZONES ||
17317 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17318 					continue;
17319 				mp1 = ip_copymsg(first_mp);
17320 				if (mp1 == NULL)
17321 					continue;
17322 				icmp_inbound(q, mp1, B_TRUE, ill,
17323 				    0, sum, mctl_present, B_TRUE,
17324 				    recv_ill, ilm->ilm_zoneid);
17325 				last_zoneid = ilm->ilm_zoneid;
17326 			}
17327 			ILM_WALKER_RELE(recv_ill);
17328 		} else if (ire->ire_type == IRE_BROADCAST) {
17329 			/*
17330 			 * In the broadcast case, there may be many zones
17331 			 * which need a copy of the packet delivered to them.
17332 			 * There is one IRE_BROADCAST per broadcast address
17333 			 * and per zone; we walk those using a helper function.
17334 			 * In addition, the sending of the packet for ire is
17335 			 * delayed until all of the other ires have been
17336 			 * processed.
17337 			 */
17338 			IRB_REFHOLD(ire->ire_bucket);
17339 			ire_zone = NULL;
17340 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17341 			    ire)) != NULL) {
17342 				mp1 = ip_copymsg(first_mp);
17343 				if (mp1 == NULL)
17344 					continue;
17345 
17346 				UPDATE_IB_PKT_COUNT(ire_zone);
17347 				ire_zone->ire_last_used_time = lbolt;
17348 				icmp_inbound(q, mp1, B_TRUE, ill,
17349 				    0, sum, mctl_present, B_TRUE,
17350 				    recv_ill, ire_zone->ire_zoneid);
17351 			}
17352 			IRB_REFRELE(ire->ire_bucket);
17353 		}
17354 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17355 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17356 		    ire->ire_zoneid);
17357 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17358 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17359 		return;
17360 	}
17361 	case IPPROTO_IGMP:
17362 		/*
17363 		 * If we are not willing to accept IGMP packets in clear,
17364 		 * then check with global policy.
17365 		 */
17366 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17367 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17368 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17369 			if (first_mp == NULL)
17370 				return;
17371 		}
17372 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17373 			freemsg(first_mp);
17374 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17375 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17376 			return;
17377 		}
17378 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17379 			/* Bad packet - discarded by igmp_input */
17380 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17381 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17382 			if (mctl_present)
17383 				freeb(first_mp);
17384 			return;
17385 		}
17386 		/*
17387 		 * igmp_input() may have returned the pulled up message.
17388 		 * So first_mp and ipha need to be reinitialized.
17389 		 */
17390 		ipha = (ipha_t *)mp->b_rptr;
17391 		if (mctl_present)
17392 			first_mp->b_cont = mp;
17393 		else
17394 			first_mp = mp;
17395 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17396 		    connf_head != NULL) {
17397 			/* No user-level listener for IGMP packets */
17398 			goto drop_pkt;
17399 		}
17400 		/* deliver to local raw users */
17401 		break;
17402 	case IPPROTO_PIM:
17403 		/*
17404 		 * If we are not willing to accept PIM packets in clear,
17405 		 * then check with global policy.
17406 		 */
17407 		if (ipst->ips_pim_accept_clear_messages == 0) {
17408 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17409 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17410 			if (first_mp == NULL)
17411 				return;
17412 		}
17413 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17414 			freemsg(first_mp);
17415 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17416 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17417 			return;
17418 		}
17419 		if (pim_input(q, mp, ill) != 0) {
17420 			/* Bad packet - discarded by pim_input */
17421 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17422 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17423 			if (mctl_present)
17424 				freeb(first_mp);
17425 			return;
17426 		}
17427 
17428 		/*
17429 		 * pim_input() may have pulled up the message so ipha needs to
17430 		 * be reinitialized.
17431 		 */
17432 		ipha = (ipha_t *)mp->b_rptr;
17433 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17434 		    connf_head != NULL) {
17435 			/* No user-level listener for PIM packets */
17436 			goto drop_pkt;
17437 		}
17438 		/* deliver to local raw users */
17439 		break;
17440 	case IPPROTO_ENCAP:
17441 		/*
17442 		 * Handle self-encapsulated packets (IP-in-IP where
17443 		 * the inner addresses == the outer addresses).
17444 		 */
17445 		hdr_length = IPH_HDR_LENGTH(ipha);
17446 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17447 		    mp->b_wptr) {
17448 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17449 			    sizeof (ipha_t) - mp->b_rptr)) {
17450 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17451 				freemsg(first_mp);
17452 				return;
17453 			}
17454 			ipha = (ipha_t *)mp->b_rptr;
17455 		}
17456 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17457 		/*
17458 		 * Check the sanity of the inner IP header.
17459 		 */
17460 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17461 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17462 			freemsg(first_mp);
17463 			return;
17464 		}
17465 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17466 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17467 			freemsg(first_mp);
17468 			return;
17469 		}
17470 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17471 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17472 			ipsec_in_t *ii;
17473 
17474 			/*
17475 			 * Self-encapsulated tunnel packet. Remove
17476 			 * the outer IP header and fanout again.
17477 			 * We also need to make sure that the inner
17478 			 * header is pulled up until options.
17479 			 */
17480 			mp->b_rptr = (uchar_t *)inner_ipha;
17481 			ipha = inner_ipha;
17482 			hdr_length = IPH_HDR_LENGTH(ipha);
17483 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17484 				if (!pullupmsg(mp, (uchar_t *)ipha +
17485 				    + hdr_length - mp->b_rptr)) {
17486 					freemsg(first_mp);
17487 					return;
17488 				}
17489 				ipha = (ipha_t *)mp->b_rptr;
17490 			}
17491 			if (hdr_length > sizeof (ipha_t)) {
17492 				/* We got options on the inner packet. */
17493 				ipaddr_t dst = ipha->ipha_dst;
17494 
17495 				if (ip_rput_options(q, mp, ipha, &dst, ipst) ==
17496 				    -1) {
17497 					/* Bad options! */
17498 					return;
17499 				}
17500 				if (dst != ipha->ipha_dst) {
17501 					/*
17502 					 * Someone put a source-route in
17503 					 * the inside header of a self-
17504 					 * encapsulated packet.  Drop it
17505 					 * with extreme prejudice and let
17506 					 * the sender know.
17507 					 */
17508 					icmp_unreachable(q, first_mp,
17509 					    ICMP_SOURCE_ROUTE_FAILED,
17510 					    recv_ill->ill_zoneid, ipst);
17511 					return;
17512 				}
17513 			}
17514 			if (!mctl_present) {
17515 				ASSERT(first_mp == mp);
17516 				/*
17517 				 * This means that somebody is sending
17518 				 * Self-encapsualted packets without AH/ESP.
17519 				 * If AH/ESP was present, we would have already
17520 				 * allocated the first_mp.
17521 				 *
17522 				 * Send this packet to find a tunnel endpoint.
17523 				 * if I can't find one, an ICMP
17524 				 * PROTOCOL_UNREACHABLE will get sent.
17525 				 */
17526 				goto fanout;
17527 			}
17528 			/*
17529 			 * We generally store the ill_index if we need to
17530 			 * do IPsec processing as we lose the ill queue when
17531 			 * we come back. But in this case, we never should
17532 			 * have to store the ill_index here as it should have
17533 			 * been stored previously when we processed the
17534 			 * AH/ESP header in this routine or for non-ipsec
17535 			 * cases, we still have the queue. But for some bad
17536 			 * packets from the wire, we can get to IPsec after
17537 			 * this and we better store the index for that case.
17538 			 */
17539 			ill = (ill_t *)q->q_ptr;
17540 			ii = (ipsec_in_t *)first_mp->b_rptr;
17541 			ii->ipsec_in_ill_index =
17542 			    ill->ill_phyint->phyint_ifindex;
17543 			ii->ipsec_in_rill_index =
17544 			    recv_ill->ill_phyint->phyint_ifindex;
17545 			if (ii->ipsec_in_decaps) {
17546 				/*
17547 				 * This packet is self-encapsulated multiple
17548 				 * times. We don't want to recurse infinitely.
17549 				 * To keep it simple, drop the packet.
17550 				 */
17551 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17552 				freemsg(first_mp);
17553 				return;
17554 			}
17555 			ii->ipsec_in_decaps = B_TRUE;
17556 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17557 			    ire);
17558 			return;
17559 		}
17560 		break;
17561 	case IPPROTO_AH:
17562 	case IPPROTO_ESP: {
17563 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17564 
17565 		/*
17566 		 * Fast path for AH/ESP. If this is the first time
17567 		 * we are sending a datagram to AH/ESP, allocate
17568 		 * a IPSEC_IN message and prepend it. Otherwise,
17569 		 * just fanout.
17570 		 */
17571 
17572 		int ipsec_rc;
17573 		ipsec_in_t *ii;
17574 		netstack_t *ns = ipst->ips_netstack;
17575 
17576 		IP_STAT(ipst, ipsec_proto_ahesp);
17577 		if (!mctl_present) {
17578 			ASSERT(first_mp == mp);
17579 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17580 			if (first_mp == NULL) {
17581 				ip1dbg(("ip_proto_input: IPSEC_IN "
17582 				    "allocation failure.\n"));
17583 				freemsg(hada_mp); /* okay ifnull */
17584 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17585 				freemsg(mp);
17586 				return;
17587 			}
17588 			/*
17589 			 * Store the ill_index so that when we come back
17590 			 * from IPsec we ride on the same queue.
17591 			 */
17592 			ill = (ill_t *)q->q_ptr;
17593 			ii = (ipsec_in_t *)first_mp->b_rptr;
17594 			ii->ipsec_in_ill_index =
17595 			    ill->ill_phyint->phyint_ifindex;
17596 			ii->ipsec_in_rill_index =
17597 			    recv_ill->ill_phyint->phyint_ifindex;
17598 			first_mp->b_cont = mp;
17599 			/*
17600 			 * Cache hardware acceleration info.
17601 			 */
17602 			if (hada_mp != NULL) {
17603 				IPSECHW_DEBUG(IPSECHW_PKT,
17604 				    ("ip_rput_local: caching data attr.\n"));
17605 				ii->ipsec_in_accelerated = B_TRUE;
17606 				ii->ipsec_in_da = hada_mp;
17607 				hada_mp = NULL;
17608 			}
17609 		} else {
17610 			ii = (ipsec_in_t *)first_mp->b_rptr;
17611 		}
17612 
17613 		ii->ipsec_in_esp_udp_ports = esp_udp_ports;
17614 
17615 		if (!ipsec_loaded(ipss)) {
17616 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17617 			    ire->ire_zoneid, ipst);
17618 			return;
17619 		}
17620 
17621 		ns = ipst->ips_netstack;
17622 		/* select inbound SA and have IPsec process the pkt */
17623 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17624 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17625 			boolean_t esp_in_udp_sa;
17626 			if (esph == NULL)
17627 				return;
17628 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17629 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17630 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
17631 			    IPSA_F_NATT) != 0);
17632 			/*
17633 			 * The following is a fancy, but quick, way of saying:
17634 			 * ESP-in-UDP SA and Raw ESP packet --> drop
17635 			 *    OR
17636 			 * ESP SA and ESP-in-UDP packet --> drop
17637 			 */
17638 			if (esp_in_udp_sa != esp_in_udp_packet) {
17639 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17640 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
17641 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
17642 				    &ns->netstack_ipsec->ipsec_dropper);
17643 				return;
17644 			}
17645 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17646 			    first_mp, esph);
17647 		} else {
17648 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17649 			if (ah == NULL)
17650 				return;
17651 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17652 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17653 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17654 			    first_mp, ah);
17655 		}
17656 
17657 		switch (ipsec_rc) {
17658 		case IPSEC_STATUS_SUCCESS:
17659 			break;
17660 		case IPSEC_STATUS_FAILED:
17661 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17662 			/* FALLTHRU */
17663 		case IPSEC_STATUS_PENDING:
17664 			return;
17665 		}
17666 		/* we're done with IPsec processing, send it up */
17667 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17668 		return;
17669 	}
17670 	default:
17671 		break;
17672 	}
17673 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17674 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17675 		    ire->ire_zoneid));
17676 		goto drop_pkt;
17677 	}
17678 	/*
17679 	 * Handle protocols with which IP is less intimate.  There
17680 	 * can be more than one stream bound to a particular
17681 	 * protocol.  When this is the case, each one gets a copy
17682 	 * of any incoming packets.
17683 	 */
17684 fanout:
17685 	ip_fanout_proto(q, first_mp, ill, ipha,
17686 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17687 	    B_TRUE, recv_ill, ire->ire_zoneid);
17688 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17689 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17690 	return;
17691 
17692 drop_pkt:
17693 	freemsg(first_mp);
17694 	if (hada_mp != NULL)
17695 		freeb(hada_mp);
17696 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17697 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17698 #undef	rptr
17699 #undef  iphs
17700 
17701 }
17702 
17703 /*
17704  * Update any source route, record route or timestamp options.
17705  * Check that we are at end of strict source route.
17706  * The options have already been checked for sanity in ip_rput_options().
17707  */
17708 static boolean_t
17709 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17710     ip_stack_t *ipst)
17711 {
17712 	ipoptp_t	opts;
17713 	uchar_t		*opt;
17714 	uint8_t		optval;
17715 	uint8_t		optlen;
17716 	ipaddr_t	dst;
17717 	uint32_t	ts;
17718 	ire_t		*dst_ire;
17719 	timestruc_t	now;
17720 	zoneid_t	zoneid;
17721 	ill_t		*ill;
17722 
17723 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17724 
17725 	ip2dbg(("ip_rput_local_options\n"));
17726 
17727 	for (optval = ipoptp_first(&opts, ipha);
17728 	    optval != IPOPT_EOL;
17729 	    optval = ipoptp_next(&opts)) {
17730 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17731 		opt = opts.ipoptp_cur;
17732 		optlen = opts.ipoptp_len;
17733 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17734 		    optval, optlen));
17735 		switch (optval) {
17736 			uint32_t off;
17737 		case IPOPT_SSRR:
17738 		case IPOPT_LSRR:
17739 			off = opt[IPOPT_OFFSET];
17740 			off--;
17741 			if (optlen < IP_ADDR_LEN ||
17742 			    off > optlen - IP_ADDR_LEN) {
17743 				/* End of source route */
17744 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17745 				break;
17746 			}
17747 			/*
17748 			 * This will only happen if two consecutive entries
17749 			 * in the source route contains our address or if
17750 			 * it is a packet with a loose source route which
17751 			 * reaches us before consuming the whole source route
17752 			 */
17753 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17754 			if (optval == IPOPT_SSRR) {
17755 				goto bad_src_route;
17756 			}
17757 			/*
17758 			 * Hack: instead of dropping the packet truncate the
17759 			 * source route to what has been used by filling the
17760 			 * rest with IPOPT_NOP.
17761 			 */
17762 			opt[IPOPT_OLEN] = (uint8_t)off;
17763 			while (off < optlen) {
17764 				opt[off++] = IPOPT_NOP;
17765 			}
17766 			break;
17767 		case IPOPT_RR:
17768 			off = opt[IPOPT_OFFSET];
17769 			off--;
17770 			if (optlen < IP_ADDR_LEN ||
17771 			    off > optlen - IP_ADDR_LEN) {
17772 				/* No more room - ignore */
17773 				ip1dbg((
17774 				    "ip_rput_local_options: end of RR\n"));
17775 				break;
17776 			}
17777 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17778 			    IP_ADDR_LEN);
17779 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17780 			break;
17781 		case IPOPT_TS:
17782 			/* Insert timestamp if there is romm */
17783 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17784 			case IPOPT_TS_TSONLY:
17785 				off = IPOPT_TS_TIMELEN;
17786 				break;
17787 			case IPOPT_TS_PRESPEC:
17788 			case IPOPT_TS_PRESPEC_RFC791:
17789 				/* Verify that the address matched */
17790 				off = opt[IPOPT_OFFSET] - 1;
17791 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17792 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17793 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
17794 				    ipst);
17795 				if (dst_ire == NULL) {
17796 					/* Not for us */
17797 					break;
17798 				}
17799 				ire_refrele(dst_ire);
17800 				/* FALLTHRU */
17801 			case IPOPT_TS_TSANDADDR:
17802 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17803 				break;
17804 			default:
17805 				/*
17806 				 * ip_*put_options should have already
17807 				 * dropped this packet.
17808 				 */
17809 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17810 				    "unknown IT - bug in ip_rput_options?\n");
17811 				return (B_TRUE);	/* Keep "lint" happy */
17812 			}
17813 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17814 				/* Increase overflow counter */
17815 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17816 				opt[IPOPT_POS_OV_FLG] =
17817 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17818 				    (off << 4));
17819 				break;
17820 			}
17821 			off = opt[IPOPT_OFFSET] - 1;
17822 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17823 			case IPOPT_TS_PRESPEC:
17824 			case IPOPT_TS_PRESPEC_RFC791:
17825 			case IPOPT_TS_TSANDADDR:
17826 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17827 				    IP_ADDR_LEN);
17828 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17829 				/* FALLTHRU */
17830 			case IPOPT_TS_TSONLY:
17831 				off = opt[IPOPT_OFFSET] - 1;
17832 				/* Compute # of milliseconds since midnight */
17833 				gethrestime(&now);
17834 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17835 				    now.tv_nsec / (NANOSEC / MILLISEC);
17836 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17837 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17838 				break;
17839 			}
17840 			break;
17841 		}
17842 	}
17843 	return (B_TRUE);
17844 
17845 bad_src_route:
17846 	q = WR(q);
17847 	if (q->q_next != NULL)
17848 		ill = q->q_ptr;
17849 	else
17850 		ill = NULL;
17851 
17852 	/* make sure we clear any indication of a hardware checksum */
17853 	DB_CKSUMFLAGS(mp) = 0;
17854 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
17855 	if (zoneid == ALL_ZONES)
17856 		freemsg(mp);
17857 	else
17858 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17859 	return (B_FALSE);
17860 
17861 }
17862 
17863 /*
17864  * Process IP options in an inbound packet.  If an option affects the
17865  * effective destination address, return the next hop address via dstp.
17866  * Returns -1 if something fails in which case an ICMP error has been sent
17867  * and mp freed.
17868  */
17869 static int
17870 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
17871     ip_stack_t *ipst)
17872 {
17873 	ipoptp_t	opts;
17874 	uchar_t		*opt;
17875 	uint8_t		optval;
17876 	uint8_t		optlen;
17877 	ipaddr_t	dst;
17878 	intptr_t	code = 0;
17879 	ire_t		*ire = NULL;
17880 	zoneid_t	zoneid;
17881 	ill_t		*ill;
17882 
17883 	ip2dbg(("ip_rput_options\n"));
17884 	dst = ipha->ipha_dst;
17885 	for (optval = ipoptp_first(&opts, ipha);
17886 	    optval != IPOPT_EOL;
17887 	    optval = ipoptp_next(&opts)) {
17888 		opt = opts.ipoptp_cur;
17889 		optlen = opts.ipoptp_len;
17890 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17891 		    optval, optlen));
17892 		/*
17893 		 * Note: we need to verify the checksum before we
17894 		 * modify anything thus this routine only extracts the next
17895 		 * hop dst from any source route.
17896 		 */
17897 		switch (optval) {
17898 			uint32_t off;
17899 		case IPOPT_SSRR:
17900 		case IPOPT_LSRR:
17901 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17902 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17903 			if (ire == NULL) {
17904 				if (optval == IPOPT_SSRR) {
17905 					ip1dbg(("ip_rput_options: not next"
17906 					    " strict source route 0x%x\n",
17907 					    ntohl(dst)));
17908 					code = (char *)&ipha->ipha_dst -
17909 					    (char *)ipha;
17910 					goto param_prob; /* RouterReq's */
17911 				}
17912 				ip2dbg(("ip_rput_options: "
17913 				    "not next source route 0x%x\n",
17914 				    ntohl(dst)));
17915 				break;
17916 			}
17917 			ire_refrele(ire);
17918 
17919 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17920 				ip1dbg((
17921 				    "ip_rput_options: bad option offset\n"));
17922 				code = (char *)&opt[IPOPT_OLEN] -
17923 				    (char *)ipha;
17924 				goto param_prob;
17925 			}
17926 			off = opt[IPOPT_OFFSET];
17927 			off--;
17928 		redo_srr:
17929 			if (optlen < IP_ADDR_LEN ||
17930 			    off > optlen - IP_ADDR_LEN) {
17931 				/* End of source route */
17932 				ip1dbg(("ip_rput_options: end of SR\n"));
17933 				break;
17934 			}
17935 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17936 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
17937 			    ntohl(dst)));
17938 
17939 			/*
17940 			 * Check if our address is present more than
17941 			 * once as consecutive hops in source route.
17942 			 * XXX verify per-interface ip_forwarding
17943 			 * for source route?
17944 			 */
17945 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17946 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17947 
17948 			if (ire != NULL) {
17949 				ire_refrele(ire);
17950 				off += IP_ADDR_LEN;
17951 				goto redo_srr;
17952 			}
17953 
17954 			if (dst == htonl(INADDR_LOOPBACK)) {
17955 				ip1dbg(("ip_rput_options: loopback addr in "
17956 				    "source route!\n"));
17957 				goto bad_src_route;
17958 			}
17959 			/*
17960 			 * For strict: verify that dst is directly
17961 			 * reachable.
17962 			 */
17963 			if (optval == IPOPT_SSRR) {
17964 				ire = ire_ftable_lookup(dst, 0, 0,
17965 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
17966 				    MBLK_GETLABEL(mp),
17967 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
17968 				if (ire == NULL) {
17969 					ip1dbg(("ip_rput_options: SSRR not "
17970 					    "directly reachable: 0x%x\n",
17971 					    ntohl(dst)));
17972 					goto bad_src_route;
17973 				}
17974 				ire_refrele(ire);
17975 			}
17976 			/*
17977 			 * Defer update of the offset and the record route
17978 			 * until the packet is forwarded.
17979 			 */
17980 			break;
17981 		case IPOPT_RR:
17982 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17983 				ip1dbg((
17984 				    "ip_rput_options: bad option offset\n"));
17985 				code = (char *)&opt[IPOPT_OLEN] -
17986 				    (char *)ipha;
17987 				goto param_prob;
17988 			}
17989 			break;
17990 		case IPOPT_TS:
17991 			/*
17992 			 * Verify that length >= 5 and that there is either
17993 			 * room for another timestamp or that the overflow
17994 			 * counter is not maxed out.
17995 			 */
17996 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
17997 			if (optlen < IPOPT_MINLEN_IT) {
17998 				goto param_prob;
17999 			}
18000 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18001 				ip1dbg((
18002 				    "ip_rput_options: bad option offset\n"));
18003 				code = (char *)&opt[IPOPT_OFFSET] -
18004 				    (char *)ipha;
18005 				goto param_prob;
18006 			}
18007 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18008 			case IPOPT_TS_TSONLY:
18009 				off = IPOPT_TS_TIMELEN;
18010 				break;
18011 			case IPOPT_TS_TSANDADDR:
18012 			case IPOPT_TS_PRESPEC:
18013 			case IPOPT_TS_PRESPEC_RFC791:
18014 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18015 				break;
18016 			default:
18017 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
18018 				    (char *)ipha;
18019 				goto param_prob;
18020 			}
18021 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
18022 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
18023 				/*
18024 				 * No room and the overflow counter is 15
18025 				 * already.
18026 				 */
18027 				goto param_prob;
18028 			}
18029 			break;
18030 		}
18031 	}
18032 
18033 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
18034 		*dstp = dst;
18035 		return (0);
18036 	}
18037 
18038 	ip1dbg(("ip_rput_options: error processing IP options."));
18039 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
18040 
18041 param_prob:
18042 	q = WR(q);
18043 	if (q->q_next != NULL)
18044 		ill = q->q_ptr;
18045 	else
18046 		ill = NULL;
18047 
18048 	/* make sure we clear any indication of a hardware checksum */
18049 	DB_CKSUMFLAGS(mp) = 0;
18050 	/* Don't know whether this is for non-global or global/forwarding */
18051 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18052 	if (zoneid == ALL_ZONES)
18053 		freemsg(mp);
18054 	else
18055 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
18056 	return (-1);
18057 
18058 bad_src_route:
18059 	q = WR(q);
18060 	if (q->q_next != NULL)
18061 		ill = q->q_ptr;
18062 	else
18063 		ill = NULL;
18064 
18065 	/* make sure we clear any indication of a hardware checksum */
18066 	DB_CKSUMFLAGS(mp) = 0;
18067 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18068 	if (zoneid == ALL_ZONES)
18069 		freemsg(mp);
18070 	else
18071 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18072 	return (-1);
18073 }
18074 
18075 /*
18076  * IP & ICMP info in >=14 msg's ...
18077  *  - ip fixed part (mib2_ip_t)
18078  *  - icmp fixed part (mib2_icmp_t)
18079  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18080  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18081  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18082  *  - ipRouteAttributeTable (ip 102)	labeled routes
18083  *  - ip multicast membership (ip_member_t)
18084  *  - ip multicast source filtering (ip_grpsrc_t)
18085  *  - igmp fixed part (struct igmpstat)
18086  *  - multicast routing stats (struct mrtstat)
18087  *  - multicast routing vifs (array of struct vifctl)
18088  *  - multicast routing routes (array of struct mfcctl)
18089  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18090  *					One per ill plus one generic
18091  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18092  *					One per ill plus one generic
18093  *  - ipv6RouteEntry			all IPv6 IREs
18094  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18095  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18096  *  - ipv6AddrEntry			all IPv6 ipifs
18097  *  - ipv6 multicast membership (ipv6_member_t)
18098  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18099  *
18100  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18101  *
18102  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18103  * already filled in by the caller.
18104  * Return value of 0 indicates that no messages were sent and caller
18105  * should free mpctl.
18106  */
18107 int
18108 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
18109 {
18110 	ip_stack_t *ipst;
18111 	sctp_stack_t *sctps;
18112 
18113 	if (q->q_next != NULL) {
18114 		ipst = ILLQ_TO_IPST(q);
18115 	} else {
18116 		ipst = CONNQ_TO_IPST(q);
18117 	}
18118 	ASSERT(ipst != NULL);
18119 	sctps = ipst->ips_netstack->netstack_sctp;
18120 
18121 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18122 		return (0);
18123 	}
18124 
18125 	/*
18126 	 * For the purposes of the (broken) packet shell use
18127 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
18128 	 * to make TCP and UDP appear first in the list of mib items.
18129 	 * TBD: We could expand this and use it in netstat so that
18130 	 * the kernel doesn't have to produce large tables (connections,
18131 	 * routes, etc) when netstat only wants the statistics or a particular
18132 	 * table.
18133 	 */
18134 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
18135 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
18136 			return (1);
18137 		}
18138 	}
18139 
18140 	if (level != MIB2_TCP) {
18141 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
18142 			return (1);
18143 		}
18144 	}
18145 
18146 	if (level != MIB2_UDP) {
18147 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
18148 			return (1);
18149 		}
18150 	}
18151 
18152 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18153 	    ipst)) == NULL) {
18154 		return (1);
18155 	}
18156 
18157 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18158 		return (1);
18159 	}
18160 
18161 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18162 		return (1);
18163 	}
18164 
18165 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18166 		return (1);
18167 	}
18168 
18169 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18170 		return (1);
18171 	}
18172 
18173 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18174 		return (1);
18175 	}
18176 
18177 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18178 		return (1);
18179 	}
18180 
18181 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18182 		return (1);
18183 	}
18184 
18185 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18186 		return (1);
18187 	}
18188 
18189 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18190 		return (1);
18191 	}
18192 
18193 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18194 		return (1);
18195 	}
18196 
18197 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18198 		return (1);
18199 	}
18200 
18201 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18202 		return (1);
18203 	}
18204 
18205 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18206 		return (1);
18207 	}
18208 
18209 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, ipst)) == NULL) {
18210 		return (1);
18211 	}
18212 
18213 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, ipst);
18214 	if (mpctl == NULL) {
18215 		return (1);
18216 	}
18217 
18218 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18219 		return (1);
18220 	}
18221 	freemsg(mpctl);
18222 	return (1);
18223 }
18224 
18225 
18226 /* Get global (legacy) IPv4 statistics */
18227 static mblk_t *
18228 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18229     ip_stack_t *ipst)
18230 {
18231 	mib2_ip_t		old_ip_mib;
18232 	struct opthdr		*optp;
18233 	mblk_t			*mp2ctl;
18234 
18235 	/*
18236 	 * make a copy of the original message
18237 	 */
18238 	mp2ctl = copymsg(mpctl);
18239 
18240 	/* fixed length IP structure... */
18241 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18242 	optp->level = MIB2_IP;
18243 	optp->name = 0;
18244 	SET_MIB(old_ip_mib.ipForwarding,
18245 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18246 	SET_MIB(old_ip_mib.ipDefaultTTL,
18247 	    (uint32_t)ipst->ips_ip_def_ttl);
18248 	SET_MIB(old_ip_mib.ipReasmTimeout,
18249 	    ipst->ips_ip_g_frag_timeout);
18250 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18251 	    sizeof (mib2_ipAddrEntry_t));
18252 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18253 	    sizeof (mib2_ipRouteEntry_t));
18254 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18255 	    sizeof (mib2_ipNetToMediaEntry_t));
18256 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18257 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18258 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18259 	    sizeof (mib2_ipAttributeEntry_t));
18260 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18261 
18262 	/*
18263 	 * Grab the statistics from the new IP MIB
18264 	 */
18265 	SET_MIB(old_ip_mib.ipInReceives,
18266 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18267 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18268 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18269 	SET_MIB(old_ip_mib.ipForwDatagrams,
18270 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18271 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18272 	    ipmib->ipIfStatsInUnknownProtos);
18273 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18274 	SET_MIB(old_ip_mib.ipInDelivers,
18275 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18276 	SET_MIB(old_ip_mib.ipOutRequests,
18277 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18278 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18279 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18280 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18281 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18282 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18283 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18284 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18285 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18286 
18287 	/* ipRoutingDiscards is not being used */
18288 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18289 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18290 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18291 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18292 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18293 	    ipmib->ipIfStatsReasmDuplicates);
18294 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18295 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18296 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18297 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18298 	SET_MIB(old_ip_mib.rawipInOverflows,
18299 	    ipmib->rawipIfStatsInOverflows);
18300 
18301 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18302 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18303 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18304 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18305 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18306 	    ipmib->ipIfStatsOutSwitchIPVersion);
18307 
18308 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18309 	    (int)sizeof (old_ip_mib))) {
18310 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18311 		    (uint_t)sizeof (old_ip_mib)));
18312 	}
18313 
18314 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18315 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18316 	    (int)optp->level, (int)optp->name, (int)optp->len));
18317 	qreply(q, mpctl);
18318 	return (mp2ctl);
18319 }
18320 
18321 /* Per interface IPv4 statistics */
18322 static mblk_t *
18323 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18324 {
18325 	struct opthdr		*optp;
18326 	mblk_t			*mp2ctl;
18327 	ill_t			*ill;
18328 	ill_walk_context_t	ctx;
18329 	mblk_t			*mp_tail = NULL;
18330 	mib2_ipIfStatsEntry_t	global_ip_mib;
18331 
18332 	/*
18333 	 * Make a copy of the original message
18334 	 */
18335 	mp2ctl = copymsg(mpctl);
18336 
18337 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18338 	optp->level = MIB2_IP;
18339 	optp->name = MIB2_IP_TRAFFIC_STATS;
18340 	/* Include "unknown interface" ip_mib */
18341 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18342 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18343 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18344 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18345 	    (ipst->ips_ip_g_forward ? 1 : 2));
18346 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18347 	    (uint32_t)ipst->ips_ip_def_ttl);
18348 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18349 	    sizeof (mib2_ipIfStatsEntry_t));
18350 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18351 	    sizeof (mib2_ipAddrEntry_t));
18352 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18353 	    sizeof (mib2_ipRouteEntry_t));
18354 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18355 	    sizeof (mib2_ipNetToMediaEntry_t));
18356 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18357 	    sizeof (ip_member_t));
18358 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18359 	    sizeof (ip_grpsrc_t));
18360 
18361 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18362 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18363 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18364 		    "failed to allocate %u bytes\n",
18365 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18366 	}
18367 
18368 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18369 
18370 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18371 	ill = ILL_START_WALK_V4(&ctx, ipst);
18372 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18373 		ill->ill_ip_mib->ipIfStatsIfIndex =
18374 		    ill->ill_phyint->phyint_ifindex;
18375 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18376 		    (ipst->ips_ip_g_forward ? 1 : 2));
18377 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18378 		    (uint32_t)ipst->ips_ip_def_ttl);
18379 
18380 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18381 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18382 		    (char *)ill->ill_ip_mib,
18383 		    (int)sizeof (*ill->ill_ip_mib))) {
18384 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18385 			    "failed to allocate %u bytes\n",
18386 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18387 		}
18388 	}
18389 	rw_exit(&ipst->ips_ill_g_lock);
18390 
18391 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18392 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18393 	    "level %d, name %d, len %d\n",
18394 	    (int)optp->level, (int)optp->name, (int)optp->len));
18395 	qreply(q, mpctl);
18396 
18397 	if (mp2ctl == NULL)
18398 		return (NULL);
18399 
18400 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18401 }
18402 
18403 /* Global IPv4 ICMP statistics */
18404 static mblk_t *
18405 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18406 {
18407 	struct opthdr		*optp;
18408 	mblk_t			*mp2ctl;
18409 
18410 	/*
18411 	 * Make a copy of the original message
18412 	 */
18413 	mp2ctl = copymsg(mpctl);
18414 
18415 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18416 	optp->level = MIB2_ICMP;
18417 	optp->name = 0;
18418 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18419 	    (int)sizeof (ipst->ips_icmp_mib))) {
18420 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18421 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18422 	}
18423 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18424 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18425 	    (int)optp->level, (int)optp->name, (int)optp->len));
18426 	qreply(q, mpctl);
18427 	return (mp2ctl);
18428 }
18429 
18430 /* Global IPv4 IGMP statistics */
18431 static mblk_t *
18432 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18433 {
18434 	struct opthdr		*optp;
18435 	mblk_t			*mp2ctl;
18436 
18437 	/*
18438 	 * make a copy of the original message
18439 	 */
18440 	mp2ctl = copymsg(mpctl);
18441 
18442 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18443 	optp->level = EXPER_IGMP;
18444 	optp->name = 0;
18445 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18446 	    (int)sizeof (ipst->ips_igmpstat))) {
18447 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18448 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18449 	}
18450 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18451 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18452 	    (int)optp->level, (int)optp->name, (int)optp->len));
18453 	qreply(q, mpctl);
18454 	return (mp2ctl);
18455 }
18456 
18457 /* Global IPv4 Multicast Routing statistics */
18458 static mblk_t *
18459 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18460 {
18461 	struct opthdr		*optp;
18462 	mblk_t			*mp2ctl;
18463 
18464 	/*
18465 	 * make a copy of the original message
18466 	 */
18467 	mp2ctl = copymsg(mpctl);
18468 
18469 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18470 	optp->level = EXPER_DVMRP;
18471 	optp->name = 0;
18472 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18473 		ip0dbg(("ip_mroute_stats: failed\n"));
18474 	}
18475 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18476 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18477 	    (int)optp->level, (int)optp->name, (int)optp->len));
18478 	qreply(q, mpctl);
18479 	return (mp2ctl);
18480 }
18481 
18482 /* IPv4 address information */
18483 static mblk_t *
18484 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18485 {
18486 	struct opthdr		*optp;
18487 	mblk_t			*mp2ctl;
18488 	mblk_t			*mp_tail = NULL;
18489 	ill_t			*ill;
18490 	ipif_t			*ipif;
18491 	uint_t			bitval;
18492 	mib2_ipAddrEntry_t	mae;
18493 	zoneid_t		zoneid;
18494 	ill_walk_context_t ctx;
18495 
18496 	/*
18497 	 * make a copy of the original message
18498 	 */
18499 	mp2ctl = copymsg(mpctl);
18500 
18501 	/* ipAddrEntryTable */
18502 
18503 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18504 	optp->level = MIB2_IP;
18505 	optp->name = MIB2_IP_ADDR;
18506 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18507 
18508 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18509 	ill = ILL_START_WALK_V4(&ctx, ipst);
18510 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18511 		for (ipif = ill->ill_ipif; ipif != NULL;
18512 		    ipif = ipif->ipif_next) {
18513 			if (ipif->ipif_zoneid != zoneid &&
18514 			    ipif->ipif_zoneid != ALL_ZONES)
18515 				continue;
18516 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18517 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18518 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18519 
18520 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18521 			    OCTET_LENGTH);
18522 			mae.ipAdEntIfIndex.o_length =
18523 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18524 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18525 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18526 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18527 			mae.ipAdEntInfo.ae_subnet_len =
18528 			    ip_mask_to_plen(ipif->ipif_net_mask);
18529 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18530 			for (bitval = 1;
18531 			    bitval &&
18532 			    !(bitval & ipif->ipif_brd_addr);
18533 			    bitval <<= 1)
18534 				noop;
18535 			mae.ipAdEntBcastAddr = bitval;
18536 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18537 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18538 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18539 			mae.ipAdEntInfo.ae_broadcast_addr =
18540 			    ipif->ipif_brd_addr;
18541 			mae.ipAdEntInfo.ae_pp_dst_addr =
18542 			    ipif->ipif_pp_dst_addr;
18543 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18544 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18545 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18546 
18547 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18548 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18549 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18550 				    "allocate %u bytes\n",
18551 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18552 			}
18553 		}
18554 	}
18555 	rw_exit(&ipst->ips_ill_g_lock);
18556 
18557 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18558 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18559 	    (int)optp->level, (int)optp->name, (int)optp->len));
18560 	qreply(q, mpctl);
18561 	return (mp2ctl);
18562 }
18563 
18564 /* IPv6 address information */
18565 static mblk_t *
18566 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18567 {
18568 	struct opthdr		*optp;
18569 	mblk_t			*mp2ctl;
18570 	mblk_t			*mp_tail = NULL;
18571 	ill_t			*ill;
18572 	ipif_t			*ipif;
18573 	mib2_ipv6AddrEntry_t	mae6;
18574 	zoneid_t		zoneid;
18575 	ill_walk_context_t	ctx;
18576 
18577 	/*
18578 	 * make a copy of the original message
18579 	 */
18580 	mp2ctl = copymsg(mpctl);
18581 
18582 	/* ipv6AddrEntryTable */
18583 
18584 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18585 	optp->level = MIB2_IP6;
18586 	optp->name = MIB2_IP6_ADDR;
18587 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18588 
18589 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18590 	ill = ILL_START_WALK_V6(&ctx, ipst);
18591 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18592 		for (ipif = ill->ill_ipif; ipif != NULL;
18593 		    ipif = ipif->ipif_next) {
18594 			if (ipif->ipif_zoneid != zoneid &&
18595 			    ipif->ipif_zoneid != ALL_ZONES)
18596 				continue;
18597 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18598 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18599 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18600 
18601 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18602 			    OCTET_LENGTH);
18603 			mae6.ipv6AddrIfIndex.o_length =
18604 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18605 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18606 			mae6.ipv6AddrPfxLength =
18607 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18608 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18609 			mae6.ipv6AddrInfo.ae_subnet_len =
18610 			    mae6.ipv6AddrPfxLength;
18611 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18612 
18613 			/* Type: stateless(1), stateful(2), unknown(3) */
18614 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18615 				mae6.ipv6AddrType = 1;
18616 			else
18617 				mae6.ipv6AddrType = 2;
18618 			/* Anycast: true(1), false(2) */
18619 			if (ipif->ipif_flags & IPIF_ANYCAST)
18620 				mae6.ipv6AddrAnycastFlag = 1;
18621 			else
18622 				mae6.ipv6AddrAnycastFlag = 2;
18623 
18624 			/*
18625 			 * Address status: preferred(1), deprecated(2),
18626 			 * invalid(3), inaccessible(4), unknown(5)
18627 			 */
18628 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18629 				mae6.ipv6AddrStatus = 3;
18630 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18631 				mae6.ipv6AddrStatus = 2;
18632 			else
18633 				mae6.ipv6AddrStatus = 1;
18634 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18635 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18636 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18637 			    ipif->ipif_v6pp_dst_addr;
18638 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18639 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18640 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18641 			mae6.ipv6AddrIdentifier = ill->ill_token;
18642 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18643 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18644 			mae6.ipv6AddrRetransmitTime =
18645 			    ill->ill_reachable_retrans_time;
18646 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18647 			    (char *)&mae6,
18648 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18649 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18650 				    "allocate %u bytes\n",
18651 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18652 			}
18653 		}
18654 	}
18655 	rw_exit(&ipst->ips_ill_g_lock);
18656 
18657 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18658 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18659 	    (int)optp->level, (int)optp->name, (int)optp->len));
18660 	qreply(q, mpctl);
18661 	return (mp2ctl);
18662 }
18663 
18664 /* IPv4 multicast group membership. */
18665 static mblk_t *
18666 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18667 {
18668 	struct opthdr		*optp;
18669 	mblk_t			*mp2ctl;
18670 	ill_t			*ill;
18671 	ipif_t			*ipif;
18672 	ilm_t			*ilm;
18673 	ip_member_t		ipm;
18674 	mblk_t			*mp_tail = NULL;
18675 	ill_walk_context_t	ctx;
18676 	zoneid_t		zoneid;
18677 
18678 	/*
18679 	 * make a copy of the original message
18680 	 */
18681 	mp2ctl = copymsg(mpctl);
18682 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18683 
18684 	/* ipGroupMember table */
18685 	optp = (struct opthdr *)&mpctl->b_rptr[
18686 	    sizeof (struct T_optmgmt_ack)];
18687 	optp->level = MIB2_IP;
18688 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18689 
18690 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18691 	ill = ILL_START_WALK_V4(&ctx, ipst);
18692 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18693 		ILM_WALKER_HOLD(ill);
18694 		for (ipif = ill->ill_ipif; ipif != NULL;
18695 		    ipif = ipif->ipif_next) {
18696 			if (ipif->ipif_zoneid != zoneid &&
18697 			    ipif->ipif_zoneid != ALL_ZONES)
18698 				continue;	/* not this zone */
18699 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
18700 			    OCTET_LENGTH);
18701 			ipm.ipGroupMemberIfIndex.o_length =
18702 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18703 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18704 				ASSERT(ilm->ilm_ipif != NULL);
18705 				ASSERT(ilm->ilm_ill == NULL);
18706 				if (ilm->ilm_ipif != ipif)
18707 					continue;
18708 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18709 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18710 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18711 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18712 				    (char *)&ipm, (int)sizeof (ipm))) {
18713 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18714 					    "failed to allocate %u bytes\n",
18715 					    (uint_t)sizeof (ipm)));
18716 				}
18717 			}
18718 		}
18719 		ILM_WALKER_RELE(ill);
18720 	}
18721 	rw_exit(&ipst->ips_ill_g_lock);
18722 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18723 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18724 	    (int)optp->level, (int)optp->name, (int)optp->len));
18725 	qreply(q, mpctl);
18726 	return (mp2ctl);
18727 }
18728 
18729 /* IPv6 multicast group membership. */
18730 static mblk_t *
18731 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18732 {
18733 	struct opthdr		*optp;
18734 	mblk_t			*mp2ctl;
18735 	ill_t			*ill;
18736 	ilm_t			*ilm;
18737 	ipv6_member_t		ipm6;
18738 	mblk_t			*mp_tail = NULL;
18739 	ill_walk_context_t	ctx;
18740 	zoneid_t		zoneid;
18741 
18742 	/*
18743 	 * make a copy of the original message
18744 	 */
18745 	mp2ctl = copymsg(mpctl);
18746 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18747 
18748 	/* ip6GroupMember table */
18749 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18750 	optp->level = MIB2_IP6;
18751 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18752 
18753 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18754 	ill = ILL_START_WALK_V6(&ctx, ipst);
18755 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18756 		ILM_WALKER_HOLD(ill);
18757 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18758 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18759 			ASSERT(ilm->ilm_ipif == NULL);
18760 			ASSERT(ilm->ilm_ill != NULL);
18761 			if (ilm->ilm_zoneid != zoneid)
18762 				continue;	/* not this zone */
18763 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18764 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18765 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18766 			if (!snmp_append_data2(mpctl->b_cont,
18767 			    &mp_tail,
18768 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18769 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18770 				    "failed to allocate %u bytes\n",
18771 				    (uint_t)sizeof (ipm6)));
18772 			}
18773 		}
18774 		ILM_WALKER_RELE(ill);
18775 	}
18776 	rw_exit(&ipst->ips_ill_g_lock);
18777 
18778 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18779 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18780 	    (int)optp->level, (int)optp->name, (int)optp->len));
18781 	qreply(q, mpctl);
18782 	return (mp2ctl);
18783 }
18784 
18785 /* IP multicast filtered sources */
18786 static mblk_t *
18787 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18788 {
18789 	struct opthdr		*optp;
18790 	mblk_t			*mp2ctl;
18791 	ill_t			*ill;
18792 	ipif_t			*ipif;
18793 	ilm_t			*ilm;
18794 	ip_grpsrc_t		ips;
18795 	mblk_t			*mp_tail = NULL;
18796 	ill_walk_context_t	ctx;
18797 	zoneid_t		zoneid;
18798 	int			i;
18799 	slist_t			*sl;
18800 
18801 	/*
18802 	 * make a copy of the original message
18803 	 */
18804 	mp2ctl = copymsg(mpctl);
18805 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18806 
18807 	/* ipGroupSource table */
18808 	optp = (struct opthdr *)&mpctl->b_rptr[
18809 	    sizeof (struct T_optmgmt_ack)];
18810 	optp->level = MIB2_IP;
18811 	optp->name = EXPER_IP_GROUP_SOURCES;
18812 
18813 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18814 	ill = ILL_START_WALK_V4(&ctx, ipst);
18815 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18816 		ILM_WALKER_HOLD(ill);
18817 		for (ipif = ill->ill_ipif; ipif != NULL;
18818 		    ipif = ipif->ipif_next) {
18819 			if (ipif->ipif_zoneid != zoneid)
18820 				continue;	/* not this zone */
18821 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
18822 			    OCTET_LENGTH);
18823 			ips.ipGroupSourceIfIndex.o_length =
18824 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18825 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18826 				ASSERT(ilm->ilm_ipif != NULL);
18827 				ASSERT(ilm->ilm_ill == NULL);
18828 				sl = ilm->ilm_filter;
18829 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18830 					continue;
18831 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18832 				for (i = 0; i < sl->sl_numsrc; i++) {
18833 					if (!IN6_IS_ADDR_V4MAPPED(
18834 					    &sl->sl_addr[i]))
18835 						continue;
18836 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18837 					    ips.ipGroupSourceAddress);
18838 					if (snmp_append_data2(mpctl->b_cont,
18839 					    &mp_tail, (char *)&ips,
18840 					    (int)sizeof (ips)) == 0) {
18841 						ip1dbg(("ip_snmp_get_mib2_"
18842 						    "ip_group_src: failed to "
18843 						    "allocate %u bytes\n",
18844 						    (uint_t)sizeof (ips)));
18845 					}
18846 				}
18847 			}
18848 		}
18849 		ILM_WALKER_RELE(ill);
18850 	}
18851 	rw_exit(&ipst->ips_ill_g_lock);
18852 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18853 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18854 	    (int)optp->level, (int)optp->name, (int)optp->len));
18855 	qreply(q, mpctl);
18856 	return (mp2ctl);
18857 }
18858 
18859 /* IPv6 multicast filtered sources. */
18860 static mblk_t *
18861 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18862 {
18863 	struct opthdr		*optp;
18864 	mblk_t			*mp2ctl;
18865 	ill_t			*ill;
18866 	ilm_t			*ilm;
18867 	ipv6_grpsrc_t		ips6;
18868 	mblk_t			*mp_tail = NULL;
18869 	ill_walk_context_t	ctx;
18870 	zoneid_t		zoneid;
18871 	int			i;
18872 	slist_t			*sl;
18873 
18874 	/*
18875 	 * make a copy of the original message
18876 	 */
18877 	mp2ctl = copymsg(mpctl);
18878 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18879 
18880 	/* ip6GroupMember table */
18881 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18882 	optp->level = MIB2_IP6;
18883 	optp->name = EXPER_IP6_GROUP_SOURCES;
18884 
18885 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18886 	ill = ILL_START_WALK_V6(&ctx, ipst);
18887 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18888 		ILM_WALKER_HOLD(ill);
18889 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18890 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18891 			ASSERT(ilm->ilm_ipif == NULL);
18892 			ASSERT(ilm->ilm_ill != NULL);
18893 			sl = ilm->ilm_filter;
18894 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18895 				continue;
18896 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18897 			for (i = 0; i < sl->sl_numsrc; i++) {
18898 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18899 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18900 				    (char *)&ips6, (int)sizeof (ips6))) {
18901 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18902 					    "group_src: failed to allocate "
18903 					    "%u bytes\n",
18904 					    (uint_t)sizeof (ips6)));
18905 				}
18906 			}
18907 		}
18908 		ILM_WALKER_RELE(ill);
18909 	}
18910 	rw_exit(&ipst->ips_ill_g_lock);
18911 
18912 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18913 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18914 	    (int)optp->level, (int)optp->name, (int)optp->len));
18915 	qreply(q, mpctl);
18916 	return (mp2ctl);
18917 }
18918 
18919 /* Multicast routing virtual interface table. */
18920 static mblk_t *
18921 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18922 {
18923 	struct opthdr		*optp;
18924 	mblk_t			*mp2ctl;
18925 
18926 	/*
18927 	 * make a copy of the original message
18928 	 */
18929 	mp2ctl = copymsg(mpctl);
18930 
18931 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18932 	optp->level = EXPER_DVMRP;
18933 	optp->name = EXPER_DVMRP_VIF;
18934 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
18935 		ip0dbg(("ip_mroute_vif: failed\n"));
18936 	}
18937 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18938 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
18939 	    (int)optp->level, (int)optp->name, (int)optp->len));
18940 	qreply(q, mpctl);
18941 	return (mp2ctl);
18942 }
18943 
18944 /* Multicast routing table. */
18945 static mblk_t *
18946 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18947 {
18948 	struct opthdr		*optp;
18949 	mblk_t			*mp2ctl;
18950 
18951 	/*
18952 	 * make a copy of the original message
18953 	 */
18954 	mp2ctl = copymsg(mpctl);
18955 
18956 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18957 	optp->level = EXPER_DVMRP;
18958 	optp->name = EXPER_DVMRP_MRT;
18959 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
18960 		ip0dbg(("ip_mroute_mrt: failed\n"));
18961 	}
18962 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18963 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
18964 	    (int)optp->level, (int)optp->name, (int)optp->len));
18965 	qreply(q, mpctl);
18966 	return (mp2ctl);
18967 }
18968 
18969 /*
18970  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
18971  * in one IRE walk.
18972  */
18973 static mblk_t *
18974 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18975 {
18976 	struct opthdr	*optp;
18977 	mblk_t		*mp2ctl;	/* Returned */
18978 	mblk_t		*mp3ctl;	/* nettomedia */
18979 	mblk_t		*mp4ctl;	/* routeattrs */
18980 	iproutedata_t	ird;
18981 	zoneid_t	zoneid;
18982 
18983 	/*
18984 	 * make copies of the original message
18985 	 *	- mp2ctl is returned unchanged to the caller for his use
18986 	 *	- mpctl is sent upstream as ipRouteEntryTable
18987 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
18988 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
18989 	 */
18990 	mp2ctl = copymsg(mpctl);
18991 	mp3ctl = copymsg(mpctl);
18992 	mp4ctl = copymsg(mpctl);
18993 	if (mp3ctl == NULL || mp4ctl == NULL) {
18994 		freemsg(mp4ctl);
18995 		freemsg(mp3ctl);
18996 		freemsg(mp2ctl);
18997 		freemsg(mpctl);
18998 		return (NULL);
18999 	}
19000 
19001 	bzero(&ird, sizeof (ird));
19002 
19003 	ird.ird_route.lp_head = mpctl->b_cont;
19004 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19005 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19006 
19007 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19008 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
19009 
19010 	/* ipRouteEntryTable in mpctl */
19011 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19012 	optp->level = MIB2_IP;
19013 	optp->name = MIB2_IP_ROUTE;
19014 	optp->len = msgdsize(ird.ird_route.lp_head);
19015 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19016 	    (int)optp->level, (int)optp->name, (int)optp->len));
19017 	qreply(q, mpctl);
19018 
19019 	/* ipNetToMediaEntryTable in mp3ctl */
19020 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19021 	optp->level = MIB2_IP;
19022 	optp->name = MIB2_IP_MEDIA;
19023 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19024 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19025 	    (int)optp->level, (int)optp->name, (int)optp->len));
19026 	qreply(q, mp3ctl);
19027 
19028 	/* ipRouteAttributeTable in mp4ctl */
19029 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19030 	optp->level = MIB2_IP;
19031 	optp->name = EXPER_IP_RTATTR;
19032 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19033 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19034 	    (int)optp->level, (int)optp->name, (int)optp->len));
19035 	if (optp->len == 0)
19036 		freemsg(mp4ctl);
19037 	else
19038 		qreply(q, mp4ctl);
19039 
19040 	return (mp2ctl);
19041 }
19042 
19043 /*
19044  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
19045  * ipv6NetToMediaEntryTable in an NDP walk.
19046  */
19047 static mblk_t *
19048 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19049 {
19050 	struct opthdr	*optp;
19051 	mblk_t		*mp2ctl;	/* Returned */
19052 	mblk_t		*mp3ctl;	/* nettomedia */
19053 	mblk_t		*mp4ctl;	/* routeattrs */
19054 	iproutedata_t	ird;
19055 	zoneid_t	zoneid;
19056 
19057 	/*
19058 	 * make copies of the original message
19059 	 *	- mp2ctl is returned unchanged to the caller for his use
19060 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19061 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19062 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19063 	 */
19064 	mp2ctl = copymsg(mpctl);
19065 	mp3ctl = copymsg(mpctl);
19066 	mp4ctl = copymsg(mpctl);
19067 	if (mp3ctl == NULL || mp4ctl == NULL) {
19068 		freemsg(mp4ctl);
19069 		freemsg(mp3ctl);
19070 		freemsg(mp2ctl);
19071 		freemsg(mpctl);
19072 		return (NULL);
19073 	}
19074 
19075 	bzero(&ird, sizeof (ird));
19076 
19077 	ird.ird_route.lp_head = mpctl->b_cont;
19078 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19079 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19080 
19081 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19082 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19083 
19084 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19085 	optp->level = MIB2_IP6;
19086 	optp->name = MIB2_IP6_ROUTE;
19087 	optp->len = msgdsize(ird.ird_route.lp_head);
19088 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19089 	    (int)optp->level, (int)optp->name, (int)optp->len));
19090 	qreply(q, mpctl);
19091 
19092 	/* ipv6NetToMediaEntryTable in mp3ctl */
19093 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19094 
19095 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19096 	optp->level = MIB2_IP6;
19097 	optp->name = MIB2_IP6_MEDIA;
19098 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19099 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19100 	    (int)optp->level, (int)optp->name, (int)optp->len));
19101 	qreply(q, mp3ctl);
19102 
19103 	/* ipv6RouteAttributeTable in mp4ctl */
19104 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19105 	optp->level = MIB2_IP6;
19106 	optp->name = EXPER_IP_RTATTR;
19107 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19108 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19109 	    (int)optp->level, (int)optp->name, (int)optp->len));
19110 	if (optp->len == 0)
19111 		freemsg(mp4ctl);
19112 	else
19113 		qreply(q, mp4ctl);
19114 
19115 	return (mp2ctl);
19116 }
19117 
19118 /*
19119  * IPv6 mib: One per ill
19120  */
19121 static mblk_t *
19122 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19123 {
19124 	struct opthdr		*optp;
19125 	mblk_t			*mp2ctl;
19126 	ill_t			*ill;
19127 	ill_walk_context_t	ctx;
19128 	mblk_t			*mp_tail = NULL;
19129 
19130 	/*
19131 	 * Make a copy of the original message
19132 	 */
19133 	mp2ctl = copymsg(mpctl);
19134 
19135 	/* fixed length IPv6 structure ... */
19136 
19137 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19138 	optp->level = MIB2_IP6;
19139 	optp->name = 0;
19140 	/* Include "unknown interface" ip6_mib */
19141 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19142 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19143 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19144 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19145 	    ipst->ips_ipv6_forward ? 1 : 2);
19146 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19147 	    ipst->ips_ipv6_def_hops);
19148 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19149 	    sizeof (mib2_ipIfStatsEntry_t));
19150 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19151 	    sizeof (mib2_ipv6AddrEntry_t));
19152 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19153 	    sizeof (mib2_ipv6RouteEntry_t));
19154 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19155 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19156 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19157 	    sizeof (ipv6_member_t));
19158 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19159 	    sizeof (ipv6_grpsrc_t));
19160 
19161 	/*
19162 	 * Synchronize 64- and 32-bit counters
19163 	 */
19164 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19165 	    ipIfStatsHCInReceives);
19166 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19167 	    ipIfStatsHCInDelivers);
19168 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19169 	    ipIfStatsHCOutRequests);
19170 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19171 	    ipIfStatsHCOutForwDatagrams);
19172 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19173 	    ipIfStatsHCOutMcastPkts);
19174 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19175 	    ipIfStatsHCInMcastPkts);
19176 
19177 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19178 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19179 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19180 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19181 	}
19182 
19183 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19184 	ill = ILL_START_WALK_V6(&ctx, ipst);
19185 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19186 		ill->ill_ip_mib->ipIfStatsIfIndex =
19187 		    ill->ill_phyint->phyint_ifindex;
19188 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19189 		    ipst->ips_ipv6_forward ? 1 : 2);
19190 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19191 		    ill->ill_max_hops);
19192 
19193 		/*
19194 		 * Synchronize 64- and 32-bit counters
19195 		 */
19196 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19197 		    ipIfStatsHCInReceives);
19198 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19199 		    ipIfStatsHCInDelivers);
19200 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19201 		    ipIfStatsHCOutRequests);
19202 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19203 		    ipIfStatsHCOutForwDatagrams);
19204 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19205 		    ipIfStatsHCOutMcastPkts);
19206 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19207 		    ipIfStatsHCInMcastPkts);
19208 
19209 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19210 		    (char *)ill->ill_ip_mib,
19211 		    (int)sizeof (*ill->ill_ip_mib))) {
19212 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19213 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19214 		}
19215 	}
19216 	rw_exit(&ipst->ips_ill_g_lock);
19217 
19218 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19219 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19220 	    (int)optp->level, (int)optp->name, (int)optp->len));
19221 	qreply(q, mpctl);
19222 	return (mp2ctl);
19223 }
19224 
19225 /*
19226  * ICMPv6 mib: One per ill
19227  */
19228 static mblk_t *
19229 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19230 {
19231 	struct opthdr		*optp;
19232 	mblk_t			*mp2ctl;
19233 	ill_t			*ill;
19234 	ill_walk_context_t	ctx;
19235 	mblk_t			*mp_tail = NULL;
19236 	/*
19237 	 * Make a copy of the original message
19238 	 */
19239 	mp2ctl = copymsg(mpctl);
19240 
19241 	/* fixed length ICMPv6 structure ... */
19242 
19243 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19244 	optp->level = MIB2_ICMP6;
19245 	optp->name = 0;
19246 	/* Include "unknown interface" icmp6_mib */
19247 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19248 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19249 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19250 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19251 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19252 	    (char *)&ipst->ips_icmp6_mib,
19253 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19254 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19255 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19256 	}
19257 
19258 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19259 	ill = ILL_START_WALK_V6(&ctx, ipst);
19260 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19261 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19262 		    ill->ill_phyint->phyint_ifindex;
19263 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19264 		    (char *)ill->ill_icmp6_mib,
19265 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19266 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19267 			    "%u bytes\n",
19268 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19269 		}
19270 	}
19271 	rw_exit(&ipst->ips_ill_g_lock);
19272 
19273 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19274 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19275 	    (int)optp->level, (int)optp->name, (int)optp->len));
19276 	qreply(q, mpctl);
19277 	return (mp2ctl);
19278 }
19279 
19280 /*
19281  * ire_walk routine to create both ipRouteEntryTable and
19282  * ipRouteAttributeTable in one IRE walk
19283  */
19284 static void
19285 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19286 {
19287 	ill_t				*ill;
19288 	ipif_t				*ipif;
19289 	mib2_ipRouteEntry_t		*re;
19290 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19291 	ipaddr_t			gw_addr;
19292 	tsol_ire_gw_secattr_t		*attrp;
19293 	tsol_gc_t			*gc = NULL;
19294 	tsol_gcgrp_t			*gcgrp = NULL;
19295 	uint_t				sacnt = 0;
19296 	int				i;
19297 
19298 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19299 
19300 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19301 		return;
19302 
19303 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19304 		mutex_enter(&attrp->igsa_lock);
19305 		if ((gc = attrp->igsa_gc) != NULL) {
19306 			gcgrp = gc->gc_grp;
19307 			ASSERT(gcgrp != NULL);
19308 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19309 			sacnt = 1;
19310 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19311 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19312 			gc = gcgrp->gcgrp_head;
19313 			sacnt = gcgrp->gcgrp_count;
19314 		}
19315 		mutex_exit(&attrp->igsa_lock);
19316 
19317 		/* do nothing if there's no gc to report */
19318 		if (gc == NULL) {
19319 			ASSERT(sacnt == 0);
19320 			if (gcgrp != NULL) {
19321 				/* we might as well drop the lock now */
19322 				rw_exit(&gcgrp->gcgrp_rwlock);
19323 				gcgrp = NULL;
19324 			}
19325 			attrp = NULL;
19326 		}
19327 
19328 		ASSERT(gc == NULL || (gcgrp != NULL &&
19329 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19330 	}
19331 	ASSERT(sacnt == 0 || gc != NULL);
19332 
19333 	if (sacnt != 0 &&
19334 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19335 		kmem_free(re, sizeof (*re));
19336 		rw_exit(&gcgrp->gcgrp_rwlock);
19337 		return;
19338 	}
19339 
19340 	/*
19341 	 * Return all IRE types for route table... let caller pick and choose
19342 	 */
19343 	re->ipRouteDest = ire->ire_addr;
19344 	ipif = ire->ire_ipif;
19345 	re->ipRouteIfIndex.o_length = 0;
19346 	if (ire->ire_type == IRE_CACHE) {
19347 		ill = (ill_t *)ire->ire_stq->q_ptr;
19348 		re->ipRouteIfIndex.o_length =
19349 		    ill->ill_name_length == 0 ? 0 :
19350 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19351 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19352 		    re->ipRouteIfIndex.o_length);
19353 	} else if (ipif != NULL) {
19354 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19355 		re->ipRouteIfIndex.o_length =
19356 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19357 	}
19358 	re->ipRouteMetric1 = -1;
19359 	re->ipRouteMetric2 = -1;
19360 	re->ipRouteMetric3 = -1;
19361 	re->ipRouteMetric4 = -1;
19362 
19363 	gw_addr = ire->ire_gateway_addr;
19364 
19365 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19366 		re->ipRouteNextHop = ire->ire_src_addr;
19367 	else
19368 		re->ipRouteNextHop = gw_addr;
19369 	/* indirect(4), direct(3), or invalid(2) */
19370 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19371 		re->ipRouteType = 2;
19372 	else
19373 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19374 	re->ipRouteProto = -1;
19375 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19376 	re->ipRouteMask = ire->ire_mask;
19377 	re->ipRouteMetric5 = -1;
19378 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19379 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19380 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19381 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19382 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19383 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19384 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19385 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19386 
19387 	if (ire->ire_flags & RTF_DYNAMIC) {
19388 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19389 	} else {
19390 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19391 	}
19392 
19393 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19394 	    (char *)re, (int)sizeof (*re))) {
19395 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19396 		    (uint_t)sizeof (*re)));
19397 	}
19398 
19399 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19400 		iaeptr->iae_routeidx = ird->ird_idx;
19401 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19402 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19403 	}
19404 
19405 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19406 	    (char *)iae, sacnt * sizeof (*iae))) {
19407 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19408 		    (unsigned)(sacnt * sizeof (*iae))));
19409 	}
19410 
19411 	/* bump route index for next pass */
19412 	ird->ird_idx++;
19413 
19414 	kmem_free(re, sizeof (*re));
19415 	if (sacnt != 0)
19416 		kmem_free(iae, sacnt * sizeof (*iae));
19417 
19418 	if (gcgrp != NULL)
19419 		rw_exit(&gcgrp->gcgrp_rwlock);
19420 }
19421 
19422 /*
19423  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19424  */
19425 static void
19426 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19427 {
19428 	ill_t				*ill;
19429 	ipif_t				*ipif;
19430 	mib2_ipv6RouteEntry_t		*re;
19431 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19432 	in6_addr_t			gw_addr_v6;
19433 	tsol_ire_gw_secattr_t		*attrp;
19434 	tsol_gc_t			*gc = NULL;
19435 	tsol_gcgrp_t			*gcgrp = NULL;
19436 	uint_t				sacnt = 0;
19437 	int				i;
19438 
19439 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19440 
19441 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19442 		return;
19443 
19444 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19445 		mutex_enter(&attrp->igsa_lock);
19446 		if ((gc = attrp->igsa_gc) != NULL) {
19447 			gcgrp = gc->gc_grp;
19448 			ASSERT(gcgrp != NULL);
19449 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19450 			sacnt = 1;
19451 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19452 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19453 			gc = gcgrp->gcgrp_head;
19454 			sacnt = gcgrp->gcgrp_count;
19455 		}
19456 		mutex_exit(&attrp->igsa_lock);
19457 
19458 		/* do nothing if there's no gc to report */
19459 		if (gc == NULL) {
19460 			ASSERT(sacnt == 0);
19461 			if (gcgrp != NULL) {
19462 				/* we might as well drop the lock now */
19463 				rw_exit(&gcgrp->gcgrp_rwlock);
19464 				gcgrp = NULL;
19465 			}
19466 			attrp = NULL;
19467 		}
19468 
19469 		ASSERT(gc == NULL || (gcgrp != NULL &&
19470 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19471 	}
19472 	ASSERT(sacnt == 0 || gc != NULL);
19473 
19474 	if (sacnt != 0 &&
19475 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19476 		kmem_free(re, sizeof (*re));
19477 		rw_exit(&gcgrp->gcgrp_rwlock);
19478 		return;
19479 	}
19480 
19481 	/*
19482 	 * Return all IRE types for route table... let caller pick and choose
19483 	 */
19484 	re->ipv6RouteDest = ire->ire_addr_v6;
19485 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19486 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19487 	re->ipv6RouteIfIndex.o_length = 0;
19488 	ipif = ire->ire_ipif;
19489 	if (ire->ire_type == IRE_CACHE) {
19490 		ill = (ill_t *)ire->ire_stq->q_ptr;
19491 		re->ipv6RouteIfIndex.o_length =
19492 		    ill->ill_name_length == 0 ? 0 :
19493 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19494 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19495 		    re->ipv6RouteIfIndex.o_length);
19496 	} else if (ipif != NULL) {
19497 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19498 		re->ipv6RouteIfIndex.o_length =
19499 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19500 	}
19501 
19502 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19503 
19504 	mutex_enter(&ire->ire_lock);
19505 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19506 	mutex_exit(&ire->ire_lock);
19507 
19508 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19509 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19510 	else
19511 		re->ipv6RouteNextHop = gw_addr_v6;
19512 
19513 	/* remote(4), local(3), or discard(2) */
19514 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19515 		re->ipv6RouteType = 2;
19516 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19517 		re->ipv6RouteType = 3;
19518 	else
19519 		re->ipv6RouteType = 4;
19520 
19521 	re->ipv6RouteProtocol	= -1;
19522 	re->ipv6RoutePolicy	= 0;
19523 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19524 	re->ipv6RouteNextHopRDI	= 0;
19525 	re->ipv6RouteWeight	= 0;
19526 	re->ipv6RouteMetric	= 0;
19527 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19528 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19529 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19530 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19531 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19532 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19533 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19534 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19535 
19536 	if (ire->ire_flags & RTF_DYNAMIC) {
19537 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19538 	} else {
19539 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19540 	}
19541 
19542 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19543 	    (char *)re, (int)sizeof (*re))) {
19544 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19545 		    (uint_t)sizeof (*re)));
19546 	}
19547 
19548 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19549 		iaeptr->iae_routeidx = ird->ird_idx;
19550 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19551 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19552 	}
19553 
19554 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19555 	    (char *)iae, sacnt * sizeof (*iae))) {
19556 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19557 		    (unsigned)(sacnt * sizeof (*iae))));
19558 	}
19559 
19560 	/* bump route index for next pass */
19561 	ird->ird_idx++;
19562 
19563 	kmem_free(re, sizeof (*re));
19564 	if (sacnt != 0)
19565 		kmem_free(iae, sacnt * sizeof (*iae));
19566 
19567 	if (gcgrp != NULL)
19568 		rw_exit(&gcgrp->gcgrp_rwlock);
19569 }
19570 
19571 /*
19572  * ndp_walk routine to create ipv6NetToMediaEntryTable
19573  */
19574 static int
19575 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19576 {
19577 	ill_t				*ill;
19578 	mib2_ipv6NetToMediaEntry_t	ntme;
19579 	dl_unitdata_req_t		*dl;
19580 
19581 	ill = nce->nce_ill;
19582 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19583 		return (0);
19584 
19585 	/*
19586 	 * Neighbor cache entry attached to IRE with on-link
19587 	 * destination.
19588 	 */
19589 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19590 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19591 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19592 	    (nce->nce_res_mp != NULL)) {
19593 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19594 		ntme.ipv6NetToMediaPhysAddress.o_length =
19595 		    dl->dl_dest_addr_length;
19596 	} else {
19597 		ntme.ipv6NetToMediaPhysAddress.o_length =
19598 		    ill->ill_phys_addr_length;
19599 	}
19600 	if (nce->nce_res_mp != NULL) {
19601 		bcopy((char *)nce->nce_res_mp->b_rptr +
19602 		    NCE_LL_ADDR_OFFSET(ill),
19603 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19604 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19605 	} else {
19606 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19607 		    ill->ill_phys_addr_length);
19608 	}
19609 	/*
19610 	 * Note: Returns ND_* states. Should be:
19611 	 * reachable(1), stale(2), delay(3), probe(4),
19612 	 * invalid(5), unknown(6)
19613 	 */
19614 	ntme.ipv6NetToMediaState = nce->nce_state;
19615 	ntme.ipv6NetToMediaLastUpdated = 0;
19616 
19617 	/* other(1), dynamic(2), static(3), local(4) */
19618 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19619 		ntme.ipv6NetToMediaType = 4;
19620 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19621 		ntme.ipv6NetToMediaType = 1;
19622 	} else {
19623 		ntme.ipv6NetToMediaType = 2;
19624 	}
19625 
19626 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19627 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19628 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19629 		    (uint_t)sizeof (ntme)));
19630 	}
19631 	return (0);
19632 }
19633 
19634 /*
19635  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19636  */
19637 /* ARGSUSED */
19638 int
19639 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19640 {
19641 	switch (level) {
19642 	case MIB2_IP:
19643 	case MIB2_ICMP:
19644 		switch (name) {
19645 		default:
19646 			break;
19647 		}
19648 		return (1);
19649 	default:
19650 		return (1);
19651 	}
19652 }
19653 
19654 /*
19655  * When there exists both a 64- and 32-bit counter of a particular type
19656  * (i.e., InReceives), only the 64-bit counters are added.
19657  */
19658 void
19659 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19660 {
19661 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19662 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19663 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19664 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19665 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19666 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19667 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19668 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19669 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19670 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19671 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19672 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19673 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19674 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19675 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19676 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19677 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19678 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19679 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19680 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19681 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19682 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19683 	    o2->ipIfStatsInWrongIPVersion);
19684 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19685 	    o2->ipIfStatsInWrongIPVersion);
19686 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19687 	    o2->ipIfStatsOutSwitchIPVersion);
19688 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19689 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19690 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19691 	    o2->ipIfStatsHCInForwDatagrams);
19692 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19693 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19694 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19695 	    o2->ipIfStatsHCOutForwDatagrams);
19696 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19697 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19698 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19699 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19700 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19701 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19702 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19703 	    o2->ipIfStatsHCOutMcastOctets);
19704 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19705 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19706 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19707 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19708 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19709 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19710 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19711 }
19712 
19713 void
19714 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19715 {
19716 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19717 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19718 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19719 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19720 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19721 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19722 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19723 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19724 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19725 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19726 	    o2->ipv6IfIcmpInRouterSolicits);
19727 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19728 	    o2->ipv6IfIcmpInRouterAdvertisements);
19729 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19730 	    o2->ipv6IfIcmpInNeighborSolicits);
19731 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19732 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19733 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19734 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19735 	    o2->ipv6IfIcmpInGroupMembQueries);
19736 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19737 	    o2->ipv6IfIcmpInGroupMembResponses);
19738 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19739 	    o2->ipv6IfIcmpInGroupMembReductions);
19740 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19741 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19742 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19743 	    o2->ipv6IfIcmpOutDestUnreachs);
19744 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19745 	    o2->ipv6IfIcmpOutAdminProhibs);
19746 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19747 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19748 	    o2->ipv6IfIcmpOutParmProblems);
19749 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19750 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19751 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19752 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19753 	    o2->ipv6IfIcmpOutRouterSolicits);
19754 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19755 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19756 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19757 	    o2->ipv6IfIcmpOutNeighborSolicits);
19758 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19759 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19760 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19761 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19762 	    o2->ipv6IfIcmpOutGroupMembQueries);
19763 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19764 	    o2->ipv6IfIcmpOutGroupMembResponses);
19765 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19766 	    o2->ipv6IfIcmpOutGroupMembReductions);
19767 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19768 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19769 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19770 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19771 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19772 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19773 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19774 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19775 	    o2->ipv6IfIcmpInGroupMembTotal);
19776 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19777 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19778 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19779 	    o2->ipv6IfIcmpInGroupMembBadReports);
19780 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19781 	    o2->ipv6IfIcmpInGroupMembOurReports);
19782 }
19783 
19784 /*
19785  * Called before the options are updated to check if this packet will
19786  * be source routed from here.
19787  * This routine assumes that the options are well formed i.e. that they
19788  * have already been checked.
19789  */
19790 static boolean_t
19791 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
19792 {
19793 	ipoptp_t	opts;
19794 	uchar_t		*opt;
19795 	uint8_t		optval;
19796 	uint8_t		optlen;
19797 	ipaddr_t	dst;
19798 	ire_t		*ire;
19799 
19800 	if (IS_SIMPLE_IPH(ipha)) {
19801 		ip2dbg(("not source routed\n"));
19802 		return (B_FALSE);
19803 	}
19804 	dst = ipha->ipha_dst;
19805 	for (optval = ipoptp_first(&opts, ipha);
19806 	    optval != IPOPT_EOL;
19807 	    optval = ipoptp_next(&opts)) {
19808 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19809 		opt = opts.ipoptp_cur;
19810 		optlen = opts.ipoptp_len;
19811 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19812 		    optval, optlen));
19813 		switch (optval) {
19814 			uint32_t off;
19815 		case IPOPT_SSRR:
19816 		case IPOPT_LSRR:
19817 			/*
19818 			 * If dst is one of our addresses and there are some
19819 			 * entries left in the source route return (true).
19820 			 */
19821 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19822 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
19823 			if (ire == NULL) {
19824 				ip2dbg(("ip_source_routed: not next"
19825 				    " source route 0x%x\n",
19826 				    ntohl(dst)));
19827 				return (B_FALSE);
19828 			}
19829 			ire_refrele(ire);
19830 			off = opt[IPOPT_OFFSET];
19831 			off--;
19832 			if (optlen < IP_ADDR_LEN ||
19833 			    off > optlen - IP_ADDR_LEN) {
19834 				/* End of source route */
19835 				ip1dbg(("ip_source_routed: end of SR\n"));
19836 				return (B_FALSE);
19837 			}
19838 			return (B_TRUE);
19839 		}
19840 	}
19841 	ip2dbg(("not source routed\n"));
19842 	return (B_FALSE);
19843 }
19844 
19845 /*
19846  * Check if the packet contains any source route.
19847  */
19848 static boolean_t
19849 ip_source_route_included(ipha_t *ipha)
19850 {
19851 	ipoptp_t	opts;
19852 	uint8_t		optval;
19853 
19854 	if (IS_SIMPLE_IPH(ipha))
19855 		return (B_FALSE);
19856 	for (optval = ipoptp_first(&opts, ipha);
19857 	    optval != IPOPT_EOL;
19858 	    optval = ipoptp_next(&opts)) {
19859 		switch (optval) {
19860 		case IPOPT_SSRR:
19861 		case IPOPT_LSRR:
19862 			return (B_TRUE);
19863 		}
19864 	}
19865 	return (B_FALSE);
19866 }
19867 
19868 /*
19869  * Called when the IRE expiration timer fires.
19870  */
19871 void
19872 ip_trash_timer_expire(void *args)
19873 {
19874 	int			flush_flag = 0;
19875 	ire_expire_arg_t	iea;
19876 	ip_stack_t		*ipst = (ip_stack_t *)args;
19877 
19878 	iea.iea_ipst = ipst;	/* No netstack_hold */
19879 
19880 	/*
19881 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19882 	 * This lock makes sure that a new invocation of this function
19883 	 * that occurs due to an almost immediate timer firing will not
19884 	 * progress beyond this point until the current invocation is done
19885 	 */
19886 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19887 	ipst->ips_ip_ire_expire_id = 0;
19888 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19889 
19890 	/* Periodic timer */
19891 	if (ipst->ips_ip_ire_arp_time_elapsed >=
19892 	    ipst->ips_ip_ire_arp_interval) {
19893 		/*
19894 		 * Remove all IRE_CACHE entries since they might
19895 		 * contain arp information.
19896 		 */
19897 		flush_flag |= FLUSH_ARP_TIME;
19898 		ipst->ips_ip_ire_arp_time_elapsed = 0;
19899 		IP_STAT(ipst, ip_ire_arp_timer_expired);
19900 	}
19901 	if (ipst->ips_ip_ire_rd_time_elapsed >=
19902 	    ipst->ips_ip_ire_redir_interval) {
19903 		/* Remove all redirects */
19904 		flush_flag |= FLUSH_REDIRECT_TIME;
19905 		ipst->ips_ip_ire_rd_time_elapsed = 0;
19906 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
19907 	}
19908 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
19909 	    ipst->ips_ip_ire_pathmtu_interval) {
19910 		/* Increase path mtu */
19911 		flush_flag |= FLUSH_MTU_TIME;
19912 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
19913 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
19914 	}
19915 
19916 	/*
19917 	 * Optimize for the case when there are no redirects in the
19918 	 * ftable, that is, no need to walk the ftable in that case.
19919 	 */
19920 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
19921 		iea.iea_flush_flag = flush_flag;
19922 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
19923 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
19924 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
19925 		    NULL, ALL_ZONES, ipst);
19926 	}
19927 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
19928 	    ipst->ips_ip_redirect_cnt > 0) {
19929 		iea.iea_flush_flag = flush_flag;
19930 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
19931 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
19932 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
19933 	}
19934 	if (flush_flag & FLUSH_MTU_TIME) {
19935 		/*
19936 		 * Walk all IPv6 IRE's and update them
19937 		 * Note that ARP and redirect timers are not
19938 		 * needed since NUD handles stale entries.
19939 		 */
19940 		flush_flag = FLUSH_MTU_TIME;
19941 		iea.iea_flush_flag = flush_flag;
19942 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
19943 		    ALL_ZONES, ipst);
19944 	}
19945 
19946 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
19947 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
19948 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
19949 
19950 	/*
19951 	 * Hold the lock to serialize timeout calls and prevent
19952 	 * stale values in ip_ire_expire_id. Otherwise it is possible
19953 	 * for the timer to fire and a new invocation of this function
19954 	 * to start before the return value of timeout has been stored
19955 	 * in ip_ire_expire_id by the current invocation.
19956 	 */
19957 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19958 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
19959 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
19960 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19961 }
19962 
19963 /*
19964  * Called by the memory allocator subsystem directly, when the system
19965  * is running low on memory.
19966  */
19967 /* ARGSUSED */
19968 void
19969 ip_trash_ire_reclaim(void *args)
19970 {
19971 	netstack_handle_t nh;
19972 	netstack_t *ns;
19973 
19974 	netstack_next_init(&nh);
19975 	while ((ns = netstack_next(&nh)) != NULL) {
19976 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
19977 		netstack_rele(ns);
19978 	}
19979 	netstack_next_fini(&nh);
19980 }
19981 
19982 static void
19983 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
19984 {
19985 	ire_cache_count_t icc;
19986 	ire_cache_reclaim_t icr;
19987 	ncc_cache_count_t ncc;
19988 	nce_cache_reclaim_t ncr;
19989 	uint_t delete_cnt;
19990 	/*
19991 	 * Memory reclaim call back.
19992 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
19993 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
19994 	 * entries, determine what fraction to free for
19995 	 * each category of IRE_CACHE entries giving absolute priority
19996 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
19997 	 * entry will be freed unless all offlink entries are freed).
19998 	 */
19999 	icc.icc_total = 0;
20000 	icc.icc_unused = 0;
20001 	icc.icc_offlink = 0;
20002 	icc.icc_pmtu = 0;
20003 	icc.icc_onlink = 0;
20004 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20005 
20006 	/*
20007 	 * Free NCEs for IPv6 like the onlink ires.
20008 	 */
20009 	ncc.ncc_total = 0;
20010 	ncc.ncc_host = 0;
20011 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
20012 
20013 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
20014 	    icc.icc_pmtu + icc.icc_onlink);
20015 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
20016 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
20017 	if (delete_cnt == 0)
20018 		return;
20019 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
20020 	/* Always delete all unused offlink entries */
20021 	icr.icr_ipst = ipst;
20022 	icr.icr_unused = 1;
20023 	if (delete_cnt <= icc.icc_unused) {
20024 		/*
20025 		 * Only need to free unused entries.  In other words,
20026 		 * there are enough unused entries to free to meet our
20027 		 * target number of freed ire cache entries.
20028 		 */
20029 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
20030 		ncr.ncr_host = 0;
20031 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
20032 		/*
20033 		 * Only need to free unused entries, plus a fraction of offlink
20034 		 * entries.  It follows from the first if statement that
20035 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
20036 		 */
20037 		delete_cnt -= icc.icc_unused;
20038 		/* Round up # deleted by truncating fraction */
20039 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
20040 		icr.icr_pmtu = icr.icr_onlink = 0;
20041 		ncr.ncr_host = 0;
20042 	} else if (delete_cnt <=
20043 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
20044 		/*
20045 		 * Free all unused and offlink entries, plus a fraction of
20046 		 * pmtu entries.  It follows from the previous if statement
20047 		 * that icc_pmtu is non-zero, and that
20048 		 * delete_cnt != icc_unused + icc_offlink.
20049 		 */
20050 		icr.icr_offlink = 1;
20051 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
20052 		/* Round up # deleted by truncating fraction */
20053 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20054 		icr.icr_onlink = 0;
20055 		ncr.ncr_host = 0;
20056 	} else {
20057 		/*
20058 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20059 		 * of onlink entries.  If we're here, then we know that
20060 		 * icc_onlink is non-zero, and that
20061 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20062 		 */
20063 		icr.icr_offlink = icr.icr_pmtu = 1;
20064 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20065 		    icc.icc_pmtu;
20066 		/* Round up # deleted by truncating fraction */
20067 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20068 		/* Using the same delete fraction as for onlink IREs */
20069 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20070 	}
20071 #ifdef DEBUG
20072 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20073 	    "fractions %d/%d/%d/%d\n",
20074 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20075 	    icc.icc_unused, icc.icc_offlink,
20076 	    icc.icc_pmtu, icc.icc_onlink,
20077 	    icr.icr_unused, icr.icr_offlink,
20078 	    icr.icr_pmtu, icr.icr_onlink));
20079 #endif
20080 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20081 	if (ncr.ncr_host != 0)
20082 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20083 		    (uchar_t *)&ncr, ipst);
20084 #ifdef DEBUG
20085 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20086 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20087 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20088 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20089 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20090 	    icc.icc_pmtu, icc.icc_onlink));
20091 #endif
20092 }
20093 
20094 /*
20095  * ip_unbind is called when a copy of an unbind request is received from the
20096  * upper level protocol.  We remove this conn from any fanout hash list it is
20097  * on, and zero out the bind information.  No reply is expected up above.
20098  */
20099 mblk_t *
20100 ip_unbind(queue_t *q, mblk_t *mp)
20101 {
20102 	conn_t	*connp = Q_TO_CONN(q);
20103 
20104 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20105 
20106 	if (is_system_labeled() && connp->conn_anon_port) {
20107 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20108 		    connp->conn_mlp_type, connp->conn_ulp,
20109 		    ntohs(connp->conn_lport), B_FALSE);
20110 		connp->conn_anon_port = 0;
20111 	}
20112 	connp->conn_mlp_type = mlptSingle;
20113 
20114 	ipcl_hash_remove(connp);
20115 
20116 	ASSERT(mp->b_cont == NULL);
20117 	/*
20118 	 * Convert mp into a T_OK_ACK
20119 	 */
20120 	mp = mi_tpi_ok_ack_alloc(mp);
20121 
20122 	/*
20123 	 * should not happen in practice... T_OK_ACK is smaller than the
20124 	 * original message.
20125 	 */
20126 	if (mp == NULL)
20127 		return (NULL);
20128 
20129 	return (mp);
20130 }
20131 
20132 /*
20133  * Write side put procedure.  Outbound data, IOCTLs, responses from
20134  * resolvers, etc, come down through here.
20135  *
20136  * arg2 is always a queue_t *.
20137  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20138  * the zoneid.
20139  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20140  */
20141 void
20142 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20143 {
20144 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20145 }
20146 
20147 void
20148 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20149     ip_opt_info_t *infop)
20150 {
20151 	conn_t		*connp = NULL;
20152 	queue_t		*q = (queue_t *)arg2;
20153 	ipha_t		*ipha;
20154 #define	rptr	((uchar_t *)ipha)
20155 	ire_t		*ire = NULL;
20156 	ire_t		*sctp_ire = NULL;
20157 	uint32_t	v_hlen_tos_len;
20158 	ipaddr_t	dst;
20159 	mblk_t		*first_mp = NULL;
20160 	boolean_t	mctl_present;
20161 	ipsec_out_t	*io;
20162 	int		match_flags;
20163 	ill_t		*attach_ill = NULL;
20164 					/* Bind to IPIF_NOFAILOVER ill etc. */
20165 	ill_t		*xmit_ill = NULL;	/* IP_PKTINFO etc. */
20166 	ipif_t		*dst_ipif;
20167 	boolean_t	multirt_need_resolve = B_FALSE;
20168 	mblk_t		*copy_mp = NULL;
20169 	int		err;
20170 	zoneid_t	zoneid;
20171 	boolean_t	need_decref = B_FALSE;
20172 	boolean_t	ignore_dontroute = B_FALSE;
20173 	boolean_t	ignore_nexthop = B_FALSE;
20174 	boolean_t	ip_nexthop = B_FALSE;
20175 	ipaddr_t	nexthop_addr;
20176 	ip_stack_t	*ipst;
20177 
20178 #ifdef	_BIG_ENDIAN
20179 #define	V_HLEN	(v_hlen_tos_len >> 24)
20180 #else
20181 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20182 #endif
20183 
20184 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20185 	    "ip_wput_start: q %p", q);
20186 
20187 	/*
20188 	 * ip_wput fast path
20189 	 */
20190 
20191 	/* is packet from ARP ? */
20192 	if (q->q_next != NULL) {
20193 		zoneid = (zoneid_t)(uintptr_t)arg;
20194 		goto qnext;
20195 	}
20196 
20197 	connp = (conn_t *)arg;
20198 	ASSERT(connp != NULL);
20199 	zoneid = connp->conn_zoneid;
20200 	ipst = connp->conn_netstack->netstack_ip;
20201 
20202 	/* is queue flow controlled? */
20203 	if ((q->q_first != NULL || connp->conn_draining) &&
20204 	    (caller == IP_WPUT)) {
20205 		ASSERT(!need_decref);
20206 		(void) putq(q, mp);
20207 		return;
20208 	}
20209 
20210 	/* Multidata transmit? */
20211 	if (DB_TYPE(mp) == M_MULTIDATA) {
20212 		/*
20213 		 * We should never get here, since all Multidata messages
20214 		 * originating from tcp should have been directed over to
20215 		 * tcp_multisend() in the first place.
20216 		 */
20217 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20218 		freemsg(mp);
20219 		return;
20220 	} else if (DB_TYPE(mp) != M_DATA)
20221 		goto notdata;
20222 
20223 	if (mp->b_flag & MSGHASREF) {
20224 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20225 		mp->b_flag &= ~MSGHASREF;
20226 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20227 		need_decref = B_TRUE;
20228 	}
20229 	ipha = (ipha_t *)mp->b_rptr;
20230 
20231 	/* is IP header non-aligned or mblk smaller than basic IP header */
20232 #ifndef SAFETY_BEFORE_SPEED
20233 	if (!OK_32PTR(rptr) ||
20234 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20235 		goto hdrtoosmall;
20236 #endif
20237 
20238 	ASSERT(OK_32PTR(ipha));
20239 
20240 	/*
20241 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20242 	 * wrong version, we'll catch it again in ip_output_v6.
20243 	 *
20244 	 * Note that this is *only* locally-generated output here, and never
20245 	 * forwarded data, and that we need to deal only with transports that
20246 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20247 	 * label.)
20248 	 */
20249 	if (is_system_labeled() &&
20250 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20251 	    !connp->conn_ulp_labeled) {
20252 		err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20253 		    connp->conn_mac_exempt, ipst);
20254 		ipha = (ipha_t *)mp->b_rptr;
20255 		if (err != 0) {
20256 			first_mp = mp;
20257 			if (err == EINVAL)
20258 				goto icmp_parameter_problem;
20259 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20260 			goto discard_pkt;
20261 		}
20262 	}
20263 
20264 	ASSERT(infop != NULL);
20265 
20266 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20267 		/*
20268 		 * IP_PKTINFO ancillary option is present.
20269 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20270 		 * allows using address of any zone as the source address.
20271 		 */
20272 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20273 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20274 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20275 		if (ire == NULL)
20276 			goto drop_pkt;
20277 		ire_refrele(ire);
20278 		ire = NULL;
20279 	}
20280 
20281 	/*
20282 	 * IP_DONTFAILOVER_IF and IP_BOUND_IF have precedence over ill index
20283 	 * passed in IP_PKTINFO.
20284 	 */
20285 	if (infop->ip_opt_ill_index != 0 &&
20286 	    connp->conn_outgoing_ill == NULL &&
20287 	    connp->conn_nofailover_ill == NULL) {
20288 
20289 		xmit_ill = ill_lookup_on_ifindex(
20290 		    infop->ip_opt_ill_index, B_FALSE, NULL, NULL, NULL, NULL,
20291 		    ipst);
20292 
20293 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20294 			goto drop_pkt;
20295 		/*
20296 		 * check that there is an ipif belonging
20297 		 * to our zone. IPCL_ZONEID is not used because
20298 		 * IP_ALLZONES option is valid only when the ill is
20299 		 * accessible from all zones i.e has a valid ipif in
20300 		 * all zones.
20301 		 */
20302 		if (!ipif_lookup_zoneid_group(xmit_ill, zoneid, 0, NULL)) {
20303 			goto drop_pkt;
20304 		}
20305 	}
20306 
20307 	/*
20308 	 * If there is a policy, try to attach an ipsec_out in
20309 	 * the front. At the end, first_mp either points to a
20310 	 * M_DATA message or IPSEC_OUT message linked to a
20311 	 * M_DATA message. We have to do it now as we might
20312 	 * lose the "conn" if we go through ip_newroute.
20313 	 */
20314 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20315 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20316 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20317 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20318 			if (need_decref)
20319 				CONN_DEC_REF(connp);
20320 			return;
20321 		} else {
20322 			ASSERT(mp->b_datap->db_type == M_CTL);
20323 			first_mp = mp;
20324 			mp = mp->b_cont;
20325 			mctl_present = B_TRUE;
20326 		}
20327 	} else {
20328 		first_mp = mp;
20329 		mctl_present = B_FALSE;
20330 	}
20331 
20332 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20333 
20334 	/* is wrong version or IP options present */
20335 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20336 		goto version_hdrlen_check;
20337 	dst = ipha->ipha_dst;
20338 
20339 	if (connp->conn_nofailover_ill != NULL) {
20340 		attach_ill = conn_get_held_ill(connp,
20341 		    &connp->conn_nofailover_ill, &err);
20342 		if (err == ILL_LOOKUP_FAILED) {
20343 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20344 			if (need_decref)
20345 				CONN_DEC_REF(connp);
20346 			freemsg(first_mp);
20347 			return;
20348 		}
20349 	}
20350 
20351 	/* If IP_BOUND_IF has been set, use that ill. */
20352 	if (connp->conn_outgoing_ill != NULL) {
20353 		xmit_ill = conn_get_held_ill(connp,
20354 		    &connp->conn_outgoing_ill, &err);
20355 		if (err == ILL_LOOKUP_FAILED)
20356 			goto drop_pkt;
20357 
20358 		goto send_from_ill;
20359 	}
20360 
20361 	/* is packet multicast? */
20362 	if (CLASSD(dst))
20363 		goto multicast;
20364 
20365 	/*
20366 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20367 	 * takes precedence over conn_dontroute and conn_nexthop_set
20368 	 */
20369 	if (xmit_ill != NULL)
20370 		goto send_from_ill;
20371 
20372 	if (connp->conn_dontroute || connp->conn_nexthop_set) {
20373 		/*
20374 		 * If the destination is a broadcast, local, or loopback
20375 		 * address, SO_DONTROUTE and IP_NEXTHOP go through the
20376 		 * standard path.
20377 		 */
20378 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20379 		if ((ire == NULL) || (ire->ire_type &
20380 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK)) == 0) {
20381 			if (ire != NULL) {
20382 				ire_refrele(ire);
20383 				/* No more access to ire */
20384 				ire = NULL;
20385 			}
20386 			/*
20387 			 * bypass routing checks and go directly to interface.
20388 			 */
20389 			if (connp->conn_dontroute)
20390 				goto dontroute;
20391 
20392 			ASSERT(connp->conn_nexthop_set);
20393 			ip_nexthop = B_TRUE;
20394 			nexthop_addr = connp->conn_nexthop_v4;
20395 			goto send_from_ill;
20396 		}
20397 
20398 		/* Must be a broadcast, a loopback or a local ire */
20399 		ire_refrele(ire);
20400 		/* No more access to ire */
20401 		ire = NULL;
20402 	}
20403 
20404 	if (attach_ill != NULL)
20405 		goto send_from_ill;
20406 
20407 	/*
20408 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20409 	 * this for the tcp global queue and listen end point
20410 	 * as it does not really have a real destination to
20411 	 * talk to.  This is also true for SCTP.
20412 	 */
20413 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20414 	    !connp->conn_fully_bound) {
20415 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20416 		if (ire == NULL)
20417 			goto noirefound;
20418 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20419 		    "ip_wput_end: q %p (%S)", q, "end");
20420 
20421 		/*
20422 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20423 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20424 		 */
20425 		if (ire->ire_flags & RTF_MULTIRT) {
20426 
20427 			/*
20428 			 * Force the TTL of multirouted packets if required.
20429 			 * The TTL of such packets is bounded by the
20430 			 * ip_multirt_ttl ndd variable.
20431 			 */
20432 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20433 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20434 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20435 				    "(was %d), dst 0x%08x\n",
20436 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20437 				    ntohl(ire->ire_addr)));
20438 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20439 			}
20440 			/*
20441 			 * We look at this point if there are pending
20442 			 * unresolved routes. ire_multirt_resolvable()
20443 			 * checks in O(n) that all IRE_OFFSUBNET ire
20444 			 * entries for the packet's destination and
20445 			 * flagged RTF_MULTIRT are currently resolved.
20446 			 * If some remain unresolved, we make a copy
20447 			 * of the current message. It will be used
20448 			 * to initiate additional route resolutions.
20449 			 */
20450 			multirt_need_resolve =
20451 			    ire_multirt_need_resolve(ire->ire_addr,
20452 			    MBLK_GETLABEL(first_mp), ipst);
20453 			ip2dbg(("ip_wput[TCP]: ire %p, "
20454 			    "multirt_need_resolve %d, first_mp %p\n",
20455 			    (void *)ire, multirt_need_resolve,
20456 			    (void *)first_mp));
20457 			if (multirt_need_resolve) {
20458 				copy_mp = copymsg(first_mp);
20459 				if (copy_mp != NULL) {
20460 					MULTIRT_DEBUG_TAG(copy_mp);
20461 				}
20462 			}
20463 		}
20464 
20465 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20466 
20467 		/*
20468 		 * Try to resolve another multiroute if
20469 		 * ire_multirt_need_resolve() deemed it necessary.
20470 		 */
20471 		if (copy_mp != NULL)
20472 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20473 		if (need_decref)
20474 			CONN_DEC_REF(connp);
20475 		return;
20476 	}
20477 
20478 	/*
20479 	 * Access to conn_ire_cache. (protected by conn_lock)
20480 	 *
20481 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20482 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20483 	 * send a packet or two with the IRE_CACHE that is going away.
20484 	 * Access to the ire requires an ire refhold on the ire prior to
20485 	 * its use since an interface unplumb thread may delete the cached
20486 	 * ire and release the refhold at any time.
20487 	 *
20488 	 * Caching an ire in the conn_ire_cache
20489 	 *
20490 	 * o Caching an ire pointer in the conn requires a strict check for
20491 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20492 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20493 	 * in the conn is done after making sure under the bucket lock that the
20494 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20495 	 * caching an ire after the unplumb thread has cleaned up the conn.
20496 	 * If the conn does not send a packet subsequently the unplumb thread
20497 	 * will be hanging waiting for the ire count to drop to zero.
20498 	 *
20499 	 * o We also need to atomically test for a null conn_ire_cache and
20500 	 * set the conn_ire_cache under the the protection of the conn_lock
20501 	 * to avoid races among concurrent threads trying to simultaneously
20502 	 * cache an ire in the conn_ire_cache.
20503 	 */
20504 	mutex_enter(&connp->conn_lock);
20505 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20506 
20507 	if (ire != NULL && ire->ire_addr == dst &&
20508 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20509 
20510 		IRE_REFHOLD(ire);
20511 		mutex_exit(&connp->conn_lock);
20512 
20513 	} else {
20514 		boolean_t cached = B_FALSE;
20515 		connp->conn_ire_cache = NULL;
20516 		mutex_exit(&connp->conn_lock);
20517 		/* Release the old ire */
20518 		if (ire != NULL && sctp_ire == NULL)
20519 			IRE_REFRELE_NOTR(ire);
20520 
20521 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20522 		if (ire == NULL)
20523 			goto noirefound;
20524 		IRE_REFHOLD_NOTR(ire);
20525 
20526 		mutex_enter(&connp->conn_lock);
20527 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20528 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20529 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20530 				if (connp->conn_ulp == IPPROTO_TCP)
20531 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20532 				connp->conn_ire_cache = ire;
20533 				cached = B_TRUE;
20534 			}
20535 			rw_exit(&ire->ire_bucket->irb_lock);
20536 		}
20537 		mutex_exit(&connp->conn_lock);
20538 
20539 		/*
20540 		 * We can continue to use the ire but since it was
20541 		 * not cached, we should drop the extra reference.
20542 		 */
20543 		if (!cached)
20544 			IRE_REFRELE_NOTR(ire);
20545 	}
20546 
20547 
20548 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20549 	    "ip_wput_end: q %p (%S)", q, "end");
20550 
20551 	/*
20552 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20553 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20554 	 */
20555 	if (ire->ire_flags & RTF_MULTIRT) {
20556 
20557 		/*
20558 		 * Force the TTL of multirouted packets if required.
20559 		 * The TTL of such packets is bounded by the
20560 		 * ip_multirt_ttl ndd variable.
20561 		 */
20562 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20563 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20564 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20565 			    "(was %d), dst 0x%08x\n",
20566 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20567 			    ntohl(ire->ire_addr)));
20568 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20569 		}
20570 
20571 		/*
20572 		 * At this point, we check to see if there are any pending
20573 		 * unresolved routes. ire_multirt_resolvable()
20574 		 * checks in O(n) that all IRE_OFFSUBNET ire
20575 		 * entries for the packet's destination and
20576 		 * flagged RTF_MULTIRT are currently resolved.
20577 		 * If some remain unresolved, we make a copy
20578 		 * of the current message. It will be used
20579 		 * to initiate additional route resolutions.
20580 		 */
20581 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20582 		    MBLK_GETLABEL(first_mp), ipst);
20583 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20584 		    "multirt_need_resolve %d, first_mp %p\n",
20585 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20586 		if (multirt_need_resolve) {
20587 			copy_mp = copymsg(first_mp);
20588 			if (copy_mp != NULL) {
20589 				MULTIRT_DEBUG_TAG(copy_mp);
20590 			}
20591 		}
20592 	}
20593 
20594 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20595 
20596 	/*
20597 	 * Try to resolve another multiroute if
20598 	 * ire_multirt_resolvable() deemed it necessary
20599 	 */
20600 	if (copy_mp != NULL)
20601 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20602 	if (need_decref)
20603 		CONN_DEC_REF(connp);
20604 	return;
20605 
20606 qnext:
20607 	/*
20608 	 * Upper Level Protocols pass down complete IP datagrams
20609 	 * as M_DATA messages.	Everything else is a sideshow.
20610 	 *
20611 	 * 1) We could be re-entering ip_wput because of ip_neworute
20612 	 *    in which case we could have a IPSEC_OUT message. We
20613 	 *    need to pass through ip_wput like other datagrams and
20614 	 *    hence cannot branch to ip_wput_nondata.
20615 	 *
20616 	 * 2) ARP, AH, ESP, and other clients who are on the module
20617 	 *    instance of IP stream, give us something to deal with.
20618 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20619 	 *
20620 	 * 3) ICMP replies also could come here.
20621 	 */
20622 	ipst = ILLQ_TO_IPST(q);
20623 
20624 	if (DB_TYPE(mp) != M_DATA) {
20625 notdata:
20626 		if (DB_TYPE(mp) == M_CTL) {
20627 			/*
20628 			 * M_CTL messages are used by ARP, AH and ESP to
20629 			 * communicate with IP. We deal with IPSEC_IN and
20630 			 * IPSEC_OUT here. ip_wput_nondata handles other
20631 			 * cases.
20632 			 */
20633 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20634 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20635 				first_mp = mp->b_cont;
20636 				first_mp->b_flag &= ~MSGHASREF;
20637 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20638 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20639 				CONN_DEC_REF(connp);
20640 				connp = NULL;
20641 			}
20642 			if (ii->ipsec_info_type == IPSEC_IN) {
20643 				/*
20644 				 * Either this message goes back to
20645 				 * IPsec for further processing or to
20646 				 * ULP after policy checks.
20647 				 */
20648 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20649 				return;
20650 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20651 				io = (ipsec_out_t *)ii;
20652 				if (io->ipsec_out_proc_begin) {
20653 					/*
20654 					 * IPsec processing has already started.
20655 					 * Complete it.
20656 					 * IPQoS notes: We don't care what is
20657 					 * in ipsec_out_ill_index since this
20658 					 * won't be processed for IPQoS policies
20659 					 * in ipsec_out_process.
20660 					 */
20661 					ipsec_out_process(q, mp, NULL,
20662 					    io->ipsec_out_ill_index);
20663 					return;
20664 				} else {
20665 					connp = (q->q_next != NULL) ?
20666 					    NULL : Q_TO_CONN(q);
20667 					first_mp = mp;
20668 					mp = mp->b_cont;
20669 					mctl_present = B_TRUE;
20670 				}
20671 				zoneid = io->ipsec_out_zoneid;
20672 				ASSERT(zoneid != ALL_ZONES);
20673 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20674 				/*
20675 				 * It's an IPsec control message requesting
20676 				 * an SADB update to be sent to the IPsec
20677 				 * hardware acceleration capable ills.
20678 				 */
20679 				ipsec_ctl_t *ipsec_ctl =
20680 				    (ipsec_ctl_t *)mp->b_rptr;
20681 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20682 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20683 				mblk_t *cmp = mp->b_cont;
20684 
20685 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20686 				ASSERT(cmp != NULL);
20687 
20688 				freeb(mp);
20689 				ill_ipsec_capab_send_all(satype, cmp, sa,
20690 				    ipst->ips_netstack);
20691 				return;
20692 			} else {
20693 				/*
20694 				 * This must be ARP or special TSOL signaling.
20695 				 */
20696 				ip_wput_nondata(NULL, q, mp, NULL);
20697 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20698 				    "ip_wput_end: q %p (%S)", q, "nondata");
20699 				return;
20700 			}
20701 		} else {
20702 			/*
20703 			 * This must be non-(ARP/AH/ESP) messages.
20704 			 */
20705 			ASSERT(!need_decref);
20706 			ip_wput_nondata(NULL, q, mp, NULL);
20707 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20708 			    "ip_wput_end: q %p (%S)", q, "nondata");
20709 			return;
20710 		}
20711 	} else {
20712 		first_mp = mp;
20713 		mctl_present = B_FALSE;
20714 	}
20715 
20716 	ASSERT(first_mp != NULL);
20717 	/*
20718 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20719 	 * to make sure that this packet goes out on the same interface it
20720 	 * came in. We handle that here.
20721 	 */
20722 	if (mctl_present) {
20723 		uint_t ifindex;
20724 
20725 		io = (ipsec_out_t *)first_mp->b_rptr;
20726 		if (io->ipsec_out_attach_if || io->ipsec_out_ip_nexthop) {
20727 			/*
20728 			 * We may have lost the conn context if we are
20729 			 * coming here from ip_newroute(). Copy the
20730 			 * nexthop information.
20731 			 */
20732 			if (io->ipsec_out_ip_nexthop) {
20733 				ip_nexthop = B_TRUE;
20734 				nexthop_addr = io->ipsec_out_nexthop_addr;
20735 
20736 				ipha = (ipha_t *)mp->b_rptr;
20737 				dst = ipha->ipha_dst;
20738 				goto send_from_ill;
20739 			} else {
20740 				ASSERT(io->ipsec_out_ill_index != 0);
20741 				ifindex = io->ipsec_out_ill_index;
20742 				attach_ill = ill_lookup_on_ifindex(ifindex,
20743 				    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20744 				if (attach_ill == NULL) {
20745 					ASSERT(xmit_ill == NULL);
20746 					ip1dbg(("ip_output: bad ifindex for "
20747 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20748 					    ifindex));
20749 					freemsg(first_mp);
20750 					BUMP_MIB(&ipst->ips_ip_mib,
20751 					    ipIfStatsOutDiscards);
20752 					ASSERT(!need_decref);
20753 					return;
20754 				}
20755 			}
20756 		}
20757 	}
20758 
20759 	ASSERT(xmit_ill == NULL);
20760 
20761 	/* We have a complete IP datagram heading outbound. */
20762 	ipha = (ipha_t *)mp->b_rptr;
20763 
20764 #ifndef SPEED_BEFORE_SAFETY
20765 	/*
20766 	 * Make sure we have a full-word aligned message and that at least
20767 	 * a simple IP header is accessible in the first message.  If not,
20768 	 * try a pullup.  For labeled systems we need to always take this
20769 	 * path as M_CTLs are "notdata" but have trailing data to process.
20770 	 */
20771 	if (!OK_32PTR(rptr) ||
20772 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH || is_system_labeled()) {
20773 hdrtoosmall:
20774 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20775 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20776 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20777 			if (first_mp == NULL)
20778 				first_mp = mp;
20779 			goto discard_pkt;
20780 		}
20781 
20782 		/* This function assumes that mp points to an IPv4 packet. */
20783 		if (is_system_labeled() && q->q_next == NULL &&
20784 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20785 		    !connp->conn_ulp_labeled) {
20786 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20787 			    connp->conn_mac_exempt, ipst);
20788 			ipha = (ipha_t *)mp->b_rptr;
20789 			if (first_mp != NULL)
20790 				first_mp->b_cont = mp;
20791 			if (err != 0) {
20792 				if (first_mp == NULL)
20793 					first_mp = mp;
20794 				if (err == EINVAL)
20795 					goto icmp_parameter_problem;
20796 				ip2dbg(("ip_wput: label check failed (%d)\n",
20797 				    err));
20798 				goto discard_pkt;
20799 			}
20800 		}
20801 
20802 		ipha = (ipha_t *)mp->b_rptr;
20803 		if (first_mp == NULL) {
20804 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20805 			/*
20806 			 * If we got here because of "goto hdrtoosmall"
20807 			 * We need to attach a IPSEC_OUT.
20808 			 */
20809 			if (connp->conn_out_enforce_policy) {
20810 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
20811 				    NULL, ipha->ipha_protocol,
20812 				    ipst->ips_netstack)) == NULL)) {
20813 					BUMP_MIB(&ipst->ips_ip_mib,
20814 					    ipIfStatsOutDiscards);
20815 					if (need_decref)
20816 						CONN_DEC_REF(connp);
20817 					return;
20818 				} else {
20819 					ASSERT(mp->b_datap->db_type == M_CTL);
20820 					first_mp = mp;
20821 					mp = mp->b_cont;
20822 					mctl_present = B_TRUE;
20823 				}
20824 			} else {
20825 				first_mp = mp;
20826 				mctl_present = B_FALSE;
20827 			}
20828 		}
20829 	}
20830 #endif
20831 
20832 	/* Most of the code below is written for speed, not readability */
20833 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20834 
20835 	/*
20836 	 * If ip_newroute() fails, we're going to need a full
20837 	 * header for the icmp wraparound.
20838 	 */
20839 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20840 		uint_t	v_hlen;
20841 version_hdrlen_check:
20842 		ASSERT(first_mp != NULL);
20843 		v_hlen = V_HLEN;
20844 		/*
20845 		 * siphon off IPv6 packets coming down from transport
20846 		 * layer modules here.
20847 		 * Note: high-order bit carries NUD reachability confirmation
20848 		 */
20849 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20850 			/*
20851 			 * FIXME: assume that callers of ip_output* call
20852 			 * the right version?
20853 			 */
20854 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
20855 			ASSERT(xmit_ill == NULL);
20856 			if (attach_ill != NULL)
20857 				ill_refrele(attach_ill);
20858 			if (need_decref)
20859 				mp->b_flag |= MSGHASREF;
20860 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20861 			return;
20862 		}
20863 
20864 		if ((v_hlen >> 4) != IP_VERSION) {
20865 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20866 			    "ip_wput_end: q %p (%S)", q, "badvers");
20867 			goto discard_pkt;
20868 		}
20869 		/*
20870 		 * Is the header length at least 20 bytes?
20871 		 *
20872 		 * Are there enough bytes accessible in the header?  If
20873 		 * not, try a pullup.
20874 		 */
20875 		v_hlen &= 0xF;
20876 		v_hlen <<= 2;
20877 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20878 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20879 			    "ip_wput_end: q %p (%S)", q, "badlen");
20880 			goto discard_pkt;
20881 		}
20882 		if (v_hlen > (mp->b_wptr - rptr)) {
20883 			if (!pullupmsg(mp, v_hlen)) {
20884 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20885 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20886 				goto discard_pkt;
20887 			}
20888 			ipha = (ipha_t *)mp->b_rptr;
20889 		}
20890 		/*
20891 		 * Move first entry from any source route into ipha_dst and
20892 		 * verify the options
20893 		 */
20894 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
20895 		    zoneid, ipst)) {
20896 			ASSERT(xmit_ill == NULL);
20897 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20898 			if (attach_ill != NULL)
20899 				ill_refrele(attach_ill);
20900 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20901 			    "ip_wput_end: q %p (%S)", q, "badopts");
20902 			if (need_decref)
20903 				CONN_DEC_REF(connp);
20904 			return;
20905 		}
20906 	}
20907 	dst = ipha->ipha_dst;
20908 
20909 	/*
20910 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20911 	 * we have to run the packet through ip_newroute which will take
20912 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
20913 	 * a resolver, or assigning a default gateway, etc.
20914 	 */
20915 	if (CLASSD(dst)) {
20916 		ipif_t	*ipif;
20917 		uint32_t setsrc = 0;
20918 
20919 multicast:
20920 		ASSERT(first_mp != NULL);
20921 		ip2dbg(("ip_wput: CLASSD\n"));
20922 		if (connp == NULL) {
20923 			/*
20924 			 * Use the first good ipif on the ill.
20925 			 * XXX Should this ever happen? (Appears
20926 			 * to show up with just ppp and no ethernet due
20927 			 * to in.rdisc.)
20928 			 * However, ire_send should be able to
20929 			 * call ip_wput_ire directly.
20930 			 *
20931 			 * XXX Also, this can happen for ICMP and other packets
20932 			 * with multicast source addresses.  Perhaps we should
20933 			 * fix things so that we drop the packet in question,
20934 			 * but for now, just run with it.
20935 			 */
20936 			ill_t *ill = (ill_t *)q->q_ptr;
20937 
20938 			/*
20939 			 * Don't honor attach_if for this case. If ill
20940 			 * is part of the group, ipif could belong to
20941 			 * any ill and we cannot maintain attach_ill
20942 			 * and ipif_ill same anymore and the assert
20943 			 * below would fail.
20944 			 */
20945 			if (mctl_present && io->ipsec_out_attach_if) {
20946 				io->ipsec_out_ill_index = 0;
20947 				io->ipsec_out_attach_if = B_FALSE;
20948 				ASSERT(attach_ill != NULL);
20949 				ill_refrele(attach_ill);
20950 				attach_ill = NULL;
20951 			}
20952 
20953 			ASSERT(attach_ill == NULL);
20954 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
20955 			if (ipif == NULL) {
20956 				if (need_decref)
20957 					CONN_DEC_REF(connp);
20958 				freemsg(first_mp);
20959 				return;
20960 			}
20961 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
20962 			    ntohl(dst), ill->ill_name));
20963 		} else {
20964 			/*
20965 			 * The order of precedence is IP_BOUND_IF, IP_PKTINFO
20966 			 * and IP_MULTICAST_IF.  The block comment above this
20967 			 * function explains the locking mechanism used here.
20968 			 */
20969 			if (xmit_ill == NULL) {
20970 				xmit_ill = conn_get_held_ill(connp,
20971 				    &connp->conn_outgoing_ill, &err);
20972 				if (err == ILL_LOOKUP_FAILED) {
20973 					ip1dbg(("ip_wput: No ill for "
20974 					    "IP_BOUND_IF\n"));
20975 					BUMP_MIB(&ipst->ips_ip_mib,
20976 					    ipIfStatsOutNoRoutes);
20977 					goto drop_pkt;
20978 				}
20979 			}
20980 
20981 			if (xmit_ill == NULL) {
20982 				ipif = conn_get_held_ipif(connp,
20983 				    &connp->conn_multicast_ipif, &err);
20984 				if (err == IPIF_LOOKUP_FAILED) {
20985 					ip1dbg(("ip_wput: No ipif for "
20986 					    "multicast\n"));
20987 					BUMP_MIB(&ipst->ips_ip_mib,
20988 					    ipIfStatsOutNoRoutes);
20989 					goto drop_pkt;
20990 				}
20991 			}
20992 			if (xmit_ill != NULL) {
20993 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20994 				if (ipif == NULL) {
20995 					ip1dbg(("ip_wput: No ipif for "
20996 					    "xmit_ill\n"));
20997 					BUMP_MIB(&ipst->ips_ip_mib,
20998 					    ipIfStatsOutNoRoutes);
20999 					goto drop_pkt;
21000 				}
21001 			} else if (ipif == NULL || ipif->ipif_isv6) {
21002 				/*
21003 				 * We must do this ipif determination here
21004 				 * else we could pass through ip_newroute
21005 				 * and come back here without the conn context.
21006 				 *
21007 				 * Note: we do late binding i.e. we bind to
21008 				 * the interface when the first packet is sent.
21009 				 * For performance reasons we do not rebind on
21010 				 * each packet but keep the binding until the
21011 				 * next IP_MULTICAST_IF option.
21012 				 *
21013 				 * conn_multicast_{ipif,ill} are shared between
21014 				 * IPv4 and IPv6 and AF_INET6 sockets can
21015 				 * send both IPv4 and IPv6 packets. Hence
21016 				 * we have to check that "isv6" matches above.
21017 				 */
21018 				if (ipif != NULL)
21019 					ipif_refrele(ipif);
21020 				ipif = ipif_lookup_group(dst, zoneid, ipst);
21021 				if (ipif == NULL) {
21022 					ip1dbg(("ip_wput: No ipif for "
21023 					    "multicast\n"));
21024 					BUMP_MIB(&ipst->ips_ip_mib,
21025 					    ipIfStatsOutNoRoutes);
21026 					goto drop_pkt;
21027 				}
21028 				err = conn_set_held_ipif(connp,
21029 				    &connp->conn_multicast_ipif, ipif);
21030 				if (err == IPIF_LOOKUP_FAILED) {
21031 					ipif_refrele(ipif);
21032 					ip1dbg(("ip_wput: No ipif for "
21033 					    "multicast\n"));
21034 					BUMP_MIB(&ipst->ips_ip_mib,
21035 					    ipIfStatsOutNoRoutes);
21036 					goto drop_pkt;
21037 				}
21038 			}
21039 		}
21040 		ASSERT(!ipif->ipif_isv6);
21041 		/*
21042 		 * As we may lose the conn by the time we reach ip_wput_ire,
21043 		 * we copy conn_multicast_loop and conn_dontroute on to an
21044 		 * ipsec_out. In case if this datagram goes out secure,
21045 		 * we need the ill_index also. Copy that also into the
21046 		 * ipsec_out.
21047 		 */
21048 		if (mctl_present) {
21049 			io = (ipsec_out_t *)first_mp->b_rptr;
21050 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21051 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21052 		} else {
21053 			ASSERT(mp == first_mp);
21054 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21055 			    BPRI_HI)) == NULL) {
21056 				ipif_refrele(ipif);
21057 				first_mp = mp;
21058 				goto discard_pkt;
21059 			}
21060 			first_mp->b_datap->db_type = M_CTL;
21061 			first_mp->b_wptr += sizeof (ipsec_info_t);
21062 			/* ipsec_out_secure is B_FALSE now */
21063 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21064 			io = (ipsec_out_t *)first_mp->b_rptr;
21065 			io->ipsec_out_type = IPSEC_OUT;
21066 			io->ipsec_out_len = sizeof (ipsec_out_t);
21067 			io->ipsec_out_use_global_policy = B_TRUE;
21068 			io->ipsec_out_ns = ipst->ips_netstack;
21069 			first_mp->b_cont = mp;
21070 			mctl_present = B_TRUE;
21071 		}
21072 		if (attach_ill != NULL) {
21073 			ASSERT(attach_ill == ipif->ipif_ill);
21074 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21075 
21076 			/*
21077 			 * Check if we need an ire that will not be
21078 			 * looked up by anybody else i.e. HIDDEN.
21079 			 */
21080 			if (ill_is_probeonly(attach_ill)) {
21081 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21082 			}
21083 			io->ipsec_out_ill_index =
21084 			    attach_ill->ill_phyint->phyint_ifindex;
21085 			io->ipsec_out_attach_if = B_TRUE;
21086 		} else {
21087 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21088 			io->ipsec_out_ill_index =
21089 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21090 		}
21091 		if (connp != NULL) {
21092 			io->ipsec_out_multicast_loop =
21093 			    connp->conn_multicast_loop;
21094 			io->ipsec_out_dontroute = connp->conn_dontroute;
21095 			io->ipsec_out_zoneid = connp->conn_zoneid;
21096 		}
21097 		/*
21098 		 * If the application uses IP_MULTICAST_IF with
21099 		 * different logical addresses of the same ILL, we
21100 		 * need to make sure that the soruce address of
21101 		 * the packet matches the logical IP address used
21102 		 * in the option. We do it by initializing ipha_src
21103 		 * here. This should keep IPsec also happy as
21104 		 * when we return from IPsec processing, we don't
21105 		 * have to worry about getting the right address on
21106 		 * the packet. Thus it is sufficient to look for
21107 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21108 		 * MATCH_IRE_IPIF.
21109 		 *
21110 		 * NOTE : We need to do it for non-secure case also as
21111 		 * this might go out secure if there is a global policy
21112 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
21113 		 * address, the source should be initialized already and
21114 		 * hence we won't be initializing here.
21115 		 *
21116 		 * As we do not have the ire yet, it is possible that
21117 		 * we set the source address here and then later discover
21118 		 * that the ire implies the source address to be assigned
21119 		 * through the RTF_SETSRC flag.
21120 		 * In that case, the setsrc variable will remind us
21121 		 * that overwritting the source address by the one
21122 		 * of the RTF_SETSRC-flagged ire is allowed.
21123 		 */
21124 		if (ipha->ipha_src == INADDR_ANY &&
21125 		    (connp == NULL || !connp->conn_unspec_src)) {
21126 			ipha->ipha_src = ipif->ipif_src_addr;
21127 			setsrc = RTF_SETSRC;
21128 		}
21129 		/*
21130 		 * Find an IRE which matches the destination and the outgoing
21131 		 * queue (i.e. the outgoing interface.)
21132 		 * For loopback use a unicast IP address for
21133 		 * the ire lookup.
21134 		 */
21135 		if (IS_LOOPBACK(ipif->ipif_ill))
21136 			dst = ipif->ipif_lcl_addr;
21137 
21138 		/*
21139 		 * If xmit_ill is set, we branch out to ip_newroute_ipif.
21140 		 * We don't need to lookup ire in ctable as the packet
21141 		 * needs to be sent to the destination through the specified
21142 		 * ill irrespective of ires in the cache table.
21143 		 */
21144 		ire = NULL;
21145 		if (xmit_ill == NULL) {
21146 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21147 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21148 		}
21149 
21150 		/*
21151 		 * refrele attach_ill as its not needed anymore.
21152 		 */
21153 		if (attach_ill != NULL) {
21154 			ill_refrele(attach_ill);
21155 			attach_ill = NULL;
21156 		}
21157 
21158 		if (ire == NULL) {
21159 			/*
21160 			 * Multicast loopback and multicast forwarding is
21161 			 * done in ip_wput_ire.
21162 			 *
21163 			 * Mark this packet to make it be delivered to
21164 			 * ip_wput_ire after the new ire has been
21165 			 * created.
21166 			 *
21167 			 * The call to ip_newroute_ipif takes into account
21168 			 * the setsrc reminder. In any case, we take care
21169 			 * of the RTF_MULTIRT flag.
21170 			 */
21171 			mp->b_prev = mp->b_next = NULL;
21172 			if (xmit_ill == NULL ||
21173 			    xmit_ill->ill_ipif_up_count > 0) {
21174 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21175 				    setsrc | RTF_MULTIRT, zoneid, infop);
21176 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21177 				    "ip_wput_end: q %p (%S)", q, "noire");
21178 			} else {
21179 				freemsg(first_mp);
21180 			}
21181 			ipif_refrele(ipif);
21182 			if (xmit_ill != NULL)
21183 				ill_refrele(xmit_ill);
21184 			if (need_decref)
21185 				CONN_DEC_REF(connp);
21186 			return;
21187 		}
21188 
21189 		ipif_refrele(ipif);
21190 		ipif = NULL;
21191 		ASSERT(xmit_ill == NULL);
21192 
21193 		/*
21194 		 * Honor the RTF_SETSRC flag for multicast packets,
21195 		 * if allowed by the setsrc reminder.
21196 		 */
21197 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21198 			ipha->ipha_src = ire->ire_src_addr;
21199 		}
21200 
21201 		/*
21202 		 * Unconditionally force the TTL to 1 for
21203 		 * multirouted multicast packets:
21204 		 * multirouted multicast should not cross
21205 		 * multicast routers.
21206 		 */
21207 		if (ire->ire_flags & RTF_MULTIRT) {
21208 			if (ipha->ipha_ttl > 1) {
21209 				ip2dbg(("ip_wput: forcing multicast "
21210 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21211 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21212 				ipha->ipha_ttl = 1;
21213 			}
21214 		}
21215 	} else {
21216 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
21217 		if ((ire != NULL) && (ire->ire_type &
21218 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21219 			ignore_dontroute = B_TRUE;
21220 			ignore_nexthop = B_TRUE;
21221 		}
21222 		if (ire != NULL) {
21223 			ire_refrele(ire);
21224 			ire = NULL;
21225 		}
21226 		/*
21227 		 * Guard against coming in from arp in which case conn is NULL.
21228 		 * Also guard against non M_DATA with dontroute set but
21229 		 * destined to local, loopback or broadcast addresses.
21230 		 */
21231 		if (connp != NULL && connp->conn_dontroute &&
21232 		    !ignore_dontroute) {
21233 dontroute:
21234 			/*
21235 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21236 			 * routing protocols from seeing false direct
21237 			 * connectivity.
21238 			 */
21239 			ipha->ipha_ttl = 1;
21240 
21241 			/* If suitable ipif not found, drop packet */
21242 			dst_ipif = ipif_lookup_onlink_addr(dst, zoneid, ipst);
21243 			if (dst_ipif == NULL) {
21244 noroute:
21245 				ip1dbg(("ip_wput: no route for dst using"
21246 				    " SO_DONTROUTE\n"));
21247 				BUMP_MIB(&ipst->ips_ip_mib,
21248 				    ipIfStatsOutNoRoutes);
21249 				mp->b_prev = mp->b_next = NULL;
21250 				if (first_mp == NULL)
21251 					first_mp = mp;
21252 				goto drop_pkt;
21253 			} else {
21254 				/*
21255 				 * If suitable ipif has been found, set
21256 				 * xmit_ill to the corresponding
21257 				 * ipif_ill because we'll be using the
21258 				 * send_from_ill logic below.
21259 				 */
21260 				ASSERT(xmit_ill == NULL);
21261 				xmit_ill = dst_ipif->ipif_ill;
21262 				mutex_enter(&xmit_ill->ill_lock);
21263 				if (!ILL_CAN_LOOKUP(xmit_ill)) {
21264 					mutex_exit(&xmit_ill->ill_lock);
21265 					xmit_ill = NULL;
21266 					ipif_refrele(dst_ipif);
21267 					goto noroute;
21268 				}
21269 				ill_refhold_locked(xmit_ill);
21270 				mutex_exit(&xmit_ill->ill_lock);
21271 				ipif_refrele(dst_ipif);
21272 			}
21273 		}
21274 		/*
21275 		 * If we are bound to IPIF_NOFAILOVER address, look for
21276 		 * an IRE_CACHE matching the ill.
21277 		 */
21278 send_from_ill:
21279 		if (attach_ill != NULL) {
21280 			ipif_t	*attach_ipif;
21281 
21282 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21283 
21284 			/*
21285 			 * Check if we need an ire that will not be
21286 			 * looked up by anybody else i.e. HIDDEN.
21287 			 */
21288 			if (ill_is_probeonly(attach_ill)) {
21289 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21290 			}
21291 
21292 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
21293 			if (attach_ipif == NULL) {
21294 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
21295 				goto discard_pkt;
21296 			}
21297 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
21298 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21299 			ipif_refrele(attach_ipif);
21300 		} else if (xmit_ill != NULL) {
21301 			ipif_t *ipif;
21302 
21303 			/*
21304 			 * Mark this packet as originated locally
21305 			 */
21306 			mp->b_prev = mp->b_next = NULL;
21307 
21308 			/*
21309 			 * Could be SO_DONTROUTE case also.
21310 			 * Verify that at least one ipif is up on the ill.
21311 			 */
21312 			if (xmit_ill->ill_ipif_up_count == 0) {
21313 				ip1dbg(("ip_output: xmit_ill %s is down\n",
21314 				    xmit_ill->ill_name));
21315 				goto drop_pkt;
21316 			}
21317 
21318 			ipif = ipif_get_next_ipif(NULL, xmit_ill);
21319 			if (ipif == NULL) {
21320 				ip1dbg(("ip_output: xmit_ill %s NULL ipif\n",
21321 				    xmit_ill->ill_name));
21322 				goto drop_pkt;
21323 			}
21324 
21325 			/*
21326 			 * Look for a ire that is part of the group,
21327 			 * if found use it else call ip_newroute_ipif.
21328 			 * IPCL_ZONEID is not used for matching because
21329 			 * IP_ALLZONES option is valid only when the
21330 			 * ill is accessible from all zones i.e has a
21331 			 * valid ipif in all zones.
21332 			 */
21333 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21334 			ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21335 			    MBLK_GETLABEL(mp), match_flags, ipst);
21336 			/*
21337 			 * If an ire exists use it or else create
21338 			 * an ire but don't add it to the cache.
21339 			 * Adding an ire may cause issues with
21340 			 * asymmetric routing.
21341 			 * In case of multiroute always act as if
21342 			 * ire does not exist.
21343 			 */
21344 			if (ire == NULL || ire->ire_flags & RTF_MULTIRT) {
21345 				if (ire != NULL)
21346 					ire_refrele(ire);
21347 				ip_newroute_ipif(q, first_mp, ipif,
21348 				    dst, connp, 0, zoneid, infop);
21349 				ipif_refrele(ipif);
21350 				ip1dbg(("ip_output: xmit_ill via %s\n",
21351 				    xmit_ill->ill_name));
21352 				ill_refrele(xmit_ill);
21353 				if (need_decref)
21354 					CONN_DEC_REF(connp);
21355 				return;
21356 			}
21357 			ipif_refrele(ipif);
21358 		} else if (ip_nexthop || (connp != NULL &&
21359 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21360 			if (!ip_nexthop) {
21361 				ip_nexthop = B_TRUE;
21362 				nexthop_addr = connp->conn_nexthop_v4;
21363 			}
21364 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21365 			    MATCH_IRE_GW;
21366 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21367 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21368 		} else {
21369 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp),
21370 			    ipst);
21371 		}
21372 		if (!ire) {
21373 			/*
21374 			 * Make sure we don't load spread if this
21375 			 * is IPIF_NOFAILOVER case.
21376 			 */
21377 			if ((attach_ill != NULL) ||
21378 			    (ip_nexthop && !ignore_nexthop)) {
21379 				if (mctl_present) {
21380 					io = (ipsec_out_t *)first_mp->b_rptr;
21381 					ASSERT(first_mp->b_datap->db_type ==
21382 					    M_CTL);
21383 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21384 				} else {
21385 					ASSERT(mp == first_mp);
21386 					first_mp = allocb(
21387 					    sizeof (ipsec_info_t), BPRI_HI);
21388 					if (first_mp == NULL) {
21389 						first_mp = mp;
21390 						goto discard_pkt;
21391 					}
21392 					first_mp->b_datap->db_type = M_CTL;
21393 					first_mp->b_wptr +=
21394 					    sizeof (ipsec_info_t);
21395 					/* ipsec_out_secure is B_FALSE now */
21396 					bzero(first_mp->b_rptr,
21397 					    sizeof (ipsec_info_t));
21398 					io = (ipsec_out_t *)first_mp->b_rptr;
21399 					io->ipsec_out_type = IPSEC_OUT;
21400 					io->ipsec_out_len =
21401 					    sizeof (ipsec_out_t);
21402 					io->ipsec_out_use_global_policy =
21403 					    B_TRUE;
21404 					io->ipsec_out_ns = ipst->ips_netstack;
21405 					first_mp->b_cont = mp;
21406 					mctl_present = B_TRUE;
21407 				}
21408 				if (attach_ill != NULL) {
21409 					io->ipsec_out_ill_index = attach_ill->
21410 					    ill_phyint->phyint_ifindex;
21411 					io->ipsec_out_attach_if = B_TRUE;
21412 				} else {
21413 					io->ipsec_out_ip_nexthop = ip_nexthop;
21414 					io->ipsec_out_nexthop_addr =
21415 					    nexthop_addr;
21416 				}
21417 			}
21418 noirefound:
21419 			/*
21420 			 * Mark this packet as having originated on
21421 			 * this machine.  This will be noted in
21422 			 * ire_add_then_send, which needs to know
21423 			 * whether to run it back through ip_wput or
21424 			 * ip_rput following successful resolution.
21425 			 */
21426 			mp->b_prev = NULL;
21427 			mp->b_next = NULL;
21428 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21429 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21430 			    "ip_wput_end: q %p (%S)", q, "newroute");
21431 			if (attach_ill != NULL)
21432 				ill_refrele(attach_ill);
21433 			if (xmit_ill != NULL)
21434 				ill_refrele(xmit_ill);
21435 			if (need_decref)
21436 				CONN_DEC_REF(connp);
21437 			return;
21438 		}
21439 	}
21440 
21441 	/* We now know where we are going with it. */
21442 
21443 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21444 	    "ip_wput_end: q %p (%S)", q, "end");
21445 
21446 	/*
21447 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21448 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21449 	 */
21450 	if (ire->ire_flags & RTF_MULTIRT) {
21451 		/*
21452 		 * Force the TTL of multirouted packets if required.
21453 		 * The TTL of such packets is bounded by the
21454 		 * ip_multirt_ttl ndd variable.
21455 		 */
21456 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21457 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21458 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21459 			    "(was %d), dst 0x%08x\n",
21460 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21461 			    ntohl(ire->ire_addr)));
21462 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21463 		}
21464 		/*
21465 		 * At this point, we check to see if there are any pending
21466 		 * unresolved routes. ire_multirt_resolvable()
21467 		 * checks in O(n) that all IRE_OFFSUBNET ire
21468 		 * entries for the packet's destination and
21469 		 * flagged RTF_MULTIRT are currently resolved.
21470 		 * If some remain unresolved, we make a copy
21471 		 * of the current message. It will be used
21472 		 * to initiate additional route resolutions.
21473 		 */
21474 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21475 		    MBLK_GETLABEL(first_mp), ipst);
21476 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21477 		    "multirt_need_resolve %d, first_mp %p\n",
21478 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21479 		if (multirt_need_resolve) {
21480 			copy_mp = copymsg(first_mp);
21481 			if (copy_mp != NULL) {
21482 				MULTIRT_DEBUG_TAG(copy_mp);
21483 			}
21484 		}
21485 	}
21486 
21487 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21488 	/*
21489 	 * Try to resolve another multiroute if
21490 	 * ire_multirt_resolvable() deemed it necessary.
21491 	 * At this point, we need to distinguish
21492 	 * multicasts from other packets. For multicasts,
21493 	 * we call ip_newroute_ipif() and request that both
21494 	 * multirouting and setsrc flags are checked.
21495 	 */
21496 	if (copy_mp != NULL) {
21497 		if (CLASSD(dst)) {
21498 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21499 			if (ipif) {
21500 				ASSERT(infop->ip_opt_ill_index == 0);
21501 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21502 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21503 				ipif_refrele(ipif);
21504 			} else {
21505 				MULTIRT_DEBUG_UNTAG(copy_mp);
21506 				freemsg(copy_mp);
21507 				copy_mp = NULL;
21508 			}
21509 		} else {
21510 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21511 		}
21512 	}
21513 	if (attach_ill != NULL)
21514 		ill_refrele(attach_ill);
21515 	if (xmit_ill != NULL)
21516 		ill_refrele(xmit_ill);
21517 	if (need_decref)
21518 		CONN_DEC_REF(connp);
21519 	return;
21520 
21521 icmp_parameter_problem:
21522 	/* could not have originated externally */
21523 	ASSERT(mp->b_prev == NULL);
21524 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21525 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21526 		/* it's the IP header length that's in trouble */
21527 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21528 		first_mp = NULL;
21529 	}
21530 
21531 discard_pkt:
21532 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21533 drop_pkt:
21534 	ip1dbg(("ip_wput: dropped packet\n"));
21535 	if (ire != NULL)
21536 		ire_refrele(ire);
21537 	if (need_decref)
21538 		CONN_DEC_REF(connp);
21539 	freemsg(first_mp);
21540 	if (attach_ill != NULL)
21541 		ill_refrele(attach_ill);
21542 	if (xmit_ill != NULL)
21543 		ill_refrele(xmit_ill);
21544 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21545 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21546 }
21547 
21548 /*
21549  * If this is a conn_t queue, then we pass in the conn. This includes the
21550  * zoneid.
21551  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21552  * in which case we use the global zoneid since those are all part of
21553  * the global zone.
21554  */
21555 void
21556 ip_wput(queue_t *q, mblk_t *mp)
21557 {
21558 	if (CONN_Q(q))
21559 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21560 	else
21561 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21562 }
21563 
21564 /*
21565  *
21566  * The following rules must be observed when accessing any ipif or ill
21567  * that has been cached in the conn. Typically conn_nofailover_ill,
21568  * conn_outgoing_ill, conn_multicast_ipif and conn_multicast_ill.
21569  *
21570  * Access: The ipif or ill pointed to from the conn can be accessed under
21571  * the protection of the conn_lock or after it has been refheld under the
21572  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21573  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21574  * The reason for this is that a concurrent unplumb could actually be
21575  * cleaning up these cached pointers by walking the conns and might have
21576  * finished cleaning up the conn in question. The macros check that an
21577  * unplumb has not yet started on the ipif or ill.
21578  *
21579  * Caching: An ipif or ill pointer may be cached in the conn only after
21580  * making sure that an unplumb has not started. So the caching is done
21581  * while holding both the conn_lock and the ill_lock and after using the
21582  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21583  * flag before starting the cleanup of conns.
21584  *
21585  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21586  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21587  * or a reference to the ipif or a reference to an ire that references the
21588  * ipif. An ipif does not change its ill except for failover/failback. Since
21589  * failover/failback happens only after bringing down the ipif and making sure
21590  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
21591  * the above holds.
21592  */
21593 ipif_t *
21594 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21595 {
21596 	ipif_t	*ipif;
21597 	ill_t	*ill;
21598 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21599 
21600 	*err = 0;
21601 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21602 	mutex_enter(&connp->conn_lock);
21603 	ipif = *ipifp;
21604 	if (ipif != NULL) {
21605 		ill = ipif->ipif_ill;
21606 		mutex_enter(&ill->ill_lock);
21607 		if (IPIF_CAN_LOOKUP(ipif)) {
21608 			ipif_refhold_locked(ipif);
21609 			mutex_exit(&ill->ill_lock);
21610 			mutex_exit(&connp->conn_lock);
21611 			rw_exit(&ipst->ips_ill_g_lock);
21612 			return (ipif);
21613 		} else {
21614 			*err = IPIF_LOOKUP_FAILED;
21615 		}
21616 		mutex_exit(&ill->ill_lock);
21617 	}
21618 	mutex_exit(&connp->conn_lock);
21619 	rw_exit(&ipst->ips_ill_g_lock);
21620 	return (NULL);
21621 }
21622 
21623 ill_t *
21624 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21625 {
21626 	ill_t	*ill;
21627 
21628 	*err = 0;
21629 	mutex_enter(&connp->conn_lock);
21630 	ill = *illp;
21631 	if (ill != NULL) {
21632 		mutex_enter(&ill->ill_lock);
21633 		if (ILL_CAN_LOOKUP(ill)) {
21634 			ill_refhold_locked(ill);
21635 			mutex_exit(&ill->ill_lock);
21636 			mutex_exit(&connp->conn_lock);
21637 			return (ill);
21638 		} else {
21639 			*err = ILL_LOOKUP_FAILED;
21640 		}
21641 		mutex_exit(&ill->ill_lock);
21642 	}
21643 	mutex_exit(&connp->conn_lock);
21644 	return (NULL);
21645 }
21646 
21647 static int
21648 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21649 {
21650 	ill_t	*ill;
21651 
21652 	ill = ipif->ipif_ill;
21653 	mutex_enter(&connp->conn_lock);
21654 	mutex_enter(&ill->ill_lock);
21655 	if (IPIF_CAN_LOOKUP(ipif)) {
21656 		*ipifp = ipif;
21657 		mutex_exit(&ill->ill_lock);
21658 		mutex_exit(&connp->conn_lock);
21659 		return (0);
21660 	}
21661 	mutex_exit(&ill->ill_lock);
21662 	mutex_exit(&connp->conn_lock);
21663 	return (IPIF_LOOKUP_FAILED);
21664 }
21665 
21666 /*
21667  * This is called if the outbound datagram needs fragmentation.
21668  *
21669  * NOTE : This function does not ire_refrele the ire argument passed in.
21670  */
21671 static void
21672 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21673     ip_stack_t *ipst)
21674 {
21675 	ipha_t		*ipha;
21676 	mblk_t		*mp;
21677 	uint32_t	v_hlen_tos_len;
21678 	uint32_t	max_frag;
21679 	uint32_t	frag_flag;
21680 	boolean_t	dont_use;
21681 
21682 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21683 		mp = ipsec_mp->b_cont;
21684 	} else {
21685 		mp = ipsec_mp;
21686 	}
21687 
21688 	ipha = (ipha_t *)mp->b_rptr;
21689 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21690 
21691 #ifdef	_BIG_ENDIAN
21692 #define	V_HLEN	(v_hlen_tos_len >> 24)
21693 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21694 #else
21695 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21696 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21697 #endif
21698 
21699 #ifndef SPEED_BEFORE_SAFETY
21700 	/*
21701 	 * Check that ipha_length is consistent with
21702 	 * the mblk length
21703 	 */
21704 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21705 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21706 		    LENGTH, msgdsize(mp)));
21707 		freemsg(ipsec_mp);
21708 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21709 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21710 		    "packet length mismatch");
21711 		return;
21712 	}
21713 #endif
21714 	/*
21715 	 * Don't use frag_flag if pre-built packet or source
21716 	 * routed or if multicast (since multicast packets do not solicit
21717 	 * ICMP "packet too big" messages). Get the values of
21718 	 * max_frag and frag_flag atomically by acquiring the
21719 	 * ire_lock.
21720 	 */
21721 	mutex_enter(&ire->ire_lock);
21722 	max_frag = ire->ire_max_frag;
21723 	frag_flag = ire->ire_frag_flag;
21724 	mutex_exit(&ire->ire_lock);
21725 
21726 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21727 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21728 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21729 
21730 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21731 	    (dont_use ? 0 : frag_flag), zoneid, ipst);
21732 }
21733 
21734 /*
21735  * Used for deciding the MSS size for the upper layer. Thus
21736  * we need to check the outbound policy values in the conn.
21737  */
21738 int
21739 conn_ipsec_length(conn_t *connp)
21740 {
21741 	ipsec_latch_t *ipl;
21742 
21743 	ipl = connp->conn_latch;
21744 	if (ipl == NULL)
21745 		return (0);
21746 
21747 	if (ipl->ipl_out_policy == NULL)
21748 		return (0);
21749 
21750 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21751 }
21752 
21753 /*
21754  * Returns an estimate of the IPsec headers size. This is used if
21755  * we don't want to call into IPsec to get the exact size.
21756  */
21757 int
21758 ipsec_out_extra_length(mblk_t *ipsec_mp)
21759 {
21760 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21761 	ipsec_action_t *a;
21762 
21763 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21764 	if (!io->ipsec_out_secure)
21765 		return (0);
21766 
21767 	a = io->ipsec_out_act;
21768 
21769 	if (a == NULL) {
21770 		ASSERT(io->ipsec_out_policy != NULL);
21771 		a = io->ipsec_out_policy->ipsp_act;
21772 	}
21773 	ASSERT(a != NULL);
21774 
21775 	return (a->ipa_ovhd);
21776 }
21777 
21778 /*
21779  * Returns an estimate of the IPsec headers size. This is used if
21780  * we don't want to call into IPsec to get the exact size.
21781  */
21782 int
21783 ipsec_in_extra_length(mblk_t *ipsec_mp)
21784 {
21785 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21786 	ipsec_action_t *a;
21787 
21788 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21789 
21790 	a = ii->ipsec_in_action;
21791 	return (a == NULL ? 0 : a->ipa_ovhd);
21792 }
21793 
21794 /*
21795  * If there are any source route options, return the true final
21796  * destination. Otherwise, return the destination.
21797  */
21798 ipaddr_t
21799 ip_get_dst(ipha_t *ipha)
21800 {
21801 	ipoptp_t	opts;
21802 	uchar_t		*opt;
21803 	uint8_t		optval;
21804 	uint8_t		optlen;
21805 	ipaddr_t	dst;
21806 	uint32_t off;
21807 
21808 	dst = ipha->ipha_dst;
21809 
21810 	if (IS_SIMPLE_IPH(ipha))
21811 		return (dst);
21812 
21813 	for (optval = ipoptp_first(&opts, ipha);
21814 	    optval != IPOPT_EOL;
21815 	    optval = ipoptp_next(&opts)) {
21816 		opt = opts.ipoptp_cur;
21817 		optlen = opts.ipoptp_len;
21818 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21819 		switch (optval) {
21820 		case IPOPT_SSRR:
21821 		case IPOPT_LSRR:
21822 			off = opt[IPOPT_OFFSET];
21823 			/*
21824 			 * If one of the conditions is true, it means
21825 			 * end of options and dst already has the right
21826 			 * value.
21827 			 */
21828 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21829 				off = optlen - IP_ADDR_LEN;
21830 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21831 			}
21832 			return (dst);
21833 		default:
21834 			break;
21835 		}
21836 	}
21837 
21838 	return (dst);
21839 }
21840 
21841 mblk_t *
21842 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21843     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21844 {
21845 	ipsec_out_t	*io;
21846 	mblk_t		*first_mp;
21847 	boolean_t policy_present;
21848 	ip_stack_t	*ipst;
21849 	ipsec_stack_t	*ipss;
21850 
21851 	ASSERT(ire != NULL);
21852 	ipst = ire->ire_ipst;
21853 	ipss = ipst->ips_netstack->netstack_ipsec;
21854 
21855 	first_mp = mp;
21856 	if (mp->b_datap->db_type == M_CTL) {
21857 		io = (ipsec_out_t *)first_mp->b_rptr;
21858 		/*
21859 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21860 		 *
21861 		 * 1) There is per-socket policy (including cached global
21862 		 *    policy) or a policy on the IP-in-IP tunnel.
21863 		 * 2) There is no per-socket policy, but it is
21864 		 *    a multicast packet that needs to go out
21865 		 *    on a specific interface. This is the case
21866 		 *    where (ip_wput and ip_wput_multicast) attaches
21867 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21868 		 *
21869 		 * In case (2) we check with global policy to
21870 		 * see if there is a match and set the ill_index
21871 		 * appropriately so that we can lookup the ire
21872 		 * properly in ip_wput_ipsec_out.
21873 		 */
21874 
21875 		/*
21876 		 * ipsec_out_use_global_policy is set to B_FALSE
21877 		 * in ipsec_in_to_out(). Refer to that function for
21878 		 * details.
21879 		 */
21880 		if ((io->ipsec_out_latch == NULL) &&
21881 		    (io->ipsec_out_use_global_policy)) {
21882 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21883 			    ire, connp, unspec_src, zoneid));
21884 		}
21885 		if (!io->ipsec_out_secure) {
21886 			/*
21887 			 * If this is not a secure packet, drop
21888 			 * the IPSEC_OUT mp and treat it as a clear
21889 			 * packet. This happens when we are sending
21890 			 * a ICMP reply back to a clear packet. See
21891 			 * ipsec_in_to_out() for details.
21892 			 */
21893 			mp = first_mp->b_cont;
21894 			freeb(first_mp);
21895 		}
21896 		return (mp);
21897 	}
21898 	/*
21899 	 * See whether we need to attach a global policy here. We
21900 	 * don't depend on the conn (as it could be null) for deciding
21901 	 * what policy this datagram should go through because it
21902 	 * should have happened in ip_wput if there was some
21903 	 * policy. This normally happens for connections which are not
21904 	 * fully bound preventing us from caching policies in
21905 	 * ip_bind. Packets coming from the TCP listener/global queue
21906 	 * - which are non-hard_bound - could also be affected by
21907 	 * applying policy here.
21908 	 *
21909 	 * If this packet is coming from tcp global queue or listener,
21910 	 * we will be applying policy here.  This may not be *right*
21911 	 * if these packets are coming from the detached connection as
21912 	 * it could have gone in clear before. This happens only if a
21913 	 * TCP connection started when there is no policy and somebody
21914 	 * added policy before it became detached. Thus packets of the
21915 	 * detached connection could go out secure and the other end
21916 	 * would drop it because it will be expecting in clear. The
21917 	 * converse is not true i.e if somebody starts a TCP
21918 	 * connection and deletes the policy, all the packets will
21919 	 * still go out with the policy that existed before deleting
21920 	 * because ip_unbind sends up policy information which is used
21921 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21922 	 * TCP to attach a dummy IPSEC_OUT and set
21923 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21924 	 * affect performance for normal cases, we are not doing it.
21925 	 * Thus, set policy before starting any TCP connections.
21926 	 *
21927 	 * NOTE - We might apply policy even for a hard bound connection
21928 	 * - for which we cached policy in ip_bind - if somebody added
21929 	 * global policy after we inherited the policy in ip_bind.
21930 	 * This means that the packets that were going out in clear
21931 	 * previously would start going secure and hence get dropped
21932 	 * on the other side. To fix this, TCP attaches a dummy
21933 	 * ipsec_out and make sure that we don't apply global policy.
21934 	 */
21935 	if (ipha != NULL)
21936 		policy_present = ipss->ipsec_outbound_v4_policy_present;
21937 	else
21938 		policy_present = ipss->ipsec_outbound_v6_policy_present;
21939 	if (!policy_present)
21940 		return (mp);
21941 
21942 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21943 	    zoneid));
21944 }
21945 
21946 ire_t *
21947 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
21948 {
21949 	ipaddr_t addr;
21950 	ire_t *save_ire;
21951 	irb_t *irb;
21952 	ill_group_t *illgrp;
21953 	int	err;
21954 
21955 	save_ire = ire;
21956 	addr = ire->ire_addr;
21957 
21958 	ASSERT(ire->ire_type == IRE_BROADCAST);
21959 
21960 	illgrp = connp->conn_outgoing_ill->ill_group;
21961 	if (illgrp == NULL) {
21962 		*conn_outgoing_ill = conn_get_held_ill(connp,
21963 		    &connp->conn_outgoing_ill, &err);
21964 		if (err == ILL_LOOKUP_FAILED) {
21965 			ire_refrele(save_ire);
21966 			return (NULL);
21967 		}
21968 		return (save_ire);
21969 	}
21970 	/*
21971 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
21972 	 * If it is part of the group, we need to send on the ire
21973 	 * that has been cleared of IRE_MARK_NORECV and that belongs
21974 	 * to this group. This is okay as IP_BOUND_IF really means
21975 	 * any ill in the group. We depend on the fact that the
21976 	 * first ire in the group is always cleared of IRE_MARK_NORECV
21977 	 * if such an ire exists. This is possible only if you have
21978 	 * at least one ill in the group that has not failed.
21979 	 *
21980 	 * First get to the ire that matches the address and group.
21981 	 *
21982 	 * We don't look for an ire with a matching zoneid because a given zone
21983 	 * won't always have broadcast ires on all ills in the group.
21984 	 */
21985 	irb = ire->ire_bucket;
21986 	rw_enter(&irb->irb_lock, RW_READER);
21987 	if (ire->ire_marks & IRE_MARK_NORECV) {
21988 		/*
21989 		 * If the current zone only has an ire broadcast for this
21990 		 * address marked NORECV, the ire we want is ahead in the
21991 		 * bucket, so we look it up deliberately ignoring the zoneid.
21992 		 */
21993 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
21994 			if (ire->ire_addr != addr)
21995 				continue;
21996 			/* skip over deleted ires */
21997 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
21998 				continue;
21999 		}
22000 	}
22001 	while (ire != NULL) {
22002 		/*
22003 		 * If a new interface is coming up, we could end up
22004 		 * seeing the loopback ire and the non-loopback ire
22005 		 * may not have been added yet. So check for ire_stq
22006 		 */
22007 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
22008 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
22009 			break;
22010 		}
22011 		ire = ire->ire_next;
22012 	}
22013 	if (ire != NULL && ire->ire_addr == addr &&
22014 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
22015 		IRE_REFHOLD(ire);
22016 		rw_exit(&irb->irb_lock);
22017 		ire_refrele(save_ire);
22018 		*conn_outgoing_ill = ire_to_ill(ire);
22019 		/*
22020 		 * Refhold the ill to make the conn_outgoing_ill
22021 		 * independent of the ire. ip_wput_ire goes in a loop
22022 		 * and may refrele the ire. Since we have an ire at this
22023 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
22024 		 */
22025 		ill_refhold(*conn_outgoing_ill);
22026 		return (ire);
22027 	}
22028 	rw_exit(&irb->irb_lock);
22029 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
22030 	/*
22031 	 * If we can't find a suitable ire, return the original ire.
22032 	 */
22033 	return (save_ire);
22034 }
22035 
22036 /*
22037  * This function does the ire_refrele of the ire passed in as the
22038  * argument. As this function looks up more ires i.e broadcast ires,
22039  * it needs to REFRELE them. Currently, for simplicity we don't
22040  * differentiate the one passed in and looked up here. We always
22041  * REFRELE.
22042  * IPQoS Notes:
22043  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
22044  * IPsec packets are done in ipsec_out_process.
22045  *
22046  */
22047 void
22048 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
22049     zoneid_t zoneid)
22050 {
22051 	ipha_t		*ipha;
22052 #define	rptr	((uchar_t *)ipha)
22053 	queue_t		*stq;
22054 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
22055 	uint32_t	v_hlen_tos_len;
22056 	uint32_t	ttl_protocol;
22057 	ipaddr_t	src;
22058 	ipaddr_t	dst;
22059 	uint32_t	cksum;
22060 	ipaddr_t	orig_src;
22061 	ire_t		*ire1;
22062 	mblk_t		*next_mp;
22063 	uint_t		hlen;
22064 	uint16_t	*up;
22065 	uint32_t	max_frag = ire->ire_max_frag;
22066 	ill_t		*ill = ire_to_ill(ire);
22067 	int		clusterwide;
22068 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
22069 	int		ipsec_len;
22070 	mblk_t		*first_mp;
22071 	ipsec_out_t	*io;
22072 	boolean_t	conn_dontroute;		/* conn value for multicast */
22073 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
22074 	boolean_t	multicast_forward;	/* Should we forward ? */
22075 	boolean_t	unspec_src;
22076 	ill_t		*conn_outgoing_ill = NULL;
22077 	ill_t		*ire_ill;
22078 	ill_t		*ire1_ill;
22079 	ill_t		*out_ill;
22080 	uint32_t 	ill_index = 0;
22081 	boolean_t	multirt_send = B_FALSE;
22082 	int		err;
22083 	ipxmit_state_t	pktxmit_state;
22084 	ip_stack_t	*ipst = ire->ire_ipst;
22085 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22086 
22087 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22088 	    "ip_wput_ire_start: q %p", q);
22089 
22090 	multicast_forward = B_FALSE;
22091 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22092 
22093 	if (ire->ire_flags & RTF_MULTIRT) {
22094 		/*
22095 		 * Multirouting case. The bucket where ire is stored
22096 		 * probably holds other RTF_MULTIRT flagged ire
22097 		 * to the destination. In this call to ip_wput_ire,
22098 		 * we attempt to send the packet through all
22099 		 * those ires. Thus, we first ensure that ire is the
22100 		 * first RTF_MULTIRT ire in the bucket,
22101 		 * before walking the ire list.
22102 		 */
22103 		ire_t *first_ire;
22104 		irb_t *irb = ire->ire_bucket;
22105 		ASSERT(irb != NULL);
22106 
22107 		/* Make sure we do not omit any multiroute ire. */
22108 		IRB_REFHOLD(irb);
22109 		for (first_ire = irb->irb_ire;
22110 		    first_ire != NULL;
22111 		    first_ire = first_ire->ire_next) {
22112 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22113 			    (first_ire->ire_addr == ire->ire_addr) &&
22114 			    !(first_ire->ire_marks &
22115 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
22116 				break;
22117 			}
22118 		}
22119 
22120 		if ((first_ire != NULL) && (first_ire != ire)) {
22121 			IRE_REFHOLD(first_ire);
22122 			ire_refrele(ire);
22123 			ire = first_ire;
22124 			ill = ire_to_ill(ire);
22125 		}
22126 		IRB_REFRELE(irb);
22127 	}
22128 
22129 	/*
22130 	 * conn_outgoing_ill variable is used only in the broadcast loop.
22131 	 * for performance we don't grab the mutexs in the fastpath
22132 	 */
22133 	if ((connp != NULL) &&
22134 	    (ire->ire_type == IRE_BROADCAST) &&
22135 	    ((connp->conn_nofailover_ill != NULL) ||
22136 	    (connp->conn_outgoing_ill != NULL))) {
22137 		/*
22138 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
22139 		 * option. So, see if this endpoint is bound to a
22140 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
22141 		 * that if the interface is failed, we will still send
22142 		 * the packet on the same ill which is what we want.
22143 		 */
22144 		conn_outgoing_ill = conn_get_held_ill(connp,
22145 		    &connp->conn_nofailover_ill, &err);
22146 		if (err == ILL_LOOKUP_FAILED) {
22147 			ire_refrele(ire);
22148 			freemsg(mp);
22149 			return;
22150 		}
22151 		if (conn_outgoing_ill == NULL) {
22152 			/*
22153 			 * Choose a good ill in the group to send the
22154 			 * packets on.
22155 			 */
22156 			ire = conn_set_outgoing_ill(connp, ire,
22157 			    &conn_outgoing_ill);
22158 			if (ire == NULL) {
22159 				freemsg(mp);
22160 				return;
22161 			}
22162 		}
22163 	}
22164 
22165 	if (mp->b_datap->db_type != M_CTL) {
22166 		ipha = (ipha_t *)mp->b_rptr;
22167 	} else {
22168 		io = (ipsec_out_t *)mp->b_rptr;
22169 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22170 		ASSERT(zoneid == io->ipsec_out_zoneid);
22171 		ASSERT(zoneid != ALL_ZONES);
22172 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22173 		dst = ipha->ipha_dst;
22174 		/*
22175 		 * For the multicast case, ipsec_out carries conn_dontroute and
22176 		 * conn_multicast_loop as conn may not be available here. We
22177 		 * need this for multicast loopback and forwarding which is done
22178 		 * later in the code.
22179 		 */
22180 		if (CLASSD(dst)) {
22181 			conn_dontroute = io->ipsec_out_dontroute;
22182 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22183 			/*
22184 			 * If conn_dontroute is not set or conn_multicast_loop
22185 			 * is set, we need to do forwarding/loopback. For
22186 			 * datagrams from ip_wput_multicast, conn_dontroute is
22187 			 * set to B_TRUE and conn_multicast_loop is set to
22188 			 * B_FALSE so that we neither do forwarding nor
22189 			 * loopback.
22190 			 */
22191 			if (!conn_dontroute || conn_multicast_loop)
22192 				multicast_forward = B_TRUE;
22193 		}
22194 	}
22195 
22196 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22197 	    ire->ire_zoneid != ALL_ZONES) {
22198 		/*
22199 		 * When a zone sends a packet to another zone, we try to deliver
22200 		 * the packet under the same conditions as if the destination
22201 		 * was a real node on the network. To do so, we look for a
22202 		 * matching route in the forwarding table.
22203 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22204 		 * ip_newroute() does.
22205 		 * Note that IRE_LOCAL are special, since they are used
22206 		 * when the zoneid doesn't match in some cases. This means that
22207 		 * we need to handle ipha_src differently since ire_src_addr
22208 		 * belongs to the receiving zone instead of the sending zone.
22209 		 * When ip_restrict_interzone_loopback is set, then
22210 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22211 		 * for loopback between zones when the logical "Ethernet" would
22212 		 * have looped them back.
22213 		 */
22214 		ire_t *src_ire;
22215 
22216 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22217 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22218 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22219 		if (src_ire != NULL &&
22220 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22221 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22222 		    ire_local_same_ill_group(ire, src_ire))) {
22223 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22224 				ipha->ipha_src = src_ire->ire_src_addr;
22225 			ire_refrele(src_ire);
22226 		} else {
22227 			ire_refrele(ire);
22228 			if (conn_outgoing_ill != NULL)
22229 				ill_refrele(conn_outgoing_ill);
22230 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22231 			if (src_ire != NULL) {
22232 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22233 					ire_refrele(src_ire);
22234 					freemsg(mp);
22235 					return;
22236 				}
22237 				ire_refrele(src_ire);
22238 			}
22239 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22240 				/* Failed */
22241 				freemsg(mp);
22242 				return;
22243 			}
22244 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22245 			    ipst);
22246 			return;
22247 		}
22248 	}
22249 
22250 	if (mp->b_datap->db_type == M_CTL ||
22251 	    ipss->ipsec_outbound_v4_policy_present) {
22252 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22253 		    unspec_src, zoneid);
22254 		if (mp == NULL) {
22255 			ire_refrele(ire);
22256 			if (conn_outgoing_ill != NULL)
22257 				ill_refrele(conn_outgoing_ill);
22258 			return;
22259 		}
22260 		/*
22261 		 * Trusted Extensions supports all-zones interfaces, so
22262 		 * zoneid == ALL_ZONES is valid, but IPsec maps ALL_ZONES to
22263 		 * the global zone.
22264 		 */
22265 		if (zoneid == ALL_ZONES && mp->b_datap->db_type == M_CTL) {
22266 			io = (ipsec_out_t *)mp->b_rptr;
22267 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
22268 			zoneid = io->ipsec_out_zoneid;
22269 		}
22270 	}
22271 
22272 	first_mp = mp;
22273 	ipsec_len = 0;
22274 
22275 	if (first_mp->b_datap->db_type == M_CTL) {
22276 		io = (ipsec_out_t *)first_mp->b_rptr;
22277 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22278 		mp = first_mp->b_cont;
22279 		ipsec_len = ipsec_out_extra_length(first_mp);
22280 		ASSERT(ipsec_len >= 0);
22281 		/* We already picked up the zoneid from the M_CTL above */
22282 		ASSERT(zoneid == io->ipsec_out_zoneid);
22283 		ASSERT(zoneid != ALL_ZONES);
22284 
22285 		/*
22286 		 * Drop M_CTL here if IPsec processing is not needed.
22287 		 * (Non-IPsec use of M_CTL extracted any information it
22288 		 * needed above).
22289 		 */
22290 		if (ipsec_len == 0) {
22291 			freeb(first_mp);
22292 			first_mp = mp;
22293 		}
22294 	}
22295 
22296 	/*
22297 	 * Fast path for ip_wput_ire
22298 	 */
22299 
22300 	ipha = (ipha_t *)mp->b_rptr;
22301 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22302 	dst = ipha->ipha_dst;
22303 
22304 	/*
22305 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22306 	 * if the socket is a SOCK_RAW type. The transport checksum should
22307 	 * be provided in the pre-built packet, so we don't need to compute it.
22308 	 * Also, other application set flags, like DF, should not be altered.
22309 	 * Other transport MUST pass down zero.
22310 	 */
22311 	ip_hdr_included = ipha->ipha_ident;
22312 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22313 
22314 	if (CLASSD(dst)) {
22315 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22316 		    ntohl(dst),
22317 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22318 		    ntohl(ire->ire_addr)));
22319 	}
22320 
22321 /* Macros to extract header fields from data already in registers */
22322 #ifdef	_BIG_ENDIAN
22323 #define	V_HLEN	(v_hlen_tos_len >> 24)
22324 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22325 #define	PROTO	(ttl_protocol & 0xFF)
22326 #else
22327 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22328 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22329 #define	PROTO	(ttl_protocol >> 8)
22330 #endif
22331 
22332 
22333 	orig_src = src = ipha->ipha_src;
22334 	/* (The loop back to "another" is explained down below.) */
22335 another:;
22336 	/*
22337 	 * Assign an ident value for this packet.  We assign idents on
22338 	 * a per destination basis out of the IRE.  There could be
22339 	 * other threads targeting the same destination, so we have to
22340 	 * arrange for a atomic increment.  Note that we use a 32-bit
22341 	 * atomic add because it has better performance than its
22342 	 * 16-bit sibling.
22343 	 *
22344 	 * If running in cluster mode and if the source address
22345 	 * belongs to a replicated service then vector through
22346 	 * cl_inet_ipident vector to allocate ip identifier
22347 	 * NOTE: This is a contract private interface with the
22348 	 * clustering group.
22349 	 */
22350 	clusterwide = 0;
22351 	if (cl_inet_ipident) {
22352 		ASSERT(cl_inet_isclusterwide);
22353 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
22354 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
22355 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
22356 			    AF_INET, (uint8_t *)(uintptr_t)src,
22357 			    (uint8_t *)(uintptr_t)dst);
22358 			clusterwide = 1;
22359 		}
22360 	}
22361 	if (!clusterwide) {
22362 		ipha->ipha_ident =
22363 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22364 	}
22365 
22366 #ifndef _BIG_ENDIAN
22367 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22368 #endif
22369 
22370 	/*
22371 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22372 	 * This is needed to obey conn_unspec_src when packets go through
22373 	 * ip_newroute + arp.
22374 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22375 	 */
22376 	if (src == INADDR_ANY && !unspec_src) {
22377 		/*
22378 		 * Assign the appropriate source address from the IRE if none
22379 		 * was specified.
22380 		 */
22381 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22382 
22383 		/*
22384 		 * With IP multipathing, broadcast packets are sent on the ire
22385 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
22386 		 * the group. However, this ire might not be in the same zone so
22387 		 * we can't always use its source address. We look for a
22388 		 * broadcast ire in the same group and in the right zone.
22389 		 */
22390 		if (ire->ire_type == IRE_BROADCAST &&
22391 		    ire->ire_zoneid != zoneid) {
22392 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
22393 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
22394 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
22395 			if (src_ire != NULL) {
22396 				src = src_ire->ire_src_addr;
22397 				ire_refrele(src_ire);
22398 			} else {
22399 				ire_refrele(ire);
22400 				if (conn_outgoing_ill != NULL)
22401 					ill_refrele(conn_outgoing_ill);
22402 				freemsg(first_mp);
22403 				if (ill != NULL) {
22404 					BUMP_MIB(ill->ill_ip_mib,
22405 					    ipIfStatsOutDiscards);
22406 				} else {
22407 					BUMP_MIB(&ipst->ips_ip_mib,
22408 					    ipIfStatsOutDiscards);
22409 				}
22410 				return;
22411 			}
22412 		} else {
22413 			src = ire->ire_src_addr;
22414 		}
22415 
22416 		if (connp == NULL) {
22417 			ip1dbg(("ip_wput_ire: no connp and no src "
22418 			    "address for dst 0x%x, using src 0x%x\n",
22419 			    ntohl(dst),
22420 			    ntohl(src)));
22421 		}
22422 		ipha->ipha_src = src;
22423 	}
22424 	stq = ire->ire_stq;
22425 
22426 	/*
22427 	 * We only allow ire chains for broadcasts since there will
22428 	 * be multiple IRE_CACHE entries for the same multicast
22429 	 * address (one per ipif).
22430 	 */
22431 	next_mp = NULL;
22432 
22433 	/* broadcast packet */
22434 	if (ire->ire_type == IRE_BROADCAST)
22435 		goto broadcast;
22436 
22437 	/* loopback ? */
22438 	if (stq == NULL)
22439 		goto nullstq;
22440 
22441 	/* The ill_index for outbound ILL */
22442 	ill_index = Q_TO_INDEX(stq);
22443 
22444 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22445 	ttl_protocol = ((uint16_t *)ipha)[4];
22446 
22447 	/* pseudo checksum (do it in parts for IP header checksum) */
22448 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22449 
22450 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22451 		queue_t *dev_q = stq->q_next;
22452 
22453 		/* flow controlled */
22454 		if ((dev_q->q_next || dev_q->q_first) &&
22455 		    !canput(dev_q))
22456 			goto blocked;
22457 		if ((PROTO == IPPROTO_UDP) &&
22458 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22459 			hlen = (V_HLEN & 0xF) << 2;
22460 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22461 			if (*up != 0) {
22462 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22463 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22464 				/* Software checksum? */
22465 				if (DB_CKSUMFLAGS(mp) == 0) {
22466 					IP_STAT(ipst, ip_out_sw_cksum);
22467 					IP_STAT_UPDATE(ipst,
22468 					    ip_udp_out_sw_cksum_bytes,
22469 					    LENGTH - hlen);
22470 				}
22471 			}
22472 		}
22473 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22474 		hlen = (V_HLEN & 0xF) << 2;
22475 		if (PROTO == IPPROTO_TCP) {
22476 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22477 			/*
22478 			 * The packet header is processed once and for all, even
22479 			 * in the multirouting case. We disable hardware
22480 			 * checksum if the packet is multirouted, as it will be
22481 			 * replicated via several interfaces, and not all of
22482 			 * them may have this capability.
22483 			 */
22484 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22485 			    LENGTH, max_frag, ipsec_len, cksum);
22486 			/* Software checksum? */
22487 			if (DB_CKSUMFLAGS(mp) == 0) {
22488 				IP_STAT(ipst, ip_out_sw_cksum);
22489 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22490 				    LENGTH - hlen);
22491 			}
22492 		} else {
22493 			sctp_hdr_t	*sctph;
22494 
22495 			ASSERT(PROTO == IPPROTO_SCTP);
22496 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22497 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22498 			/*
22499 			 * Zero out the checksum field to ensure proper
22500 			 * checksum calculation.
22501 			 */
22502 			sctph->sh_chksum = 0;
22503 #ifdef	DEBUG
22504 			if (!skip_sctp_cksum)
22505 #endif
22506 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22507 		}
22508 	}
22509 
22510 	/*
22511 	 * If this is a multicast packet and originated from ip_wput
22512 	 * we need to do loopback and forwarding checks. If it comes
22513 	 * from ip_wput_multicast, we SHOULD not do this.
22514 	 */
22515 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22516 
22517 	/* checksum */
22518 	cksum += ttl_protocol;
22519 
22520 	/* fragment the packet */
22521 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22522 		goto fragmentit;
22523 	/*
22524 	 * Don't use frag_flag if packet is pre-built or source
22525 	 * routed or if multicast (since multicast packets do
22526 	 * not solicit ICMP "packet too big" messages).
22527 	 */
22528 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22529 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22530 	    !ip_source_route_included(ipha)) &&
22531 	    !CLASSD(ipha->ipha_dst))
22532 		ipha->ipha_fragment_offset_and_flags |=
22533 		    htons(ire->ire_frag_flag);
22534 
22535 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22536 		/* calculate IP header checksum */
22537 		cksum += ipha->ipha_ident;
22538 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22539 		cksum += ipha->ipha_fragment_offset_and_flags;
22540 
22541 		/* IP options present */
22542 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22543 		if (hlen)
22544 			goto checksumoptions;
22545 
22546 		/* calculate hdr checksum */
22547 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22548 		cksum = ~(cksum + (cksum >> 16));
22549 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22550 	}
22551 	if (ipsec_len != 0) {
22552 		/*
22553 		 * We will do the rest of the processing after
22554 		 * we come back from IPsec in ip_wput_ipsec_out().
22555 		 */
22556 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22557 
22558 		io = (ipsec_out_t *)first_mp->b_rptr;
22559 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
22560 		    ill_phyint->phyint_ifindex;
22561 
22562 		ipsec_out_process(q, first_mp, ire, ill_index);
22563 		ire_refrele(ire);
22564 		if (conn_outgoing_ill != NULL)
22565 			ill_refrele(conn_outgoing_ill);
22566 		return;
22567 	}
22568 
22569 	/*
22570 	 * In most cases, the emission loop below is entered only
22571 	 * once. Only in the case where the ire holds the
22572 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22573 	 * flagged ires in the bucket, and send the packet
22574 	 * through all crossed RTF_MULTIRT routes.
22575 	 */
22576 	if (ire->ire_flags & RTF_MULTIRT) {
22577 		multirt_send = B_TRUE;
22578 	}
22579 	do {
22580 		if (multirt_send) {
22581 			irb_t *irb;
22582 			/*
22583 			 * We are in a multiple send case, need to get
22584 			 * the next ire and make a duplicate of the packet.
22585 			 * ire1 holds here the next ire to process in the
22586 			 * bucket. If multirouting is expected,
22587 			 * any non-RTF_MULTIRT ire that has the
22588 			 * right destination address is ignored.
22589 			 */
22590 			irb = ire->ire_bucket;
22591 			ASSERT(irb != NULL);
22592 
22593 			IRB_REFHOLD(irb);
22594 			for (ire1 = ire->ire_next;
22595 			    ire1 != NULL;
22596 			    ire1 = ire1->ire_next) {
22597 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22598 					continue;
22599 				if (ire1->ire_addr != ire->ire_addr)
22600 					continue;
22601 				if (ire1->ire_marks &
22602 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22603 					continue;
22604 
22605 				/* Got one */
22606 				IRE_REFHOLD(ire1);
22607 				break;
22608 			}
22609 			IRB_REFRELE(irb);
22610 
22611 			if (ire1 != NULL) {
22612 				next_mp = copyb(mp);
22613 				if ((next_mp == NULL) ||
22614 				    ((mp->b_cont != NULL) &&
22615 				    ((next_mp->b_cont =
22616 				    dupmsg(mp->b_cont)) == NULL))) {
22617 					freemsg(next_mp);
22618 					next_mp = NULL;
22619 					ire_refrele(ire1);
22620 					ire1 = NULL;
22621 				}
22622 			}
22623 
22624 			/* Last multiroute ire; don't loop anymore. */
22625 			if (ire1 == NULL) {
22626 				multirt_send = B_FALSE;
22627 			}
22628 		}
22629 
22630 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22631 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22632 		    mblk_t *, mp);
22633 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22634 		    ipst->ips_ipv4firewall_physical_out,
22635 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, 0, ipst);
22636 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22637 		if (mp == NULL)
22638 			goto release_ire_and_ill;
22639 
22640 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22641 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22642 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
22643 		if ((pktxmit_state == SEND_FAILED) ||
22644 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22645 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22646 			    "- packet dropped\n"));
22647 release_ire_and_ill:
22648 			ire_refrele(ire);
22649 			if (next_mp != NULL) {
22650 				freemsg(next_mp);
22651 				ire_refrele(ire1);
22652 			}
22653 			if (conn_outgoing_ill != NULL)
22654 				ill_refrele(conn_outgoing_ill);
22655 			return;
22656 		}
22657 
22658 		if (CLASSD(dst)) {
22659 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22660 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22661 			    LENGTH);
22662 		}
22663 
22664 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22665 		    "ip_wput_ire_end: q %p (%S)",
22666 		    q, "last copy out");
22667 		IRE_REFRELE(ire);
22668 
22669 		if (multirt_send) {
22670 			ASSERT(ire1);
22671 			/*
22672 			 * Proceed with the next RTF_MULTIRT ire,
22673 			 * Also set up the send-to queue accordingly.
22674 			 */
22675 			ire = ire1;
22676 			ire1 = NULL;
22677 			stq = ire->ire_stq;
22678 			mp = next_mp;
22679 			next_mp = NULL;
22680 			ipha = (ipha_t *)mp->b_rptr;
22681 			ill_index = Q_TO_INDEX(stq);
22682 			ill = (ill_t *)stq->q_ptr;
22683 		}
22684 	} while (multirt_send);
22685 	if (conn_outgoing_ill != NULL)
22686 		ill_refrele(conn_outgoing_ill);
22687 	return;
22688 
22689 	/*
22690 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22691 	 */
22692 broadcast:
22693 	{
22694 		/*
22695 		 * To avoid broadcast storms, we usually set the TTL to 1 for
22696 		 * broadcasts.  However, if SO_DONTROUTE isn't set, this value
22697 		 * can be overridden stack-wide through the ip_broadcast_ttl
22698 		 * ndd tunable, or on a per-connection basis through the
22699 		 * IP_BROADCAST_TTL socket option.
22700 		 *
22701 		 * In the event that we are replying to incoming ICMP packets,
22702 		 * connp could be NULL.
22703 		 */
22704 		ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22705 		if (connp != NULL) {
22706 			if (connp->conn_dontroute)
22707 				ipha->ipha_ttl = 1;
22708 			else if (connp->conn_broadcast_ttl != 0)
22709 				ipha->ipha_ttl = connp->conn_broadcast_ttl;
22710 		}
22711 
22712 		/*
22713 		 * Note that we are not doing a IRB_REFHOLD here.
22714 		 * Actually we don't care if the list changes i.e
22715 		 * if somebody deletes an IRE from the list while
22716 		 * we drop the lock, the next time we come around
22717 		 * ire_next will be NULL and hence we won't send
22718 		 * out multiple copies which is fine.
22719 		 */
22720 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22721 		ire1 = ire->ire_next;
22722 		if (conn_outgoing_ill != NULL) {
22723 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22724 				ASSERT(ire1 == ire->ire_next);
22725 				if (ire1 != NULL && ire1->ire_addr == dst) {
22726 					ire_refrele(ire);
22727 					ire = ire1;
22728 					IRE_REFHOLD(ire);
22729 					ire1 = ire->ire_next;
22730 					continue;
22731 				}
22732 				rw_exit(&ire->ire_bucket->irb_lock);
22733 				/* Did not find a matching ill */
22734 				ip1dbg(("ip_wput_ire: broadcast with no "
22735 				    "matching IP_BOUND_IF ill %s dst %x\n",
22736 				    conn_outgoing_ill->ill_name, dst));
22737 				freemsg(first_mp);
22738 				if (ire != NULL)
22739 					ire_refrele(ire);
22740 				ill_refrele(conn_outgoing_ill);
22741 				return;
22742 			}
22743 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22744 			/*
22745 			 * If the next IRE has the same address and is not one
22746 			 * of the two copies that we need to send, try to see
22747 			 * whether this copy should be sent at all. This
22748 			 * assumes that we insert loopbacks first and then
22749 			 * non-loopbacks. This is acheived by inserting the
22750 			 * loopback always before non-loopback.
22751 			 * This is used to send a single copy of a broadcast
22752 			 * packet out all physical interfaces that have an
22753 			 * matching IRE_BROADCAST while also looping
22754 			 * back one copy (to ip_wput_local) for each
22755 			 * matching physical interface. However, we avoid
22756 			 * sending packets out different logical that match by
22757 			 * having ipif_up/ipif_down supress duplicate
22758 			 * IRE_BROADCASTS.
22759 			 *
22760 			 * This feature is currently used to get broadcasts
22761 			 * sent to multiple interfaces, when the broadcast
22762 			 * address being used applies to multiple interfaces.
22763 			 * For example, a whole net broadcast will be
22764 			 * replicated on every connected subnet of
22765 			 * the target net.
22766 			 *
22767 			 * Each zone has its own set of IRE_BROADCASTs, so that
22768 			 * we're able to distribute inbound packets to multiple
22769 			 * zones who share a broadcast address. We avoid looping
22770 			 * back outbound packets in different zones but on the
22771 			 * same ill, as the application would see duplicates.
22772 			 *
22773 			 * If the interfaces are part of the same group,
22774 			 * we would want to send only one copy out for
22775 			 * whole group.
22776 			 *
22777 			 * This logic assumes that ire_add_v4() groups the
22778 			 * IRE_BROADCAST entries so that those with the same
22779 			 * ire_addr and ill_group are kept together.
22780 			 */
22781 			ire_ill = ire->ire_ipif->ipif_ill;
22782 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22783 				if (ire_ill->ill_group != NULL &&
22784 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22785 					/*
22786 					 * If the current zone only has an ire
22787 					 * broadcast for this address marked
22788 					 * NORECV, the ire we want is ahead in
22789 					 * the bucket, so we look it up
22790 					 * deliberately ignoring the zoneid.
22791 					 */
22792 					for (ire1 = ire->ire_bucket->irb_ire;
22793 					    ire1 != NULL;
22794 					    ire1 = ire1->ire_next) {
22795 						ire1_ill =
22796 						    ire1->ire_ipif->ipif_ill;
22797 						if (ire1->ire_addr != dst)
22798 							continue;
22799 						/* skip over the current ire */
22800 						if (ire1 == ire)
22801 							continue;
22802 						/* skip over deleted ires */
22803 						if (ire1->ire_marks &
22804 						    IRE_MARK_CONDEMNED)
22805 							continue;
22806 						/*
22807 						 * non-loopback ire in our
22808 						 * group: use it for the next
22809 						 * pass in the loop
22810 						 */
22811 						if (ire1->ire_stq != NULL &&
22812 						    ire1_ill->ill_group ==
22813 						    ire_ill->ill_group)
22814 							break;
22815 					}
22816 				}
22817 			} else {
22818 				while (ire1 != NULL && ire1->ire_addr == dst) {
22819 					ire1_ill = ire1->ire_ipif->ipif_ill;
22820 					/*
22821 					 * We can have two broadcast ires on the
22822 					 * same ill in different zones; here
22823 					 * we'll send a copy of the packet on
22824 					 * each ill and the fanout code will
22825 					 * call conn_wantpacket() to check that
22826 					 * the zone has the broadcast address
22827 					 * configured on the ill. If the two
22828 					 * ires are in the same group we only
22829 					 * send one copy up.
22830 					 */
22831 					if (ire1_ill != ire_ill &&
22832 					    (ire1_ill->ill_group == NULL ||
22833 					    ire_ill->ill_group == NULL ||
22834 					    ire1_ill->ill_group !=
22835 					    ire_ill->ill_group)) {
22836 						break;
22837 					}
22838 					ire1 = ire1->ire_next;
22839 				}
22840 			}
22841 		}
22842 		ASSERT(multirt_send == B_FALSE);
22843 		if (ire1 != NULL && ire1->ire_addr == dst) {
22844 			if ((ire->ire_flags & RTF_MULTIRT) &&
22845 			    (ire1->ire_flags & RTF_MULTIRT)) {
22846 				/*
22847 				 * We are in the multirouting case.
22848 				 * The message must be sent at least
22849 				 * on both ires. These ires have been
22850 				 * inserted AFTER the standard ones
22851 				 * in ip_rt_add(). There are thus no
22852 				 * other ire entries for the destination
22853 				 * address in the rest of the bucket
22854 				 * that do not have the RTF_MULTIRT
22855 				 * flag. We don't process a copy
22856 				 * of the message here. This will be
22857 				 * done in the final sending loop.
22858 				 */
22859 				multirt_send = B_TRUE;
22860 			} else {
22861 				next_mp = ip_copymsg(first_mp);
22862 				if (next_mp != NULL)
22863 					IRE_REFHOLD(ire1);
22864 			}
22865 		}
22866 		rw_exit(&ire->ire_bucket->irb_lock);
22867 	}
22868 
22869 	if (stq) {
22870 		/*
22871 		 * A non-NULL send-to queue means this packet is going
22872 		 * out of this machine.
22873 		 */
22874 		out_ill = (ill_t *)stq->q_ptr;
22875 
22876 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22877 		ttl_protocol = ((uint16_t *)ipha)[4];
22878 		/*
22879 		 * We accumulate the pseudo header checksum in cksum.
22880 		 * This is pretty hairy code, so watch close.  One
22881 		 * thing to keep in mind is that UDP and TCP have
22882 		 * stored their respective datagram lengths in their
22883 		 * checksum fields.  This lines things up real nice.
22884 		 */
22885 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22886 		    (src >> 16) + (src & 0xFFFF);
22887 		/*
22888 		 * We assume the udp checksum field contains the
22889 		 * length, so to compute the pseudo header checksum,
22890 		 * all we need is the protocol number and src/dst.
22891 		 */
22892 		/* Provide the checksums for UDP and TCP. */
22893 		if ((PROTO == IPPROTO_TCP) &&
22894 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22895 			/* hlen gets the number of uchar_ts in the IP header */
22896 			hlen = (V_HLEN & 0xF) << 2;
22897 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22898 			IP_STAT(ipst, ip_out_sw_cksum);
22899 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22900 			    LENGTH - hlen);
22901 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22902 		} else if (PROTO == IPPROTO_SCTP &&
22903 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22904 			sctp_hdr_t	*sctph;
22905 
22906 			hlen = (V_HLEN & 0xF) << 2;
22907 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22908 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22909 			sctph->sh_chksum = 0;
22910 #ifdef	DEBUG
22911 			if (!skip_sctp_cksum)
22912 #endif
22913 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22914 		} else {
22915 			queue_t *dev_q = stq->q_next;
22916 
22917 			if ((dev_q->q_next || dev_q->q_first) &&
22918 			    !canput(dev_q)) {
22919 blocked:
22920 				ipha->ipha_ident = ip_hdr_included;
22921 				/*
22922 				 * If we don't have a conn to apply
22923 				 * backpressure, free the message.
22924 				 * In the ire_send path, we don't know
22925 				 * the position to requeue the packet. Rather
22926 				 * than reorder packets, we just drop this
22927 				 * packet.
22928 				 */
22929 				if (ipst->ips_ip_output_queue &&
22930 				    connp != NULL &&
22931 				    caller != IRE_SEND) {
22932 					if (caller == IP_WSRV) {
22933 						connp->conn_did_putbq = 1;
22934 						(void) putbq(connp->conn_wq,
22935 						    first_mp);
22936 						conn_drain_insert(connp);
22937 						/*
22938 						 * This is the service thread,
22939 						 * and the queue is already
22940 						 * noenabled. The check for
22941 						 * canput and the putbq is not
22942 						 * atomic. So we need to check
22943 						 * again.
22944 						 */
22945 						if (canput(stq->q_next))
22946 							connp->conn_did_putbq
22947 							    = 0;
22948 						IP_STAT(ipst, ip_conn_flputbq);
22949 					} else {
22950 						/*
22951 						 * We are not the service proc.
22952 						 * ip_wsrv will be scheduled or
22953 						 * is already running.
22954 						 */
22955 						(void) putq(connp->conn_wq,
22956 						    first_mp);
22957 					}
22958 				} else {
22959 					out_ill = (ill_t *)stq->q_ptr;
22960 					BUMP_MIB(out_ill->ill_ip_mib,
22961 					    ipIfStatsOutDiscards);
22962 					freemsg(first_mp);
22963 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22964 					    "ip_wput_ire_end: q %p (%S)",
22965 					    q, "discard");
22966 				}
22967 				ire_refrele(ire);
22968 				if (next_mp) {
22969 					ire_refrele(ire1);
22970 					freemsg(next_mp);
22971 				}
22972 				if (conn_outgoing_ill != NULL)
22973 					ill_refrele(conn_outgoing_ill);
22974 				return;
22975 			}
22976 			if ((PROTO == IPPROTO_UDP) &&
22977 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22978 				/*
22979 				 * hlen gets the number of uchar_ts in the
22980 				 * IP header
22981 				 */
22982 				hlen = (V_HLEN & 0xF) << 2;
22983 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22984 				max_frag = ire->ire_max_frag;
22985 				if (*up != 0) {
22986 					IP_CKSUM_XMIT(out_ill, ire, mp, ipha,
22987 					    up, PROTO, hlen, LENGTH, max_frag,
22988 					    ipsec_len, cksum);
22989 					/* Software checksum? */
22990 					if (DB_CKSUMFLAGS(mp) == 0) {
22991 						IP_STAT(ipst, ip_out_sw_cksum);
22992 						IP_STAT_UPDATE(ipst,
22993 						    ip_udp_out_sw_cksum_bytes,
22994 						    LENGTH - hlen);
22995 					}
22996 				}
22997 			}
22998 		}
22999 		/*
23000 		 * Need to do this even when fragmenting. The local
23001 		 * loopback can be done without computing checksums
23002 		 * but forwarding out other interface must be done
23003 		 * after the IP checksum (and ULP checksums) have been
23004 		 * computed.
23005 		 *
23006 		 * NOTE : multicast_forward is set only if this packet
23007 		 * originated from ip_wput. For packets originating from
23008 		 * ip_wput_multicast, it is not set.
23009 		 */
23010 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
23011 multi_loopback:
23012 			ip2dbg(("ip_wput: multicast, loop %d\n",
23013 			    conn_multicast_loop));
23014 
23015 			/*  Forget header checksum offload */
23016 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
23017 
23018 			/*
23019 			 * Local loopback of multicasts?  Check the
23020 			 * ill.
23021 			 *
23022 			 * Note that the loopback function will not come
23023 			 * in through ip_rput - it will only do the
23024 			 * client fanout thus we need to do an mforward
23025 			 * as well.  The is different from the BSD
23026 			 * logic.
23027 			 */
23028 			if (ill != NULL) {
23029 				ilm_t	*ilm;
23030 
23031 				ILM_WALKER_HOLD(ill);
23032 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
23033 				    ALL_ZONES);
23034 				ILM_WALKER_RELE(ill);
23035 				if (ilm != NULL) {
23036 					/*
23037 					 * Pass along the virtual output q.
23038 					 * ip_wput_local() will distribute the
23039 					 * packet to all the matching zones,
23040 					 * except the sending zone when
23041 					 * IP_MULTICAST_LOOP is false.
23042 					 */
23043 					ip_multicast_loopback(q, ill, first_mp,
23044 					    conn_multicast_loop ? 0 :
23045 					    IP_FF_NO_MCAST_LOOP, zoneid);
23046 				}
23047 			}
23048 			if (ipha->ipha_ttl == 0) {
23049 				/*
23050 				 * 0 => only to this host i.e. we are
23051 				 * done. We are also done if this was the
23052 				 * loopback interface since it is sufficient
23053 				 * to loopback one copy of a multicast packet.
23054 				 */
23055 				freemsg(first_mp);
23056 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23057 				    "ip_wput_ire_end: q %p (%S)",
23058 				    q, "loopback");
23059 				ire_refrele(ire);
23060 				if (conn_outgoing_ill != NULL)
23061 					ill_refrele(conn_outgoing_ill);
23062 				return;
23063 			}
23064 			/*
23065 			 * ILLF_MULTICAST is checked in ip_newroute
23066 			 * i.e. we don't need to check it here since
23067 			 * all IRE_CACHEs come from ip_newroute.
23068 			 * For multicast traffic, SO_DONTROUTE is interpreted
23069 			 * to mean only send the packet out the interface
23070 			 * (optionally specified with IP_MULTICAST_IF)
23071 			 * and do not forward it out additional interfaces.
23072 			 * RSVP and the rsvp daemon is an example of a
23073 			 * protocol and user level process that
23074 			 * handles it's own routing. Hence, it uses the
23075 			 * SO_DONTROUTE option to accomplish this.
23076 			 */
23077 
23078 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
23079 			    ill != NULL) {
23080 				/* Unconditionally redo the checksum */
23081 				ipha->ipha_hdr_checksum = 0;
23082 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23083 
23084 				/*
23085 				 * If this needs to go out secure, we need
23086 				 * to wait till we finish the IPsec
23087 				 * processing.
23088 				 */
23089 				if (ipsec_len == 0 &&
23090 				    ip_mforward(ill, ipha, mp)) {
23091 					freemsg(first_mp);
23092 					ip1dbg(("ip_wput: mforward failed\n"));
23093 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23094 					    "ip_wput_ire_end: q %p (%S)",
23095 					    q, "mforward failed");
23096 					ire_refrele(ire);
23097 					if (conn_outgoing_ill != NULL)
23098 						ill_refrele(conn_outgoing_ill);
23099 					return;
23100 				}
23101 			}
23102 		}
23103 		max_frag = ire->ire_max_frag;
23104 		cksum += ttl_protocol;
23105 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23106 			/* No fragmentation required for this one. */
23107 			/*
23108 			 * Don't use frag_flag if packet is pre-built or source
23109 			 * routed or if multicast (since multicast packets do
23110 			 * not solicit ICMP "packet too big" messages).
23111 			 */
23112 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23113 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23114 			    !ip_source_route_included(ipha)) &&
23115 			    !CLASSD(ipha->ipha_dst))
23116 				ipha->ipha_fragment_offset_and_flags |=
23117 				    htons(ire->ire_frag_flag);
23118 
23119 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23120 				/* Complete the IP header checksum. */
23121 				cksum += ipha->ipha_ident;
23122 				cksum += (v_hlen_tos_len >> 16)+
23123 				    (v_hlen_tos_len & 0xFFFF);
23124 				cksum += ipha->ipha_fragment_offset_and_flags;
23125 				hlen = (V_HLEN & 0xF) -
23126 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23127 				if (hlen) {
23128 checksumoptions:
23129 					/*
23130 					 * Account for the IP Options in the IP
23131 					 * header checksum.
23132 					 */
23133 					up = (uint16_t *)(rptr+
23134 					    IP_SIMPLE_HDR_LENGTH);
23135 					do {
23136 						cksum += up[0];
23137 						cksum += up[1];
23138 						up += 2;
23139 					} while (--hlen);
23140 				}
23141 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23142 				cksum = ~(cksum + (cksum >> 16));
23143 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23144 			}
23145 			if (ipsec_len != 0) {
23146 				ipsec_out_process(q, first_mp, ire, ill_index);
23147 				if (!next_mp) {
23148 					ire_refrele(ire);
23149 					if (conn_outgoing_ill != NULL)
23150 						ill_refrele(conn_outgoing_ill);
23151 					return;
23152 				}
23153 				goto next;
23154 			}
23155 
23156 			/*
23157 			 * multirt_send has already been handled
23158 			 * for broadcast, but not yet for multicast
23159 			 * or IP options.
23160 			 */
23161 			if (next_mp == NULL) {
23162 				if (ire->ire_flags & RTF_MULTIRT) {
23163 					multirt_send = B_TRUE;
23164 				}
23165 			}
23166 
23167 			/*
23168 			 * In most cases, the emission loop below is
23169 			 * entered only once. Only in the case where
23170 			 * the ire holds the RTF_MULTIRT flag, do we loop
23171 			 * to process all RTF_MULTIRT ires in the bucket,
23172 			 * and send the packet through all crossed
23173 			 * RTF_MULTIRT routes.
23174 			 */
23175 			do {
23176 				if (multirt_send) {
23177 					irb_t *irb;
23178 
23179 					irb = ire->ire_bucket;
23180 					ASSERT(irb != NULL);
23181 					/*
23182 					 * We are in a multiple send case,
23183 					 * need to get the next IRE and make
23184 					 * a duplicate of the packet.
23185 					 */
23186 					IRB_REFHOLD(irb);
23187 					for (ire1 = ire->ire_next;
23188 					    ire1 != NULL;
23189 					    ire1 = ire1->ire_next) {
23190 						if (!(ire1->ire_flags &
23191 						    RTF_MULTIRT)) {
23192 							continue;
23193 						}
23194 						if (ire1->ire_addr !=
23195 						    ire->ire_addr) {
23196 							continue;
23197 						}
23198 						if (ire1->ire_marks &
23199 						    (IRE_MARK_CONDEMNED|
23200 						    IRE_MARK_HIDDEN)) {
23201 							continue;
23202 						}
23203 
23204 						/* Got one */
23205 						IRE_REFHOLD(ire1);
23206 						break;
23207 					}
23208 					IRB_REFRELE(irb);
23209 
23210 					if (ire1 != NULL) {
23211 						next_mp = copyb(mp);
23212 						if ((next_mp == NULL) ||
23213 						    ((mp->b_cont != NULL) &&
23214 						    ((next_mp->b_cont =
23215 						    dupmsg(mp->b_cont))
23216 						    == NULL))) {
23217 							freemsg(next_mp);
23218 							next_mp = NULL;
23219 							ire_refrele(ire1);
23220 							ire1 = NULL;
23221 						}
23222 					}
23223 
23224 					/*
23225 					 * Last multiroute ire; don't loop
23226 					 * anymore. The emission is over
23227 					 * and next_mp is NULL.
23228 					 */
23229 					if (ire1 == NULL) {
23230 						multirt_send = B_FALSE;
23231 					}
23232 				}
23233 
23234 				out_ill = ire_to_ill(ire);
23235 				DTRACE_PROBE4(ip4__physical__out__start,
23236 				    ill_t *, NULL,
23237 				    ill_t *, out_ill,
23238 				    ipha_t *, ipha, mblk_t *, mp);
23239 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23240 				    ipst->ips_ipv4firewall_physical_out,
23241 				    NULL, out_ill, ipha, mp, mp, 0, ipst);
23242 				DTRACE_PROBE1(ip4__physical__out__end,
23243 				    mblk_t *, mp);
23244 				if (mp == NULL)
23245 					goto release_ire_and_ill_2;
23246 
23247 				ASSERT(ipsec_len == 0);
23248 				mp->b_prev =
23249 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23250 				DTRACE_PROBE2(ip__xmit__2,
23251 				    mblk_t *, mp, ire_t *, ire);
23252 				pktxmit_state = ip_xmit_v4(mp, ire,
23253 				    NULL, B_TRUE);
23254 				if ((pktxmit_state == SEND_FAILED) ||
23255 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23256 release_ire_and_ill_2:
23257 					if (next_mp) {
23258 						freemsg(next_mp);
23259 						ire_refrele(ire1);
23260 					}
23261 					ire_refrele(ire);
23262 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23263 					    "ip_wput_ire_end: q %p (%S)",
23264 					    q, "discard MDATA");
23265 					if (conn_outgoing_ill != NULL)
23266 						ill_refrele(conn_outgoing_ill);
23267 					return;
23268 				}
23269 
23270 				if (CLASSD(dst)) {
23271 					BUMP_MIB(out_ill->ill_ip_mib,
23272 					    ipIfStatsHCOutMcastPkts);
23273 					UPDATE_MIB(out_ill->ill_ip_mib,
23274 					    ipIfStatsHCOutMcastOctets,
23275 					    LENGTH);
23276 				} else if (ire->ire_type == IRE_BROADCAST) {
23277 					BUMP_MIB(out_ill->ill_ip_mib,
23278 					    ipIfStatsHCOutBcastPkts);
23279 				}
23280 
23281 				if (multirt_send) {
23282 					/*
23283 					 * We are in a multiple send case,
23284 					 * need to re-enter the sending loop
23285 					 * using the next ire.
23286 					 */
23287 					ire_refrele(ire);
23288 					ire = ire1;
23289 					stq = ire->ire_stq;
23290 					mp = next_mp;
23291 					next_mp = NULL;
23292 					ipha = (ipha_t *)mp->b_rptr;
23293 					ill_index = Q_TO_INDEX(stq);
23294 				}
23295 			} while (multirt_send);
23296 
23297 			if (!next_mp) {
23298 				/*
23299 				 * Last copy going out (the ultra-common
23300 				 * case).  Note that we intentionally replicate
23301 				 * the putnext rather than calling it before
23302 				 * the next_mp check in hopes of a little
23303 				 * tail-call action out of the compiler.
23304 				 */
23305 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23306 				    "ip_wput_ire_end: q %p (%S)",
23307 				    q, "last copy out(1)");
23308 				ire_refrele(ire);
23309 				if (conn_outgoing_ill != NULL)
23310 					ill_refrele(conn_outgoing_ill);
23311 				return;
23312 			}
23313 			/* More copies going out below. */
23314 		} else {
23315 			int offset;
23316 fragmentit:
23317 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23318 			/*
23319 			 * If this would generate a icmp_frag_needed message,
23320 			 * we need to handle it before we do the IPsec
23321 			 * processing. Otherwise, we need to strip the IPsec
23322 			 * headers before we send up the message to the ULPs
23323 			 * which becomes messy and difficult.
23324 			 */
23325 			if (ipsec_len != 0) {
23326 				if ((max_frag < (unsigned int)(LENGTH +
23327 				    ipsec_len)) && (offset & IPH_DF)) {
23328 					out_ill = (ill_t *)stq->q_ptr;
23329 					BUMP_MIB(out_ill->ill_ip_mib,
23330 					    ipIfStatsOutFragFails);
23331 					BUMP_MIB(out_ill->ill_ip_mib,
23332 					    ipIfStatsOutFragReqds);
23333 					ipha->ipha_hdr_checksum = 0;
23334 					ipha->ipha_hdr_checksum =
23335 					    (uint16_t)ip_csum_hdr(ipha);
23336 					icmp_frag_needed(ire->ire_stq, first_mp,
23337 					    max_frag, zoneid, ipst);
23338 					if (!next_mp) {
23339 						ire_refrele(ire);
23340 						if (conn_outgoing_ill != NULL) {
23341 							ill_refrele(
23342 							    conn_outgoing_ill);
23343 						}
23344 						return;
23345 					}
23346 				} else {
23347 					/*
23348 					 * This won't cause a icmp_frag_needed
23349 					 * message. to be generated. Send it on
23350 					 * the wire. Note that this could still
23351 					 * cause fragmentation and all we
23352 					 * do is the generation of the message
23353 					 * to the ULP if needed before IPsec.
23354 					 */
23355 					if (!next_mp) {
23356 						ipsec_out_process(q, first_mp,
23357 						    ire, ill_index);
23358 						TRACE_2(TR_FAC_IP,
23359 						    TR_IP_WPUT_IRE_END,
23360 						    "ip_wput_ire_end: q %p "
23361 						    "(%S)", q,
23362 						    "last ipsec_out_process");
23363 						ire_refrele(ire);
23364 						if (conn_outgoing_ill != NULL) {
23365 							ill_refrele(
23366 							    conn_outgoing_ill);
23367 						}
23368 						return;
23369 					}
23370 					ipsec_out_process(q, first_mp,
23371 					    ire, ill_index);
23372 				}
23373 			} else {
23374 				/*
23375 				 * Initiate IPPF processing. For
23376 				 * fragmentable packets we finish
23377 				 * all QOS packet processing before
23378 				 * calling:
23379 				 * ip_wput_ire_fragmentit->ip_wput_frag
23380 				 */
23381 
23382 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23383 					ip_process(IPP_LOCAL_OUT, &mp,
23384 					    ill_index);
23385 					if (mp == NULL) {
23386 						out_ill = (ill_t *)stq->q_ptr;
23387 						BUMP_MIB(out_ill->ill_ip_mib,
23388 						    ipIfStatsOutDiscards);
23389 						if (next_mp != NULL) {
23390 							freemsg(next_mp);
23391 							ire_refrele(ire1);
23392 						}
23393 						ire_refrele(ire);
23394 						TRACE_2(TR_FAC_IP,
23395 						    TR_IP_WPUT_IRE_END,
23396 						    "ip_wput_ire: q %p (%S)",
23397 						    q, "discard MDATA");
23398 						if (conn_outgoing_ill != NULL) {
23399 							ill_refrele(
23400 							    conn_outgoing_ill);
23401 						}
23402 						return;
23403 					}
23404 				}
23405 				if (!next_mp) {
23406 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23407 					    "ip_wput_ire_end: q %p (%S)",
23408 					    q, "last fragmentation");
23409 					ip_wput_ire_fragmentit(mp, ire,
23410 					    zoneid, ipst);
23411 					ire_refrele(ire);
23412 					if (conn_outgoing_ill != NULL)
23413 						ill_refrele(conn_outgoing_ill);
23414 					return;
23415 				}
23416 				ip_wput_ire_fragmentit(mp, ire, zoneid, ipst);
23417 			}
23418 		}
23419 	} else {
23420 nullstq:
23421 		/* A NULL stq means the destination address is local. */
23422 		UPDATE_OB_PKT_COUNT(ire);
23423 		ire->ire_last_used_time = lbolt;
23424 		ASSERT(ire->ire_ipif != NULL);
23425 		if (!next_mp) {
23426 			/*
23427 			 * Is there an "in" and "out" for traffic local
23428 			 * to a host (loopback)?  The code in Solaris doesn't
23429 			 * explicitly draw a line in its code for in vs out,
23430 			 * so we've had to draw a line in the sand: ip_wput_ire
23431 			 * is considered to be the "output" side and
23432 			 * ip_wput_local to be the "input" side.
23433 			 */
23434 			out_ill = ire_to_ill(ire);
23435 
23436 			/*
23437 			 * DTrace this as ip:::send.  A blocked packet will
23438 			 * fire the send probe, but not the receive probe.
23439 			 */
23440 			DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23441 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23442 			    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23443 
23444 			DTRACE_PROBE4(ip4__loopback__out__start,
23445 			    ill_t *, NULL, ill_t *, out_ill,
23446 			    ipha_t *, ipha, mblk_t *, first_mp);
23447 
23448 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23449 			    ipst->ips_ipv4firewall_loopback_out,
23450 			    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23451 
23452 			DTRACE_PROBE1(ip4__loopback__out_end,
23453 			    mblk_t *, first_mp);
23454 
23455 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23456 			    "ip_wput_ire_end: q %p (%S)",
23457 			    q, "local address");
23458 
23459 			if (first_mp != NULL)
23460 				ip_wput_local(q, out_ill, ipha,
23461 				    first_mp, ire, 0, ire->ire_zoneid);
23462 			ire_refrele(ire);
23463 			if (conn_outgoing_ill != NULL)
23464 				ill_refrele(conn_outgoing_ill);
23465 			return;
23466 		}
23467 
23468 		out_ill = ire_to_ill(ire);
23469 
23470 		/*
23471 		 * DTrace this as ip:::send.  A blocked packet will fire the
23472 		 * send probe, but not the receive probe.
23473 		 */
23474 		DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23475 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23476 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23477 
23478 		DTRACE_PROBE4(ip4__loopback__out__start,
23479 		    ill_t *, NULL, ill_t *, out_ill,
23480 		    ipha_t *, ipha, mblk_t *, first_mp);
23481 
23482 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23483 		    ipst->ips_ipv4firewall_loopback_out,
23484 		    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23485 
23486 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23487 
23488 		if (first_mp != NULL)
23489 			ip_wput_local(q, out_ill, ipha,
23490 			    first_mp, ire, 0, ire->ire_zoneid);
23491 	}
23492 next:
23493 	/*
23494 	 * More copies going out to additional interfaces.
23495 	 * ire1 has already been held. We don't need the
23496 	 * "ire" anymore.
23497 	 */
23498 	ire_refrele(ire);
23499 	ire = ire1;
23500 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23501 	mp = next_mp;
23502 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23503 	ill = ire_to_ill(ire);
23504 	first_mp = mp;
23505 	if (ipsec_len != 0) {
23506 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23507 		mp = mp->b_cont;
23508 	}
23509 	dst = ire->ire_addr;
23510 	ipha = (ipha_t *)mp->b_rptr;
23511 	/*
23512 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23513 	 * Restore ipha_ident "no checksum" flag.
23514 	 */
23515 	src = orig_src;
23516 	ipha->ipha_ident = ip_hdr_included;
23517 	goto another;
23518 
23519 #undef	rptr
23520 #undef	Q_TO_INDEX
23521 }
23522 
23523 /*
23524  * Routine to allocate a message that is used to notify the ULP about MDT.
23525  * The caller may provide a pointer to the link-layer MDT capabilities,
23526  * or NULL if MDT is to be disabled on the stream.
23527  */
23528 mblk_t *
23529 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23530 {
23531 	mblk_t *mp;
23532 	ip_mdt_info_t *mdti;
23533 	ill_mdt_capab_t *idst;
23534 
23535 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23536 		DB_TYPE(mp) = M_CTL;
23537 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23538 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23539 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23540 		idst = &(mdti->mdt_capab);
23541 
23542 		/*
23543 		 * If the caller provides us with the capability, copy
23544 		 * it over into our notification message; otherwise
23545 		 * we zero out the capability portion.
23546 		 */
23547 		if (isrc != NULL)
23548 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23549 		else
23550 			bzero((caddr_t)idst, sizeof (*idst));
23551 	}
23552 	return (mp);
23553 }
23554 
23555 /*
23556  * Routine which determines whether MDT can be enabled on the destination
23557  * IRE and IPC combination, and if so, allocates and returns the MDT
23558  * notification mblk that may be used by ULP.  We also check if we need to
23559  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23560  * MDT usage in the past have been lifted.  This gets called during IP
23561  * and ULP binding.
23562  */
23563 mblk_t *
23564 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23565     ill_mdt_capab_t *mdt_cap)
23566 {
23567 	mblk_t *mp;
23568 	boolean_t rc = B_FALSE;
23569 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23570 
23571 	ASSERT(dst_ire != NULL);
23572 	ASSERT(connp != NULL);
23573 	ASSERT(mdt_cap != NULL);
23574 
23575 	/*
23576 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23577 	 * Multidata, which is handled in tcp_multisend().  This
23578 	 * is the reason why we do all these checks here, to ensure
23579 	 * that we don't enable Multidata for the cases which we
23580 	 * can't handle at the moment.
23581 	 */
23582 	do {
23583 		/* Only do TCP at the moment */
23584 		if (connp->conn_ulp != IPPROTO_TCP)
23585 			break;
23586 
23587 		/*
23588 		 * IPsec outbound policy present?  Note that we get here
23589 		 * after calling ipsec_conn_cache_policy() where the global
23590 		 * policy checking is performed.  conn_latch will be
23591 		 * non-NULL as long as there's a policy defined,
23592 		 * i.e. conn_out_enforce_policy may be NULL in such case
23593 		 * when the connection is non-secure, and hence we check
23594 		 * further if the latch refers to an outbound policy.
23595 		 */
23596 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23597 			break;
23598 
23599 		/* CGTP (multiroute) is enabled? */
23600 		if (dst_ire->ire_flags & RTF_MULTIRT)
23601 			break;
23602 
23603 		/* Outbound IPQoS enabled? */
23604 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23605 			/*
23606 			 * In this case, we disable MDT for this and all
23607 			 * future connections going over the interface.
23608 			 */
23609 			mdt_cap->ill_mdt_on = 0;
23610 			break;
23611 		}
23612 
23613 		/* socket option(s) present? */
23614 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23615 			break;
23616 
23617 		rc = B_TRUE;
23618 	/* CONSTCOND */
23619 	} while (0);
23620 
23621 	/* Remember the result */
23622 	connp->conn_mdt_ok = rc;
23623 
23624 	if (!rc)
23625 		return (NULL);
23626 	else if (!mdt_cap->ill_mdt_on) {
23627 		/*
23628 		 * If MDT has been previously turned off in the past, and we
23629 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23630 		 * then enable it for this interface.
23631 		 */
23632 		mdt_cap->ill_mdt_on = 1;
23633 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23634 		    "interface %s\n", ill_name));
23635 	}
23636 
23637 	/* Allocate the MDT info mblk */
23638 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23639 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23640 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23641 		return (NULL);
23642 	}
23643 	return (mp);
23644 }
23645 
23646 /*
23647  * Routine to allocate a message that is used to notify the ULP about LSO.
23648  * The caller may provide a pointer to the link-layer LSO capabilities,
23649  * or NULL if LSO is to be disabled on the stream.
23650  */
23651 mblk_t *
23652 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23653 {
23654 	mblk_t *mp;
23655 	ip_lso_info_t *lsoi;
23656 	ill_lso_capab_t *idst;
23657 
23658 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23659 		DB_TYPE(mp) = M_CTL;
23660 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23661 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23662 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23663 		idst = &(lsoi->lso_capab);
23664 
23665 		/*
23666 		 * If the caller provides us with the capability, copy
23667 		 * it over into our notification message; otherwise
23668 		 * we zero out the capability portion.
23669 		 */
23670 		if (isrc != NULL)
23671 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23672 		else
23673 			bzero((caddr_t)idst, sizeof (*idst));
23674 	}
23675 	return (mp);
23676 }
23677 
23678 /*
23679  * Routine which determines whether LSO can be enabled on the destination
23680  * IRE and IPC combination, and if so, allocates and returns the LSO
23681  * notification mblk that may be used by ULP.  We also check if we need to
23682  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23683  * LSO usage in the past have been lifted.  This gets called during IP
23684  * and ULP binding.
23685  */
23686 mblk_t *
23687 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23688     ill_lso_capab_t *lso_cap)
23689 {
23690 	mblk_t *mp;
23691 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23692 
23693 	ASSERT(dst_ire != NULL);
23694 	ASSERT(connp != NULL);
23695 	ASSERT(lso_cap != NULL);
23696 
23697 	connp->conn_lso_ok = B_TRUE;
23698 
23699 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23700 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23701 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23702 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23703 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23704 		connp->conn_lso_ok = B_FALSE;
23705 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23706 			/*
23707 			 * Disable LSO for this and all future connections going
23708 			 * over the interface.
23709 			 */
23710 			lso_cap->ill_lso_on = 0;
23711 		}
23712 	}
23713 
23714 	if (!connp->conn_lso_ok)
23715 		return (NULL);
23716 	else if (!lso_cap->ill_lso_on) {
23717 		/*
23718 		 * If LSO has been previously turned off in the past, and we
23719 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23720 		 * then enable it for this interface.
23721 		 */
23722 		lso_cap->ill_lso_on = 1;
23723 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23724 		    ill_name));
23725 	}
23726 
23727 	/* Allocate the LSO info mblk */
23728 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23729 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23730 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23731 
23732 	return (mp);
23733 }
23734 
23735 /*
23736  * Create destination address attribute, and fill it with the physical
23737  * destination address and SAP taken from the template DL_UNITDATA_REQ
23738  * message block.
23739  */
23740 boolean_t
23741 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23742 {
23743 	dl_unitdata_req_t *dlurp;
23744 	pattr_t *pa;
23745 	pattrinfo_t pa_info;
23746 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23747 	uint_t das_len, das_off;
23748 
23749 	ASSERT(dlmp != NULL);
23750 
23751 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23752 	das_len = dlurp->dl_dest_addr_length;
23753 	das_off = dlurp->dl_dest_addr_offset;
23754 
23755 	pa_info.type = PATTR_DSTADDRSAP;
23756 	pa_info.len = sizeof (**das) + das_len - 1;
23757 
23758 	/* create and associate the attribute */
23759 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23760 	if (pa != NULL) {
23761 		ASSERT(*das != NULL);
23762 		(*das)->addr_is_group = 0;
23763 		(*das)->addr_len = (uint8_t)das_len;
23764 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23765 	}
23766 
23767 	return (pa != NULL);
23768 }
23769 
23770 /*
23771  * Create hardware checksum attribute and fill it with the values passed.
23772  */
23773 boolean_t
23774 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23775     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23776 {
23777 	pattr_t *pa;
23778 	pattrinfo_t pa_info;
23779 
23780 	ASSERT(mmd != NULL);
23781 
23782 	pa_info.type = PATTR_HCKSUM;
23783 	pa_info.len = sizeof (pattr_hcksum_t);
23784 
23785 	/* create and associate the attribute */
23786 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23787 	if (pa != NULL) {
23788 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23789 
23790 		hck->hcksum_start_offset = start_offset;
23791 		hck->hcksum_stuff_offset = stuff_offset;
23792 		hck->hcksum_end_offset = end_offset;
23793 		hck->hcksum_flags = flags;
23794 	}
23795 	return (pa != NULL);
23796 }
23797 
23798 /*
23799  * Create zerocopy attribute and fill it with the specified flags
23800  */
23801 boolean_t
23802 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23803 {
23804 	pattr_t *pa;
23805 	pattrinfo_t pa_info;
23806 
23807 	ASSERT(mmd != NULL);
23808 	pa_info.type = PATTR_ZCOPY;
23809 	pa_info.len = sizeof (pattr_zcopy_t);
23810 
23811 	/* create and associate the attribute */
23812 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23813 	if (pa != NULL) {
23814 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23815 
23816 		zcopy->zcopy_flags = flags;
23817 	}
23818 	return (pa != NULL);
23819 }
23820 
23821 /*
23822  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23823  * block chain. We could rewrite to handle arbitrary message block chains but
23824  * that would make the code complicated and slow. Right now there three
23825  * restrictions:
23826  *
23827  *   1. The first message block must contain the complete IP header and
23828  *	at least 1 byte of payload data.
23829  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23830  *	so that we can use a single Multidata message.
23831  *   3. No frag must be distributed over two or more message blocks so
23832  *	that we don't need more than two packet descriptors per frag.
23833  *
23834  * The above restrictions allow us to support userland applications (which
23835  * will send down a single message block) and NFS over UDP (which will
23836  * send down a chain of at most three message blocks).
23837  *
23838  * We also don't use MDT for payloads with less than or equal to
23839  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23840  */
23841 boolean_t
23842 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23843 {
23844 	int	blocks;
23845 	ssize_t	total, missing, size;
23846 
23847 	ASSERT(mp != NULL);
23848 	ASSERT(hdr_len > 0);
23849 
23850 	size = MBLKL(mp) - hdr_len;
23851 	if (size <= 0)
23852 		return (B_FALSE);
23853 
23854 	/* The first mblk contains the header and some payload. */
23855 	blocks = 1;
23856 	total = size;
23857 	size %= len;
23858 	missing = (size == 0) ? 0 : (len - size);
23859 	mp = mp->b_cont;
23860 
23861 	while (mp != NULL) {
23862 		/*
23863 		 * Give up if we encounter a zero length message block.
23864 		 * In practice, this should rarely happen and therefore
23865 		 * not worth the trouble of freeing and re-linking the
23866 		 * mblk from the chain to handle such case.
23867 		 */
23868 		if ((size = MBLKL(mp)) == 0)
23869 			return (B_FALSE);
23870 
23871 		/* Too many payload buffers for a single Multidata message? */
23872 		if (++blocks > MULTIDATA_MAX_PBUFS)
23873 			return (B_FALSE);
23874 
23875 		total += size;
23876 		/* Is a frag distributed over two or more message blocks? */
23877 		if (missing > size)
23878 			return (B_FALSE);
23879 		size -= missing;
23880 
23881 		size %= len;
23882 		missing = (size == 0) ? 0 : (len - size);
23883 
23884 		mp = mp->b_cont;
23885 	}
23886 
23887 	return (total > ip_wput_frag_mdt_min);
23888 }
23889 
23890 /*
23891  * Outbound IPv4 fragmentation routine using MDT.
23892  */
23893 static void
23894 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23895     uint32_t frag_flag, int offset)
23896 {
23897 	ipha_t		*ipha_orig;
23898 	int		i1, ip_data_end;
23899 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23900 	mblk_t		*hdr_mp, *md_mp = NULL;
23901 	unsigned char	*hdr_ptr, *pld_ptr;
23902 	multidata_t	*mmd;
23903 	ip_pdescinfo_t	pdi;
23904 	ill_t		*ill;
23905 	ip_stack_t	*ipst = ire->ire_ipst;
23906 
23907 	ASSERT(DB_TYPE(mp) == M_DATA);
23908 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23909 
23910 	ill = ire_to_ill(ire);
23911 	ASSERT(ill != NULL);
23912 
23913 	ipha_orig = (ipha_t *)mp->b_rptr;
23914 	mp->b_rptr += sizeof (ipha_t);
23915 
23916 	/* Calculate how many packets we will send out */
23917 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23918 	pkts = (i1 + len - 1) / len;
23919 	ASSERT(pkts > 1);
23920 
23921 	/* Allocate a message block which will hold all the IP Headers. */
23922 	wroff = ipst->ips_ip_wroff_extra;
23923 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23924 
23925 	i1 = pkts * hdr_chunk_len;
23926 	/*
23927 	 * Create the header buffer, Multidata and destination address
23928 	 * and SAP attribute that should be associated with it.
23929 	 */
23930 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23931 	    ((hdr_mp->b_wptr += i1),
23932 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23933 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23934 		freemsg(mp);
23935 		if (md_mp == NULL) {
23936 			freemsg(hdr_mp);
23937 		} else {
23938 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
23939 			freemsg(md_mp);
23940 		}
23941 		IP_STAT(ipst, ip_frag_mdt_allocfail);
23942 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
23943 		return;
23944 	}
23945 	IP_STAT(ipst, ip_frag_mdt_allocd);
23946 
23947 	/*
23948 	 * Add a payload buffer to the Multidata; this operation must not
23949 	 * fail, or otherwise our logic in this routine is broken.  There
23950 	 * is no memory allocation done by the routine, so any returned
23951 	 * failure simply tells us that we've done something wrong.
23952 	 *
23953 	 * A failure tells us that either we're adding the same payload
23954 	 * buffer more than once, or we're trying to add more buffers than
23955 	 * allowed.  None of the above cases should happen, and we panic
23956 	 * because either there's horrible heap corruption, and/or
23957 	 * programming mistake.
23958 	 */
23959 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23960 		goto pbuf_panic;
23961 
23962 	hdr_ptr = hdr_mp->b_rptr;
23963 	pld_ptr = mp->b_rptr;
23964 
23965 	/* Establish the ending byte offset, based on the starting offset. */
23966 	offset <<= 3;
23967 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23968 	    IP_SIMPLE_HDR_LENGTH;
23969 
23970 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23971 
23972 	while (pld_ptr < mp->b_wptr) {
23973 		ipha_t		*ipha;
23974 		uint16_t	offset_and_flags;
23975 		uint16_t	ip_len;
23976 		int		error;
23977 
23978 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23979 		ipha = (ipha_t *)(hdr_ptr + wroff);
23980 		ASSERT(OK_32PTR(ipha));
23981 		*ipha = *ipha_orig;
23982 
23983 		if (ip_data_end - offset > len) {
23984 			offset_and_flags = IPH_MF;
23985 		} else {
23986 			/*
23987 			 * Last frag. Set len to the length of this last piece.
23988 			 */
23989 			len = ip_data_end - offset;
23990 			/* A frag of a frag might have IPH_MF non-zero */
23991 			offset_and_flags =
23992 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23993 			    IPH_MF;
23994 		}
23995 		offset_and_flags |= (uint16_t)(offset >> 3);
23996 		offset_and_flags |= (uint16_t)frag_flag;
23997 		/* Store the offset and flags in the IP header. */
23998 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23999 
24000 		/* Store the length in the IP header. */
24001 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
24002 		ipha->ipha_length = htons(ip_len);
24003 
24004 		/*
24005 		 * Set the IP header checksum.  Note that mp is just
24006 		 * the header, so this is easy to pass to ip_csum.
24007 		 */
24008 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24009 
24010 		DTRACE_IP7(send, mblk_t *, md_mp, conn_t *, NULL, void_ip_t *,
24011 		    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *,
24012 		    NULL, int, 0);
24013 
24014 		/*
24015 		 * Record offset and size of header and data of the next packet
24016 		 * in the multidata message.
24017 		 */
24018 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
24019 		PDESC_PLD_INIT(&pdi);
24020 		i1 = MIN(mp->b_wptr - pld_ptr, len);
24021 		ASSERT(i1 > 0);
24022 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
24023 		if (i1 == len) {
24024 			pld_ptr += len;
24025 		} else {
24026 			i1 = len - i1;
24027 			mp = mp->b_cont;
24028 			ASSERT(mp != NULL);
24029 			ASSERT(MBLKL(mp) >= i1);
24030 			/*
24031 			 * Attach the next payload message block to the
24032 			 * multidata message.
24033 			 */
24034 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24035 				goto pbuf_panic;
24036 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
24037 			pld_ptr = mp->b_rptr + i1;
24038 		}
24039 
24040 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
24041 		    KM_NOSLEEP)) == NULL) {
24042 			/*
24043 			 * Any failure other than ENOMEM indicates that we
24044 			 * have passed in invalid pdesc info or parameters
24045 			 * to mmd_addpdesc, which must not happen.
24046 			 *
24047 			 * EINVAL is a result of failure on boundary checks
24048 			 * against the pdesc info contents.  It should not
24049 			 * happen, and we panic because either there's
24050 			 * horrible heap corruption, and/or programming
24051 			 * mistake.
24052 			 */
24053 			if (error != ENOMEM) {
24054 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
24055 				    "pdesc logic error detected for "
24056 				    "mmd %p pinfo %p (%d)\n",
24057 				    (void *)mmd, (void *)&pdi, error);
24058 				/* NOTREACHED */
24059 			}
24060 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
24061 			/* Free unattached payload message blocks as well */
24062 			md_mp->b_cont = mp->b_cont;
24063 			goto free_mmd;
24064 		}
24065 
24066 		/* Advance fragment offset. */
24067 		offset += len;
24068 
24069 		/* Advance to location for next header in the buffer. */
24070 		hdr_ptr += hdr_chunk_len;
24071 
24072 		/* Did we reach the next payload message block? */
24073 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
24074 			mp = mp->b_cont;
24075 			/*
24076 			 * Attach the next message block with payload
24077 			 * data to the multidata message.
24078 			 */
24079 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24080 				goto pbuf_panic;
24081 			pld_ptr = mp->b_rptr;
24082 		}
24083 	}
24084 
24085 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
24086 	ASSERT(mp->b_wptr == pld_ptr);
24087 
24088 	/* Update IP statistics */
24089 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
24090 
24091 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
24092 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
24093 
24094 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
24095 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
24096 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
24097 
24098 	if (pkt_type == OB_PKT) {
24099 		ire->ire_ob_pkt_count += pkts;
24100 		if (ire->ire_ipif != NULL)
24101 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
24102 	} else {
24103 		/* The type is IB_PKT in the forwarding path. */
24104 		ire->ire_ib_pkt_count += pkts;
24105 		ASSERT(!IRE_IS_LOCAL(ire));
24106 		if (ire->ire_type & IRE_BROADCAST) {
24107 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
24108 		} else {
24109 			UPDATE_MIB(ill->ill_ip_mib,
24110 			    ipIfStatsHCOutForwDatagrams, pkts);
24111 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
24112 		}
24113 	}
24114 	ire->ire_last_used_time = lbolt;
24115 	/* Send it down */
24116 	putnext(ire->ire_stq, md_mp);
24117 	return;
24118 
24119 pbuf_panic:
24120 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
24121 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
24122 	    pbuf_idx);
24123 	/* NOTREACHED */
24124 }
24125 
24126 /*
24127  * Outbound IP fragmentation routine.
24128  *
24129  * NOTE : This routine does not ire_refrele the ire that is passed in
24130  * as the argument.
24131  */
24132 static void
24133 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
24134     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst)
24135 {
24136 	int		i1;
24137 	mblk_t		*ll_hdr_mp;
24138 	int 		ll_hdr_len;
24139 	int		hdr_len;
24140 	mblk_t		*hdr_mp;
24141 	ipha_t		*ipha;
24142 	int		ip_data_end;
24143 	int		len;
24144 	mblk_t		*mp = mp_orig, *mp1;
24145 	int		offset;
24146 	queue_t		*q;
24147 	uint32_t	v_hlen_tos_len;
24148 	mblk_t		*first_mp;
24149 	boolean_t	mctl_present;
24150 	ill_t		*ill;
24151 	ill_t		*out_ill;
24152 	mblk_t		*xmit_mp;
24153 	mblk_t		*carve_mp;
24154 	ire_t		*ire1 = NULL;
24155 	ire_t		*save_ire = NULL;
24156 	mblk_t  	*next_mp = NULL;
24157 	boolean_t	last_frag = B_FALSE;
24158 	boolean_t	multirt_send = B_FALSE;
24159 	ire_t		*first_ire = NULL;
24160 	irb_t		*irb = NULL;
24161 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24162 
24163 	ill = ire_to_ill(ire);
24164 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24165 
24166 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24167 
24168 	if (max_frag == 0) {
24169 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24170 		    " -  dropping packet\n"));
24171 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24172 		freemsg(mp);
24173 		return;
24174 	}
24175 
24176 	/*
24177 	 * IPsec does not allow hw accelerated packets to be fragmented
24178 	 * This check is made in ip_wput_ipsec_out prior to coming here
24179 	 * via ip_wput_ire_fragmentit.
24180 	 *
24181 	 * If at this point we have an ire whose ARP request has not
24182 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24183 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24184 	 * This packet and all fragmentable packets for this ire will
24185 	 * continue to get dropped while ire_nce->nce_state remains in
24186 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24187 	 * ND_REACHABLE, all subsquent large packets for this ire will
24188 	 * get fragemented and sent out by this function.
24189 	 */
24190 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24191 		/* If nce_state is ND_INITIAL, trigger ARP query */
24192 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
24193 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24194 		    " -  dropping packet\n"));
24195 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24196 		freemsg(mp);
24197 		return;
24198 	}
24199 
24200 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24201 	    "ip_wput_frag_start:");
24202 
24203 	if (mp->b_datap->db_type == M_CTL) {
24204 		first_mp = mp;
24205 		mp_orig = mp = mp->b_cont;
24206 		mctl_present = B_TRUE;
24207 	} else {
24208 		first_mp = mp;
24209 		mctl_present = B_FALSE;
24210 	}
24211 
24212 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24213 	ipha = (ipha_t *)mp->b_rptr;
24214 
24215 	/*
24216 	 * If the Don't Fragment flag is on, generate an ICMP destination
24217 	 * unreachable, fragmentation needed.
24218 	 */
24219 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24220 	if (offset & IPH_DF) {
24221 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24222 		if (is_system_labeled()) {
24223 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24224 			    ire->ire_max_frag - max_frag, AF_INET);
24225 		}
24226 		/*
24227 		 * Need to compute hdr checksum if called from ip_wput_ire.
24228 		 * Note that ip_rput_forward verifies the checksum before
24229 		 * calling this routine so in that case this is a noop.
24230 		 */
24231 		ipha->ipha_hdr_checksum = 0;
24232 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24233 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24234 		    ipst);
24235 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24236 		    "ip_wput_frag_end:(%S)",
24237 		    "don't fragment");
24238 		return;
24239 	}
24240 	/*
24241 	 * Labeled systems adjust max_frag if they add a label
24242 	 * to send the correct path mtu.  We need the real mtu since we
24243 	 * are fragmenting the packet after label adjustment.
24244 	 */
24245 	if (is_system_labeled())
24246 		max_frag = ire->ire_max_frag;
24247 	if (mctl_present)
24248 		freeb(first_mp);
24249 	/*
24250 	 * Establish the starting offset.  May not be zero if we are fragging
24251 	 * a fragment that is being forwarded.
24252 	 */
24253 	offset = offset & IPH_OFFSET;
24254 
24255 	/* TODO why is this test needed? */
24256 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24257 	if (((max_frag - LENGTH) & ~7) < 8) {
24258 		/* TODO: notify ulp somehow */
24259 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24260 		freemsg(mp);
24261 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24262 		    "ip_wput_frag_end:(%S)",
24263 		    "len < 8");
24264 		return;
24265 	}
24266 
24267 	hdr_len = (V_HLEN & 0xF) << 2;
24268 
24269 	ipha->ipha_hdr_checksum = 0;
24270 
24271 	/*
24272 	 * Establish the number of bytes maximum per frag, after putting
24273 	 * in the header.
24274 	 */
24275 	len = (max_frag - hdr_len) & ~7;
24276 
24277 	/* Check if we can use MDT to send out the frags. */
24278 	ASSERT(!IRE_IS_LOCAL(ire));
24279 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24280 	    ipst->ips_ip_multidata_outbound &&
24281 	    !(ire->ire_flags & RTF_MULTIRT) &&
24282 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24283 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24284 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24285 		ASSERT(ill->ill_mdt_capab != NULL);
24286 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24287 			/*
24288 			 * If MDT has been previously turned off in the past,
24289 			 * and we currently can do MDT (due to IPQoS policy
24290 			 * removal, etc.) then enable it for this interface.
24291 			 */
24292 			ill->ill_mdt_capab->ill_mdt_on = 1;
24293 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24294 			    ill->ill_name));
24295 		}
24296 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24297 		    offset);
24298 		return;
24299 	}
24300 
24301 	/* Get a copy of the header for the trailing frags */
24302 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst);
24303 	if (!hdr_mp) {
24304 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24305 		freemsg(mp);
24306 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24307 		    "ip_wput_frag_end:(%S)",
24308 		    "couldn't copy hdr");
24309 		return;
24310 	}
24311 	if (DB_CRED(mp) != NULL)
24312 		mblk_setcred(hdr_mp, DB_CRED(mp));
24313 
24314 	/* Store the starting offset, with the MoreFrags flag. */
24315 	i1 = offset | IPH_MF | frag_flag;
24316 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24317 
24318 	/* Establish the ending byte offset, based on the starting offset. */
24319 	offset <<= 3;
24320 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24321 
24322 	/* Store the length of the first fragment in the IP header. */
24323 	i1 = len + hdr_len;
24324 	ASSERT(i1 <= IP_MAXPACKET);
24325 	ipha->ipha_length = htons((uint16_t)i1);
24326 
24327 	/*
24328 	 * Compute the IP header checksum for the first frag.  We have to
24329 	 * watch out that we stop at the end of the header.
24330 	 */
24331 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24332 
24333 	/*
24334 	 * Now carve off the first frag.  Note that this will include the
24335 	 * original IP header.
24336 	 */
24337 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24338 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24339 		freeb(hdr_mp);
24340 		freemsg(mp_orig);
24341 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24342 		    "ip_wput_frag_end:(%S)",
24343 		    "couldn't carve first");
24344 		return;
24345 	}
24346 
24347 	/*
24348 	 * Multirouting case. Each fragment is replicated
24349 	 * via all non-condemned RTF_MULTIRT routes
24350 	 * currently resolved.
24351 	 * We ensure that first_ire is the first RTF_MULTIRT
24352 	 * ire in the bucket.
24353 	 */
24354 	if (ire->ire_flags & RTF_MULTIRT) {
24355 		irb = ire->ire_bucket;
24356 		ASSERT(irb != NULL);
24357 
24358 		multirt_send = B_TRUE;
24359 
24360 		/* Make sure we do not omit any multiroute ire. */
24361 		IRB_REFHOLD(irb);
24362 		for (first_ire = irb->irb_ire;
24363 		    first_ire != NULL;
24364 		    first_ire = first_ire->ire_next) {
24365 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24366 			    (first_ire->ire_addr == ire->ire_addr) &&
24367 			    !(first_ire->ire_marks &
24368 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
24369 				break;
24370 			}
24371 		}
24372 
24373 		if (first_ire != NULL) {
24374 			if (first_ire != ire) {
24375 				IRE_REFHOLD(first_ire);
24376 				/*
24377 				 * Do not release the ire passed in
24378 				 * as the argument.
24379 				 */
24380 				ire = first_ire;
24381 			} else {
24382 				first_ire = NULL;
24383 			}
24384 		}
24385 		IRB_REFRELE(irb);
24386 
24387 		/*
24388 		 * Save the first ire; we will need to restore it
24389 		 * for the trailing frags.
24390 		 * We REFHOLD save_ire, as each iterated ire will be
24391 		 * REFRELEd.
24392 		 */
24393 		save_ire = ire;
24394 		IRE_REFHOLD(save_ire);
24395 	}
24396 
24397 	/*
24398 	 * First fragment emission loop.
24399 	 * In most cases, the emission loop below is entered only
24400 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24401 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24402 	 * bucket, and send the fragment through all crossed
24403 	 * RTF_MULTIRT routes.
24404 	 */
24405 	do {
24406 		if (ire->ire_flags & RTF_MULTIRT) {
24407 			/*
24408 			 * We are in a multiple send case, need to get
24409 			 * the next ire and make a copy of the packet.
24410 			 * ire1 holds here the next ire to process in the
24411 			 * bucket. If multirouting is expected,
24412 			 * any non-RTF_MULTIRT ire that has the
24413 			 * right destination address is ignored.
24414 			 *
24415 			 * We have to take into account the MTU of
24416 			 * each walked ire. max_frag is set by the
24417 			 * the caller and generally refers to
24418 			 * the primary ire entry. Here we ensure that
24419 			 * no route with a lower MTU will be used, as
24420 			 * fragments are carved once for all ires,
24421 			 * then replicated.
24422 			 */
24423 			ASSERT(irb != NULL);
24424 			IRB_REFHOLD(irb);
24425 			for (ire1 = ire->ire_next;
24426 			    ire1 != NULL;
24427 			    ire1 = ire1->ire_next) {
24428 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24429 					continue;
24430 				if (ire1->ire_addr != ire->ire_addr)
24431 					continue;
24432 				if (ire1->ire_marks &
24433 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24434 					continue;
24435 				/*
24436 				 * Ensure we do not exceed the MTU
24437 				 * of the next route.
24438 				 */
24439 				if (ire1->ire_max_frag < max_frag) {
24440 					ip_multirt_bad_mtu(ire1, max_frag);
24441 					continue;
24442 				}
24443 
24444 				/* Got one. */
24445 				IRE_REFHOLD(ire1);
24446 				break;
24447 			}
24448 			IRB_REFRELE(irb);
24449 
24450 			if (ire1 != NULL) {
24451 				next_mp = copyb(mp);
24452 				if ((next_mp == NULL) ||
24453 				    ((mp->b_cont != NULL) &&
24454 				    ((next_mp->b_cont =
24455 				    dupmsg(mp->b_cont)) == NULL))) {
24456 					freemsg(next_mp);
24457 					next_mp = NULL;
24458 					ire_refrele(ire1);
24459 					ire1 = NULL;
24460 				}
24461 			}
24462 
24463 			/* Last multiroute ire; don't loop anymore. */
24464 			if (ire1 == NULL) {
24465 				multirt_send = B_FALSE;
24466 			}
24467 		}
24468 
24469 		ll_hdr_len = 0;
24470 		LOCK_IRE_FP_MP(ire);
24471 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24472 		if (ll_hdr_mp != NULL) {
24473 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24474 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24475 		} else {
24476 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24477 		}
24478 
24479 		/* If there is a transmit header, get a copy for this frag. */
24480 		/*
24481 		 * TODO: should check db_ref before calling ip_carve_mp since
24482 		 * it might give us a dup.
24483 		 */
24484 		if (!ll_hdr_mp) {
24485 			/* No xmit header. */
24486 			xmit_mp = mp;
24487 
24488 		/* We have a link-layer header that can fit in our mblk. */
24489 		} else if (mp->b_datap->db_ref == 1 &&
24490 		    ll_hdr_len != 0 &&
24491 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24492 			/* M_DATA fastpath */
24493 			mp->b_rptr -= ll_hdr_len;
24494 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24495 			xmit_mp = mp;
24496 
24497 		/* Corner case if copyb has failed */
24498 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24499 			UNLOCK_IRE_FP_MP(ire);
24500 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24501 			freeb(hdr_mp);
24502 			freemsg(mp);
24503 			freemsg(mp_orig);
24504 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24505 			    "ip_wput_frag_end:(%S)",
24506 			    "discard");
24507 
24508 			if (multirt_send) {
24509 				ASSERT(ire1);
24510 				ASSERT(next_mp);
24511 
24512 				freemsg(next_mp);
24513 				ire_refrele(ire1);
24514 			}
24515 			if (save_ire != NULL)
24516 				IRE_REFRELE(save_ire);
24517 
24518 			if (first_ire != NULL)
24519 				ire_refrele(first_ire);
24520 			return;
24521 
24522 		/*
24523 		 * Case of res_mp OR the fastpath mp can't fit
24524 		 * in the mblk
24525 		 */
24526 		} else {
24527 			xmit_mp->b_cont = mp;
24528 			if (DB_CRED(mp) != NULL)
24529 				mblk_setcred(xmit_mp, DB_CRED(mp));
24530 			/*
24531 			 * Get priority marking, if any.
24532 			 * We propagate the CoS marking from the
24533 			 * original packet that went to QoS processing
24534 			 * in ip_wput_ire to the newly carved mp.
24535 			 */
24536 			if (DB_TYPE(xmit_mp) == M_DATA)
24537 				xmit_mp->b_band = mp->b_band;
24538 		}
24539 		UNLOCK_IRE_FP_MP(ire);
24540 
24541 		q = ire->ire_stq;
24542 		out_ill = (ill_t *)q->q_ptr;
24543 
24544 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24545 
24546 		DTRACE_PROBE4(ip4__physical__out__start,
24547 		    ill_t *, NULL, ill_t *, out_ill,
24548 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24549 
24550 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24551 		    ipst->ips_ipv4firewall_physical_out,
24552 		    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24553 
24554 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24555 
24556 		if (xmit_mp != NULL) {
24557 			DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *, NULL,
24558 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
24559 			    ipha_t *, ipha, ip6_t *, NULL, int, 0);
24560 
24561 			putnext(q, xmit_mp);
24562 
24563 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24564 			UPDATE_MIB(out_ill->ill_ip_mib,
24565 			    ipIfStatsHCOutOctets, i1);
24566 
24567 			if (pkt_type != OB_PKT) {
24568 				/*
24569 				 * Update the packet count and MIB stats
24570 				 * of trailing RTF_MULTIRT ires.
24571 				 */
24572 				UPDATE_OB_PKT_COUNT(ire);
24573 				BUMP_MIB(out_ill->ill_ip_mib,
24574 				    ipIfStatsOutFragReqds);
24575 			}
24576 		}
24577 
24578 		if (multirt_send) {
24579 			/*
24580 			 * We are in a multiple send case; look for
24581 			 * the next ire and re-enter the loop.
24582 			 */
24583 			ASSERT(ire1);
24584 			ASSERT(next_mp);
24585 			/* REFRELE the current ire before looping */
24586 			ire_refrele(ire);
24587 			ire = ire1;
24588 			ire1 = NULL;
24589 			mp = next_mp;
24590 			next_mp = NULL;
24591 		}
24592 	} while (multirt_send);
24593 
24594 	ASSERT(ire1 == NULL);
24595 
24596 	/* Restore the original ire; we need it for the trailing frags */
24597 	if (save_ire != NULL) {
24598 		/* REFRELE the last iterated ire */
24599 		ire_refrele(ire);
24600 		/* save_ire has been REFHOLDed */
24601 		ire = save_ire;
24602 		save_ire = NULL;
24603 		q = ire->ire_stq;
24604 	}
24605 
24606 	if (pkt_type == OB_PKT) {
24607 		UPDATE_OB_PKT_COUNT(ire);
24608 	} else {
24609 		out_ill = (ill_t *)q->q_ptr;
24610 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24611 		UPDATE_IB_PKT_COUNT(ire);
24612 	}
24613 
24614 	/* Advance the offset to the second frag starting point. */
24615 	offset += len;
24616 	/*
24617 	 * Update hdr_len from the copied header - there might be less options
24618 	 * in the later fragments.
24619 	 */
24620 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24621 	/* Loop until done. */
24622 	for (;;) {
24623 		uint16_t	offset_and_flags;
24624 		uint16_t	ip_len;
24625 
24626 		if (ip_data_end - offset > len) {
24627 			/*
24628 			 * Carve off the appropriate amount from the original
24629 			 * datagram.
24630 			 */
24631 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24632 				mp = NULL;
24633 				break;
24634 			}
24635 			/*
24636 			 * More frags after this one.  Get another copy
24637 			 * of the header.
24638 			 */
24639 			if (carve_mp->b_datap->db_ref == 1 &&
24640 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24641 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24642 				/* Inline IP header */
24643 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24644 				    hdr_mp->b_rptr;
24645 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24646 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24647 				mp = carve_mp;
24648 			} else {
24649 				if (!(mp = copyb(hdr_mp))) {
24650 					freemsg(carve_mp);
24651 					break;
24652 				}
24653 				/* Get priority marking, if any. */
24654 				mp->b_band = carve_mp->b_band;
24655 				mp->b_cont = carve_mp;
24656 			}
24657 			ipha = (ipha_t *)mp->b_rptr;
24658 			offset_and_flags = IPH_MF;
24659 		} else {
24660 			/*
24661 			 * Last frag.  Consume the header. Set len to
24662 			 * the length of this last piece.
24663 			 */
24664 			len = ip_data_end - offset;
24665 
24666 			/*
24667 			 * Carve off the appropriate amount from the original
24668 			 * datagram.
24669 			 */
24670 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24671 				mp = NULL;
24672 				break;
24673 			}
24674 			if (carve_mp->b_datap->db_ref == 1 &&
24675 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24676 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24677 				/* Inline IP header */
24678 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24679 				    hdr_mp->b_rptr;
24680 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24681 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24682 				mp = carve_mp;
24683 				freeb(hdr_mp);
24684 				hdr_mp = mp;
24685 			} else {
24686 				mp = hdr_mp;
24687 				/* Get priority marking, if any. */
24688 				mp->b_band = carve_mp->b_band;
24689 				mp->b_cont = carve_mp;
24690 			}
24691 			ipha = (ipha_t *)mp->b_rptr;
24692 			/* A frag of a frag might have IPH_MF non-zero */
24693 			offset_and_flags =
24694 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24695 			    IPH_MF;
24696 		}
24697 		offset_and_flags |= (uint16_t)(offset >> 3);
24698 		offset_and_flags |= (uint16_t)frag_flag;
24699 		/* Store the offset and flags in the IP header. */
24700 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24701 
24702 		/* Store the length in the IP header. */
24703 		ip_len = (uint16_t)(len + hdr_len);
24704 		ipha->ipha_length = htons(ip_len);
24705 
24706 		/*
24707 		 * Set the IP header checksum.	Note that mp is just
24708 		 * the header, so this is easy to pass to ip_csum.
24709 		 */
24710 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24711 
24712 		/* Attach a transmit header, if any, and ship it. */
24713 		if (pkt_type == OB_PKT) {
24714 			UPDATE_OB_PKT_COUNT(ire);
24715 		} else {
24716 			out_ill = (ill_t *)q->q_ptr;
24717 			BUMP_MIB(out_ill->ill_ip_mib,
24718 			    ipIfStatsHCOutForwDatagrams);
24719 			UPDATE_IB_PKT_COUNT(ire);
24720 		}
24721 
24722 		if (ire->ire_flags & RTF_MULTIRT) {
24723 			irb = ire->ire_bucket;
24724 			ASSERT(irb != NULL);
24725 
24726 			multirt_send = B_TRUE;
24727 
24728 			/*
24729 			 * Save the original ire; we will need to restore it
24730 			 * for the tailing frags.
24731 			 */
24732 			save_ire = ire;
24733 			IRE_REFHOLD(save_ire);
24734 		}
24735 		/*
24736 		 * Emission loop for this fragment, similar
24737 		 * to what is done for the first fragment.
24738 		 */
24739 		do {
24740 			if (multirt_send) {
24741 				/*
24742 				 * We are in a multiple send case, need to get
24743 				 * the next ire and make a copy of the packet.
24744 				 */
24745 				ASSERT(irb != NULL);
24746 				IRB_REFHOLD(irb);
24747 				for (ire1 = ire->ire_next;
24748 				    ire1 != NULL;
24749 				    ire1 = ire1->ire_next) {
24750 					if (!(ire1->ire_flags & RTF_MULTIRT))
24751 						continue;
24752 					if (ire1->ire_addr != ire->ire_addr)
24753 						continue;
24754 					if (ire1->ire_marks &
24755 					    (IRE_MARK_CONDEMNED|
24756 					    IRE_MARK_HIDDEN)) {
24757 						continue;
24758 					}
24759 					/*
24760 					 * Ensure we do not exceed the MTU
24761 					 * of the next route.
24762 					 */
24763 					if (ire1->ire_max_frag < max_frag) {
24764 						ip_multirt_bad_mtu(ire1,
24765 						    max_frag);
24766 						continue;
24767 					}
24768 
24769 					/* Got one. */
24770 					IRE_REFHOLD(ire1);
24771 					break;
24772 				}
24773 				IRB_REFRELE(irb);
24774 
24775 				if (ire1 != NULL) {
24776 					next_mp = copyb(mp);
24777 					if ((next_mp == NULL) ||
24778 					    ((mp->b_cont != NULL) &&
24779 					    ((next_mp->b_cont =
24780 					    dupmsg(mp->b_cont)) == NULL))) {
24781 						freemsg(next_mp);
24782 						next_mp = NULL;
24783 						ire_refrele(ire1);
24784 						ire1 = NULL;
24785 					}
24786 				}
24787 
24788 				/* Last multiroute ire; don't loop anymore. */
24789 				if (ire1 == NULL) {
24790 					multirt_send = B_FALSE;
24791 				}
24792 			}
24793 
24794 			/* Update transmit header */
24795 			ll_hdr_len = 0;
24796 			LOCK_IRE_FP_MP(ire);
24797 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24798 			if (ll_hdr_mp != NULL) {
24799 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24800 				ll_hdr_len = MBLKL(ll_hdr_mp);
24801 			} else {
24802 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24803 			}
24804 
24805 			if (!ll_hdr_mp) {
24806 				xmit_mp = mp;
24807 
24808 			/*
24809 			 * We have link-layer header that can fit in
24810 			 * our mblk.
24811 			 */
24812 			} else if (mp->b_datap->db_ref == 1 &&
24813 			    ll_hdr_len != 0 &&
24814 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24815 				/* M_DATA fastpath */
24816 				mp->b_rptr -= ll_hdr_len;
24817 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24818 				    ll_hdr_len);
24819 				xmit_mp = mp;
24820 
24821 			/*
24822 			 * Case of res_mp OR the fastpath mp can't fit
24823 			 * in the mblk
24824 			 */
24825 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24826 				xmit_mp->b_cont = mp;
24827 				if (DB_CRED(mp) != NULL)
24828 					mblk_setcred(xmit_mp, DB_CRED(mp));
24829 				/* Get priority marking, if any. */
24830 				if (DB_TYPE(xmit_mp) == M_DATA)
24831 					xmit_mp->b_band = mp->b_band;
24832 
24833 			/* Corner case if copyb failed */
24834 			} else {
24835 				/*
24836 				 * Exit both the replication and
24837 				 * fragmentation loops.
24838 				 */
24839 				UNLOCK_IRE_FP_MP(ire);
24840 				goto drop_pkt;
24841 			}
24842 			UNLOCK_IRE_FP_MP(ire);
24843 
24844 			mp1 = mp;
24845 			out_ill = (ill_t *)q->q_ptr;
24846 
24847 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24848 
24849 			DTRACE_PROBE4(ip4__physical__out__start,
24850 			    ill_t *, NULL, ill_t *, out_ill,
24851 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24852 
24853 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24854 			    ipst->ips_ipv4firewall_physical_out,
24855 			    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24856 
24857 			DTRACE_PROBE1(ip4__physical__out__end,
24858 			    mblk_t *, xmit_mp);
24859 
24860 			if (mp != mp1 && hdr_mp == mp1)
24861 				hdr_mp = mp;
24862 			if (mp != mp1 && mp_orig == mp1)
24863 				mp_orig = mp;
24864 
24865 			if (xmit_mp != NULL) {
24866 				DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *,
24867 				    NULL, void_ip_t *, ipha,
24868 				    __dtrace_ipsr_ill_t *, out_ill, ipha_t *,
24869 				    ipha, ip6_t *, NULL, int, 0);
24870 
24871 				putnext(q, xmit_mp);
24872 
24873 				BUMP_MIB(out_ill->ill_ip_mib,
24874 				    ipIfStatsHCOutTransmits);
24875 				UPDATE_MIB(out_ill->ill_ip_mib,
24876 				    ipIfStatsHCOutOctets, ip_len);
24877 
24878 				if (pkt_type != OB_PKT) {
24879 					/*
24880 					 * Update the packet count of trailing
24881 					 * RTF_MULTIRT ires.
24882 					 */
24883 					UPDATE_OB_PKT_COUNT(ire);
24884 				}
24885 			}
24886 
24887 			/* All done if we just consumed the hdr_mp. */
24888 			if (mp == hdr_mp) {
24889 				last_frag = B_TRUE;
24890 				BUMP_MIB(out_ill->ill_ip_mib,
24891 				    ipIfStatsOutFragOKs);
24892 			}
24893 
24894 			if (multirt_send) {
24895 				/*
24896 				 * We are in a multiple send case; look for
24897 				 * the next ire and re-enter the loop.
24898 				 */
24899 				ASSERT(ire1);
24900 				ASSERT(next_mp);
24901 				/* REFRELE the current ire before looping */
24902 				ire_refrele(ire);
24903 				ire = ire1;
24904 				ire1 = NULL;
24905 				q = ire->ire_stq;
24906 				mp = next_mp;
24907 				next_mp = NULL;
24908 			}
24909 		} while (multirt_send);
24910 		/*
24911 		 * Restore the original ire; we need it for the
24912 		 * trailing frags
24913 		 */
24914 		if (save_ire != NULL) {
24915 			ASSERT(ire1 == NULL);
24916 			/* REFRELE the last iterated ire */
24917 			ire_refrele(ire);
24918 			/* save_ire has been REFHOLDed */
24919 			ire = save_ire;
24920 			q = ire->ire_stq;
24921 			save_ire = NULL;
24922 		}
24923 
24924 		if (last_frag) {
24925 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24926 			    "ip_wput_frag_end:(%S)",
24927 			    "consumed hdr_mp");
24928 
24929 			if (first_ire != NULL)
24930 				ire_refrele(first_ire);
24931 			return;
24932 		}
24933 		/* Otherwise, advance and loop. */
24934 		offset += len;
24935 	}
24936 
24937 drop_pkt:
24938 	/* Clean up following allocation failure. */
24939 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24940 	freemsg(mp);
24941 	if (mp != hdr_mp)
24942 		freeb(hdr_mp);
24943 	if (mp != mp_orig)
24944 		freemsg(mp_orig);
24945 
24946 	if (save_ire != NULL)
24947 		IRE_REFRELE(save_ire);
24948 	if (first_ire != NULL)
24949 		ire_refrele(first_ire);
24950 
24951 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24952 	    "ip_wput_frag_end:(%S)",
24953 	    "end--alloc failure");
24954 }
24955 
24956 /*
24957  * Copy the header plus those options which have the copy bit set
24958  */
24959 static mblk_t *
24960 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst)
24961 {
24962 	mblk_t	*mp;
24963 	uchar_t	*up;
24964 
24965 	/*
24966 	 * Quick check if we need to look for options without the copy bit
24967 	 * set
24968 	 */
24969 	mp = allocb(ipst->ips_ip_wroff_extra + hdr_len, BPRI_HI);
24970 	if (!mp)
24971 		return (mp);
24972 	mp->b_rptr += ipst->ips_ip_wroff_extra;
24973 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24974 		bcopy(rptr, mp->b_rptr, hdr_len);
24975 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
24976 		return (mp);
24977 	}
24978 	up  = mp->b_rptr;
24979 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24980 	up += IP_SIMPLE_HDR_LENGTH;
24981 	rptr += IP_SIMPLE_HDR_LENGTH;
24982 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24983 	while (hdr_len > 0) {
24984 		uint32_t optval;
24985 		uint32_t optlen;
24986 
24987 		optval = *rptr;
24988 		if (optval == IPOPT_EOL)
24989 			break;
24990 		if (optval == IPOPT_NOP)
24991 			optlen = 1;
24992 		else
24993 			optlen = rptr[1];
24994 		if (optval & IPOPT_COPY) {
24995 			bcopy(rptr, up, optlen);
24996 			up += optlen;
24997 		}
24998 		rptr += optlen;
24999 		hdr_len -= optlen;
25000 	}
25001 	/*
25002 	 * Make sure that we drop an even number of words by filling
25003 	 * with EOL to the next word boundary.
25004 	 */
25005 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
25006 	    hdr_len & 0x3; hdr_len++)
25007 		*up++ = IPOPT_EOL;
25008 	mp->b_wptr = up;
25009 	/* Update header length */
25010 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
25011 	return (mp);
25012 }
25013 
25014 /*
25015  * Delivery to local recipients including fanout to multiple recipients.
25016  * Does not do checksumming of UDP/TCP.
25017  * Note: q should be the read side queue for either the ill or conn.
25018  * Note: rq should be the read side q for the lower (ill) stream.
25019  * We don't send packets to IPPF processing, thus the last argument
25020  * to all the fanout calls are B_FALSE.
25021  */
25022 void
25023 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
25024     int fanout_flags, zoneid_t zoneid)
25025 {
25026 	uint32_t	protocol;
25027 	mblk_t		*first_mp;
25028 	boolean_t	mctl_present;
25029 	int		ire_type;
25030 #define	rptr	((uchar_t *)ipha)
25031 	ip_stack_t	*ipst = ill->ill_ipst;
25032 
25033 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
25034 	    "ip_wput_local_start: q %p", q);
25035 
25036 	if (ire != NULL) {
25037 		ire_type = ire->ire_type;
25038 	} else {
25039 		/*
25040 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
25041 		 * packet is not multicast, we can't tell the ire type.
25042 		 */
25043 		ASSERT(CLASSD(ipha->ipha_dst));
25044 		ire_type = IRE_BROADCAST;
25045 	}
25046 
25047 	first_mp = mp;
25048 	if (first_mp->b_datap->db_type == M_CTL) {
25049 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
25050 		if (!io->ipsec_out_secure) {
25051 			/*
25052 			 * This ipsec_out_t was allocated in ip_wput
25053 			 * for multicast packets to store the ill_index.
25054 			 * As this is being delivered locally, we don't
25055 			 * need this anymore.
25056 			 */
25057 			mp = first_mp->b_cont;
25058 			freeb(first_mp);
25059 			first_mp = mp;
25060 			mctl_present = B_FALSE;
25061 		} else {
25062 			/*
25063 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
25064 			 * security properties for the looped-back packet.
25065 			 */
25066 			mctl_present = B_TRUE;
25067 			mp = first_mp->b_cont;
25068 			ASSERT(mp != NULL);
25069 			ipsec_out_to_in(first_mp);
25070 		}
25071 	} else {
25072 		mctl_present = B_FALSE;
25073 	}
25074 
25075 	DTRACE_PROBE4(ip4__loopback__in__start,
25076 	    ill_t *, ill, ill_t *, NULL,
25077 	    ipha_t *, ipha, mblk_t *, first_mp);
25078 
25079 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
25080 	    ipst->ips_ipv4firewall_loopback_in,
25081 	    ill, NULL, ipha, first_mp, mp, 0, ipst);
25082 
25083 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
25084 
25085 	if (first_mp == NULL)
25086 		return;
25087 
25088 	DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL, void_ip_t *,
25089 	    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *, NULL,
25090 	    int, 1);
25091 
25092 	ipst->ips_loopback_packets++;
25093 
25094 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
25095 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
25096 	if (!IS_SIMPLE_IPH(ipha)) {
25097 		ip_wput_local_options(ipha, ipst);
25098 	}
25099 
25100 	protocol = ipha->ipha_protocol;
25101 	switch (protocol) {
25102 	case IPPROTO_ICMP: {
25103 		ire_t		*ire_zone;
25104 		ilm_t		*ilm;
25105 		mblk_t		*mp1;
25106 		zoneid_t	last_zoneid;
25107 
25108 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
25109 			ASSERT(ire_type == IRE_BROADCAST);
25110 			/*
25111 			 * In the multicast case, applications may have joined
25112 			 * the group from different zones, so we need to deliver
25113 			 * the packet to each of them. Loop through the
25114 			 * multicast memberships structures (ilm) on the receive
25115 			 * ill and send a copy of the packet up each matching
25116 			 * one. However, we don't do this for multicasts sent on
25117 			 * the loopback interface (PHYI_LOOPBACK flag set) as
25118 			 * they must stay in the sender's zone.
25119 			 *
25120 			 * ilm_add_v6() ensures that ilms in the same zone are
25121 			 * contiguous in the ill_ilm list. We use this property
25122 			 * to avoid sending duplicates needed when two
25123 			 * applications in the same zone join the same group on
25124 			 * different logical interfaces: we ignore the ilm if
25125 			 * it's zoneid is the same as the last matching one.
25126 			 * In addition, the sending of the packet for
25127 			 * ire_zoneid is delayed until all of the other ilms
25128 			 * have been exhausted.
25129 			 */
25130 			last_zoneid = -1;
25131 			ILM_WALKER_HOLD(ill);
25132 			for (ilm = ill->ill_ilm; ilm != NULL;
25133 			    ilm = ilm->ilm_next) {
25134 				if ((ilm->ilm_flags & ILM_DELETED) ||
25135 				    ipha->ipha_dst != ilm->ilm_addr ||
25136 				    ilm->ilm_zoneid == last_zoneid ||
25137 				    ilm->ilm_zoneid == zoneid ||
25138 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25139 					continue;
25140 				mp1 = ip_copymsg(first_mp);
25141 				if (mp1 == NULL)
25142 					continue;
25143 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25144 				    mctl_present, B_FALSE, ill,
25145 				    ilm->ilm_zoneid);
25146 				last_zoneid = ilm->ilm_zoneid;
25147 			}
25148 			ILM_WALKER_RELE(ill);
25149 			/*
25150 			 * Loopback case: the sending endpoint has
25151 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25152 			 * dispatch the multicast packet to the sending zone.
25153 			 */
25154 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25155 				freemsg(first_mp);
25156 				return;
25157 			}
25158 		} else if (ire_type == IRE_BROADCAST) {
25159 			/*
25160 			 * In the broadcast case, there may be many zones
25161 			 * which need a copy of the packet delivered to them.
25162 			 * There is one IRE_BROADCAST per broadcast address
25163 			 * and per zone; we walk those using a helper function.
25164 			 * In addition, the sending of the packet for zoneid is
25165 			 * delayed until all of the other ires have been
25166 			 * processed.
25167 			 */
25168 			IRB_REFHOLD(ire->ire_bucket);
25169 			ire_zone = NULL;
25170 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25171 			    ire)) != NULL) {
25172 				mp1 = ip_copymsg(first_mp);
25173 				if (mp1 == NULL)
25174 					continue;
25175 
25176 				UPDATE_IB_PKT_COUNT(ire_zone);
25177 				ire_zone->ire_last_used_time = lbolt;
25178 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25179 				    mctl_present, B_FALSE, ill,
25180 				    ire_zone->ire_zoneid);
25181 			}
25182 			IRB_REFRELE(ire->ire_bucket);
25183 		}
25184 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25185 		    0, mctl_present, B_FALSE, ill, zoneid);
25186 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25187 		    "ip_wput_local_end: q %p (%S)",
25188 		    q, "icmp");
25189 		return;
25190 	}
25191 	case IPPROTO_IGMP:
25192 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25193 			/* Bad packet - discarded by igmp_input */
25194 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25195 			    "ip_wput_local_end: q %p (%S)",
25196 			    q, "igmp_input--bad packet");
25197 			if (mctl_present)
25198 				freeb(first_mp);
25199 			return;
25200 		}
25201 		/*
25202 		 * igmp_input() may have returned the pulled up message.
25203 		 * So first_mp and ipha need to be reinitialized.
25204 		 */
25205 		ipha = (ipha_t *)mp->b_rptr;
25206 		if (mctl_present)
25207 			first_mp->b_cont = mp;
25208 		else
25209 			first_mp = mp;
25210 		/* deliver to local raw users */
25211 		break;
25212 	case IPPROTO_ENCAP:
25213 		/*
25214 		 * This case is covered by either ip_fanout_proto, or by
25215 		 * the above security processing for self-tunneled packets.
25216 		 */
25217 		break;
25218 	case IPPROTO_UDP: {
25219 		uint16_t	*up;
25220 		uint32_t	ports;
25221 
25222 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25223 		    UDP_PORTS_OFFSET);
25224 		/* Force a 'valid' checksum. */
25225 		up[3] = 0;
25226 
25227 		ports = *(uint32_t *)up;
25228 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25229 		    (ire_type == IRE_BROADCAST),
25230 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25231 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25232 		    ill, zoneid);
25233 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25234 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25235 		return;
25236 	}
25237 	case IPPROTO_TCP: {
25238 
25239 		/*
25240 		 * For TCP, discard broadcast packets.
25241 		 */
25242 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25243 			freemsg(first_mp);
25244 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25245 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25246 			return;
25247 		}
25248 
25249 		if (mp->b_datap->db_type == M_DATA) {
25250 			/*
25251 			 * M_DATA mblk, so init mblk (chain) for no struio().
25252 			 */
25253 			mblk_t	*mp1 = mp;
25254 
25255 			do {
25256 				mp1->b_datap->db_struioflag = 0;
25257 			} while ((mp1 = mp1->b_cont) != NULL);
25258 		}
25259 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25260 		    <= mp->b_wptr);
25261 		ip_fanout_tcp(q, first_mp, ill, ipha,
25262 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25263 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25264 		    mctl_present, B_FALSE, zoneid);
25265 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25266 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25267 		return;
25268 	}
25269 	case IPPROTO_SCTP:
25270 	{
25271 		uint32_t	ports;
25272 
25273 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25274 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25275 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25276 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25277 		return;
25278 	}
25279 
25280 	default:
25281 		break;
25282 	}
25283 	/*
25284 	 * Find a client for some other protocol.  We give
25285 	 * copies to multiple clients, if more than one is
25286 	 * bound.
25287 	 */
25288 	ip_fanout_proto(q, first_mp, ill, ipha,
25289 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25290 	    mctl_present, B_FALSE, ill, zoneid);
25291 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25292 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25293 #undef	rptr
25294 }
25295 
25296 /*
25297  * Update any source route, record route, or timestamp options.
25298  * Check that we are at end of strict source route.
25299  * The options have been sanity checked by ip_wput_options().
25300  */
25301 static void
25302 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25303 {
25304 	ipoptp_t	opts;
25305 	uchar_t		*opt;
25306 	uint8_t		optval;
25307 	uint8_t		optlen;
25308 	ipaddr_t	dst;
25309 	uint32_t	ts;
25310 	ire_t		*ire;
25311 	timestruc_t	now;
25312 
25313 	ip2dbg(("ip_wput_local_options\n"));
25314 	for (optval = ipoptp_first(&opts, ipha);
25315 	    optval != IPOPT_EOL;
25316 	    optval = ipoptp_next(&opts)) {
25317 		opt = opts.ipoptp_cur;
25318 		optlen = opts.ipoptp_len;
25319 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25320 		switch (optval) {
25321 			uint32_t off;
25322 		case IPOPT_SSRR:
25323 		case IPOPT_LSRR:
25324 			off = opt[IPOPT_OFFSET];
25325 			off--;
25326 			if (optlen < IP_ADDR_LEN ||
25327 			    off > optlen - IP_ADDR_LEN) {
25328 				/* End of source route */
25329 				break;
25330 			}
25331 			/*
25332 			 * This will only happen if two consecutive entries
25333 			 * in the source route contains our address or if
25334 			 * it is a packet with a loose source route which
25335 			 * reaches us before consuming the whole source route
25336 			 */
25337 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25338 			if (optval == IPOPT_SSRR) {
25339 				return;
25340 			}
25341 			/*
25342 			 * Hack: instead of dropping the packet truncate the
25343 			 * source route to what has been used by filling the
25344 			 * rest with IPOPT_NOP.
25345 			 */
25346 			opt[IPOPT_OLEN] = (uint8_t)off;
25347 			while (off < optlen) {
25348 				opt[off++] = IPOPT_NOP;
25349 			}
25350 			break;
25351 		case IPOPT_RR:
25352 			off = opt[IPOPT_OFFSET];
25353 			off--;
25354 			if (optlen < IP_ADDR_LEN ||
25355 			    off > optlen - IP_ADDR_LEN) {
25356 				/* No more room - ignore */
25357 				ip1dbg((
25358 				    "ip_wput_forward_options: end of RR\n"));
25359 				break;
25360 			}
25361 			dst = htonl(INADDR_LOOPBACK);
25362 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25363 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25364 			break;
25365 		case IPOPT_TS:
25366 			/* Insert timestamp if there is romm */
25367 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25368 			case IPOPT_TS_TSONLY:
25369 				off = IPOPT_TS_TIMELEN;
25370 				break;
25371 			case IPOPT_TS_PRESPEC:
25372 			case IPOPT_TS_PRESPEC_RFC791:
25373 				/* Verify that the address matched */
25374 				off = opt[IPOPT_OFFSET] - 1;
25375 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25376 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25377 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25378 				    ipst);
25379 				if (ire == NULL) {
25380 					/* Not for us */
25381 					break;
25382 				}
25383 				ire_refrele(ire);
25384 				/* FALLTHRU */
25385 			case IPOPT_TS_TSANDADDR:
25386 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25387 				break;
25388 			default:
25389 				/*
25390 				 * ip_*put_options should have already
25391 				 * dropped this packet.
25392 				 */
25393 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25394 				    "unknown IT - bug in ip_wput_options?\n");
25395 				return;	/* Keep "lint" happy */
25396 			}
25397 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25398 				/* Increase overflow counter */
25399 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25400 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25401 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25402 				    (off << 4);
25403 				break;
25404 			}
25405 			off = opt[IPOPT_OFFSET] - 1;
25406 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25407 			case IPOPT_TS_PRESPEC:
25408 			case IPOPT_TS_PRESPEC_RFC791:
25409 			case IPOPT_TS_TSANDADDR:
25410 				dst = htonl(INADDR_LOOPBACK);
25411 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25412 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25413 				/* FALLTHRU */
25414 			case IPOPT_TS_TSONLY:
25415 				off = opt[IPOPT_OFFSET] - 1;
25416 				/* Compute # of milliseconds since midnight */
25417 				gethrestime(&now);
25418 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25419 				    now.tv_nsec / (NANOSEC / MILLISEC);
25420 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25421 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25422 				break;
25423 			}
25424 			break;
25425 		}
25426 	}
25427 }
25428 
25429 /*
25430  * Send out a multicast packet on interface ipif.
25431  * The sender does not have an conn.
25432  * Caller verifies that this isn't a PHYI_LOOPBACK.
25433  */
25434 void
25435 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25436 {
25437 	ipha_t	*ipha;
25438 	ire_t	*ire;
25439 	ipaddr_t	dst;
25440 	mblk_t		*first_mp;
25441 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25442 
25443 	/* igmp_sendpkt always allocates a ipsec_out_t */
25444 	ASSERT(mp->b_datap->db_type == M_CTL);
25445 	ASSERT(!ipif->ipif_isv6);
25446 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25447 
25448 	first_mp = mp;
25449 	mp = first_mp->b_cont;
25450 	ASSERT(mp->b_datap->db_type == M_DATA);
25451 	ipha = (ipha_t *)mp->b_rptr;
25452 
25453 	/*
25454 	 * Find an IRE which matches the destination and the outgoing
25455 	 * queue (i.e. the outgoing interface.)
25456 	 */
25457 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25458 		dst = ipif->ipif_pp_dst_addr;
25459 	else
25460 		dst = ipha->ipha_dst;
25461 	/*
25462 	 * The source address has already been initialized by the
25463 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25464 	 * be sufficient rather than MATCH_IRE_IPIF.
25465 	 *
25466 	 * This function is used for sending IGMP packets. We need
25467 	 * to make sure that we send the packet out of the interface
25468 	 * (ipif->ipif_ill) where we joined the group. This is to
25469 	 * prevent from switches doing IGMP snooping to send us multicast
25470 	 * packets for a given group on the interface we have joined.
25471 	 * If we can't find an ire, igmp_sendpkt has already initialized
25472 	 * ipsec_out_attach_if so that this will not be load spread in
25473 	 * ip_newroute_ipif.
25474 	 */
25475 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25476 	    MATCH_IRE_ILL, ipst);
25477 	if (!ire) {
25478 		/*
25479 		 * Mark this packet to make it be delivered to
25480 		 * ip_wput_ire after the new ire has been
25481 		 * created.
25482 		 */
25483 		mp->b_prev = NULL;
25484 		mp->b_next = NULL;
25485 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25486 		    zoneid, &zero_info);
25487 		return;
25488 	}
25489 
25490 	/*
25491 	 * Honor the RTF_SETSRC flag; this is the only case
25492 	 * where we force this addr whatever the current src addr is,
25493 	 * because this address is set by igmp_sendpkt(), and
25494 	 * cannot be specified by any user.
25495 	 */
25496 	if (ire->ire_flags & RTF_SETSRC) {
25497 		ipha->ipha_src = ire->ire_src_addr;
25498 	}
25499 
25500 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25501 }
25502 
25503 /*
25504  * NOTE : This function does not ire_refrele the ire argument passed in.
25505  *
25506  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25507  * failure. The nce_fp_mp can vanish any time in the case of
25508  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25509  * the ire_lock to access the nce_fp_mp in this case.
25510  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25511  * prepending a fastpath message IPQoS processing must precede it, we also set
25512  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25513  * (IPQoS might have set the b_band for CoS marking).
25514  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25515  * must follow it so that IPQoS can mark the dl_priority field for CoS
25516  * marking, if needed.
25517  */
25518 static mblk_t *
25519 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc,
25520     uint32_t ill_index, ipha_t **iphap)
25521 {
25522 	uint_t	hlen;
25523 	ipha_t *ipha;
25524 	mblk_t *mp1;
25525 	boolean_t qos_done = B_FALSE;
25526 	uchar_t	*ll_hdr;
25527 	ip_stack_t	*ipst = ire->ire_ipst;
25528 
25529 #define	rptr	((uchar_t *)ipha)
25530 
25531 	ipha = (ipha_t *)mp->b_rptr;
25532 	hlen = 0;
25533 	LOCK_IRE_FP_MP(ire);
25534 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25535 		ASSERT(DB_TYPE(mp1) == M_DATA);
25536 		/* Initiate IPPF processing */
25537 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25538 			UNLOCK_IRE_FP_MP(ire);
25539 			ip_process(proc, &mp, ill_index);
25540 			if (mp == NULL)
25541 				return (NULL);
25542 
25543 			ipha = (ipha_t *)mp->b_rptr;
25544 			LOCK_IRE_FP_MP(ire);
25545 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25546 				qos_done = B_TRUE;
25547 				goto no_fp_mp;
25548 			}
25549 			ASSERT(DB_TYPE(mp1) == M_DATA);
25550 		}
25551 		hlen = MBLKL(mp1);
25552 		/*
25553 		 * Check if we have enough room to prepend fastpath
25554 		 * header
25555 		 */
25556 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25557 			ll_hdr = rptr - hlen;
25558 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25559 			/*
25560 			 * Set the b_rptr to the start of the link layer
25561 			 * header
25562 			 */
25563 			mp->b_rptr = ll_hdr;
25564 			mp1 = mp;
25565 		} else {
25566 			mp1 = copyb(mp1);
25567 			if (mp1 == NULL)
25568 				goto unlock_err;
25569 			mp1->b_band = mp->b_band;
25570 			mp1->b_cont = mp;
25571 			/*
25572 			 * certain system generated traffic may not
25573 			 * have cred/label in ip header block. This
25574 			 * is true even for a labeled system. But for
25575 			 * labeled traffic, inherit the label in the
25576 			 * new header.
25577 			 */
25578 			if (DB_CRED(mp) != NULL)
25579 				mblk_setcred(mp1, DB_CRED(mp));
25580 			/*
25581 			 * XXX disable ICK_VALID and compute checksum
25582 			 * here; can happen if nce_fp_mp changes and
25583 			 * it can't be copied now due to insufficient
25584 			 * space. (unlikely, fp mp can change, but it
25585 			 * does not increase in length)
25586 			 */
25587 		}
25588 		UNLOCK_IRE_FP_MP(ire);
25589 	} else {
25590 no_fp_mp:
25591 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25592 		if (mp1 == NULL) {
25593 unlock_err:
25594 			UNLOCK_IRE_FP_MP(ire);
25595 			freemsg(mp);
25596 			return (NULL);
25597 		}
25598 		UNLOCK_IRE_FP_MP(ire);
25599 		mp1->b_cont = mp;
25600 		/*
25601 		 * certain system generated traffic may not
25602 		 * have cred/label in ip header block. This
25603 		 * is true even for a labeled system. But for
25604 		 * labeled traffic, inherit the label in the
25605 		 * new header.
25606 		 */
25607 		if (DB_CRED(mp) != NULL)
25608 			mblk_setcred(mp1, DB_CRED(mp));
25609 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25610 			ip_process(proc, &mp1, ill_index);
25611 			if (mp1 == NULL)
25612 				return (NULL);
25613 
25614 			if (mp1->b_cont == NULL)
25615 				ipha = NULL;
25616 			else
25617 				ipha = (ipha_t *)mp1->b_cont->b_rptr;
25618 		}
25619 	}
25620 
25621 	*iphap = ipha;
25622 	return (mp1);
25623 #undef rptr
25624 }
25625 
25626 /*
25627  * Finish the outbound IPsec processing for an IPv6 packet. This function
25628  * is called from ipsec_out_process() if the IPsec packet was processed
25629  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25630  * asynchronously.
25631  */
25632 void
25633 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25634     ire_t *ire_arg)
25635 {
25636 	in6_addr_t *v6dstp;
25637 	ire_t *ire;
25638 	mblk_t *mp;
25639 	ip6_t *ip6h1;
25640 	uint_t	ill_index;
25641 	ipsec_out_t *io;
25642 	boolean_t attach_if, hwaccel;
25643 	uint32_t flags = IP6_NO_IPPOLICY;
25644 	int match_flags;
25645 	zoneid_t zoneid;
25646 	boolean_t ill_need_rele = B_FALSE;
25647 	boolean_t ire_need_rele = B_FALSE;
25648 	ip_stack_t	*ipst;
25649 
25650 	mp = ipsec_mp->b_cont;
25651 	ip6h1 = (ip6_t *)mp->b_rptr;
25652 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25653 	ASSERT(io->ipsec_out_ns != NULL);
25654 	ipst = io->ipsec_out_ns->netstack_ip;
25655 	ill_index = io->ipsec_out_ill_index;
25656 	if (io->ipsec_out_reachable) {
25657 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25658 	}
25659 	attach_if = io->ipsec_out_attach_if;
25660 	hwaccel = io->ipsec_out_accelerated;
25661 	zoneid = io->ipsec_out_zoneid;
25662 	ASSERT(zoneid != ALL_ZONES);
25663 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25664 	/* Multicast addresses should have non-zero ill_index. */
25665 	v6dstp = &ip6h->ip6_dst;
25666 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25667 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25668 	ASSERT(!attach_if || ill_index != 0);
25669 	if (ill_index != 0) {
25670 		if (ill == NULL) {
25671 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
25672 			    B_TRUE, ipst);
25673 
25674 			/* Failure case frees things for us. */
25675 			if (ill == NULL)
25676 				return;
25677 
25678 			ill_need_rele = B_TRUE;
25679 		}
25680 		/*
25681 		 * If this packet needs to go out on a particular interface
25682 		 * honor it.
25683 		 */
25684 		if (attach_if) {
25685 			match_flags = MATCH_IRE_ILL;
25686 
25687 			/*
25688 			 * Check if we need an ire that will not be
25689 			 * looked up by anybody else i.e. HIDDEN.
25690 			 */
25691 			if (ill_is_probeonly(ill)) {
25692 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25693 			}
25694 		}
25695 	}
25696 	ASSERT(mp != NULL);
25697 
25698 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25699 		boolean_t unspec_src;
25700 		ipif_t	*ipif;
25701 
25702 		/*
25703 		 * Use the ill_index to get the right ill.
25704 		 */
25705 		unspec_src = io->ipsec_out_unspec_src;
25706 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25707 		if (ipif == NULL) {
25708 			if (ill_need_rele)
25709 				ill_refrele(ill);
25710 			freemsg(ipsec_mp);
25711 			return;
25712 		}
25713 
25714 		if (ire_arg != NULL) {
25715 			ire = ire_arg;
25716 		} else {
25717 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25718 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25719 			ire_need_rele = B_TRUE;
25720 		}
25721 		if (ire != NULL) {
25722 			ipif_refrele(ipif);
25723 			/*
25724 			 * XXX Do the multicast forwarding now, as the IPsec
25725 			 * processing has been done.
25726 			 */
25727 			goto send;
25728 		}
25729 
25730 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25731 		mp->b_prev = NULL;
25732 		mp->b_next = NULL;
25733 
25734 		/*
25735 		 * If the IPsec packet was processed asynchronously,
25736 		 * drop it now.
25737 		 */
25738 		if (q == NULL) {
25739 			if (ill_need_rele)
25740 				ill_refrele(ill);
25741 			freemsg(ipsec_mp);
25742 			return;
25743 		}
25744 
25745 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
25746 		    unspec_src, zoneid);
25747 		ipif_refrele(ipif);
25748 	} else {
25749 		if (attach_if) {
25750 			ipif_t	*ipif;
25751 
25752 			ipif = ipif_get_next_ipif(NULL, ill);
25753 			if (ipif == NULL) {
25754 				if (ill_need_rele)
25755 					ill_refrele(ill);
25756 				freemsg(ipsec_mp);
25757 				return;
25758 			}
25759 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25760 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25761 			ire_need_rele = B_TRUE;
25762 			ipif_refrele(ipif);
25763 		} else {
25764 			if (ire_arg != NULL) {
25765 				ire = ire_arg;
25766 			} else {
25767 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL,
25768 				    ipst);
25769 				ire_need_rele = B_TRUE;
25770 			}
25771 		}
25772 		if (ire != NULL)
25773 			goto send;
25774 		/*
25775 		 * ire disappeared underneath.
25776 		 *
25777 		 * What we need to do here is the ip_newroute
25778 		 * logic to get the ire without doing the IPsec
25779 		 * processing. Follow the same old path. But this
25780 		 * time, ip_wput or ire_add_then_send will call us
25781 		 * directly as all the IPsec operations are done.
25782 		 */
25783 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25784 		mp->b_prev = NULL;
25785 		mp->b_next = NULL;
25786 
25787 		/*
25788 		 * If the IPsec packet was processed asynchronously,
25789 		 * drop it now.
25790 		 */
25791 		if (q == NULL) {
25792 			if (ill_need_rele)
25793 				ill_refrele(ill);
25794 			freemsg(ipsec_mp);
25795 			return;
25796 		}
25797 
25798 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25799 		    zoneid, ipst);
25800 	}
25801 	if (ill != NULL && ill_need_rele)
25802 		ill_refrele(ill);
25803 	return;
25804 send:
25805 	if (ill != NULL && ill_need_rele)
25806 		ill_refrele(ill);
25807 
25808 	/* Local delivery */
25809 	if (ire->ire_stq == NULL) {
25810 		ill_t	*out_ill;
25811 		ASSERT(q != NULL);
25812 
25813 		/* PFHooks: LOOPBACK_OUT */
25814 		out_ill = ire_to_ill(ire);
25815 
25816 		/*
25817 		 * DTrace this as ip:::send.  A blocked packet will fire the
25818 		 * send probe, but not the receive probe.
25819 		 */
25820 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
25821 		    void_ip_t *, ip6h, __dtrace_ipsr_ill_t *, out_ill,
25822 		    ipha_t *, NULL, ip6_t *, ip6h, int, 1);
25823 
25824 		DTRACE_PROBE4(ip6__loopback__out__start,
25825 		    ill_t *, NULL, ill_t *, out_ill,
25826 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25827 
25828 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25829 		    ipst->ips_ipv6firewall_loopback_out,
25830 		    NULL, out_ill, ip6h1, ipsec_mp, mp, 0, ipst);
25831 
25832 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25833 
25834 		if (ipsec_mp != NULL)
25835 			ip_wput_local_v6(RD(q), out_ill,
25836 			    ip6h, ipsec_mp, ire, 0);
25837 		if (ire_need_rele)
25838 			ire_refrele(ire);
25839 		return;
25840 	}
25841 	/*
25842 	 * Everything is done. Send it out on the wire.
25843 	 * We force the insertion of a fragment header using the
25844 	 * IPH_FRAG_HDR flag in two cases:
25845 	 * - after reception of an ICMPv6 "packet too big" message
25846 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25847 	 * - for multirouted IPv6 packets, so that the receiver can
25848 	 *   discard duplicates according to their fragment identifier
25849 	 */
25850 	/* XXX fix flow control problems. */
25851 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25852 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25853 		if (hwaccel) {
25854 			/*
25855 			 * hardware acceleration does not handle these
25856 			 * "slow path" cases.
25857 			 */
25858 			/* IPsec KSTATS: should bump bean counter here. */
25859 			if (ire_need_rele)
25860 				ire_refrele(ire);
25861 			freemsg(ipsec_mp);
25862 			return;
25863 		}
25864 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25865 		    (mp->b_cont ? msgdsize(mp) :
25866 		    mp->b_wptr - (uchar_t *)ip6h)) {
25867 			/* IPsec KSTATS: should bump bean counter here. */
25868 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25869 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25870 			    msgdsize(mp)));
25871 			if (ire_need_rele)
25872 				ire_refrele(ire);
25873 			freemsg(ipsec_mp);
25874 			return;
25875 		}
25876 		ASSERT(mp->b_prev == NULL);
25877 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25878 		    ntohs(ip6h->ip6_plen) +
25879 		    IPV6_HDR_LEN, ire->ire_max_frag));
25880 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25881 		    ire->ire_max_frag);
25882 	} else {
25883 		UPDATE_OB_PKT_COUNT(ire);
25884 		ire->ire_last_used_time = lbolt;
25885 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25886 	}
25887 	if (ire_need_rele)
25888 		ire_refrele(ire);
25889 	freeb(ipsec_mp);
25890 }
25891 
25892 void
25893 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25894 {
25895 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25896 	da_ipsec_t *hada;	/* data attributes */
25897 	ill_t *ill = (ill_t *)q->q_ptr;
25898 
25899 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25900 
25901 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25902 		/* IPsec KSTATS: Bump lose counter here! */
25903 		freemsg(mp);
25904 		return;
25905 	}
25906 
25907 	/*
25908 	 * It's an IPsec packet that must be
25909 	 * accelerated by the Provider, and the
25910 	 * outbound ill is IPsec acceleration capable.
25911 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25912 	 * to the ill.
25913 	 * IPsec KSTATS: should bump packet counter here.
25914 	 */
25915 
25916 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25917 	if (hada_mp == NULL) {
25918 		/* IPsec KSTATS: should bump packet counter here. */
25919 		freemsg(mp);
25920 		return;
25921 	}
25922 
25923 	hada_mp->b_datap->db_type = M_CTL;
25924 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25925 	hada_mp->b_cont = mp;
25926 
25927 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25928 	bzero(hada, sizeof (da_ipsec_t));
25929 	hada->da_type = IPHADA_M_CTL;
25930 
25931 	putnext(q, hada_mp);
25932 }
25933 
25934 /*
25935  * Finish the outbound IPsec processing. This function is called from
25936  * ipsec_out_process() if the IPsec packet was processed
25937  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25938  * asynchronously.
25939  */
25940 void
25941 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25942     ire_t *ire_arg)
25943 {
25944 	uint32_t v_hlen_tos_len;
25945 	ipaddr_t	dst;
25946 	ipif_t	*ipif = NULL;
25947 	ire_t *ire;
25948 	ire_t *ire1 = NULL;
25949 	mblk_t *next_mp = NULL;
25950 	uint32_t max_frag;
25951 	boolean_t multirt_send = B_FALSE;
25952 	mblk_t *mp;
25953 	ipha_t *ipha1;
25954 	uint_t	ill_index;
25955 	ipsec_out_t *io;
25956 	boolean_t attach_if;
25957 	int match_flags;
25958 	irb_t *irb = NULL;
25959 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25960 	zoneid_t zoneid;
25961 	ipxmit_state_t	pktxmit_state;
25962 	ip_stack_t	*ipst;
25963 
25964 #ifdef	_BIG_ENDIAN
25965 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25966 #else
25967 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25968 #endif
25969 
25970 	mp = ipsec_mp->b_cont;
25971 	ipha1 = (ipha_t *)mp->b_rptr;
25972 	ASSERT(mp != NULL);
25973 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25974 	dst = ipha->ipha_dst;
25975 
25976 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25977 	ill_index = io->ipsec_out_ill_index;
25978 	attach_if = io->ipsec_out_attach_if;
25979 	zoneid = io->ipsec_out_zoneid;
25980 	ASSERT(zoneid != ALL_ZONES);
25981 	ipst = io->ipsec_out_ns->netstack_ip;
25982 	ASSERT(io->ipsec_out_ns != NULL);
25983 
25984 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25985 	if (ill_index != 0) {
25986 		if (ill == NULL) {
25987 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
25988 			    ill_index, B_FALSE, ipst);
25989 
25990 			/* Failure case frees things for us. */
25991 			if (ill == NULL)
25992 				return;
25993 
25994 			ill_need_rele = B_TRUE;
25995 		}
25996 		/*
25997 		 * If this packet needs to go out on a particular interface
25998 		 * honor it.
25999 		 */
26000 		if (attach_if) {
26001 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
26002 
26003 			/*
26004 			 * Check if we need an ire that will not be
26005 			 * looked up by anybody else i.e. HIDDEN.
26006 			 */
26007 			if (ill_is_probeonly(ill)) {
26008 				match_flags |= MATCH_IRE_MARK_HIDDEN;
26009 			}
26010 		}
26011 	}
26012 
26013 	if (CLASSD(dst)) {
26014 		boolean_t conn_dontroute;
26015 		/*
26016 		 * Use the ill_index to get the right ipif.
26017 		 */
26018 		conn_dontroute = io->ipsec_out_dontroute;
26019 		if (ill_index == 0)
26020 			ipif = ipif_lookup_group(dst, zoneid, ipst);
26021 		else
26022 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
26023 		if (ipif == NULL) {
26024 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
26025 			    " multicast\n"));
26026 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
26027 			freemsg(ipsec_mp);
26028 			goto done;
26029 		}
26030 		/*
26031 		 * ipha_src has already been intialized with the
26032 		 * value of the ipif in ip_wput. All we need now is
26033 		 * an ire to send this downstream.
26034 		 */
26035 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
26036 		    MBLK_GETLABEL(mp), match_flags, ipst);
26037 		if (ire != NULL) {
26038 			ill_t *ill1;
26039 			/*
26040 			 * Do the multicast forwarding now, as the IPsec
26041 			 * processing has been done.
26042 			 */
26043 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
26044 			    (ill1 = ire_to_ill(ire))) {
26045 				if (ip_mforward(ill1, ipha, mp)) {
26046 					freemsg(ipsec_mp);
26047 					ip1dbg(("ip_wput_ipsec_out: mforward "
26048 					    "failed\n"));
26049 					ire_refrele(ire);
26050 					goto done;
26051 				}
26052 			}
26053 			goto send;
26054 		}
26055 
26056 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
26057 		mp->b_prev = NULL;
26058 		mp->b_next = NULL;
26059 
26060 		/*
26061 		 * If the IPsec packet was processed asynchronously,
26062 		 * drop it now.
26063 		 */
26064 		if (q == NULL) {
26065 			freemsg(ipsec_mp);
26066 			goto done;
26067 		}
26068 
26069 		/*
26070 		 * We may be using a wrong ipif to create the ire.
26071 		 * But it is okay as the source address is assigned
26072 		 * for the packet already. Next outbound packet would
26073 		 * create the IRE with the right IPIF in ip_wput.
26074 		 *
26075 		 * Also handle RTF_MULTIRT routes.
26076 		 */
26077 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
26078 		    zoneid, &zero_info);
26079 	} else {
26080 		if (attach_if) {
26081 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
26082 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
26083 		} else {
26084 			if (ire_arg != NULL) {
26085 				ire = ire_arg;
26086 				ire_need_rele = B_FALSE;
26087 			} else {
26088 				ire = ire_cache_lookup(dst, zoneid,
26089 				    MBLK_GETLABEL(mp), ipst);
26090 			}
26091 		}
26092 		if (ire != NULL) {
26093 			goto send;
26094 		}
26095 
26096 		/*
26097 		 * ire disappeared underneath.
26098 		 *
26099 		 * What we need to do here is the ip_newroute
26100 		 * logic to get the ire without doing the IPsec
26101 		 * processing. Follow the same old path. But this
26102 		 * time, ip_wput or ire_add_then_put will call us
26103 		 * directly as all the IPsec operations are done.
26104 		 */
26105 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
26106 		mp->b_prev = NULL;
26107 		mp->b_next = NULL;
26108 
26109 		/*
26110 		 * If the IPsec packet was processed asynchronously,
26111 		 * drop it now.
26112 		 */
26113 		if (q == NULL) {
26114 			freemsg(ipsec_mp);
26115 			goto done;
26116 		}
26117 
26118 		/*
26119 		 * Since we're going through ip_newroute() again, we
26120 		 * need to make sure we don't:
26121 		 *
26122 		 *	1.) Trigger the ASSERT() with the ipha_ident
26123 		 *	    overloading.
26124 		 *	2.) Redo transport-layer checksumming, since we've
26125 		 *	    already done all that to get this far.
26126 		 *
26127 		 * The easiest way not do either of the above is to set
26128 		 * the ipha_ident field to IP_HDR_INCLUDED.
26129 		 */
26130 		ipha->ipha_ident = IP_HDR_INCLUDED;
26131 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
26132 		    zoneid, ipst);
26133 	}
26134 	goto done;
26135 send:
26136 	if (ire->ire_stq == NULL) {
26137 		ill_t	*out_ill;
26138 		/*
26139 		 * Loopbacks go through ip_wput_local except for one case.
26140 		 * We come here if we generate a icmp_frag_needed message
26141 		 * after IPsec processing is over. When this function calls
26142 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
26143 		 * icmp_frag_needed. The message generated comes back here
26144 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
26145 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
26146 		 * source address as it is usually set in ip_wput_ire. As
26147 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
26148 		 * and we end up here. We can't enter ip_wput_ire once the
26149 		 * IPsec processing is over and hence we need to do it here.
26150 		 */
26151 		ASSERT(q != NULL);
26152 		UPDATE_OB_PKT_COUNT(ire);
26153 		ire->ire_last_used_time = lbolt;
26154 		if (ipha->ipha_src == 0)
26155 			ipha->ipha_src = ire->ire_src_addr;
26156 
26157 		/* PFHooks: LOOPBACK_OUT */
26158 		out_ill = ire_to_ill(ire);
26159 
26160 		/*
26161 		 * DTrace this as ip:::send.  A blocked packet will fire the
26162 		 * send probe, but not the receive probe.
26163 		 */
26164 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
26165 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
26166 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
26167 
26168 		DTRACE_PROBE4(ip4__loopback__out__start,
26169 		    ill_t *, NULL, ill_t *, out_ill,
26170 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26171 
26172 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
26173 		    ipst->ips_ipv4firewall_loopback_out,
26174 		    NULL, out_ill, ipha1, ipsec_mp, mp, 0, ipst);
26175 
26176 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26177 
26178 		if (ipsec_mp != NULL)
26179 			ip_wput_local(RD(q), out_ill,
26180 			    ipha, ipsec_mp, ire, 0, zoneid);
26181 		if (ire_need_rele)
26182 			ire_refrele(ire);
26183 		goto done;
26184 	}
26185 
26186 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26187 		/*
26188 		 * We are through with IPsec processing.
26189 		 * Fragment this and send it on the wire.
26190 		 */
26191 		if (io->ipsec_out_accelerated) {
26192 			/*
26193 			 * The packet has been accelerated but must
26194 			 * be fragmented. This should not happen
26195 			 * since AH and ESP must not accelerate
26196 			 * packets that need fragmentation, however
26197 			 * the configuration could have changed
26198 			 * since the AH or ESP processing.
26199 			 * Drop packet.
26200 			 * IPsec KSTATS: bump bean counter here.
26201 			 */
26202 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26203 			    "fragmented accelerated packet!\n"));
26204 			freemsg(ipsec_mp);
26205 		} else {
26206 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid, ipst);
26207 		}
26208 		if (ire_need_rele)
26209 			ire_refrele(ire);
26210 		goto done;
26211 	}
26212 
26213 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26214 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26215 	    (void *)ire->ire_ipif, (void *)ipif));
26216 
26217 	/*
26218 	 * Multiroute the secured packet, unless IPsec really
26219 	 * requires the packet to go out only through a particular
26220 	 * interface.
26221 	 */
26222 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
26223 		ire_t *first_ire;
26224 		irb = ire->ire_bucket;
26225 		ASSERT(irb != NULL);
26226 		/*
26227 		 * This ire has been looked up as the one that
26228 		 * goes through the given ipif;
26229 		 * make sure we do not omit any other multiroute ire
26230 		 * that may be present in the bucket before this one.
26231 		 */
26232 		IRB_REFHOLD(irb);
26233 		for (first_ire = irb->irb_ire;
26234 		    first_ire != NULL;
26235 		    first_ire = first_ire->ire_next) {
26236 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26237 			    (first_ire->ire_addr == ire->ire_addr) &&
26238 			    !(first_ire->ire_marks &
26239 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
26240 				break;
26241 			}
26242 		}
26243 
26244 		if ((first_ire != NULL) && (first_ire != ire)) {
26245 			/*
26246 			 * Don't change the ire if the packet must
26247 			 * be fragmented if sent via this new one.
26248 			 */
26249 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26250 				IRE_REFHOLD(first_ire);
26251 				if (ire_need_rele)
26252 					ire_refrele(ire);
26253 				else
26254 					ire_need_rele = B_TRUE;
26255 				ire = first_ire;
26256 			}
26257 		}
26258 		IRB_REFRELE(irb);
26259 
26260 		multirt_send = B_TRUE;
26261 		max_frag = ire->ire_max_frag;
26262 	} else {
26263 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
26264 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
26265 			    "flag, attach_if %d\n", attach_if));
26266 		}
26267 	}
26268 
26269 	/*
26270 	 * In most cases, the emission loop below is entered only once.
26271 	 * Only in the case where the ire holds the RTF_MULTIRT
26272 	 * flag, we loop to process all RTF_MULTIRT ires in the
26273 	 * bucket, and send the packet through all crossed
26274 	 * RTF_MULTIRT routes.
26275 	 */
26276 	do {
26277 		if (multirt_send) {
26278 			/*
26279 			 * ire1 holds here the next ire to process in the
26280 			 * bucket. If multirouting is expected,
26281 			 * any non-RTF_MULTIRT ire that has the
26282 			 * right destination address is ignored.
26283 			 */
26284 			ASSERT(irb != NULL);
26285 			IRB_REFHOLD(irb);
26286 			for (ire1 = ire->ire_next;
26287 			    ire1 != NULL;
26288 			    ire1 = ire1->ire_next) {
26289 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26290 					continue;
26291 				if (ire1->ire_addr != ire->ire_addr)
26292 					continue;
26293 				if (ire1->ire_marks &
26294 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
26295 					continue;
26296 				/* No loopback here */
26297 				if (ire1->ire_stq == NULL)
26298 					continue;
26299 				/*
26300 				 * Ensure we do not exceed the MTU
26301 				 * of the next route.
26302 				 */
26303 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26304 					ip_multirt_bad_mtu(ire1, max_frag);
26305 					continue;
26306 				}
26307 
26308 				IRE_REFHOLD(ire1);
26309 				break;
26310 			}
26311 			IRB_REFRELE(irb);
26312 			if (ire1 != NULL) {
26313 				/*
26314 				 * We are in a multiple send case, need to
26315 				 * make a copy of the packet.
26316 				 */
26317 				next_mp = copymsg(ipsec_mp);
26318 				if (next_mp == NULL) {
26319 					ire_refrele(ire1);
26320 					ire1 = NULL;
26321 				}
26322 			}
26323 		}
26324 		/*
26325 		 * Everything is done. Send it out on the wire
26326 		 *
26327 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26328 		 * either send it on the wire or, in the case of
26329 		 * HW acceleration, call ipsec_hw_putnext.
26330 		 */
26331 		if (ire->ire_nce &&
26332 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26333 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26334 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26335 			/*
26336 			 * If ire's link-layer is unresolved (this
26337 			 * would only happen if the incomplete ire
26338 			 * was added to cachetable via forwarding path)
26339 			 * don't bother going to ip_xmit_v4. Just drop the
26340 			 * packet.
26341 			 * There is a slight risk here, in that, if we
26342 			 * have the forwarding path create an incomplete
26343 			 * IRE, then until the IRE is completed, any
26344 			 * transmitted IPsec packets will be dropped
26345 			 * instead of being queued waiting for resolution.
26346 			 *
26347 			 * But the likelihood of a forwarding packet and a wput
26348 			 * packet sending to the same dst at the same time
26349 			 * and there not yet be an ARP entry for it is small.
26350 			 * Furthermore, if this actually happens, it might
26351 			 * be likely that wput would generate multiple
26352 			 * packets (and forwarding would also have a train
26353 			 * of packets) for that destination. If this is
26354 			 * the case, some of them would have been dropped
26355 			 * anyway, since ARP only queues a few packets while
26356 			 * waiting for resolution
26357 			 *
26358 			 * NOTE: We should really call ip_xmit_v4,
26359 			 * and let it queue the packet and send the
26360 			 * ARP query and have ARP come back thus:
26361 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26362 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26363 			 * hw accel work. But it's too complex to get
26364 			 * the IPsec hw  acceleration approach to fit
26365 			 * well with ip_xmit_v4 doing ARP without
26366 			 * doing IPsec simplification. For now, we just
26367 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26368 			 * that we can continue with the send on the next
26369 			 * attempt.
26370 			 *
26371 			 * XXX THis should be revisited, when
26372 			 * the IPsec/IP interaction is cleaned up
26373 			 */
26374 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26375 			    " - dropping packet\n"));
26376 			freemsg(ipsec_mp);
26377 			/*
26378 			 * Call ip_xmit_v4() to trigger ARP query
26379 			 * in case the nce_state is ND_INITIAL
26380 			 */
26381 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26382 			goto drop_pkt;
26383 		}
26384 
26385 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26386 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26387 		    mblk_t *, ipsec_mp);
26388 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26389 		    ipst->ips_ipv4firewall_physical_out, NULL,
26390 		    ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, 0, ipst);
26391 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26392 		if (ipsec_mp == NULL)
26393 			goto drop_pkt;
26394 
26395 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26396 		pktxmit_state = ip_xmit_v4(mp, ire,
26397 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
26398 
26399 		if ((pktxmit_state ==  SEND_FAILED) ||
26400 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26401 
26402 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26403 drop_pkt:
26404 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26405 			    ipIfStatsOutDiscards);
26406 			if (ire_need_rele)
26407 				ire_refrele(ire);
26408 			if (ire1 != NULL) {
26409 				ire_refrele(ire1);
26410 				freemsg(next_mp);
26411 			}
26412 			goto done;
26413 		}
26414 
26415 		freeb(ipsec_mp);
26416 		if (ire_need_rele)
26417 			ire_refrele(ire);
26418 
26419 		if (ire1 != NULL) {
26420 			ire = ire1;
26421 			ire_need_rele = B_TRUE;
26422 			ASSERT(next_mp);
26423 			ipsec_mp = next_mp;
26424 			mp = ipsec_mp->b_cont;
26425 			ire1 = NULL;
26426 			next_mp = NULL;
26427 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26428 		} else {
26429 			multirt_send = B_FALSE;
26430 		}
26431 	} while (multirt_send);
26432 done:
26433 	if (ill != NULL && ill_need_rele)
26434 		ill_refrele(ill);
26435 	if (ipif != NULL)
26436 		ipif_refrele(ipif);
26437 }
26438 
26439 /*
26440  * Get the ill corresponding to the specified ire, and compare its
26441  * capabilities with the protocol and algorithms specified by the
26442  * the SA obtained from ipsec_out. If they match, annotate the
26443  * ipsec_out structure to indicate that the packet needs acceleration.
26444  *
26445  *
26446  * A packet is eligible for outbound hardware acceleration if the
26447  * following conditions are satisfied:
26448  *
26449  * 1. the packet will not be fragmented
26450  * 2. the provider supports the algorithm
26451  * 3. there is no pending control message being exchanged
26452  * 4. snoop is not attached
26453  * 5. the destination address is not a broadcast or multicast address.
26454  *
26455  * Rationale:
26456  *	- Hardware drivers do not support fragmentation with
26457  *	  the current interface.
26458  *	- snoop, multicast, and broadcast may result in exposure of
26459  *	  a cleartext datagram.
26460  * We check all five of these conditions here.
26461  *
26462  * XXX would like to nuke "ire_t *" parameter here; problem is that
26463  * IRE is only way to figure out if a v4 address is a broadcast and
26464  * thus ineligible for acceleration...
26465  */
26466 static void
26467 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26468 {
26469 	ipsec_out_t *io;
26470 	mblk_t *data_mp;
26471 	uint_t plen, overhead;
26472 	ip_stack_t	*ipst;
26473 
26474 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26475 		return;
26476 
26477 	if (ill == NULL)
26478 		return;
26479 	ipst = ill->ill_ipst;
26480 	/*
26481 	 * Destination address is a broadcast or multicast.  Punt.
26482 	 */
26483 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26484 	    IRE_LOCAL)))
26485 		return;
26486 
26487 	data_mp = ipsec_mp->b_cont;
26488 
26489 	if (ill->ill_isv6) {
26490 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26491 
26492 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26493 			return;
26494 
26495 		plen = ip6h->ip6_plen;
26496 	} else {
26497 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26498 
26499 		if (CLASSD(ipha->ipha_dst))
26500 			return;
26501 
26502 		plen = ipha->ipha_length;
26503 	}
26504 	/*
26505 	 * Is there a pending DLPI control message being exchanged
26506 	 * between IP/IPsec and the DLS Provider? If there is, it
26507 	 * could be a SADB update, and the state of the DLS Provider
26508 	 * SADB might not be in sync with the SADB maintained by
26509 	 * IPsec. To avoid dropping packets or using the wrong keying
26510 	 * material, we do not accelerate this packet.
26511 	 */
26512 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26513 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26514 		    "ill_dlpi_pending! don't accelerate packet\n"));
26515 		return;
26516 	}
26517 
26518 	/*
26519 	 * Is the Provider in promiscous mode? If it does, we don't
26520 	 * accelerate the packet since it will bounce back up to the
26521 	 * listeners in the clear.
26522 	 */
26523 	if (ill->ill_promisc_on_phys) {
26524 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26525 		    "ill in promiscous mode, don't accelerate packet\n"));
26526 		return;
26527 	}
26528 
26529 	/*
26530 	 * Will the packet require fragmentation?
26531 	 */
26532 
26533 	/*
26534 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26535 	 * as is used elsewhere.
26536 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26537 	 *	+ 2-byte trailer
26538 	 */
26539 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26540 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26541 
26542 	if ((plen + overhead) > ill->ill_max_mtu)
26543 		return;
26544 
26545 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26546 
26547 	/*
26548 	 * Can the ill accelerate this IPsec protocol and algorithm
26549 	 * specified by the SA?
26550 	 */
26551 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26552 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26553 		return;
26554 	}
26555 
26556 	/*
26557 	 * Tell AH or ESP that the outbound ill is capable of
26558 	 * accelerating this packet.
26559 	 */
26560 	io->ipsec_out_is_capab_ill = B_TRUE;
26561 }
26562 
26563 /*
26564  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26565  *
26566  * If this function returns B_TRUE, the requested SA's have been filled
26567  * into the ipsec_out_*_sa pointers.
26568  *
26569  * If the function returns B_FALSE, the packet has been "consumed", most
26570  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26571  *
26572  * The SA references created by the protocol-specific "select"
26573  * function will be released when the ipsec_mp is freed, thanks to the
26574  * ipsec_out_free destructor -- see spd.c.
26575  */
26576 static boolean_t
26577 ipsec_out_select_sa(mblk_t *ipsec_mp)
26578 {
26579 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26580 	ipsec_out_t *io;
26581 	ipsec_policy_t *pp;
26582 	ipsec_action_t *ap;
26583 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26584 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26585 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26586 
26587 	if (!io->ipsec_out_secure) {
26588 		/*
26589 		 * We came here by mistake.
26590 		 * Don't bother with ipsec processing
26591 		 * We should "discourage" this path in the future.
26592 		 */
26593 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26594 		return (B_FALSE);
26595 	}
26596 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26597 	ASSERT((io->ipsec_out_policy != NULL) ||
26598 	    (io->ipsec_out_act != NULL));
26599 
26600 	ASSERT(io->ipsec_out_failed == B_FALSE);
26601 
26602 	/*
26603 	 * IPsec processing has started.
26604 	 */
26605 	io->ipsec_out_proc_begin = B_TRUE;
26606 	ap = io->ipsec_out_act;
26607 	if (ap == NULL) {
26608 		pp = io->ipsec_out_policy;
26609 		ASSERT(pp != NULL);
26610 		ap = pp->ipsp_act;
26611 		ASSERT(ap != NULL);
26612 	}
26613 
26614 	/*
26615 	 * We have an action.  now, let's select SA's.
26616 	 * (In the future, we can cache this in the conn_t..)
26617 	 */
26618 	if (ap->ipa_want_esp) {
26619 		if (io->ipsec_out_esp_sa == NULL) {
26620 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26621 			    IPPROTO_ESP);
26622 		}
26623 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26624 	}
26625 
26626 	if (ap->ipa_want_ah) {
26627 		if (io->ipsec_out_ah_sa == NULL) {
26628 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26629 			    IPPROTO_AH);
26630 		}
26631 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26632 		/*
26633 		 * The ESP and AH processing order needs to be preserved
26634 		 * when both protocols are required (ESP should be applied
26635 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26636 		 * when both ESP and AH are required, and an AH ACQUIRE
26637 		 * is needed.
26638 		 */
26639 		if (ap->ipa_want_esp && need_ah_acquire)
26640 			need_esp_acquire = B_TRUE;
26641 	}
26642 
26643 	/*
26644 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26645 	 * Release SAs that got referenced, but will not be used until we
26646 	 * acquire _all_ of the SAs we need.
26647 	 */
26648 	if (need_ah_acquire || need_esp_acquire) {
26649 		if (io->ipsec_out_ah_sa != NULL) {
26650 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26651 			io->ipsec_out_ah_sa = NULL;
26652 		}
26653 		if (io->ipsec_out_esp_sa != NULL) {
26654 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26655 			io->ipsec_out_esp_sa = NULL;
26656 		}
26657 
26658 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26659 		return (B_FALSE);
26660 	}
26661 
26662 	return (B_TRUE);
26663 }
26664 
26665 /*
26666  * Process an IPSEC_OUT message and see what you can
26667  * do with it.
26668  * IPQoS Notes:
26669  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26670  * IPsec.
26671  * XXX would like to nuke ire_t.
26672  * XXX ill_index better be "real"
26673  */
26674 void
26675 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26676 {
26677 	ipsec_out_t *io;
26678 	ipsec_policy_t *pp;
26679 	ipsec_action_t *ap;
26680 	ipha_t *ipha;
26681 	ip6_t *ip6h;
26682 	mblk_t *mp;
26683 	ill_t *ill;
26684 	zoneid_t zoneid;
26685 	ipsec_status_t ipsec_rc;
26686 	boolean_t ill_need_rele = B_FALSE;
26687 	ip_stack_t	*ipst;
26688 	ipsec_stack_t	*ipss;
26689 
26690 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26691 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26692 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26693 	ipst = io->ipsec_out_ns->netstack_ip;
26694 	mp = ipsec_mp->b_cont;
26695 
26696 	/*
26697 	 * Initiate IPPF processing. We do it here to account for packets
26698 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26699 	 * We can check for ipsec_out_proc_begin even for such packets, as
26700 	 * they will always be false (asserted below).
26701 	 */
26702 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26703 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26704 		    io->ipsec_out_ill_index : ill_index);
26705 		if (mp == NULL) {
26706 			ip2dbg(("ipsec_out_process: packet dropped "\
26707 			    "during IPPF processing\n"));
26708 			freeb(ipsec_mp);
26709 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26710 			return;
26711 		}
26712 	}
26713 
26714 	if (!io->ipsec_out_secure) {
26715 		/*
26716 		 * We came here by mistake.
26717 		 * Don't bother with ipsec processing
26718 		 * Should "discourage" this path in the future.
26719 		 */
26720 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26721 		goto done;
26722 	}
26723 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26724 	ASSERT((io->ipsec_out_policy != NULL) ||
26725 	    (io->ipsec_out_act != NULL));
26726 	ASSERT(io->ipsec_out_failed == B_FALSE);
26727 
26728 	ipss = ipst->ips_netstack->netstack_ipsec;
26729 	if (!ipsec_loaded(ipss)) {
26730 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26731 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26732 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26733 		} else {
26734 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26735 		}
26736 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26737 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26738 		    &ipss->ipsec_dropper);
26739 		return;
26740 	}
26741 
26742 	/*
26743 	 * IPsec processing has started.
26744 	 */
26745 	io->ipsec_out_proc_begin = B_TRUE;
26746 	ap = io->ipsec_out_act;
26747 	if (ap == NULL) {
26748 		pp = io->ipsec_out_policy;
26749 		ASSERT(pp != NULL);
26750 		ap = pp->ipsp_act;
26751 		ASSERT(ap != NULL);
26752 	}
26753 
26754 	/*
26755 	 * Save the outbound ill index. When the packet comes back
26756 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26757 	 * before sending it the accelerated packet.
26758 	 */
26759 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26760 		int ifindex;
26761 		ill = ire_to_ill(ire);
26762 		ifindex = ill->ill_phyint->phyint_ifindex;
26763 		io->ipsec_out_capab_ill_index = ifindex;
26764 	}
26765 
26766 	/*
26767 	 * The order of processing is first insert a IP header if needed.
26768 	 * Then insert the ESP header and then the AH header.
26769 	 */
26770 	if ((io->ipsec_out_se_done == B_FALSE) &&
26771 	    (ap->ipa_want_se)) {
26772 		/*
26773 		 * First get the outer IP header before sending
26774 		 * it to ESP.
26775 		 */
26776 		ipha_t *oipha, *iipha;
26777 		mblk_t *outer_mp, *inner_mp;
26778 
26779 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26780 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26781 			    "ipsec_out_process: "
26782 			    "Self-Encapsulation failed: Out of memory\n");
26783 			freemsg(ipsec_mp);
26784 			if (ill != NULL) {
26785 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26786 			} else {
26787 				BUMP_MIB(&ipst->ips_ip_mib,
26788 				    ipIfStatsOutDiscards);
26789 			}
26790 			return;
26791 		}
26792 		inner_mp = ipsec_mp->b_cont;
26793 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26794 		oipha = (ipha_t *)outer_mp->b_rptr;
26795 		iipha = (ipha_t *)inner_mp->b_rptr;
26796 		*oipha = *iipha;
26797 		outer_mp->b_wptr += sizeof (ipha_t);
26798 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26799 		    sizeof (ipha_t));
26800 		oipha->ipha_protocol = IPPROTO_ENCAP;
26801 		oipha->ipha_version_and_hdr_length =
26802 		    IP_SIMPLE_HDR_VERSION;
26803 		oipha->ipha_hdr_checksum = 0;
26804 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26805 		outer_mp->b_cont = inner_mp;
26806 		ipsec_mp->b_cont = outer_mp;
26807 
26808 		io->ipsec_out_se_done = B_TRUE;
26809 		io->ipsec_out_tunnel = B_TRUE;
26810 	}
26811 
26812 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26813 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26814 	    !ipsec_out_select_sa(ipsec_mp))
26815 		return;
26816 
26817 	/*
26818 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26819 	 * to do the heavy lifting.
26820 	 */
26821 	zoneid = io->ipsec_out_zoneid;
26822 	ASSERT(zoneid != ALL_ZONES);
26823 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26824 		ASSERT(io->ipsec_out_esp_sa != NULL);
26825 		io->ipsec_out_esp_done = B_TRUE;
26826 		/*
26827 		 * Note that since hw accel can only apply one transform,
26828 		 * not two, we skip hw accel for ESP if we also have AH
26829 		 * This is an design limitation of the interface
26830 		 * which should be revisited.
26831 		 */
26832 		ASSERT(ire != NULL);
26833 		if (io->ipsec_out_ah_sa == NULL) {
26834 			ill = (ill_t *)ire->ire_stq->q_ptr;
26835 			ipsec_out_is_accelerated(ipsec_mp,
26836 			    io->ipsec_out_esp_sa, ill, ire);
26837 		}
26838 
26839 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26840 		switch (ipsec_rc) {
26841 		case IPSEC_STATUS_SUCCESS:
26842 			break;
26843 		case IPSEC_STATUS_FAILED:
26844 			if (ill != NULL) {
26845 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26846 			} else {
26847 				BUMP_MIB(&ipst->ips_ip_mib,
26848 				    ipIfStatsOutDiscards);
26849 			}
26850 			/* FALLTHRU */
26851 		case IPSEC_STATUS_PENDING:
26852 			return;
26853 		}
26854 	}
26855 
26856 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26857 		ASSERT(io->ipsec_out_ah_sa != NULL);
26858 		io->ipsec_out_ah_done = B_TRUE;
26859 		if (ire == NULL) {
26860 			int idx = io->ipsec_out_capab_ill_index;
26861 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26862 			    NULL, NULL, NULL, NULL, ipst);
26863 			ill_need_rele = B_TRUE;
26864 		} else {
26865 			ill = (ill_t *)ire->ire_stq->q_ptr;
26866 		}
26867 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26868 		    ire);
26869 
26870 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26871 		switch (ipsec_rc) {
26872 		case IPSEC_STATUS_SUCCESS:
26873 			break;
26874 		case IPSEC_STATUS_FAILED:
26875 			if (ill != NULL) {
26876 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26877 			} else {
26878 				BUMP_MIB(&ipst->ips_ip_mib,
26879 				    ipIfStatsOutDiscards);
26880 			}
26881 			/* FALLTHRU */
26882 		case IPSEC_STATUS_PENDING:
26883 			if (ill != NULL && ill_need_rele)
26884 				ill_refrele(ill);
26885 			return;
26886 		}
26887 	}
26888 	/*
26889 	 * We are done with IPsec processing. Send it over
26890 	 * the wire.
26891 	 */
26892 done:
26893 	mp = ipsec_mp->b_cont;
26894 	ipha = (ipha_t *)mp->b_rptr;
26895 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26896 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
26897 	} else {
26898 		ip6h = (ip6_t *)ipha;
26899 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
26900 	}
26901 	if (ill != NULL && ill_need_rele)
26902 		ill_refrele(ill);
26903 }
26904 
26905 /* ARGSUSED */
26906 void
26907 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26908 {
26909 	opt_restart_t	*or;
26910 	int	err;
26911 	conn_t	*connp;
26912 
26913 	ASSERT(CONN_Q(q));
26914 	connp = Q_TO_CONN(q);
26915 
26916 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26917 	or = (opt_restart_t *)first_mp->b_rptr;
26918 	/*
26919 	 * We don't need to pass any credentials here since this is just
26920 	 * a restart. The credentials are passed in when svr4_optcom_req
26921 	 * is called the first time (from ip_wput_nondata).
26922 	 */
26923 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26924 		err = svr4_optcom_req(q, first_mp, NULL,
26925 		    &ip_opt_obj, B_FALSE);
26926 	} else {
26927 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26928 		err = tpi_optcom_req(q, first_mp, NULL,
26929 		    &ip_opt_obj, B_FALSE);
26930 	}
26931 	if (err != EINPROGRESS) {
26932 		/* operation is done */
26933 		CONN_OPER_PENDING_DONE(connp);
26934 	}
26935 }
26936 
26937 /*
26938  * ioctls that go through a down/up sequence may need to wait for the down
26939  * to complete. This involves waiting for the ire and ipif refcnts to go down
26940  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26941  */
26942 /* ARGSUSED */
26943 void
26944 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26945 {
26946 	struct iocblk *iocp;
26947 	mblk_t *mp1;
26948 	ip_ioctl_cmd_t *ipip;
26949 	int err;
26950 	sin_t	*sin;
26951 	struct lifreq *lifr;
26952 	struct ifreq *ifr;
26953 
26954 	iocp = (struct iocblk *)mp->b_rptr;
26955 	ASSERT(ipsq != NULL);
26956 	/* Existence of mp1 verified in ip_wput_nondata */
26957 	mp1 = mp->b_cont->b_cont;
26958 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26959 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26960 		/*
26961 		 * Special case where ipsq_current_ipif is not set:
26962 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26963 		 * ill could also have become part of a ipmp group in the
26964 		 * process, we are here as were not able to complete the
26965 		 * operation in ipif_set_values because we could not become
26966 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
26967 		 * will not be set so we need to set it.
26968 		 */
26969 		ill_t *ill = q->q_ptr;
26970 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
26971 	}
26972 	ASSERT(ipsq->ipsq_current_ipif != NULL);
26973 
26974 	if (ipip->ipi_cmd_type == IF_CMD) {
26975 		/* This a old style SIOC[GS]IF* command */
26976 		ifr = (struct ifreq *)mp1->b_rptr;
26977 		sin = (sin_t *)&ifr->ifr_addr;
26978 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26979 		/* This a new style SIOC[GS]LIF* command */
26980 		lifr = (struct lifreq *)mp1->b_rptr;
26981 		sin = (sin_t *)&lifr->lifr_addr;
26982 	} else {
26983 		sin = NULL;
26984 	}
26985 
26986 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_current_ipif, sin, q, mp,
26987 	    ipip, mp1->b_rptr);
26988 
26989 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26990 }
26991 
26992 /*
26993  * ioctl processing
26994  *
26995  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
26996  * the ioctl command in the ioctl tables, determines the copyin data size
26997  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
26998  *
26999  * ioctl processing then continues when the M_IOCDATA makes its way down to
27000  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
27001  * associated 'conn' is refheld till the end of the ioctl and the general
27002  * ioctl processing function ip_process_ioctl() is called to extract the
27003  * arguments and process the ioctl.  To simplify extraction, ioctl commands
27004  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
27005  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
27006  * is used to extract the ioctl's arguments.
27007  *
27008  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
27009  * so goes thru the serialization primitive ipsq_try_enter. Then the
27010  * appropriate function to handle the ioctl is called based on the entry in
27011  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
27012  * which also refreleases the 'conn' that was refheld at the start of the
27013  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
27014  *
27015  * Many exclusive ioctls go thru an internal down up sequence as part of
27016  * the operation. For example an attempt to change the IP address of an
27017  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
27018  * does all the cleanup such as deleting all ires that use this address.
27019  * Then we need to wait till all references to the interface go away.
27020  */
27021 void
27022 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
27023 {
27024 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
27025 	ip_ioctl_cmd_t *ipip = arg;
27026 	ip_extract_func_t *extract_funcp;
27027 	cmd_info_t ci;
27028 	int err;
27029 
27030 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
27031 
27032 	if (ipip == NULL)
27033 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27034 
27035 	/*
27036 	 * SIOCLIFADDIF needs to go thru a special path since the
27037 	 * ill may not exist yet. This happens in the case of lo0
27038 	 * which is created using this ioctl.
27039 	 */
27040 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
27041 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
27042 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27043 		return;
27044 	}
27045 
27046 	ci.ci_ipif = NULL;
27047 	if (ipip->ipi_cmd_type == MISC_CMD) {
27048 		/*
27049 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
27050 		 */
27051 		if (ipip->ipi_cmd == IF_UNITSEL) {
27052 			/* ioctl comes down the ill */
27053 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
27054 			ipif_refhold(ci.ci_ipif);
27055 		}
27056 		err = 0;
27057 		ci.ci_sin = NULL;
27058 		ci.ci_sin6 = NULL;
27059 		ci.ci_lifr = NULL;
27060 	} else {
27061 		switch (ipip->ipi_cmd_type) {
27062 		case IF_CMD:
27063 		case LIF_CMD:
27064 			extract_funcp = ip_extract_lifreq;
27065 			break;
27066 
27067 		case ARP_CMD:
27068 		case XARP_CMD:
27069 			extract_funcp = ip_extract_arpreq;
27070 			break;
27071 
27072 		case TUN_CMD:
27073 			extract_funcp = ip_extract_tunreq;
27074 			break;
27075 
27076 		case MSFILT_CMD:
27077 			extract_funcp = ip_extract_msfilter;
27078 			break;
27079 
27080 		default:
27081 			ASSERT(0);
27082 		}
27083 
27084 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
27085 		if (err != 0) {
27086 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27087 			return;
27088 		}
27089 
27090 		/*
27091 		 * All of the extraction functions return a refheld ipif.
27092 		 */
27093 		ASSERT(ci.ci_ipif != NULL);
27094 	}
27095 
27096 	if (!(ipip->ipi_flags & IPI_WR)) {
27097 		/*
27098 		 * A return value of EINPROGRESS means the ioctl is
27099 		 * either queued and waiting for some reason or has
27100 		 * already completed.
27101 		 */
27102 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
27103 		    ci.ci_lifr);
27104 		if (ci.ci_ipif != NULL)
27105 			ipif_refrele(ci.ci_ipif);
27106 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27107 		return;
27108 	}
27109 
27110 	/*
27111 	 * If ipsq is non-null, we are already being called exclusively on an
27112 	 * ill but in the case of a failover in progress it is the "from" ill,
27113 	 *  rather than the "to" ill (which is the ill ptr passed in).
27114 	 * In order to ensure we are exclusive on both ILLs we rerun
27115 	 * ipsq_try_enter() here, ipsq's support recursive entry.
27116 	 */
27117 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
27118 	ASSERT(ci.ci_ipif != NULL);
27119 
27120 	ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
27121 	    NEW_OP, B_TRUE);
27122 
27123 	/*
27124 	 * Release the ipif so that ipif_down and friends that wait for
27125 	 * references to go away are not misled about the current ipif_refcnt
27126 	 * values. We are writer so we can access the ipif even after releasing
27127 	 * the ipif.
27128 	 */
27129 	ipif_refrele(ci.ci_ipif);
27130 	if (ipsq == NULL)
27131 		return;
27132 
27133 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
27134 
27135 	/*
27136 	 * For most set ioctls that come here, this serves as a single point
27137 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
27138 	 * be any new references to the ipif. This helps functions that go
27139 	 * through this path and end up trying to wait for the refcnts
27140 	 * associated with the ipif to go down to zero. Some exceptions are
27141 	 * Failover, Failback, and Groupname commands that operate on more than
27142 	 * just the ci.ci_ipif. These commands internally determine the
27143 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
27144 	 * flags on that set. Another exception is the Removeif command that
27145 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
27146 	 * ipif to operate on.
27147 	 */
27148 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
27149 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
27150 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
27151 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
27152 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
27153 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
27154 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
27155 
27156 	/*
27157 	 * A return value of EINPROGRESS means the ioctl is
27158 	 * either queued and waiting for some reason or has
27159 	 * already completed.
27160 	 */
27161 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
27162 
27163 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27164 
27165 	ipsq_exit(ipsq);
27166 }
27167 
27168 /*
27169  * Complete the ioctl. Typically ioctls use the mi package and need to
27170  * do mi_copyout/mi_copy_done.
27171  */
27172 void
27173 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
27174 {
27175 	conn_t	*connp = NULL;
27176 
27177 	if (err == EINPROGRESS)
27178 		return;
27179 
27180 	if (CONN_Q(q)) {
27181 		connp = Q_TO_CONN(q);
27182 		ASSERT(connp->conn_ref >= 2);
27183 	}
27184 
27185 	switch (mode) {
27186 	case COPYOUT:
27187 		if (err == 0)
27188 			mi_copyout(q, mp);
27189 		else
27190 			mi_copy_done(q, mp, err);
27191 		break;
27192 
27193 	case NO_COPYOUT:
27194 		mi_copy_done(q, mp, err);
27195 		break;
27196 
27197 	default:
27198 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27199 		break;
27200 	}
27201 
27202 	/*
27203 	 * The refhold placed at the start of the ioctl is released here.
27204 	 */
27205 	if (connp != NULL)
27206 		CONN_OPER_PENDING_DONE(connp);
27207 
27208 	if (ipsq != NULL)
27209 		ipsq_current_finish(ipsq);
27210 }
27211 
27212 /*
27213  * This is called from ip_wput_nondata to resume a deferred TCP bind.
27214  */
27215 /* ARGSUSED */
27216 void
27217 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
27218 {
27219 	conn_t *connp = arg;
27220 	tcp_t	*tcp;
27221 
27222 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
27223 	tcp = connp->conn_tcp;
27224 
27225 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
27226 		freemsg(mp);
27227 	else
27228 		tcp_rput_other(tcp, mp);
27229 	CONN_OPER_PENDING_DONE(connp);
27230 }
27231 
27232 /* Called from ip_wput for all non data messages */
27233 /* ARGSUSED */
27234 void
27235 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27236 {
27237 	mblk_t		*mp1;
27238 	ire_t		*ire, *fake_ire;
27239 	ill_t		*ill;
27240 	struct iocblk	*iocp;
27241 	ip_ioctl_cmd_t	*ipip;
27242 	cred_t		*cr;
27243 	conn_t		*connp;
27244 	int		err;
27245 	nce_t		*nce;
27246 	ipif_t		*ipif;
27247 	ip_stack_t	*ipst;
27248 	char		*proto_str;
27249 
27250 	if (CONN_Q(q)) {
27251 		connp = Q_TO_CONN(q);
27252 		ipst = connp->conn_netstack->netstack_ip;
27253 	} else {
27254 		connp = NULL;
27255 		ipst = ILLQ_TO_IPST(q);
27256 	}
27257 
27258 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
27259 
27260 	switch (DB_TYPE(mp)) {
27261 	case M_IOCTL:
27262 		/*
27263 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27264 		 * will arrange to copy in associated control structures.
27265 		 */
27266 		ip_sioctl_copyin_setup(q, mp);
27267 		return;
27268 	case M_IOCDATA:
27269 		/*
27270 		 * Ensure that this is associated with one of our trans-
27271 		 * parent ioctls.  If it's not ours, discard it if we're
27272 		 * running as a driver, or pass it on if we're a module.
27273 		 */
27274 		iocp = (struct iocblk *)mp->b_rptr;
27275 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27276 		if (ipip == NULL) {
27277 			if (q->q_next == NULL) {
27278 				goto nak;
27279 			} else {
27280 				putnext(q, mp);
27281 			}
27282 			return;
27283 		}
27284 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
27285 			/*
27286 			 * the ioctl is one we recognise, but is not
27287 			 * consumed by IP as a module, pass M_IOCDATA
27288 			 * for processing downstream, but only for
27289 			 * common Streams ioctls.
27290 			 */
27291 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27292 				putnext(q, mp);
27293 				return;
27294 			} else {
27295 				goto nak;
27296 			}
27297 		}
27298 
27299 		/* IOCTL continuation following copyin or copyout. */
27300 		if (mi_copy_state(q, mp, NULL) == -1) {
27301 			/*
27302 			 * The copy operation failed.  mi_copy_state already
27303 			 * cleaned up, so we're out of here.
27304 			 */
27305 			return;
27306 		}
27307 		/*
27308 		 * If we just completed a copy in, we become writer and
27309 		 * continue processing in ip_sioctl_copyin_done.  If it
27310 		 * was a copy out, we call mi_copyout again.  If there is
27311 		 * nothing more to copy out, it will complete the IOCTL.
27312 		 */
27313 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27314 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27315 				mi_copy_done(q, mp, EPROTO);
27316 				return;
27317 			}
27318 			/*
27319 			 * Check for cases that need more copying.  A return
27320 			 * value of 0 means a second copyin has been started,
27321 			 * so we return; a return value of 1 means no more
27322 			 * copying is needed, so we continue.
27323 			 */
27324 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27325 			    MI_COPY_COUNT(mp) == 1) {
27326 				if (ip_copyin_msfilter(q, mp) == 0)
27327 					return;
27328 			}
27329 			/*
27330 			 * Refhold the conn, till the ioctl completes. This is
27331 			 * needed in case the ioctl ends up in the pending mp
27332 			 * list. Every mp in the ill_pending_mp list and
27333 			 * the ipsq_pending_mp must have a refhold on the conn
27334 			 * to resume processing. The refhold is released when
27335 			 * the ioctl completes. (normally or abnormally)
27336 			 * In all cases ip_ioctl_finish is called to finish
27337 			 * the ioctl.
27338 			 */
27339 			if (connp != NULL) {
27340 				/* This is not a reentry */
27341 				ASSERT(ipsq == NULL);
27342 				CONN_INC_REF(connp);
27343 			} else {
27344 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27345 					mi_copy_done(q, mp, EINVAL);
27346 					return;
27347 				}
27348 			}
27349 
27350 			ip_process_ioctl(ipsq, q, mp, ipip);
27351 
27352 		} else {
27353 			mi_copyout(q, mp);
27354 		}
27355 		return;
27356 nak:
27357 		iocp->ioc_error = EINVAL;
27358 		mp->b_datap->db_type = M_IOCNAK;
27359 		iocp->ioc_count = 0;
27360 		qreply(q, mp);
27361 		return;
27362 
27363 	case M_IOCNAK:
27364 		/*
27365 		 * The only way we could get here is if a resolver didn't like
27366 		 * an IOCTL we sent it.	 This shouldn't happen.
27367 		 */
27368 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27369 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27370 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27371 		freemsg(mp);
27372 		return;
27373 	case M_IOCACK:
27374 		/* /dev/ip shouldn't see this */
27375 		if (CONN_Q(q))
27376 			goto nak;
27377 
27378 		/* Finish socket ioctls passed through to ARP. */
27379 		ip_sioctl_iocack(q, mp);
27380 		return;
27381 	case M_FLUSH:
27382 		if (*mp->b_rptr & FLUSHW)
27383 			flushq(q, FLUSHALL);
27384 		if (q->q_next) {
27385 			putnext(q, mp);
27386 			return;
27387 		}
27388 		if (*mp->b_rptr & FLUSHR) {
27389 			*mp->b_rptr &= ~FLUSHW;
27390 			qreply(q, mp);
27391 			return;
27392 		}
27393 		freemsg(mp);
27394 		return;
27395 	case IRE_DB_REQ_TYPE:
27396 		if (connp == NULL) {
27397 			proto_str = "IRE_DB_REQ_TYPE";
27398 			goto protonak;
27399 		}
27400 		/* An Upper Level Protocol wants a copy of an IRE. */
27401 		ip_ire_req(q, mp);
27402 		return;
27403 	case M_CTL:
27404 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27405 			break;
27406 
27407 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27408 		    TUN_HELLO) {
27409 			ASSERT(connp != NULL);
27410 			connp->conn_flags |= IPCL_IPTUN;
27411 			freeb(mp);
27412 			return;
27413 		}
27414 
27415 		/* M_CTL messages are used by ARP to tell us things. */
27416 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27417 			break;
27418 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27419 		case AR_ENTRY_SQUERY:
27420 			ip_wput_ctl(q, mp);
27421 			return;
27422 		case AR_CLIENT_NOTIFY:
27423 			ip_arp_news(q, mp);
27424 			return;
27425 		case AR_DLPIOP_DONE:
27426 			ASSERT(q->q_next != NULL);
27427 			ill = (ill_t *)q->q_ptr;
27428 			/* qwriter_ip releases the refhold */
27429 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27430 			ill_refhold(ill);
27431 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27432 			return;
27433 		case AR_ARP_CLOSING:
27434 			/*
27435 			 * ARP (above us) is closing. If no ARP bringup is
27436 			 * currently pending, ack the message so that ARP
27437 			 * can complete its close. Also mark ill_arp_closing
27438 			 * so that new ARP bringups will fail. If any
27439 			 * ARP bringup is currently in progress, we will
27440 			 * ack this when the current ARP bringup completes.
27441 			 */
27442 			ASSERT(q->q_next != NULL);
27443 			ill = (ill_t *)q->q_ptr;
27444 			mutex_enter(&ill->ill_lock);
27445 			ill->ill_arp_closing = 1;
27446 			if (!ill->ill_arp_bringup_pending) {
27447 				mutex_exit(&ill->ill_lock);
27448 				qreply(q, mp);
27449 			} else {
27450 				mutex_exit(&ill->ill_lock);
27451 				freemsg(mp);
27452 			}
27453 			return;
27454 		case AR_ARP_EXTEND:
27455 			/*
27456 			 * The ARP module above us is capable of duplicate
27457 			 * address detection.  Old ATM drivers will not send
27458 			 * this message.
27459 			 */
27460 			ASSERT(q->q_next != NULL);
27461 			ill = (ill_t *)q->q_ptr;
27462 			ill->ill_arp_extend = B_TRUE;
27463 			freemsg(mp);
27464 			return;
27465 		default:
27466 			break;
27467 		}
27468 		break;
27469 	case M_PROTO:
27470 	case M_PCPROTO:
27471 		/*
27472 		 * The only PROTO messages we expect are ULP binds and
27473 		 * copies of option negotiation acknowledgements.
27474 		 */
27475 		switch (((union T_primitives *)mp->b_rptr)->type) {
27476 		case O_T_BIND_REQ:
27477 		case T_BIND_REQ: {
27478 			/* Request can get queued in bind */
27479 			if (connp == NULL) {
27480 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27481 				goto protonak;
27482 			}
27483 			/*
27484 			 * The transports except SCTP call ip_bind_{v4,v6}()
27485 			 * directly instead of a a putnext. SCTP doesn't
27486 			 * generate any T_BIND_REQ since it has its own
27487 			 * fanout data structures. However, ESP and AH
27488 			 * come in for regular binds; all other cases are
27489 			 * bind retries.
27490 			 */
27491 			ASSERT(!IPCL_IS_SCTP(connp));
27492 
27493 			/* Don't increment refcnt if this is a re-entry */
27494 			if (ipsq == NULL)
27495 				CONN_INC_REF(connp);
27496 
27497 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27498 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27499 			if (mp == NULL)
27500 				return;
27501 			if (IPCL_IS_TCP(connp)) {
27502 				/*
27503 				 * In the case of TCP endpoint we
27504 				 * come here only for bind retries
27505 				 */
27506 				ASSERT(ipsq != NULL);
27507 				CONN_INC_REF(connp);
27508 				squeue_fill(connp->conn_sqp, mp,
27509 				    ip_resume_tcp_bind, connp,
27510 				    SQTAG_BIND_RETRY);
27511 			} else if (IPCL_IS_UDP(connp)) {
27512 				/*
27513 				 * In the case of UDP endpoint we
27514 				 * come here only for bind retries
27515 				 */
27516 				ASSERT(ipsq != NULL);
27517 				udp_resume_bind(connp, mp);
27518 			} else if (IPCL_IS_RAWIP(connp)) {
27519 				/*
27520 				 * In the case of RAWIP endpoint we
27521 				 * come here only for bind retries
27522 				 */
27523 				ASSERT(ipsq != NULL);
27524 				rawip_resume_bind(connp, mp);
27525 			} else {
27526 				/* The case of AH and ESP */
27527 				qreply(q, mp);
27528 				CONN_OPER_PENDING_DONE(connp);
27529 			}
27530 			return;
27531 		}
27532 		case T_SVR4_OPTMGMT_REQ:
27533 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27534 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27535 
27536 			if (connp == NULL) {
27537 				proto_str = "T_SVR4_OPTMGMT_REQ";
27538 				goto protonak;
27539 			}
27540 
27541 			if (!snmpcom_req(q, mp, ip_snmp_set,
27542 			    ip_snmp_get, cr)) {
27543 				/*
27544 				 * Call svr4_optcom_req so that it can
27545 				 * generate the ack. We don't come here
27546 				 * if this operation is being restarted.
27547 				 * ip_restart_optmgmt will drop the conn ref.
27548 				 * In the case of ipsec option after the ipsec
27549 				 * load is complete conn_restart_ipsec_waiter
27550 				 * drops the conn ref.
27551 				 */
27552 				ASSERT(ipsq == NULL);
27553 				CONN_INC_REF(connp);
27554 				if (ip_check_for_ipsec_opt(q, mp))
27555 					return;
27556 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj,
27557 				    B_FALSE);
27558 				if (err != EINPROGRESS) {
27559 					/* Operation is done */
27560 					CONN_OPER_PENDING_DONE(connp);
27561 				}
27562 			}
27563 			return;
27564 		case T_OPTMGMT_REQ:
27565 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27566 			/*
27567 			 * Note: No snmpcom_req support through new
27568 			 * T_OPTMGMT_REQ.
27569 			 * Call tpi_optcom_req so that it can
27570 			 * generate the ack.
27571 			 */
27572 			if (connp == NULL) {
27573 				proto_str = "T_OPTMGMT_REQ";
27574 				goto protonak;
27575 			}
27576 
27577 			ASSERT(ipsq == NULL);
27578 			/*
27579 			 * We don't come here for restart. ip_restart_optmgmt
27580 			 * will drop the conn ref. In the case of ipsec option
27581 			 * after the ipsec load is complete
27582 			 * conn_restart_ipsec_waiter drops the conn ref.
27583 			 */
27584 			CONN_INC_REF(connp);
27585 			if (ip_check_for_ipsec_opt(q, mp))
27586 				return;
27587 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj, B_FALSE);
27588 			if (err != EINPROGRESS) {
27589 				/* Operation is done */
27590 				CONN_OPER_PENDING_DONE(connp);
27591 			}
27592 			return;
27593 		case T_UNBIND_REQ:
27594 			if (connp == NULL) {
27595 				proto_str = "T_UNBIND_REQ";
27596 				goto protonak;
27597 			}
27598 			mp = ip_unbind(q, mp);
27599 			qreply(q, mp);
27600 			return;
27601 		default:
27602 			/*
27603 			 * Have to drop any DLPI messages coming down from
27604 			 * arp (such as an info_req which would cause ip
27605 			 * to receive an extra info_ack if it was passed
27606 			 * through.
27607 			 */
27608 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27609 			    (int)*(uint_t *)mp->b_rptr));
27610 			freemsg(mp);
27611 			return;
27612 		}
27613 		/* NOTREACHED */
27614 	case IRE_DB_TYPE: {
27615 		nce_t		*nce;
27616 		ill_t		*ill;
27617 		in6_addr_t	gw_addr_v6;
27618 
27619 
27620 		/*
27621 		 * This is a response back from a resolver.  It
27622 		 * consists of a message chain containing:
27623 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27624 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27625 		 * The LL_HDR_MBLK is the DLPI header to use to get
27626 		 * the attached packet, and subsequent ones for the
27627 		 * same destination, transmitted.
27628 		 */
27629 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27630 			break;
27631 		/*
27632 		 * First, check to make sure the resolution succeeded.
27633 		 * If it failed, the second mblk will be empty.
27634 		 * If it is, free the chain, dropping the packet.
27635 		 * (We must ire_delete the ire; that frees the ire mblk)
27636 		 * We're doing this now to support PVCs for ATM; it's
27637 		 * a partial xresolv implementation. When we fully implement
27638 		 * xresolv interfaces, instead of freeing everything here
27639 		 * we'll initiate neighbor discovery.
27640 		 *
27641 		 * For v4 (ARP and other external resolvers) the resolver
27642 		 * frees the message, so no check is needed. This check
27643 		 * is required, though, for a full xresolve implementation.
27644 		 * Including this code here now both shows how external
27645 		 * resolvers can NACK a resolution request using an
27646 		 * existing design that has no specific provisions for NACKs,
27647 		 * and also takes into account that the current non-ARP
27648 		 * external resolver has been coded to use this method of
27649 		 * NACKing for all IPv6 (xresolv) cases,
27650 		 * whether our xresolv implementation is complete or not.
27651 		 *
27652 		 */
27653 		ire = (ire_t *)mp->b_rptr;
27654 		ill = ire_to_ill(ire);
27655 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27656 		if (mp1->b_rptr == mp1->b_wptr) {
27657 			if (ire->ire_ipversion == IPV6_VERSION) {
27658 				/*
27659 				 * XRESOLV interface.
27660 				 */
27661 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27662 				mutex_enter(&ire->ire_lock);
27663 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27664 				mutex_exit(&ire->ire_lock);
27665 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27666 					nce = ndp_lookup_v6(ill,
27667 					    &ire->ire_addr_v6, B_FALSE);
27668 				} else {
27669 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
27670 					    B_FALSE);
27671 				}
27672 				if (nce != NULL) {
27673 					nce_resolv_failed(nce);
27674 					ndp_delete(nce);
27675 					NCE_REFRELE(nce);
27676 				}
27677 			}
27678 			mp->b_cont = NULL;
27679 			freemsg(mp1);		/* frees the pkt as well */
27680 			ASSERT(ire->ire_nce == NULL);
27681 			ire_delete((ire_t *)mp->b_rptr);
27682 			return;
27683 		}
27684 
27685 		/*
27686 		 * Split them into IRE_MBLK and pkt and feed it into
27687 		 * ire_add_then_send. Then in ire_add_then_send
27688 		 * the IRE will be added, and then the packet will be
27689 		 * run back through ip_wput. This time it will make
27690 		 * it to the wire.
27691 		 */
27692 		mp->b_cont = NULL;
27693 		mp = mp1->b_cont;		/* now, mp points to pkt */
27694 		mp1->b_cont = NULL;
27695 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27696 		if (ire->ire_ipversion == IPV6_VERSION) {
27697 			/*
27698 			 * XRESOLV interface. Find the nce and put a copy
27699 			 * of the dl_unitdata_req in nce_res_mp
27700 			 */
27701 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27702 			mutex_enter(&ire->ire_lock);
27703 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27704 			mutex_exit(&ire->ire_lock);
27705 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27706 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
27707 				    B_FALSE);
27708 			} else {
27709 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
27710 			}
27711 			if (nce != NULL) {
27712 				/*
27713 				 * We have to protect nce_res_mp here
27714 				 * from being accessed by other threads
27715 				 * while we change the mblk pointer.
27716 				 * Other functions will also lock the nce when
27717 				 * accessing nce_res_mp.
27718 				 *
27719 				 * The reason we change the mblk pointer
27720 				 * here rather than copying the resolved address
27721 				 * into the template is that, unlike with
27722 				 * ethernet, we have no guarantee that the
27723 				 * resolved address length will be
27724 				 * smaller than or equal to the lla length
27725 				 * with which the template was allocated,
27726 				 * (for ethernet, they're equal)
27727 				 * so we have to use the actual resolved
27728 				 * address mblk - which holds the real
27729 				 * dl_unitdata_req with the resolved address.
27730 				 *
27731 				 * Doing this is the same behavior as was
27732 				 * previously used in the v4 ARP case.
27733 				 */
27734 				mutex_enter(&nce->nce_lock);
27735 				if (nce->nce_res_mp != NULL)
27736 					freemsg(nce->nce_res_mp);
27737 				nce->nce_res_mp = mp1;
27738 				mutex_exit(&nce->nce_lock);
27739 				/*
27740 				 * We do a fastpath probe here because
27741 				 * we have resolved the address without
27742 				 * using Neighbor Discovery.
27743 				 * In the non-XRESOLV v6 case, the fastpath
27744 				 * probe is done right after neighbor
27745 				 * discovery completes.
27746 				 */
27747 				if (nce->nce_res_mp != NULL) {
27748 					int res;
27749 					nce_fastpath_list_add(nce);
27750 					res = ill_fastpath_probe(ill,
27751 					    nce->nce_res_mp);
27752 					if (res != 0 && res != EAGAIN)
27753 						nce_fastpath_list_delete(nce);
27754 				}
27755 
27756 				ire_add_then_send(q, ire, mp);
27757 				/*
27758 				 * Now we have to clean out any packets
27759 				 * that may have been queued on the nce
27760 				 * while it was waiting for address resolution
27761 				 * to complete.
27762 				 */
27763 				mutex_enter(&nce->nce_lock);
27764 				mp1 = nce->nce_qd_mp;
27765 				nce->nce_qd_mp = NULL;
27766 				mutex_exit(&nce->nce_lock);
27767 				while (mp1 != NULL) {
27768 					mblk_t *nxt_mp;
27769 					queue_t *fwdq = NULL;
27770 					ill_t   *inbound_ill;
27771 					uint_t ifindex;
27772 
27773 					nxt_mp = mp1->b_next;
27774 					mp1->b_next = NULL;
27775 					/*
27776 					 * Retrieve ifindex stored in
27777 					 * ip_rput_data_v6()
27778 					 */
27779 					ifindex =
27780 					    (uint_t)(uintptr_t)mp1->b_prev;
27781 					inbound_ill =
27782 					    ill_lookup_on_ifindex(ifindex,
27783 					    B_TRUE, NULL, NULL, NULL,
27784 					    NULL, ipst);
27785 					mp1->b_prev = NULL;
27786 					if (inbound_ill != NULL)
27787 						fwdq = inbound_ill->ill_rq;
27788 
27789 					if (fwdq != NULL) {
27790 						put(fwdq, mp1);
27791 						ill_refrele(inbound_ill);
27792 					} else
27793 						put(WR(ill->ill_rq), mp1);
27794 					mp1 = nxt_mp;
27795 				}
27796 				NCE_REFRELE(nce);
27797 			} else {	/* nce is NULL; clean up */
27798 				ire_delete(ire);
27799 				freemsg(mp);
27800 				freemsg(mp1);
27801 				return;
27802 			}
27803 		} else {
27804 			nce_t *arpce;
27805 			/*
27806 			 * Link layer resolution succeeded. Recompute the
27807 			 * ire_nce.
27808 			 */
27809 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27810 			if ((arpce = ndp_lookup_v4(ill,
27811 			    (ire->ire_gateway_addr != INADDR_ANY ?
27812 			    &ire->ire_gateway_addr : &ire->ire_addr),
27813 			    B_FALSE)) == NULL) {
27814 				freeb(ire->ire_mp);
27815 				freeb(mp1);
27816 				freemsg(mp);
27817 				return;
27818 			}
27819 			mutex_enter(&arpce->nce_lock);
27820 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27821 			if (arpce->nce_state == ND_REACHABLE) {
27822 				/*
27823 				 * Someone resolved this before us;
27824 				 * cleanup the res_mp. Since ire has
27825 				 * not been added yet, the call to ire_add_v4
27826 				 * from ire_add_then_send (when a dup is
27827 				 * detected) will clean up the ire.
27828 				 */
27829 				freeb(mp1);
27830 			} else {
27831 				ASSERT(arpce->nce_res_mp == NULL);
27832 				arpce->nce_res_mp = mp1;
27833 				arpce->nce_state = ND_REACHABLE;
27834 			}
27835 			mutex_exit(&arpce->nce_lock);
27836 			if (ire->ire_marks & IRE_MARK_NOADD) {
27837 				/*
27838 				 * this ire will not be added to the ire
27839 				 * cache table, so we can set the ire_nce
27840 				 * here, as there are no atomicity constraints.
27841 				 */
27842 				ire->ire_nce = arpce;
27843 				/*
27844 				 * We are associating this nce with the ire
27845 				 * so change the nce ref taken in
27846 				 * ndp_lookup_v4() from
27847 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27848 				 */
27849 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27850 			} else {
27851 				NCE_REFRELE(arpce);
27852 			}
27853 			ire_add_then_send(q, ire, mp);
27854 		}
27855 		return;	/* All is well, the packet has been sent. */
27856 	}
27857 	case IRE_ARPRESOLVE_TYPE: {
27858 
27859 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27860 			break;
27861 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27862 		mp->b_cont = NULL;
27863 		/*
27864 		 * First, check to make sure the resolution succeeded.
27865 		 * If it failed, the second mblk will be empty.
27866 		 */
27867 		if (mp1->b_rptr == mp1->b_wptr) {
27868 			/* cleanup  the incomplete ire, free queued packets */
27869 			freemsg(mp); /* fake ire */
27870 			freeb(mp1);  /* dl_unitdata response */
27871 			return;
27872 		}
27873 
27874 		/*
27875 		 * update any incomplete nce_t found. we lookup the ctable
27876 		 * and find the nce from the ire->ire_nce because we need
27877 		 * to pass the ire to ip_xmit_v4 later, and can find both
27878 		 * ire and nce in one lookup from the ctable.
27879 		 */
27880 		fake_ire = (ire_t *)mp->b_rptr;
27881 		/*
27882 		 * By the time we come back here from ARP
27883 		 * the logical outgoing interface  of the incomplete ire
27884 		 * we added in ire_forward could have disappeared,
27885 		 * causing the incomplete ire to also have
27886 		 * dissapeared. So we need to retreive the
27887 		 * proper ipif for the ire  before looking
27888 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
27889 		 */
27890 		ill = q->q_ptr;
27891 
27892 		/* Get the outgoing ipif */
27893 		mutex_enter(&ill->ill_lock);
27894 		if (ill->ill_state_flags & ILL_CONDEMNED) {
27895 			mutex_exit(&ill->ill_lock);
27896 			freemsg(mp); /* fake ire */
27897 			freeb(mp1);  /* dl_unitdata response */
27898 			return;
27899 		}
27900 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27901 
27902 		if (ipif == NULL) {
27903 			mutex_exit(&ill->ill_lock);
27904 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27905 			freemsg(mp);
27906 			freeb(mp1);
27907 			return;
27908 		}
27909 		ipif_refhold_locked(ipif);
27910 		mutex_exit(&ill->ill_lock);
27911 		ire = ire_ctable_lookup(fake_ire->ire_addr,
27912 		    fake_ire->ire_gateway_addr, IRE_CACHE,
27913 		    ipif, fake_ire->ire_zoneid, NULL,
27914 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY|
27915 		    MATCH_IRE_TYPE), ipst);
27916 		ipif_refrele(ipif);
27917 		if (ire == NULL) {
27918 			/*
27919 			 * no ire was found; check if there is an nce
27920 			 * for this lookup; if it has no ire's pointing at it
27921 			 * cleanup.
27922 			 */
27923 			if ((nce = ndp_lookup_v4(ill,
27924 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27925 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27926 			    B_FALSE)) != NULL) {
27927 				/*
27928 				 * cleanup:
27929 				 * We check for refcnt 2 (one for the nce
27930 				 * hash list + 1 for the ref taken by
27931 				 * ndp_lookup_v4) to check that there are
27932 				 * no ire's pointing at the nce.
27933 				 */
27934 				if (nce->nce_refcnt == 2)
27935 					ndp_delete(nce);
27936 				NCE_REFRELE(nce);
27937 			}
27938 			freeb(mp1);  /* dl_unitdata response */
27939 			freemsg(mp); /* fake ire */
27940 			return;
27941 		}
27942 		nce = ire->ire_nce;
27943 		DTRACE_PROBE2(ire__arpresolve__type,
27944 		    ire_t *, ire, nce_t *, nce);
27945 		ASSERT(nce->nce_state != ND_INITIAL);
27946 		mutex_enter(&nce->nce_lock);
27947 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27948 		if (nce->nce_state == ND_REACHABLE) {
27949 			/*
27950 			 * Someone resolved this before us;
27951 			 * our response is not needed any more.
27952 			 */
27953 			mutex_exit(&nce->nce_lock);
27954 			freeb(mp1);  /* dl_unitdata response */
27955 		} else {
27956 			ASSERT(nce->nce_res_mp == NULL);
27957 			nce->nce_res_mp = mp1;
27958 			nce->nce_state = ND_REACHABLE;
27959 			mutex_exit(&nce->nce_lock);
27960 			nce_fastpath(nce);
27961 		}
27962 		/*
27963 		 * The cached nce_t has been updated to be reachable;
27964 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
27965 		 */
27966 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27967 		freemsg(mp);
27968 		/*
27969 		 * send out queued packets.
27970 		 */
27971 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
27972 
27973 		IRE_REFRELE(ire);
27974 		return;
27975 	}
27976 	default:
27977 		break;
27978 	}
27979 	if (q->q_next) {
27980 		putnext(q, mp);
27981 	} else
27982 		freemsg(mp);
27983 	return;
27984 
27985 protonak:
27986 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
27987 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
27988 		qreply(q, mp);
27989 }
27990 
27991 /*
27992  * Process IP options in an outbound packet.  Modify the destination if there
27993  * is a source route option.
27994  * Returns non-zero if something fails in which case an ICMP error has been
27995  * sent and mp freed.
27996  */
27997 static int
27998 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27999     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
28000 {
28001 	ipoptp_t	opts;
28002 	uchar_t		*opt;
28003 	uint8_t		optval;
28004 	uint8_t		optlen;
28005 	ipaddr_t	dst;
28006 	intptr_t	code = 0;
28007 	mblk_t		*mp;
28008 	ire_t		*ire = NULL;
28009 
28010 	ip2dbg(("ip_wput_options\n"));
28011 	mp = ipsec_mp;
28012 	if (mctl_present) {
28013 		mp = ipsec_mp->b_cont;
28014 	}
28015 
28016 	dst = ipha->ipha_dst;
28017 	for (optval = ipoptp_first(&opts, ipha);
28018 	    optval != IPOPT_EOL;
28019 	    optval = ipoptp_next(&opts)) {
28020 		opt = opts.ipoptp_cur;
28021 		optlen = opts.ipoptp_len;
28022 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
28023 		    optval, optlen));
28024 		switch (optval) {
28025 			uint32_t off;
28026 		case IPOPT_SSRR:
28027 		case IPOPT_LSRR:
28028 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28029 				ip1dbg((
28030 				    "ip_wput_options: bad option offset\n"));
28031 				code = (char *)&opt[IPOPT_OLEN] -
28032 				    (char *)ipha;
28033 				goto param_prob;
28034 			}
28035 			off = opt[IPOPT_OFFSET];
28036 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
28037 			    ntohl(dst)));
28038 			/*
28039 			 * For strict: verify that dst is directly
28040 			 * reachable.
28041 			 */
28042 			if (optval == IPOPT_SSRR) {
28043 				ire = ire_ftable_lookup(dst, 0, 0,
28044 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
28045 				    MBLK_GETLABEL(mp),
28046 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
28047 				if (ire == NULL) {
28048 					ip1dbg(("ip_wput_options: SSRR not"
28049 					    " directly reachable: 0x%x\n",
28050 					    ntohl(dst)));
28051 					goto bad_src_route;
28052 				}
28053 				ire_refrele(ire);
28054 			}
28055 			break;
28056 		case IPOPT_RR:
28057 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28058 				ip1dbg((
28059 				    "ip_wput_options: bad option offset\n"));
28060 				code = (char *)&opt[IPOPT_OLEN] -
28061 				    (char *)ipha;
28062 				goto param_prob;
28063 			}
28064 			break;
28065 		case IPOPT_TS:
28066 			/*
28067 			 * Verify that length >=5 and that there is either
28068 			 * room for another timestamp or that the overflow
28069 			 * counter is not maxed out.
28070 			 */
28071 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
28072 			if (optlen < IPOPT_MINLEN_IT) {
28073 				goto param_prob;
28074 			}
28075 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28076 				ip1dbg((
28077 				    "ip_wput_options: bad option offset\n"));
28078 				code = (char *)&opt[IPOPT_OFFSET] -
28079 				    (char *)ipha;
28080 				goto param_prob;
28081 			}
28082 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
28083 			case IPOPT_TS_TSONLY:
28084 				off = IPOPT_TS_TIMELEN;
28085 				break;
28086 			case IPOPT_TS_TSANDADDR:
28087 			case IPOPT_TS_PRESPEC:
28088 			case IPOPT_TS_PRESPEC_RFC791:
28089 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
28090 				break;
28091 			default:
28092 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
28093 				    (char *)ipha;
28094 				goto param_prob;
28095 			}
28096 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
28097 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
28098 				/*
28099 				 * No room and the overflow counter is 15
28100 				 * already.
28101 				 */
28102 				goto param_prob;
28103 			}
28104 			break;
28105 		}
28106 	}
28107 
28108 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
28109 		return (0);
28110 
28111 	ip1dbg(("ip_wput_options: error processing IP options."));
28112 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
28113 
28114 param_prob:
28115 	/*
28116 	 * Since ip_wput() isn't close to finished, we fill
28117 	 * in enough of the header for credible error reporting.
28118 	 */
28119 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28120 		/* Failed */
28121 		freemsg(ipsec_mp);
28122 		return (-1);
28123 	}
28124 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
28125 	return (-1);
28126 
28127 bad_src_route:
28128 	/*
28129 	 * Since ip_wput() isn't close to finished, we fill
28130 	 * in enough of the header for credible error reporting.
28131 	 */
28132 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28133 		/* Failed */
28134 		freemsg(ipsec_mp);
28135 		return (-1);
28136 	}
28137 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
28138 	return (-1);
28139 }
28140 
28141 /*
28142  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
28143  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
28144  * thru /etc/system.
28145  */
28146 #define	CONN_MAXDRAINCNT	64
28147 
28148 static void
28149 conn_drain_init(ip_stack_t *ipst)
28150 {
28151 	int i;
28152 
28153 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
28154 
28155 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
28156 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
28157 		/*
28158 		 * Default value of the number of drainers is the
28159 		 * number of cpus, subject to maximum of 8 drainers.
28160 		 */
28161 		if (boot_max_ncpus != -1)
28162 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
28163 		else
28164 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
28165 	}
28166 
28167 	ipst->ips_conn_drain_list = kmem_zalloc(ipst->ips_conn_drain_list_cnt *
28168 	    sizeof (idl_t), KM_SLEEP);
28169 
28170 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28171 		mutex_init(&ipst->ips_conn_drain_list[i].idl_lock, NULL,
28172 		    MUTEX_DEFAULT, NULL);
28173 	}
28174 }
28175 
28176 static void
28177 conn_drain_fini(ip_stack_t *ipst)
28178 {
28179 	int i;
28180 
28181 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++)
28182 		mutex_destroy(&ipst->ips_conn_drain_list[i].idl_lock);
28183 	kmem_free(ipst->ips_conn_drain_list,
28184 	    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28185 	ipst->ips_conn_drain_list = NULL;
28186 }
28187 
28188 /*
28189  * Note: For an overview of how flowcontrol is handled in IP please see the
28190  * IP Flowcontrol notes at the top of this file.
28191  *
28192  * Flow control has blocked us from proceeding. Insert the given conn in one
28193  * of the conn drain lists. These conn wq's will be qenabled later on when
28194  * STREAMS flow control does a backenable. conn_walk_drain will enable
28195  * the first conn in each of these drain lists. Each of these qenabled conns
28196  * in turn enables the next in the list, after it runs, or when it closes,
28197  * thus sustaining the drain process.
28198  *
28199  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
28200  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
28201  * running at any time, on a given conn, since there can be only 1 service proc
28202  * running on a queue at any time.
28203  */
28204 void
28205 conn_drain_insert(conn_t *connp)
28206 {
28207 	idl_t	*idl;
28208 	uint_t	index;
28209 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28210 
28211 	mutex_enter(&connp->conn_lock);
28212 	if (connp->conn_state_flags & CONN_CLOSING) {
28213 		/*
28214 		 * The conn is closing as a result of which CONN_CLOSING
28215 		 * is set. Return.
28216 		 */
28217 		mutex_exit(&connp->conn_lock);
28218 		return;
28219 	} else if (connp->conn_idl == NULL) {
28220 		/*
28221 		 * Assign the next drain list round robin. We dont' use
28222 		 * a lock, and thus it may not be strictly round robin.
28223 		 * Atomicity of load/stores is enough to make sure that
28224 		 * conn_drain_list_index is always within bounds.
28225 		 */
28226 		index = ipst->ips_conn_drain_list_index;
28227 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28228 		connp->conn_idl = &ipst->ips_conn_drain_list[index];
28229 		index++;
28230 		if (index == ipst->ips_conn_drain_list_cnt)
28231 			index = 0;
28232 		ipst->ips_conn_drain_list_index = index;
28233 	}
28234 	mutex_exit(&connp->conn_lock);
28235 
28236 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28237 	if ((connp->conn_drain_prev != NULL) ||
28238 	    (connp->conn_state_flags & CONN_CLOSING)) {
28239 		/*
28240 		 * The conn is already in the drain list, OR
28241 		 * the conn is closing. We need to check again for
28242 		 * the closing case again since close can happen
28243 		 * after we drop the conn_lock, and before we
28244 		 * acquire the CONN_DRAIN_LIST_LOCK.
28245 		 */
28246 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28247 		return;
28248 	} else {
28249 		idl = connp->conn_idl;
28250 	}
28251 
28252 	/*
28253 	 * The conn is not in the drain list. Insert it at the
28254 	 * tail of the drain list. The drain list is circular
28255 	 * and doubly linked. idl_conn points to the 1st element
28256 	 * in the list.
28257 	 */
28258 	if (idl->idl_conn == NULL) {
28259 		idl->idl_conn = connp;
28260 		connp->conn_drain_next = connp;
28261 		connp->conn_drain_prev = connp;
28262 	} else {
28263 		conn_t *head = idl->idl_conn;
28264 
28265 		connp->conn_drain_next = head;
28266 		connp->conn_drain_prev = head->conn_drain_prev;
28267 		head->conn_drain_prev->conn_drain_next = connp;
28268 		head->conn_drain_prev = connp;
28269 	}
28270 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28271 }
28272 
28273 /*
28274  * This conn is closing, and we are called from ip_close. OR
28275  * This conn has been serviced by ip_wsrv, and we need to do the tail
28276  * processing.
28277  * If this conn is part of the drain list, we may need to sustain the drain
28278  * process by qenabling the next conn in the drain list. We may also need to
28279  * remove this conn from the list, if it is done.
28280  */
28281 static void
28282 conn_drain_tail(conn_t *connp, boolean_t closing)
28283 {
28284 	idl_t *idl;
28285 
28286 	/*
28287 	 * connp->conn_idl is stable at this point, and no lock is needed
28288 	 * to check it. If we are called from ip_close, close has already
28289 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28290 	 * called us only because conn_idl is non-null. If we are called thru
28291 	 * service, conn_idl could be null, but it cannot change because
28292 	 * service is single-threaded per queue, and there cannot be another
28293 	 * instance of service trying to call conn_drain_insert on this conn
28294 	 * now.
28295 	 */
28296 	ASSERT(!closing || (connp->conn_idl != NULL));
28297 
28298 	/*
28299 	 * If connp->conn_idl is null, the conn has not been inserted into any
28300 	 * drain list even once since creation of the conn. Just return.
28301 	 */
28302 	if (connp->conn_idl == NULL)
28303 		return;
28304 
28305 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28306 
28307 	if (connp->conn_drain_prev == NULL) {
28308 		/* This conn is currently not in the drain list.  */
28309 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28310 		return;
28311 	}
28312 	idl = connp->conn_idl;
28313 	if (idl->idl_conn_draining == connp) {
28314 		/*
28315 		 * This conn is the current drainer. If this is the last conn
28316 		 * in the drain list, we need to do more checks, in the 'if'
28317 		 * below. Otherwwise we need to just qenable the next conn,
28318 		 * to sustain the draining, and is handled in the 'else'
28319 		 * below.
28320 		 */
28321 		if (connp->conn_drain_next == idl->idl_conn) {
28322 			/*
28323 			 * This conn is the last in this list. This round
28324 			 * of draining is complete. If idl_repeat is set,
28325 			 * it means another flow enabling has happened from
28326 			 * the driver/streams and we need to another round
28327 			 * of draining.
28328 			 * If there are more than 2 conns in the drain list,
28329 			 * do a left rotate by 1, so that all conns except the
28330 			 * conn at the head move towards the head by 1, and the
28331 			 * the conn at the head goes to the tail. This attempts
28332 			 * a more even share for all queues that are being
28333 			 * drained.
28334 			 */
28335 			if ((connp->conn_drain_next != connp) &&
28336 			    (idl->idl_conn->conn_drain_next != connp)) {
28337 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28338 			}
28339 			if (idl->idl_repeat) {
28340 				qenable(idl->idl_conn->conn_wq);
28341 				idl->idl_conn_draining = idl->idl_conn;
28342 				idl->idl_repeat = 0;
28343 			} else {
28344 				idl->idl_conn_draining = NULL;
28345 			}
28346 		} else {
28347 			/*
28348 			 * If the next queue that we are now qenable'ing,
28349 			 * is closing, it will remove itself from this list
28350 			 * and qenable the subsequent queue in ip_close().
28351 			 * Serialization is acheived thru idl_lock.
28352 			 */
28353 			qenable(connp->conn_drain_next->conn_wq);
28354 			idl->idl_conn_draining = connp->conn_drain_next;
28355 		}
28356 	}
28357 	if (!connp->conn_did_putbq || closing) {
28358 		/*
28359 		 * Remove ourself from the drain list, if we did not do
28360 		 * a putbq, or if the conn is closing.
28361 		 * Note: It is possible that q->q_first is non-null. It means
28362 		 * that these messages landed after we did a enableok() in
28363 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28364 		 * service them.
28365 		 */
28366 		if (connp->conn_drain_next == connp) {
28367 			/* Singleton in the list */
28368 			ASSERT(connp->conn_drain_prev == connp);
28369 			idl->idl_conn = NULL;
28370 			idl->idl_conn_draining = NULL;
28371 		} else {
28372 			connp->conn_drain_prev->conn_drain_next =
28373 			    connp->conn_drain_next;
28374 			connp->conn_drain_next->conn_drain_prev =
28375 			    connp->conn_drain_prev;
28376 			if (idl->idl_conn == connp)
28377 				idl->idl_conn = connp->conn_drain_next;
28378 			ASSERT(idl->idl_conn_draining != connp);
28379 
28380 		}
28381 		connp->conn_drain_next = NULL;
28382 		connp->conn_drain_prev = NULL;
28383 	}
28384 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28385 }
28386 
28387 /*
28388  * Write service routine. Shared perimeter entry point.
28389  * ip_wsrv can be called in any of the following ways.
28390  * 1. The device queue's messages has fallen below the low water mark
28391  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28392  *    the drain lists and backenable the first conn in each list.
28393  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28394  *    qenabled non-tcp upper layers. We start dequeing messages and call
28395  *    ip_wput for each message.
28396  */
28397 
28398 void
28399 ip_wsrv(queue_t *q)
28400 {
28401 	conn_t	*connp;
28402 	ill_t	*ill;
28403 	mblk_t	*mp;
28404 
28405 	if (q->q_next) {
28406 		ill = (ill_t *)q->q_ptr;
28407 		if (ill->ill_state_flags == 0) {
28408 			/*
28409 			 * The device flow control has opened up.
28410 			 * Walk through conn drain lists and qenable the
28411 			 * first conn in each list. This makes sense only
28412 			 * if the stream is fully plumbed and setup.
28413 			 * Hence the if check above.
28414 			 */
28415 			ip1dbg(("ip_wsrv: walking\n"));
28416 			conn_walk_drain(ill->ill_ipst);
28417 		}
28418 		return;
28419 	}
28420 
28421 	connp = Q_TO_CONN(q);
28422 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28423 
28424 	/*
28425 	 * 1. Set conn_draining flag to signal that service is active.
28426 	 *
28427 	 * 2. ip_output determines whether it has been called from service,
28428 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28429 	 *    has been called from service.
28430 	 *
28431 	 * 3. Message ordering is preserved by the following logic.
28432 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28433 	 *    the message at the tail, if conn_draining is set (i.e. service
28434 	 *    is running) or if q->q_first is non-null.
28435 	 *
28436 	 *    ii. If ip_output is called from service, and if ip_output cannot
28437 	 *    putnext due to flow control, it does a putbq.
28438 	 *
28439 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28440 	 *    (causing an infinite loop).
28441 	 */
28442 	ASSERT(!connp->conn_did_putbq);
28443 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28444 		connp->conn_draining = 1;
28445 		noenable(q);
28446 		while ((mp = getq(q)) != NULL) {
28447 			ASSERT(CONN_Q(q));
28448 
28449 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28450 			if (connp->conn_did_putbq) {
28451 				/* ip_wput did a putbq */
28452 				break;
28453 			}
28454 		}
28455 		/*
28456 		 * At this point, a thread coming down from top, calling
28457 		 * ip_wput, may end up queueing the message. We have not yet
28458 		 * enabled the queue, so ip_wsrv won't be called again.
28459 		 * To avoid this race, check q->q_first again (in the loop)
28460 		 * If the other thread queued the message before we call
28461 		 * enableok(), we will catch it in the q->q_first check.
28462 		 * If the other thread queues the message after we call
28463 		 * enableok(), ip_wsrv will be called again by STREAMS.
28464 		 */
28465 		connp->conn_draining = 0;
28466 		enableok(q);
28467 	}
28468 
28469 	/* Enable the next conn for draining */
28470 	conn_drain_tail(connp, B_FALSE);
28471 
28472 	connp->conn_did_putbq = 0;
28473 }
28474 
28475 /*
28476  * Walk the list of all conn's calling the function provided with the
28477  * specified argument for each.	 Note that this only walks conn's that
28478  * have been bound.
28479  * Applies to both IPv4 and IPv6.
28480  */
28481 static void
28482 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28483 {
28484 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28485 	    ipst->ips_ipcl_udp_fanout_size,
28486 	    func, arg, zoneid);
28487 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28488 	    ipst->ips_ipcl_conn_fanout_size,
28489 	    func, arg, zoneid);
28490 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28491 	    ipst->ips_ipcl_bind_fanout_size,
28492 	    func, arg, zoneid);
28493 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28494 	    IPPROTO_MAX, func, arg, zoneid);
28495 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28496 	    IPPROTO_MAX, func, arg, zoneid);
28497 }
28498 
28499 /*
28500  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28501  * of conns that need to be drained, check if drain is already in progress.
28502  * If so set the idl_repeat bit, indicating that the last conn in the list
28503  * needs to reinitiate the drain once again, for the list. If drain is not
28504  * in progress for the list, initiate the draining, by qenabling the 1st
28505  * conn in the list. The drain is self-sustaining, each qenabled conn will
28506  * in turn qenable the next conn, when it is done/blocked/closing.
28507  */
28508 static void
28509 conn_walk_drain(ip_stack_t *ipst)
28510 {
28511 	int i;
28512 	idl_t *idl;
28513 
28514 	IP_STAT(ipst, ip_conn_walk_drain);
28515 
28516 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28517 		idl = &ipst->ips_conn_drain_list[i];
28518 		mutex_enter(&idl->idl_lock);
28519 		if (idl->idl_conn == NULL) {
28520 			mutex_exit(&idl->idl_lock);
28521 			continue;
28522 		}
28523 		/*
28524 		 * If this list is not being drained currently by
28525 		 * an ip_wsrv thread, start the process.
28526 		 */
28527 		if (idl->idl_conn_draining == NULL) {
28528 			ASSERT(idl->idl_repeat == 0);
28529 			qenable(idl->idl_conn->conn_wq);
28530 			idl->idl_conn_draining = idl->idl_conn;
28531 		} else {
28532 			idl->idl_repeat = 1;
28533 		}
28534 		mutex_exit(&idl->idl_lock);
28535 	}
28536 }
28537 
28538 /*
28539  * Walk an conn hash table of `count' buckets, calling func for each entry.
28540  */
28541 static void
28542 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28543     zoneid_t zoneid)
28544 {
28545 	conn_t	*connp;
28546 
28547 	while (count-- > 0) {
28548 		mutex_enter(&connfp->connf_lock);
28549 		for (connp = connfp->connf_head; connp != NULL;
28550 		    connp = connp->conn_next) {
28551 			if (zoneid == GLOBAL_ZONEID ||
28552 			    zoneid == connp->conn_zoneid) {
28553 				CONN_INC_REF(connp);
28554 				mutex_exit(&connfp->connf_lock);
28555 				(*func)(connp, arg);
28556 				mutex_enter(&connfp->connf_lock);
28557 				CONN_DEC_REF(connp);
28558 			}
28559 		}
28560 		mutex_exit(&connfp->connf_lock);
28561 		connfp++;
28562 	}
28563 }
28564 
28565 /* conn_walk_fanout routine invoked for ip_conn_report for each conn. */
28566 static void
28567 conn_report1(conn_t *connp, void *mp)
28568 {
28569 	char	buf1[INET6_ADDRSTRLEN];
28570 	char	buf2[INET6_ADDRSTRLEN];
28571 	uint_t	print_len, buf_len;
28572 
28573 	ASSERT(connp != NULL);
28574 
28575 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28576 	if (buf_len <= 0)
28577 		return;
28578 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1));
28579 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2));
28580 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28581 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28582 	    "%5d %s/%05d %s/%05d\n",
28583 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28584 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28585 	    buf1, connp->conn_lport,
28586 	    buf2, connp->conn_fport);
28587 	if (print_len < buf_len) {
28588 		((mblk_t *)mp)->b_wptr += print_len;
28589 	} else {
28590 		((mblk_t *)mp)->b_wptr += buf_len;
28591 	}
28592 }
28593 
28594 /*
28595  * Named Dispatch routine to produce a formatted report on all conns
28596  * that are listed in one of the fanout tables.
28597  * This report is accessed by using the ndd utility to "get" ND variable
28598  * "ip_conn_status".
28599  */
28600 /* ARGSUSED */
28601 static int
28602 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28603 {
28604 	conn_t *connp = Q_TO_CONN(q);
28605 
28606 	(void) mi_mpprintf(mp,
28607 	    "CONN      " MI_COL_HDRPAD_STR
28608 	    "rfq      " MI_COL_HDRPAD_STR
28609 	    "stq      " MI_COL_HDRPAD_STR
28610 	    " zone local                 remote");
28611 
28612 	/*
28613 	 * Because of the ndd constraint, at most we can have 64K buffer
28614 	 * to put in all conn info.  So to be more efficient, just
28615 	 * allocate a 64K buffer here, assuming we need that large buffer.
28616 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28617 	 */
28618 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28619 		/* The following may work even if we cannot get a large buf. */
28620 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28621 		return (0);
28622 	}
28623 
28624 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
28625 	    connp->conn_netstack->netstack_ip);
28626 	return (0);
28627 }
28628 
28629 /*
28630  * Determine if the ill and multicast aspects of that packets
28631  * "matches" the conn.
28632  */
28633 boolean_t
28634 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28635     zoneid_t zoneid)
28636 {
28637 	ill_t *in_ill;
28638 	boolean_t found;
28639 	ipif_t *ipif;
28640 	ire_t *ire;
28641 	ipaddr_t dst, src;
28642 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28643 
28644 	dst = ipha->ipha_dst;
28645 	src = ipha->ipha_src;
28646 
28647 	/*
28648 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28649 	 * unicast, broadcast and multicast reception to
28650 	 * conn_incoming_ill. conn_wantpacket itself is called
28651 	 * only for BROADCAST and multicast.
28652 	 *
28653 	 * 1) ip_rput supresses duplicate broadcasts if the ill
28654 	 *    is part of a group. Hence, we should be receiving
28655 	 *    just one copy of broadcast for the whole group.
28656 	 *    Thus, if it is part of the group the packet could
28657 	 *    come on any ill of the group and hence we need a
28658 	 *    match on the group. Otherwise, match on ill should
28659 	 *    be sufficient.
28660 	 *
28661 	 * 2) ip_rput does not suppress duplicate multicast packets.
28662 	 *    If there are two interfaces in a ill group and we have
28663 	 *    2 applications (conns) joined a multicast group G on
28664 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
28665 	 *    will give us two packets because we join G on both the
28666 	 *    interfaces rather than nominating just one interface
28667 	 *    for receiving multicast like broadcast above. So,
28668 	 *    we have to call ilg_lookup_ill to filter out duplicate
28669 	 *    copies, if ill is part of a group.
28670 	 */
28671 	in_ill = connp->conn_incoming_ill;
28672 	if (in_ill != NULL) {
28673 		if (in_ill->ill_group == NULL) {
28674 			if (in_ill != ill)
28675 				return (B_FALSE);
28676 		} else if (in_ill->ill_group != ill->ill_group) {
28677 			return (B_FALSE);
28678 		}
28679 	}
28680 
28681 	if (!CLASSD(dst)) {
28682 		if (IPCL_ZONE_MATCH(connp, zoneid))
28683 			return (B_TRUE);
28684 		/*
28685 		 * The conn is in a different zone; we need to check that this
28686 		 * broadcast address is configured in the application's zone and
28687 		 * on one ill in the group.
28688 		 */
28689 		ipif = ipif_get_next_ipif(NULL, ill);
28690 		if (ipif == NULL)
28691 			return (B_FALSE);
28692 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28693 		    connp->conn_zoneid, NULL,
28694 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
28695 		ipif_refrele(ipif);
28696 		if (ire != NULL) {
28697 			ire_refrele(ire);
28698 			return (B_TRUE);
28699 		} else {
28700 			return (B_FALSE);
28701 		}
28702 	}
28703 
28704 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28705 	    connp->conn_zoneid == zoneid) {
28706 		/*
28707 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28708 		 * disabled, therefore we don't dispatch the multicast packet to
28709 		 * the sending zone.
28710 		 */
28711 		return (B_FALSE);
28712 	}
28713 
28714 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28715 		/*
28716 		 * Multicast packet on the loopback interface: we only match
28717 		 * conns who joined the group in the specified zone.
28718 		 */
28719 		return (B_FALSE);
28720 	}
28721 
28722 	if (connp->conn_multi_router) {
28723 		/* multicast packet and multicast router socket: send up */
28724 		return (B_TRUE);
28725 	}
28726 
28727 	mutex_enter(&connp->conn_lock);
28728 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28729 	mutex_exit(&connp->conn_lock);
28730 	return (found);
28731 }
28732 
28733 /*
28734  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28735  */
28736 /* ARGSUSED */
28737 static void
28738 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28739 {
28740 	ill_t *ill = (ill_t *)q->q_ptr;
28741 	mblk_t	*mp1, *mp2;
28742 	ipif_t  *ipif;
28743 	int err = 0;
28744 	conn_t *connp = NULL;
28745 	ipsq_t	*ipsq;
28746 	arc_t	*arc;
28747 
28748 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28749 
28750 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28751 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28752 
28753 	ASSERT(IAM_WRITER_ILL(ill));
28754 	mp2 = mp->b_cont;
28755 	mp->b_cont = NULL;
28756 
28757 	/*
28758 	 * We have now received the arp bringup completion message
28759 	 * from ARP. Mark the arp bringup as done. Also if the arp
28760 	 * stream has already started closing, send up the AR_ARP_CLOSING
28761 	 * ack now since ARP is waiting in close for this ack.
28762 	 */
28763 	mutex_enter(&ill->ill_lock);
28764 	ill->ill_arp_bringup_pending = 0;
28765 	if (ill->ill_arp_closing) {
28766 		mutex_exit(&ill->ill_lock);
28767 		/* Let's reuse the mp for sending the ack */
28768 		arc = (arc_t *)mp->b_rptr;
28769 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28770 		arc->arc_cmd = AR_ARP_CLOSING;
28771 		qreply(q, mp);
28772 	} else {
28773 		mutex_exit(&ill->ill_lock);
28774 		freeb(mp);
28775 	}
28776 
28777 	ipsq = ill->ill_phyint->phyint_ipsq;
28778 	ipif = ipsq->ipsq_pending_ipif;
28779 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28780 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28781 	if (mp1 == NULL) {
28782 		/* bringup was aborted by the user */
28783 		freemsg(mp2);
28784 		return;
28785 	}
28786 
28787 	/*
28788 	 * If an IOCTL is waiting on this (ipsq_current_ioctl != 0), then we
28789 	 * must have an associated conn_t.  Otherwise, we're bringing this
28790 	 * interface back up as part of handling an asynchronous event (e.g.,
28791 	 * physical address change).
28792 	 */
28793 	if (ipsq->ipsq_current_ioctl != 0) {
28794 		ASSERT(connp != NULL);
28795 		q = CONNP_TO_WQ(connp);
28796 	} else {
28797 		ASSERT(connp == NULL);
28798 		q = ill->ill_rq;
28799 	}
28800 
28801 	/*
28802 	 * If the DL_BIND_REQ fails, it is noted
28803 	 * in arc_name_offset.
28804 	 */
28805 	err = *((int *)mp2->b_rptr);
28806 	if (err == 0) {
28807 		if (ipif->ipif_isv6) {
28808 			if ((err = ipif_up_done_v6(ipif)) != 0)
28809 				ip0dbg(("ip_arp_done: init failed\n"));
28810 		} else {
28811 			if ((err = ipif_up_done(ipif)) != 0)
28812 				ip0dbg(("ip_arp_done: init failed\n"));
28813 		}
28814 	} else {
28815 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28816 	}
28817 
28818 	freemsg(mp2);
28819 
28820 	if ((err == 0) && (ill->ill_up_ipifs)) {
28821 		err = ill_up_ipifs(ill, q, mp1);
28822 		if (err == EINPROGRESS)
28823 			return;
28824 	}
28825 
28826 	if (ill->ill_up_ipifs)
28827 		ill_group_cleanup(ill);
28828 
28829 	/*
28830 	 * The operation must complete without EINPROGRESS since
28831 	 * ipsq_pending_mp_get() has removed the mblk from ipsq_pending_mp.
28832 	 * Otherwise, the operation will be stuck forever in the ipsq.
28833 	 */
28834 	ASSERT(err != EINPROGRESS);
28835 	if (ipsq->ipsq_current_ioctl != 0)
28836 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28837 	else
28838 		ipsq_current_finish(ipsq);
28839 }
28840 
28841 /* Allocate the private structure */
28842 static int
28843 ip_priv_alloc(void **bufp)
28844 {
28845 	void	*buf;
28846 
28847 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28848 		return (ENOMEM);
28849 
28850 	*bufp = buf;
28851 	return (0);
28852 }
28853 
28854 /* Function to delete the private structure */
28855 void
28856 ip_priv_free(void *buf)
28857 {
28858 	ASSERT(buf != NULL);
28859 	kmem_free(buf, sizeof (ip_priv_t));
28860 }
28861 
28862 /*
28863  * The entry point for IPPF processing.
28864  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28865  * routine just returns.
28866  *
28867  * When called, ip_process generates an ipp_packet_t structure
28868  * which holds the state information for this packet and invokes the
28869  * the classifier (via ipp_packet_process). The classification, depending on
28870  * configured filters, results in a list of actions for this packet. Invoking
28871  * an action may cause the packet to be dropped, in which case the resulting
28872  * mblk (*mpp) is NULL. proc indicates the callout position for
28873  * this packet and ill_index is the interface this packet on or will leave
28874  * on (inbound and outbound resp.).
28875  */
28876 void
28877 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28878 {
28879 	mblk_t		*mp;
28880 	ip_priv_t	*priv;
28881 	ipp_action_id_t	aid;
28882 	int		rc = 0;
28883 	ipp_packet_t	*pp;
28884 #define	IP_CLASS	"ip"
28885 
28886 	/* If the classifier is not loaded, return  */
28887 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28888 		return;
28889 	}
28890 
28891 	mp = *mpp;
28892 	ASSERT(mp != NULL);
28893 
28894 	/* Allocate the packet structure */
28895 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28896 	if (rc != 0) {
28897 		*mpp = NULL;
28898 		freemsg(mp);
28899 		return;
28900 	}
28901 
28902 	/* Allocate the private structure */
28903 	rc = ip_priv_alloc((void **)&priv);
28904 	if (rc != 0) {
28905 		*mpp = NULL;
28906 		freemsg(mp);
28907 		ipp_packet_free(pp);
28908 		return;
28909 	}
28910 	priv->proc = proc;
28911 	priv->ill_index = ill_index;
28912 	ipp_packet_set_private(pp, priv, ip_priv_free);
28913 	ipp_packet_set_data(pp, mp);
28914 
28915 	/* Invoke the classifier */
28916 	rc = ipp_packet_process(&pp);
28917 	if (pp != NULL) {
28918 		mp = ipp_packet_get_data(pp);
28919 		ipp_packet_free(pp);
28920 		if (rc != 0) {
28921 			freemsg(mp);
28922 			*mpp = NULL;
28923 		}
28924 	} else {
28925 		*mpp = NULL;
28926 	}
28927 #undef	IP_CLASS
28928 }
28929 
28930 /*
28931  * Propagate a multicast group membership operation (add/drop) on
28932  * all the interfaces crossed by the related multirt routes.
28933  * The call is considered successful if the operation succeeds
28934  * on at least one interface.
28935  */
28936 static int
28937 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28938     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28939     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28940     mblk_t *first_mp)
28941 {
28942 	ire_t		*ire_gw;
28943 	irb_t		*irb;
28944 	int		error = 0;
28945 	opt_restart_t	*or;
28946 	ip_stack_t	*ipst = ire->ire_ipst;
28947 
28948 	irb = ire->ire_bucket;
28949 	ASSERT(irb != NULL);
28950 
28951 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28952 
28953 	or = (opt_restart_t *)first_mp->b_rptr;
28954 	IRB_REFHOLD(irb);
28955 	for (; ire != NULL; ire = ire->ire_next) {
28956 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28957 			continue;
28958 		if (ire->ire_addr != group)
28959 			continue;
28960 
28961 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28962 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28963 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
28964 		/* No resolver exists for the gateway; skip this ire. */
28965 		if (ire_gw == NULL)
28966 			continue;
28967 
28968 		/*
28969 		 * This function can return EINPROGRESS. If so the operation
28970 		 * will be restarted from ip_restart_optmgmt which will
28971 		 * call ip_opt_set and option processing will restart for
28972 		 * this option. So we may end up calling 'fn' more than once.
28973 		 * This requires that 'fn' is idempotent except for the
28974 		 * return value. The operation is considered a success if
28975 		 * it succeeds at least once on any one interface.
28976 		 */
28977 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28978 		    NULL, fmode, src, first_mp);
28979 		if (error == 0)
28980 			or->or_private = CGTP_MCAST_SUCCESS;
28981 
28982 		if (ip_debug > 0) {
28983 			ulong_t	off;
28984 			char	*ksym;
28985 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28986 			ip2dbg(("ip_multirt_apply_membership: "
28987 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28988 			    "error %d [success %u]\n",
28989 			    ksym ? ksym : "?",
28990 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28991 			    error, or->or_private));
28992 		}
28993 
28994 		ire_refrele(ire_gw);
28995 		if (error == EINPROGRESS) {
28996 			IRB_REFRELE(irb);
28997 			return (error);
28998 		}
28999 	}
29000 	IRB_REFRELE(irb);
29001 	/*
29002 	 * Consider the call as successful if we succeeded on at least
29003 	 * one interface. Otherwise, return the last encountered error.
29004 	 */
29005 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
29006 }
29007 
29008 
29009 /*
29010  * Issue a warning regarding a route crossing an interface with an
29011  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
29012  * amount of time is logged.
29013  */
29014 static void
29015 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
29016 {
29017 	hrtime_t	current = gethrtime();
29018 	char		buf[INET_ADDRSTRLEN];
29019 	ip_stack_t	*ipst = ire->ire_ipst;
29020 
29021 	/* Convert interval in ms to hrtime in ns */
29022 	if (ipst->ips_multirt_bad_mtu_last_time +
29023 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
29024 	    current) {
29025 		cmn_err(CE_WARN, "ip: ignoring multiroute "
29026 		    "to %s, incorrect MTU %u (expected %u)\n",
29027 		    ip_dot_addr(ire->ire_addr, buf),
29028 		    ire->ire_max_frag, max_frag);
29029 
29030 		ipst->ips_multirt_bad_mtu_last_time = current;
29031 	}
29032 }
29033 
29034 
29035 /*
29036  * Get the CGTP (multirouting) filtering status.
29037  * If 0, the CGTP hooks are transparent.
29038  */
29039 /* ARGSUSED */
29040 static int
29041 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
29042 {
29043 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29044 
29045 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
29046 	return (0);
29047 }
29048 
29049 
29050 /*
29051  * Set the CGTP (multirouting) filtering status.
29052  * If the status is changed from active to transparent
29053  * or from transparent to active, forward the new status
29054  * to the filtering module (if loaded).
29055  */
29056 /* ARGSUSED */
29057 static int
29058 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
29059     cred_t *ioc_cr)
29060 {
29061 	long		new_value;
29062 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29063 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29064 
29065 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
29066 		return (EPERM);
29067 
29068 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
29069 	    new_value < 0 || new_value > 1) {
29070 		return (EINVAL);
29071 	}
29072 
29073 	if ((!*ip_cgtp_filter_value) && new_value) {
29074 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
29075 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
29076 		    " (module not loaded)" : "");
29077 	}
29078 	if (*ip_cgtp_filter_value && (!new_value)) {
29079 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
29080 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
29081 		    " (module not loaded)" : "");
29082 	}
29083 
29084 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29085 		int	res;
29086 		netstackid_t stackid;
29087 
29088 		stackid = ipst->ips_netstack->netstack_stackid;
29089 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
29090 		    new_value);
29091 		if (res)
29092 			return (res);
29093 	}
29094 
29095 	*ip_cgtp_filter_value = (boolean_t)new_value;
29096 
29097 	return (0);
29098 }
29099 
29100 
29101 /*
29102  * Return the expected CGTP hooks version number.
29103  */
29104 int
29105 ip_cgtp_filter_supported(void)
29106 {
29107 	return (ip_cgtp_filter_rev);
29108 }
29109 
29110 
29111 /*
29112  * CGTP hooks can be registered by invoking this function.
29113  * Checks that the version number matches.
29114  */
29115 int
29116 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
29117 {
29118 	netstack_t *ns;
29119 	ip_stack_t *ipst;
29120 
29121 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
29122 		return (ENOTSUP);
29123 
29124 	ns = netstack_find_by_stackid(stackid);
29125 	if (ns == NULL)
29126 		return (EINVAL);
29127 	ipst = ns->netstack_ip;
29128 	ASSERT(ipst != NULL);
29129 
29130 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29131 		netstack_rele(ns);
29132 		return (EALREADY);
29133 	}
29134 
29135 	ipst->ips_ip_cgtp_filter_ops = ops;
29136 	netstack_rele(ns);
29137 	return (0);
29138 }
29139 
29140 /*
29141  * CGTP hooks can be unregistered by invoking this function.
29142  * Returns ENXIO if there was no registration.
29143  * Returns EBUSY if the ndd variable has not been turned off.
29144  */
29145 int
29146 ip_cgtp_filter_unregister(netstackid_t stackid)
29147 {
29148 	netstack_t *ns;
29149 	ip_stack_t *ipst;
29150 
29151 	ns = netstack_find_by_stackid(stackid);
29152 	if (ns == NULL)
29153 		return (EINVAL);
29154 	ipst = ns->netstack_ip;
29155 	ASSERT(ipst != NULL);
29156 
29157 	if (ipst->ips_ip_cgtp_filter) {
29158 		netstack_rele(ns);
29159 		return (EBUSY);
29160 	}
29161 
29162 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
29163 		netstack_rele(ns);
29164 		return (ENXIO);
29165 	}
29166 	ipst->ips_ip_cgtp_filter_ops = NULL;
29167 	netstack_rele(ns);
29168 	return (0);
29169 }
29170 
29171 /*
29172  * Check whether there is a CGTP filter registration.
29173  * Returns non-zero if there is a registration, otherwise returns zero.
29174  * Note: returns zero if bad stackid.
29175  */
29176 int
29177 ip_cgtp_filter_is_registered(netstackid_t stackid)
29178 {
29179 	netstack_t *ns;
29180 	ip_stack_t *ipst;
29181 	int ret;
29182 
29183 	ns = netstack_find_by_stackid(stackid);
29184 	if (ns == NULL)
29185 		return (0);
29186 	ipst = ns->netstack_ip;
29187 	ASSERT(ipst != NULL);
29188 
29189 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
29190 		ret = 1;
29191 	else
29192 		ret = 0;
29193 
29194 	netstack_rele(ns);
29195 	return (ret);
29196 }
29197 
29198 static squeue_func_t
29199 ip_squeue_switch(int val)
29200 {
29201 	squeue_func_t rval = squeue_fill;
29202 
29203 	switch (val) {
29204 	case IP_SQUEUE_ENTER_NODRAIN:
29205 		rval = squeue_enter_nodrain;
29206 		break;
29207 	case IP_SQUEUE_ENTER:
29208 		rval = squeue_enter;
29209 		break;
29210 	default:
29211 		break;
29212 	}
29213 	return (rval);
29214 }
29215 
29216 /* ARGSUSED */
29217 static int
29218 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29219     caddr_t addr, cred_t *cr)
29220 {
29221 	int *v = (int *)addr;
29222 	long new_value;
29223 
29224 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29225 		return (EPERM);
29226 
29227 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29228 		return (EINVAL);
29229 
29230 	ip_input_proc = ip_squeue_switch(new_value);
29231 	*v = new_value;
29232 	return (0);
29233 }
29234 
29235 /*
29236  * Handle ndd set of variables which require PRIV_SYS_NET_CONFIG such as
29237  * ip_debug.
29238  */
29239 /* ARGSUSED */
29240 static int
29241 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29242     caddr_t addr, cred_t *cr)
29243 {
29244 	int *v = (int *)addr;
29245 	long new_value;
29246 
29247 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29248 		return (EPERM);
29249 
29250 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29251 		return (EINVAL);
29252 
29253 	*v = new_value;
29254 	return (0);
29255 }
29256 
29257 /*
29258  * Handle changes to ipmp_hook_emulation ndd variable.
29259  * Need to update phyint_hook_ifindex.
29260  * Also generate a nic plumb event should a new ifidex be assigned to a group.
29261  */
29262 static void
29263 ipmp_hook_emulation_changed(ip_stack_t *ipst)
29264 {
29265 	phyint_t *phyi;
29266 	phyint_t *phyi_tmp;
29267 	char *groupname;
29268 	int namelen;
29269 	ill_t	*ill;
29270 	boolean_t new_group;
29271 
29272 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29273 	/*
29274 	 * Group indicies are stored in the phyint - a common structure
29275 	 * to both IPv4 and IPv6.
29276 	 */
29277 	phyi = avl_first(&ipst->ips_phyint_g_list->phyint_list_avl_by_index);
29278 	for (; phyi != NULL;
29279 	    phyi = avl_walk(&ipst->ips_phyint_g_list->phyint_list_avl_by_index,
29280 	    phyi, AVL_AFTER)) {
29281 		/* Ignore the ones that do not have a group */
29282 		if (phyi->phyint_groupname_len == 0)
29283 			continue;
29284 
29285 		/*
29286 		 * Look for other phyint in group.
29287 		 * Clear name/namelen so the lookup doesn't find ourselves.
29288 		 */
29289 		namelen = phyi->phyint_groupname_len;
29290 		groupname = phyi->phyint_groupname;
29291 		phyi->phyint_groupname_len = 0;
29292 		phyi->phyint_groupname = NULL;
29293 
29294 		phyi_tmp = phyint_lookup_group(groupname, B_FALSE, ipst);
29295 		/* Restore */
29296 		phyi->phyint_groupname_len = namelen;
29297 		phyi->phyint_groupname = groupname;
29298 
29299 		new_group = B_FALSE;
29300 		if (ipst->ips_ipmp_hook_emulation) {
29301 			/*
29302 			 * If the group already exists and has already
29303 			 * been assigned a group ifindex, we use the existing
29304 			 * group_ifindex, otherwise we pick a new group_ifindex
29305 			 * here.
29306 			 */
29307 			if (phyi_tmp != NULL &&
29308 			    phyi_tmp->phyint_group_ifindex != 0) {
29309 				phyi->phyint_group_ifindex =
29310 				    phyi_tmp->phyint_group_ifindex;
29311 			} else {
29312 				/* XXX We need a recovery strategy here. */
29313 				if (!ip_assign_ifindex(
29314 				    &phyi->phyint_group_ifindex, ipst))
29315 					cmn_err(CE_PANIC,
29316 					    "ip_assign_ifindex() failed");
29317 				new_group = B_TRUE;
29318 			}
29319 		} else {
29320 			phyi->phyint_group_ifindex = 0;
29321 		}
29322 		if (ipst->ips_ipmp_hook_emulation)
29323 			phyi->phyint_hook_ifindex = phyi->phyint_group_ifindex;
29324 		else
29325 			phyi->phyint_hook_ifindex = phyi->phyint_ifindex;
29326 
29327 		/*
29328 		 * For IP Filter to find out the relationship between
29329 		 * names and interface indicies, we need to generate
29330 		 * a NE_PLUMB event when a new group can appear.
29331 		 * We always generate events when a new interface appears
29332 		 * (even when ipmp_hook_emulation is set) so there
29333 		 * is no need to generate NE_PLUMB events when
29334 		 * ipmp_hook_emulation is turned off.
29335 		 * And since it isn't critical for IP Filter to get
29336 		 * the NE_UNPLUMB events we skip those here.
29337 		 */
29338 		if (new_group) {
29339 			/*
29340 			 * First phyint in group - generate group PLUMB event.
29341 			 * Since we are not running inside the ipsq we do
29342 			 * the dispatch immediately.
29343 			 */
29344 			if (phyi->phyint_illv4 != NULL)
29345 				ill = phyi->phyint_illv4;
29346 			else
29347 				ill = phyi->phyint_illv6;
29348 
29349 			if (ill != NULL) {
29350 				mutex_enter(&ill->ill_lock);
29351 				ill_nic_info_plumb(ill, B_TRUE);
29352 				ill_nic_info_dispatch(ill);
29353 				mutex_exit(&ill->ill_lock);
29354 			}
29355 		}
29356 	}
29357 	rw_exit(&ipst->ips_ill_g_lock);
29358 }
29359 
29360 /* ARGSUSED */
29361 static int
29362 ipmp_hook_emulation_set(queue_t *q, mblk_t *mp, char *value,
29363     caddr_t addr, cred_t *cr)
29364 {
29365 	int *v = (int *)addr;
29366 	long new_value;
29367 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29368 
29369 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29370 		return (EINVAL);
29371 
29372 	if (*v != new_value) {
29373 		*v = new_value;
29374 		ipmp_hook_emulation_changed(ipst);
29375 	}
29376 	return (0);
29377 }
29378 
29379 static void *
29380 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29381 {
29382 	kstat_t *ksp;
29383 
29384 	ip_stat_t template = {
29385 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29386 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29387 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29388 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29389 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29390 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29391 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29392 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29393 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29394 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29395 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29396 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29397 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29398 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29399 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29400 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29401 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29402 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29403 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29404 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29405 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29406 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29407 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29408 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29409 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29410 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29411 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29412 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29413 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29414 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29415 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29416 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29417 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29418 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29419 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29420 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29421 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29422 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29423 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29424 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29425 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29426 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29427 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29428 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29429 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29430 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29431 	};
29432 
29433 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29434 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29435 	    KSTAT_FLAG_VIRTUAL, stackid);
29436 
29437 	if (ksp == NULL)
29438 		return (NULL);
29439 
29440 	bcopy(&template, ip_statisticsp, sizeof (template));
29441 	ksp->ks_data = (void *)ip_statisticsp;
29442 	ksp->ks_private = (void *)(uintptr_t)stackid;
29443 
29444 	kstat_install(ksp);
29445 	return (ksp);
29446 }
29447 
29448 static void
29449 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29450 {
29451 	if (ksp != NULL) {
29452 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29453 		kstat_delete_netstack(ksp, stackid);
29454 	}
29455 }
29456 
29457 static void *
29458 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29459 {
29460 	kstat_t	*ksp;
29461 
29462 	ip_named_kstat_t template = {
29463 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29464 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29465 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29466 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29467 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29468 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29469 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29470 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29471 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29472 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29473 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29474 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29475 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29476 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29477 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29478 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29479 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29480 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29481 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29482 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29483 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29484 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29485 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29486 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29487 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29488 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29489 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29490 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29491 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29492 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29493 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29494 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29495 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29496 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29497 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29498 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29499 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29500 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29501 	};
29502 
29503 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29504 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29505 	if (ksp == NULL || ksp->ks_data == NULL)
29506 		return (NULL);
29507 
29508 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29509 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29510 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29511 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29512 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29513 
29514 	template.netToMediaEntrySize.value.i32 =
29515 	    sizeof (mib2_ipNetToMediaEntry_t);
29516 
29517 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29518 
29519 	bcopy(&template, ksp->ks_data, sizeof (template));
29520 	ksp->ks_update = ip_kstat_update;
29521 	ksp->ks_private = (void *)(uintptr_t)stackid;
29522 
29523 	kstat_install(ksp);
29524 	return (ksp);
29525 }
29526 
29527 static void
29528 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29529 {
29530 	if (ksp != NULL) {
29531 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29532 		kstat_delete_netstack(ksp, stackid);
29533 	}
29534 }
29535 
29536 static int
29537 ip_kstat_update(kstat_t *kp, int rw)
29538 {
29539 	ip_named_kstat_t *ipkp;
29540 	mib2_ipIfStatsEntry_t ipmib;
29541 	ill_walk_context_t ctx;
29542 	ill_t *ill;
29543 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29544 	netstack_t	*ns;
29545 	ip_stack_t	*ipst;
29546 
29547 	if (kp == NULL || kp->ks_data == NULL)
29548 		return (EIO);
29549 
29550 	if (rw == KSTAT_WRITE)
29551 		return (EACCES);
29552 
29553 	ns = netstack_find_by_stackid(stackid);
29554 	if (ns == NULL)
29555 		return (-1);
29556 	ipst = ns->netstack_ip;
29557 	if (ipst == NULL) {
29558 		netstack_rele(ns);
29559 		return (-1);
29560 	}
29561 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29562 
29563 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29564 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29565 	ill = ILL_START_WALK_V4(&ctx, ipst);
29566 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29567 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29568 	rw_exit(&ipst->ips_ill_g_lock);
29569 
29570 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29571 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29572 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29573 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29574 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29575 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29576 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29577 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29578 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29579 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29580 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29581 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29582 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29583 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29584 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29585 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29586 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29587 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29588 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29589 
29590 	ipkp->routingDiscards.value.ui32 =	0;
29591 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29592 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29593 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29594 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29595 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29596 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29597 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29598 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29599 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29600 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29601 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29602 
29603 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29604 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29605 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29606 
29607 	netstack_rele(ns);
29608 
29609 	return (0);
29610 }
29611 
29612 static void *
29613 icmp_kstat_init(netstackid_t stackid)
29614 {
29615 	kstat_t	*ksp;
29616 
29617 	icmp_named_kstat_t template = {
29618 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29619 		{ "inErrors",		KSTAT_DATA_UINT32 },
29620 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29621 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29622 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29623 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29624 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29625 		{ "inEchos",		KSTAT_DATA_UINT32 },
29626 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29627 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29628 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29629 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29630 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29631 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29632 		{ "outErrors",		KSTAT_DATA_UINT32 },
29633 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29634 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29635 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29636 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29637 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29638 		{ "outEchos",		KSTAT_DATA_UINT32 },
29639 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29640 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29641 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29642 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29643 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29644 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29645 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29646 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29647 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29648 		{ "outDrops",		KSTAT_DATA_UINT32 },
29649 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29650 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29651 	};
29652 
29653 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29654 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29655 	if (ksp == NULL || ksp->ks_data == NULL)
29656 		return (NULL);
29657 
29658 	bcopy(&template, ksp->ks_data, sizeof (template));
29659 
29660 	ksp->ks_update = icmp_kstat_update;
29661 	ksp->ks_private = (void *)(uintptr_t)stackid;
29662 
29663 	kstat_install(ksp);
29664 	return (ksp);
29665 }
29666 
29667 static void
29668 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29669 {
29670 	if (ksp != NULL) {
29671 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29672 		kstat_delete_netstack(ksp, stackid);
29673 	}
29674 }
29675 
29676 static int
29677 icmp_kstat_update(kstat_t *kp, int rw)
29678 {
29679 	icmp_named_kstat_t *icmpkp;
29680 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29681 	netstack_t	*ns;
29682 	ip_stack_t	*ipst;
29683 
29684 	if ((kp == NULL) || (kp->ks_data == NULL))
29685 		return (EIO);
29686 
29687 	if (rw == KSTAT_WRITE)
29688 		return (EACCES);
29689 
29690 	ns = netstack_find_by_stackid(stackid);
29691 	if (ns == NULL)
29692 		return (-1);
29693 	ipst = ns->netstack_ip;
29694 	if (ipst == NULL) {
29695 		netstack_rele(ns);
29696 		return (-1);
29697 	}
29698 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29699 
29700 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29701 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29702 	icmpkp->inDestUnreachs.value.ui32 =
29703 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29704 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29705 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29706 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29707 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29708 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29709 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29710 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29711 	icmpkp->inTimestampReps.value.ui32 =
29712 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29713 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29714 	icmpkp->inAddrMaskReps.value.ui32 =
29715 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29716 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29717 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29718 	icmpkp->outDestUnreachs.value.ui32 =
29719 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29720 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29721 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29722 	icmpkp->outSrcQuenchs.value.ui32 =
29723 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29724 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29725 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29726 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29727 	icmpkp->outTimestamps.value.ui32 =
29728 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29729 	icmpkp->outTimestampReps.value.ui32 =
29730 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29731 	icmpkp->outAddrMasks.value.ui32 =
29732 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29733 	icmpkp->outAddrMaskReps.value.ui32 =
29734 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29735 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29736 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29737 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29738 	icmpkp->outFragNeeded.value.ui32 =
29739 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29740 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29741 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29742 	icmpkp->inBadRedirects.value.ui32 =
29743 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29744 
29745 	netstack_rele(ns);
29746 	return (0);
29747 }
29748 
29749 /*
29750  * This is the fanout function for raw socket opened for SCTP.  Note
29751  * that it is called after SCTP checks that there is no socket which
29752  * wants a packet.  Then before SCTP handles this out of the blue packet,
29753  * this function is called to see if there is any raw socket for SCTP.
29754  * If there is and it is bound to the correct address, the packet will
29755  * be sent to that socket.  Note that only one raw socket can be bound to
29756  * a port.  This is assured in ipcl_sctp_hash_insert();
29757  */
29758 void
29759 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29760     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29761     zoneid_t zoneid)
29762 {
29763 	conn_t		*connp;
29764 	queue_t		*rq;
29765 	mblk_t		*first_mp;
29766 	boolean_t	secure;
29767 	ip6_t		*ip6h;
29768 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29769 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29770 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
29771 	boolean_t	sctp_csum_err = B_FALSE;
29772 
29773 	if (flags & IP_FF_SCTP_CSUM_ERR) {
29774 		sctp_csum_err = B_TRUE;
29775 		flags &= ~IP_FF_SCTP_CSUM_ERR;
29776 	}
29777 
29778 	first_mp = mp;
29779 	if (mctl_present) {
29780 		mp = first_mp->b_cont;
29781 		secure = ipsec_in_is_secure(first_mp);
29782 		ASSERT(mp != NULL);
29783 	} else {
29784 		secure = B_FALSE;
29785 	}
29786 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29787 
29788 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29789 	if (connp == NULL) {
29790 		/*
29791 		 * Although raw sctp is not summed, OOB chunks must be.
29792 		 * Drop the packet here if the sctp checksum failed.
29793 		 */
29794 		if (sctp_csum_err) {
29795 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
29796 			freemsg(first_mp);
29797 			return;
29798 		}
29799 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29800 		return;
29801 	}
29802 	rq = connp->conn_rq;
29803 	if (!canputnext(rq)) {
29804 		CONN_DEC_REF(connp);
29805 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29806 		freemsg(first_mp);
29807 		return;
29808 	}
29809 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29810 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29811 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29812 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29813 		if (first_mp == NULL) {
29814 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29815 			CONN_DEC_REF(connp);
29816 			return;
29817 		}
29818 	}
29819 	/*
29820 	 * We probably should not send M_CTL message up to
29821 	 * raw socket.
29822 	 */
29823 	if (mctl_present)
29824 		freeb(first_mp);
29825 
29826 	/* Initiate IPPF processing here if needed. */
29827 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29828 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29829 		ip_process(IPP_LOCAL_IN, &mp,
29830 		    recv_ill->ill_phyint->phyint_ifindex);
29831 		if (mp == NULL) {
29832 			CONN_DEC_REF(connp);
29833 			return;
29834 		}
29835 	}
29836 
29837 	if (connp->conn_recvif || connp->conn_recvslla ||
29838 	    ((connp->conn_ip_recvpktinfo ||
29839 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29840 	    (flags & IP_FF_IPINFO))) {
29841 		int in_flags = 0;
29842 
29843 		/*
29844 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29845 		 * IPF_RECVIF.
29846 		 */
29847 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29848 			in_flags = IPF_RECVIF;
29849 		}
29850 		if (connp->conn_recvslla) {
29851 			in_flags |= IPF_RECVSLLA;
29852 		}
29853 		if (isv4) {
29854 			mp = ip_add_info(mp, recv_ill, in_flags,
29855 			    IPCL_ZONEID(connp), ipst);
29856 		} else {
29857 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29858 			if (mp == NULL) {
29859 				BUMP_MIB(recv_ill->ill_ip_mib,
29860 				    ipIfStatsInDiscards);
29861 				CONN_DEC_REF(connp);
29862 				return;
29863 			}
29864 		}
29865 	}
29866 
29867 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29868 	/*
29869 	 * We are sending the IPSEC_IN message also up. Refer
29870 	 * to comments above this function.
29871 	 * This is the SOCK_RAW, IPPROTO_SCTP case.
29872 	 */
29873 	(connp->conn_recv)(connp, mp, NULL);
29874 	CONN_DEC_REF(connp);
29875 }
29876 
29877 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29878 {									\
29879 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29880 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29881 }
29882 /*
29883  * This function should be called only if all packet processing
29884  * including fragmentation is complete. Callers of this function
29885  * must set mp->b_prev to one of these values:
29886  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29887  * prior to handing over the mp as first argument to this function.
29888  *
29889  * If the ire passed by caller is incomplete, this function
29890  * queues the packet and if necessary, sends ARP request and bails.
29891  * If the ire passed is fully resolved, we simply prepend
29892  * the link-layer header to the packet, do ipsec hw acceleration
29893  * work if necessary, and send the packet out on the wire.
29894  *
29895  * NOTE: IPsec will only call this function with fully resolved
29896  * ires if hw acceleration is involved.
29897  * TODO list :
29898  * 	a Handle M_MULTIDATA so that
29899  *	  tcp_multisend->tcp_multisend_data can
29900  *	  call ip_xmit_v4 directly
29901  *	b Handle post-ARP work for fragments so that
29902  *	  ip_wput_frag can call this function.
29903  */
29904 ipxmit_state_t
29905 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
29906 {
29907 	nce_t		*arpce;
29908 	ipha_t		*ipha;
29909 	queue_t		*q;
29910 	int		ill_index;
29911 	mblk_t		*nxt_mp, *first_mp;
29912 	boolean_t	xmit_drop = B_FALSE;
29913 	ip_proc_t	proc;
29914 	ill_t		*out_ill;
29915 	int		pkt_len;
29916 
29917 	arpce = ire->ire_nce;
29918 	ASSERT(arpce != NULL);
29919 
29920 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29921 
29922 	mutex_enter(&arpce->nce_lock);
29923 	switch (arpce->nce_state) {
29924 	case ND_REACHABLE:
29925 		/* If there are other queued packets, queue this packet */
29926 		if (arpce->nce_qd_mp != NULL) {
29927 			if (mp != NULL)
29928 				nce_queue_mp_common(arpce, mp, B_FALSE);
29929 			mp = arpce->nce_qd_mp;
29930 		}
29931 		arpce->nce_qd_mp = NULL;
29932 		mutex_exit(&arpce->nce_lock);
29933 
29934 		/*
29935 		 * Flush the queue.  In the common case, where the
29936 		 * ARP is already resolved,  it will go through the
29937 		 * while loop only once.
29938 		 */
29939 		while (mp != NULL) {
29940 
29941 			nxt_mp = mp->b_next;
29942 			mp->b_next = NULL;
29943 			ASSERT(mp->b_datap->db_type != M_CTL);
29944 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29945 			/*
29946 			 * This info is needed for IPQOS to do COS marking
29947 			 * in ip_wput_attach_llhdr->ip_process.
29948 			 */
29949 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29950 			mp->b_prev = NULL;
29951 
29952 			/* set up ill index for outbound qos processing */
29953 			out_ill = ire_to_ill(ire);
29954 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29955 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29956 			    ill_index, &ipha);
29957 			if (first_mp == NULL) {
29958 				xmit_drop = B_TRUE;
29959 				BUMP_MIB(out_ill->ill_ip_mib,
29960 				    ipIfStatsOutDiscards);
29961 				goto next_mp;
29962 			}
29963 
29964 			/* non-ipsec hw accel case */
29965 			if (io == NULL || !io->ipsec_out_accelerated) {
29966 				/* send it */
29967 				q = ire->ire_stq;
29968 				if (proc == IPP_FWD_OUT) {
29969 					UPDATE_IB_PKT_COUNT(ire);
29970 				} else {
29971 					UPDATE_OB_PKT_COUNT(ire);
29972 				}
29973 				ire->ire_last_used_time = lbolt;
29974 
29975 				if (flow_ctl_enabled || canputnext(q)) {
29976 					if (proc == IPP_FWD_OUT) {
29977 
29978 					BUMP_MIB(out_ill->ill_ip_mib,
29979 					    ipIfStatsHCOutForwDatagrams);
29980 
29981 					}
29982 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29983 					    pkt_len);
29984 
29985 					DTRACE_IP7(send, mblk_t *, first_mp,
29986 					    conn_t *, NULL, void_ip_t *, ipha,
29987 					    __dtrace_ipsr_ill_t *, out_ill,
29988 					    ipha_t *, ipha, ip6_t *, NULL, int,
29989 					    0);
29990 
29991 					putnext(q, first_mp);
29992 				} else {
29993 					BUMP_MIB(out_ill->ill_ip_mib,
29994 					    ipIfStatsOutDiscards);
29995 					xmit_drop = B_TRUE;
29996 					freemsg(first_mp);
29997 				}
29998 			} else {
29999 				/*
30000 				 * Safety Pup says: make sure this
30001 				 *  is going to the right interface!
30002 				 */
30003 				ill_t *ill1 =
30004 				    (ill_t *)ire->ire_stq->q_ptr;
30005 				int ifindex =
30006 				    ill1->ill_phyint->phyint_ifindex;
30007 				if (ifindex !=
30008 				    io->ipsec_out_capab_ill_index) {
30009 					xmit_drop = B_TRUE;
30010 					freemsg(mp);
30011 				} else {
30012 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
30013 					    pkt_len);
30014 
30015 					DTRACE_IP7(send, mblk_t *, first_mp,
30016 					    conn_t *, NULL, void_ip_t *, ipha,
30017 					    __dtrace_ipsr_ill_t *, ill1,
30018 					    ipha_t *, ipha, ip6_t *, NULL,
30019 					    int, 0);
30020 
30021 					ipsec_hw_putnext(ire->ire_stq, mp);
30022 				}
30023 			}
30024 next_mp:
30025 			mp = nxt_mp;
30026 		} /* while (mp != NULL) */
30027 		if (xmit_drop)
30028 			return (SEND_FAILED);
30029 		else
30030 			return (SEND_PASSED);
30031 
30032 	case ND_INITIAL:
30033 	case ND_INCOMPLETE:
30034 
30035 		/*
30036 		 * While we do send off packets to dests that
30037 		 * use fully-resolved CGTP routes, we do not
30038 		 * handle unresolved CGTP routes.
30039 		 */
30040 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
30041 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
30042 
30043 		if (mp != NULL) {
30044 			/* queue the packet */
30045 			nce_queue_mp_common(arpce, mp, B_FALSE);
30046 		}
30047 
30048 		if (arpce->nce_state == ND_INCOMPLETE) {
30049 			mutex_exit(&arpce->nce_lock);
30050 			DTRACE_PROBE3(ip__xmit__incomplete,
30051 			    (ire_t *), ire, (mblk_t *), mp,
30052 			    (ipsec_out_t *), io);
30053 			return (LOOKUP_IN_PROGRESS);
30054 		}
30055 
30056 		arpce->nce_state = ND_INCOMPLETE;
30057 		mutex_exit(&arpce->nce_lock);
30058 		/*
30059 		 * Note that ire_add() (called from ire_forward())
30060 		 * holds a ref on the ire until ARP is completed.
30061 		 */
30062 
30063 		ire_arpresolve(ire, ire_to_ill(ire));
30064 		return (LOOKUP_IN_PROGRESS);
30065 	default:
30066 		ASSERT(0);
30067 		mutex_exit(&arpce->nce_lock);
30068 		return (LLHDR_RESLV_FAILED);
30069 	}
30070 }
30071 
30072 #undef	UPDATE_IP_MIB_OB_COUNTERS
30073 
30074 /*
30075  * Return B_TRUE if the buffers differ in length or content.
30076  * This is used for comparing extension header buffers.
30077  * Note that an extension header would be declared different
30078  * even if all that changed was the next header value in that header i.e.
30079  * what really changed is the next extension header.
30080  */
30081 boolean_t
30082 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
30083     uint_t blen)
30084 {
30085 	if (!b_valid)
30086 		blen = 0;
30087 
30088 	if (alen != blen)
30089 		return (B_TRUE);
30090 	if (alen == 0)
30091 		return (B_FALSE);	/* Both zero length */
30092 	return (bcmp(abuf, bbuf, alen));
30093 }
30094 
30095 /*
30096  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
30097  * Return B_FALSE if memory allocation fails - don't change any state!
30098  */
30099 boolean_t
30100 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30101     const void *src, uint_t srclen)
30102 {
30103 	void *dst;
30104 
30105 	if (!src_valid)
30106 		srclen = 0;
30107 
30108 	ASSERT(*dstlenp == 0);
30109 	if (src != NULL && srclen != 0) {
30110 		dst = mi_alloc(srclen, BPRI_MED);
30111 		if (dst == NULL)
30112 			return (B_FALSE);
30113 	} else {
30114 		dst = NULL;
30115 	}
30116 	if (*dstp != NULL)
30117 		mi_free(*dstp);
30118 	*dstp = dst;
30119 	*dstlenp = dst == NULL ? 0 : srclen;
30120 	return (B_TRUE);
30121 }
30122 
30123 /*
30124  * Replace what is in *dst, *dstlen with the source.
30125  * Assumes ip_allocbuf has already been called.
30126  */
30127 void
30128 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30129     const void *src, uint_t srclen)
30130 {
30131 	if (!src_valid)
30132 		srclen = 0;
30133 
30134 	ASSERT(*dstlenp == srclen);
30135 	if (src != NULL && srclen != 0)
30136 		bcopy(src, *dstp, srclen);
30137 }
30138 
30139 /*
30140  * Free the storage pointed to by the members of an ip6_pkt_t.
30141  */
30142 void
30143 ip6_pkt_free(ip6_pkt_t *ipp)
30144 {
30145 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
30146 
30147 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
30148 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
30149 		ipp->ipp_hopopts = NULL;
30150 		ipp->ipp_hopoptslen = 0;
30151 	}
30152 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
30153 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
30154 		ipp->ipp_rtdstopts = NULL;
30155 		ipp->ipp_rtdstoptslen = 0;
30156 	}
30157 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
30158 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
30159 		ipp->ipp_dstopts = NULL;
30160 		ipp->ipp_dstoptslen = 0;
30161 	}
30162 	if (ipp->ipp_fields & IPPF_RTHDR) {
30163 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
30164 		ipp->ipp_rthdr = NULL;
30165 		ipp->ipp_rthdrlen = 0;
30166 	}
30167 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
30168 	    IPPF_RTHDR);
30169 }
30170