xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision 19397407)
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, (void *)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 			 * Inactive/Failed interfaces are not supposed to
17290 			 * respond to the multicast packets.
17291 			 */
17292 			if (ill_is_probeonly(ill)) {
17293 				freemsg(first_mp);
17294 				return;
17295 			}
17296 
17297 			/*
17298 			 * In the multicast case, applications may have joined
17299 			 * the group from different zones, so we need to deliver
17300 			 * the packet to each of them. Loop through the
17301 			 * multicast memberships structures (ilm) on the receive
17302 			 * ill and send a copy of the packet up each matching
17303 			 * one. However, we don't do this for multicasts sent on
17304 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17305 			 * they must stay in the sender's zone.
17306 			 *
17307 			 * ilm_add_v6() ensures that ilms in the same zone are
17308 			 * contiguous in the ill_ilm list. We use this property
17309 			 * to avoid sending duplicates needed when two
17310 			 * applications in the same zone join the same group on
17311 			 * different logical interfaces: we ignore the ilm if
17312 			 * its zoneid is the same as the last matching one.
17313 			 * In addition, the sending of the packet for
17314 			 * ire_zoneid is delayed until all of the other ilms
17315 			 * have been exhausted.
17316 			 */
17317 			last_zoneid = -1;
17318 			ILM_WALKER_HOLD(recv_ill);
17319 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17320 			    ilm = ilm->ilm_next) {
17321 				if ((ilm->ilm_flags & ILM_DELETED) ||
17322 				    ipha->ipha_dst != ilm->ilm_addr ||
17323 				    ilm->ilm_zoneid == last_zoneid ||
17324 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17325 				    ilm->ilm_zoneid == ALL_ZONES ||
17326 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17327 					continue;
17328 				mp1 = ip_copymsg(first_mp);
17329 				if (mp1 == NULL)
17330 					continue;
17331 				icmp_inbound(q, mp1, B_TRUE, ill,
17332 				    0, sum, mctl_present, B_TRUE,
17333 				    recv_ill, ilm->ilm_zoneid);
17334 				last_zoneid = ilm->ilm_zoneid;
17335 			}
17336 			ILM_WALKER_RELE(recv_ill);
17337 		} else if (ire->ire_type == IRE_BROADCAST) {
17338 			/*
17339 			 * In the broadcast case, there may be many zones
17340 			 * which need a copy of the packet delivered to them.
17341 			 * There is one IRE_BROADCAST per broadcast address
17342 			 * and per zone; we walk those using a helper function.
17343 			 * In addition, the sending of the packet for ire is
17344 			 * delayed until all of the other ires have been
17345 			 * processed.
17346 			 */
17347 			IRB_REFHOLD(ire->ire_bucket);
17348 			ire_zone = NULL;
17349 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17350 			    ire)) != NULL) {
17351 				mp1 = ip_copymsg(first_mp);
17352 				if (mp1 == NULL)
17353 					continue;
17354 
17355 				UPDATE_IB_PKT_COUNT(ire_zone);
17356 				ire_zone->ire_last_used_time = lbolt;
17357 				icmp_inbound(q, mp1, B_TRUE, ill,
17358 				    0, sum, mctl_present, B_TRUE,
17359 				    recv_ill, ire_zone->ire_zoneid);
17360 			}
17361 			IRB_REFRELE(ire->ire_bucket);
17362 		}
17363 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17364 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17365 		    ire->ire_zoneid);
17366 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17367 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17368 		return;
17369 	}
17370 	case IPPROTO_IGMP:
17371 		/*
17372 		 * If we are not willing to accept IGMP packets in clear,
17373 		 * then check with global policy.
17374 		 */
17375 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17376 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17377 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17378 			if (first_mp == NULL)
17379 				return;
17380 		}
17381 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17382 			freemsg(first_mp);
17383 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17384 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17385 			return;
17386 		}
17387 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17388 			/* Bad packet - discarded by igmp_input */
17389 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17390 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17391 			if (mctl_present)
17392 				freeb(first_mp);
17393 			return;
17394 		}
17395 		/*
17396 		 * igmp_input() may have returned the pulled up message.
17397 		 * So first_mp and ipha need to be reinitialized.
17398 		 */
17399 		ipha = (ipha_t *)mp->b_rptr;
17400 		if (mctl_present)
17401 			first_mp->b_cont = mp;
17402 		else
17403 			first_mp = mp;
17404 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17405 		    connf_head != NULL) {
17406 			/* No user-level listener for IGMP packets */
17407 			goto drop_pkt;
17408 		}
17409 		/* deliver to local raw users */
17410 		break;
17411 	case IPPROTO_PIM:
17412 		/*
17413 		 * If we are not willing to accept PIM packets in clear,
17414 		 * then check with global policy.
17415 		 */
17416 		if (ipst->ips_pim_accept_clear_messages == 0) {
17417 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17418 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17419 			if (first_mp == NULL)
17420 				return;
17421 		}
17422 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17423 			freemsg(first_mp);
17424 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17425 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17426 			return;
17427 		}
17428 		if (pim_input(q, mp, ill) != 0) {
17429 			/* Bad packet - discarded by pim_input */
17430 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17431 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17432 			if (mctl_present)
17433 				freeb(first_mp);
17434 			return;
17435 		}
17436 
17437 		/*
17438 		 * pim_input() may have pulled up the message so ipha needs to
17439 		 * be reinitialized.
17440 		 */
17441 		ipha = (ipha_t *)mp->b_rptr;
17442 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17443 		    connf_head != NULL) {
17444 			/* No user-level listener for PIM packets */
17445 			goto drop_pkt;
17446 		}
17447 		/* deliver to local raw users */
17448 		break;
17449 	case IPPROTO_ENCAP:
17450 		/*
17451 		 * Handle self-encapsulated packets (IP-in-IP where
17452 		 * the inner addresses == the outer addresses).
17453 		 */
17454 		hdr_length = IPH_HDR_LENGTH(ipha);
17455 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17456 		    mp->b_wptr) {
17457 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17458 			    sizeof (ipha_t) - mp->b_rptr)) {
17459 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17460 				freemsg(first_mp);
17461 				return;
17462 			}
17463 			ipha = (ipha_t *)mp->b_rptr;
17464 		}
17465 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17466 		/*
17467 		 * Check the sanity of the inner IP header.
17468 		 */
17469 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17470 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17471 			freemsg(first_mp);
17472 			return;
17473 		}
17474 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17475 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17476 			freemsg(first_mp);
17477 			return;
17478 		}
17479 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17480 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17481 			ipsec_in_t *ii;
17482 
17483 			/*
17484 			 * Self-encapsulated tunnel packet. Remove
17485 			 * the outer IP header and fanout again.
17486 			 * We also need to make sure that the inner
17487 			 * header is pulled up until options.
17488 			 */
17489 			mp->b_rptr = (uchar_t *)inner_ipha;
17490 			ipha = inner_ipha;
17491 			hdr_length = IPH_HDR_LENGTH(ipha);
17492 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17493 				if (!pullupmsg(mp, (uchar_t *)ipha +
17494 				    + hdr_length - mp->b_rptr)) {
17495 					freemsg(first_mp);
17496 					return;
17497 				}
17498 				ipha = (ipha_t *)mp->b_rptr;
17499 			}
17500 			if (hdr_length > sizeof (ipha_t)) {
17501 				/* We got options on the inner packet. */
17502 				ipaddr_t dst = ipha->ipha_dst;
17503 
17504 				if (ip_rput_options(q, mp, ipha, &dst, ipst) ==
17505 				    -1) {
17506 					/* Bad options! */
17507 					return;
17508 				}
17509 				if (dst != ipha->ipha_dst) {
17510 					/*
17511 					 * Someone put a source-route in
17512 					 * the inside header of a self-
17513 					 * encapsulated packet.  Drop it
17514 					 * with extreme prejudice and let
17515 					 * the sender know.
17516 					 */
17517 					icmp_unreachable(q, first_mp,
17518 					    ICMP_SOURCE_ROUTE_FAILED,
17519 					    recv_ill->ill_zoneid, ipst);
17520 					return;
17521 				}
17522 			}
17523 			if (!mctl_present) {
17524 				ASSERT(first_mp == mp);
17525 				/*
17526 				 * This means that somebody is sending
17527 				 * Self-encapsualted packets without AH/ESP.
17528 				 * If AH/ESP was present, we would have already
17529 				 * allocated the first_mp.
17530 				 *
17531 				 * Send this packet to find a tunnel endpoint.
17532 				 * if I can't find one, an ICMP
17533 				 * PROTOCOL_UNREACHABLE will get sent.
17534 				 */
17535 				goto fanout;
17536 			}
17537 			/*
17538 			 * We generally store the ill_index if we need to
17539 			 * do IPsec processing as we lose the ill queue when
17540 			 * we come back. But in this case, we never should
17541 			 * have to store the ill_index here as it should have
17542 			 * been stored previously when we processed the
17543 			 * AH/ESP header in this routine or for non-ipsec
17544 			 * cases, we still have the queue. But for some bad
17545 			 * packets from the wire, we can get to IPsec after
17546 			 * this and we better store the index for that case.
17547 			 */
17548 			ill = (ill_t *)q->q_ptr;
17549 			ii = (ipsec_in_t *)first_mp->b_rptr;
17550 			ii->ipsec_in_ill_index =
17551 			    ill->ill_phyint->phyint_ifindex;
17552 			ii->ipsec_in_rill_index =
17553 			    recv_ill->ill_phyint->phyint_ifindex;
17554 			if (ii->ipsec_in_decaps) {
17555 				/*
17556 				 * This packet is self-encapsulated multiple
17557 				 * times. We don't want to recurse infinitely.
17558 				 * To keep it simple, drop the packet.
17559 				 */
17560 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17561 				freemsg(first_mp);
17562 				return;
17563 			}
17564 			ii->ipsec_in_decaps = B_TRUE;
17565 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17566 			    ire);
17567 			return;
17568 		}
17569 		break;
17570 	case IPPROTO_AH:
17571 	case IPPROTO_ESP: {
17572 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17573 
17574 		/*
17575 		 * Fast path for AH/ESP. If this is the first time
17576 		 * we are sending a datagram to AH/ESP, allocate
17577 		 * a IPSEC_IN message and prepend it. Otherwise,
17578 		 * just fanout.
17579 		 */
17580 
17581 		int ipsec_rc;
17582 		ipsec_in_t *ii;
17583 		netstack_t *ns = ipst->ips_netstack;
17584 
17585 		IP_STAT(ipst, ipsec_proto_ahesp);
17586 		if (!mctl_present) {
17587 			ASSERT(first_mp == mp);
17588 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17589 			if (first_mp == NULL) {
17590 				ip1dbg(("ip_proto_input: IPSEC_IN "
17591 				    "allocation failure.\n"));
17592 				freemsg(hada_mp); /* okay ifnull */
17593 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17594 				freemsg(mp);
17595 				return;
17596 			}
17597 			/*
17598 			 * Store the ill_index so that when we come back
17599 			 * from IPsec we ride on the same queue.
17600 			 */
17601 			ill = (ill_t *)q->q_ptr;
17602 			ii = (ipsec_in_t *)first_mp->b_rptr;
17603 			ii->ipsec_in_ill_index =
17604 			    ill->ill_phyint->phyint_ifindex;
17605 			ii->ipsec_in_rill_index =
17606 			    recv_ill->ill_phyint->phyint_ifindex;
17607 			first_mp->b_cont = mp;
17608 			/*
17609 			 * Cache hardware acceleration info.
17610 			 */
17611 			if (hada_mp != NULL) {
17612 				IPSECHW_DEBUG(IPSECHW_PKT,
17613 				    ("ip_rput_local: caching data attr.\n"));
17614 				ii->ipsec_in_accelerated = B_TRUE;
17615 				ii->ipsec_in_da = hada_mp;
17616 				hada_mp = NULL;
17617 			}
17618 		} else {
17619 			ii = (ipsec_in_t *)first_mp->b_rptr;
17620 		}
17621 
17622 		ii->ipsec_in_esp_udp_ports = esp_udp_ports;
17623 
17624 		if (!ipsec_loaded(ipss)) {
17625 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17626 			    ire->ire_zoneid, ipst);
17627 			return;
17628 		}
17629 
17630 		ns = ipst->ips_netstack;
17631 		/* select inbound SA and have IPsec process the pkt */
17632 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17633 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17634 			boolean_t esp_in_udp_sa;
17635 			if (esph == NULL)
17636 				return;
17637 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17638 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17639 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
17640 			    IPSA_F_NATT) != 0);
17641 			/*
17642 			 * The following is a fancy, but quick, way of saying:
17643 			 * ESP-in-UDP SA and Raw ESP packet --> drop
17644 			 *    OR
17645 			 * ESP SA and ESP-in-UDP packet --> drop
17646 			 */
17647 			if (esp_in_udp_sa != esp_in_udp_packet) {
17648 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17649 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
17650 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
17651 				    &ns->netstack_ipsec->ipsec_dropper);
17652 				return;
17653 			}
17654 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17655 			    first_mp, esph);
17656 		} else {
17657 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17658 			if (ah == NULL)
17659 				return;
17660 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17661 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17662 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17663 			    first_mp, ah);
17664 		}
17665 
17666 		switch (ipsec_rc) {
17667 		case IPSEC_STATUS_SUCCESS:
17668 			break;
17669 		case IPSEC_STATUS_FAILED:
17670 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17671 			/* FALLTHRU */
17672 		case IPSEC_STATUS_PENDING:
17673 			return;
17674 		}
17675 		/* we're done with IPsec processing, send it up */
17676 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17677 		return;
17678 	}
17679 	default:
17680 		break;
17681 	}
17682 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17683 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17684 		    ire->ire_zoneid));
17685 		goto drop_pkt;
17686 	}
17687 	/*
17688 	 * Handle protocols with which IP is less intimate.  There
17689 	 * can be more than one stream bound to a particular
17690 	 * protocol.  When this is the case, each one gets a copy
17691 	 * of any incoming packets.
17692 	 */
17693 fanout:
17694 	ip_fanout_proto(q, first_mp, ill, ipha,
17695 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17696 	    B_TRUE, recv_ill, ire->ire_zoneid);
17697 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17698 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17699 	return;
17700 
17701 drop_pkt:
17702 	freemsg(first_mp);
17703 	if (hada_mp != NULL)
17704 		freeb(hada_mp);
17705 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17706 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17707 #undef	rptr
17708 #undef  iphs
17709 
17710 }
17711 
17712 /*
17713  * Update any source route, record route or timestamp options.
17714  * Check that we are at end of strict source route.
17715  * The options have already been checked for sanity in ip_rput_options().
17716  */
17717 static boolean_t
17718 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17719     ip_stack_t *ipst)
17720 {
17721 	ipoptp_t	opts;
17722 	uchar_t		*opt;
17723 	uint8_t		optval;
17724 	uint8_t		optlen;
17725 	ipaddr_t	dst;
17726 	uint32_t	ts;
17727 	ire_t		*dst_ire;
17728 	timestruc_t	now;
17729 	zoneid_t	zoneid;
17730 	ill_t		*ill;
17731 
17732 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17733 
17734 	ip2dbg(("ip_rput_local_options\n"));
17735 
17736 	for (optval = ipoptp_first(&opts, ipha);
17737 	    optval != IPOPT_EOL;
17738 	    optval = ipoptp_next(&opts)) {
17739 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17740 		opt = opts.ipoptp_cur;
17741 		optlen = opts.ipoptp_len;
17742 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17743 		    optval, optlen));
17744 		switch (optval) {
17745 			uint32_t off;
17746 		case IPOPT_SSRR:
17747 		case IPOPT_LSRR:
17748 			off = opt[IPOPT_OFFSET];
17749 			off--;
17750 			if (optlen < IP_ADDR_LEN ||
17751 			    off > optlen - IP_ADDR_LEN) {
17752 				/* End of source route */
17753 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17754 				break;
17755 			}
17756 			/*
17757 			 * This will only happen if two consecutive entries
17758 			 * in the source route contains our address or if
17759 			 * it is a packet with a loose source route which
17760 			 * reaches us before consuming the whole source route
17761 			 */
17762 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17763 			if (optval == IPOPT_SSRR) {
17764 				goto bad_src_route;
17765 			}
17766 			/*
17767 			 * Hack: instead of dropping the packet truncate the
17768 			 * source route to what has been used by filling the
17769 			 * rest with IPOPT_NOP.
17770 			 */
17771 			opt[IPOPT_OLEN] = (uint8_t)off;
17772 			while (off < optlen) {
17773 				opt[off++] = IPOPT_NOP;
17774 			}
17775 			break;
17776 		case IPOPT_RR:
17777 			off = opt[IPOPT_OFFSET];
17778 			off--;
17779 			if (optlen < IP_ADDR_LEN ||
17780 			    off > optlen - IP_ADDR_LEN) {
17781 				/* No more room - ignore */
17782 				ip1dbg((
17783 				    "ip_rput_local_options: end of RR\n"));
17784 				break;
17785 			}
17786 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17787 			    IP_ADDR_LEN);
17788 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17789 			break;
17790 		case IPOPT_TS:
17791 			/* Insert timestamp if there is romm */
17792 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17793 			case IPOPT_TS_TSONLY:
17794 				off = IPOPT_TS_TIMELEN;
17795 				break;
17796 			case IPOPT_TS_PRESPEC:
17797 			case IPOPT_TS_PRESPEC_RFC791:
17798 				/* Verify that the address matched */
17799 				off = opt[IPOPT_OFFSET] - 1;
17800 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17801 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17802 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
17803 				    ipst);
17804 				if (dst_ire == NULL) {
17805 					/* Not for us */
17806 					break;
17807 				}
17808 				ire_refrele(dst_ire);
17809 				/* FALLTHRU */
17810 			case IPOPT_TS_TSANDADDR:
17811 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17812 				break;
17813 			default:
17814 				/*
17815 				 * ip_*put_options should have already
17816 				 * dropped this packet.
17817 				 */
17818 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17819 				    "unknown IT - bug in ip_rput_options?\n");
17820 				return (B_TRUE);	/* Keep "lint" happy */
17821 			}
17822 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17823 				/* Increase overflow counter */
17824 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17825 				opt[IPOPT_POS_OV_FLG] =
17826 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17827 				    (off << 4));
17828 				break;
17829 			}
17830 			off = opt[IPOPT_OFFSET] - 1;
17831 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17832 			case IPOPT_TS_PRESPEC:
17833 			case IPOPT_TS_PRESPEC_RFC791:
17834 			case IPOPT_TS_TSANDADDR:
17835 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17836 				    IP_ADDR_LEN);
17837 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17838 				/* FALLTHRU */
17839 			case IPOPT_TS_TSONLY:
17840 				off = opt[IPOPT_OFFSET] - 1;
17841 				/* Compute # of milliseconds since midnight */
17842 				gethrestime(&now);
17843 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17844 				    now.tv_nsec / (NANOSEC / MILLISEC);
17845 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17846 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17847 				break;
17848 			}
17849 			break;
17850 		}
17851 	}
17852 	return (B_TRUE);
17853 
17854 bad_src_route:
17855 	q = WR(q);
17856 	if (q->q_next != NULL)
17857 		ill = q->q_ptr;
17858 	else
17859 		ill = NULL;
17860 
17861 	/* make sure we clear any indication of a hardware checksum */
17862 	DB_CKSUMFLAGS(mp) = 0;
17863 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
17864 	if (zoneid == ALL_ZONES)
17865 		freemsg(mp);
17866 	else
17867 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17868 	return (B_FALSE);
17869 
17870 }
17871 
17872 /*
17873  * Process IP options in an inbound packet.  If an option affects the
17874  * effective destination address, return the next hop address via dstp.
17875  * Returns -1 if something fails in which case an ICMP error has been sent
17876  * and mp freed.
17877  */
17878 static int
17879 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
17880     ip_stack_t *ipst)
17881 {
17882 	ipoptp_t	opts;
17883 	uchar_t		*opt;
17884 	uint8_t		optval;
17885 	uint8_t		optlen;
17886 	ipaddr_t	dst;
17887 	intptr_t	code = 0;
17888 	ire_t		*ire = NULL;
17889 	zoneid_t	zoneid;
17890 	ill_t		*ill;
17891 
17892 	ip2dbg(("ip_rput_options\n"));
17893 	dst = ipha->ipha_dst;
17894 	for (optval = ipoptp_first(&opts, ipha);
17895 	    optval != IPOPT_EOL;
17896 	    optval = ipoptp_next(&opts)) {
17897 		opt = opts.ipoptp_cur;
17898 		optlen = opts.ipoptp_len;
17899 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17900 		    optval, optlen));
17901 		/*
17902 		 * Note: we need to verify the checksum before we
17903 		 * modify anything thus this routine only extracts the next
17904 		 * hop dst from any source route.
17905 		 */
17906 		switch (optval) {
17907 			uint32_t off;
17908 		case IPOPT_SSRR:
17909 		case IPOPT_LSRR:
17910 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17911 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17912 			if (ire == NULL) {
17913 				if (optval == IPOPT_SSRR) {
17914 					ip1dbg(("ip_rput_options: not next"
17915 					    " strict source route 0x%x\n",
17916 					    ntohl(dst)));
17917 					code = (char *)&ipha->ipha_dst -
17918 					    (char *)ipha;
17919 					goto param_prob; /* RouterReq's */
17920 				}
17921 				ip2dbg(("ip_rput_options: "
17922 				    "not next source route 0x%x\n",
17923 				    ntohl(dst)));
17924 				break;
17925 			}
17926 			ire_refrele(ire);
17927 
17928 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17929 				ip1dbg((
17930 				    "ip_rput_options: bad option offset\n"));
17931 				code = (char *)&opt[IPOPT_OLEN] -
17932 				    (char *)ipha;
17933 				goto param_prob;
17934 			}
17935 			off = opt[IPOPT_OFFSET];
17936 			off--;
17937 		redo_srr:
17938 			if (optlen < IP_ADDR_LEN ||
17939 			    off > optlen - IP_ADDR_LEN) {
17940 				/* End of source route */
17941 				ip1dbg(("ip_rput_options: end of SR\n"));
17942 				break;
17943 			}
17944 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17945 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
17946 			    ntohl(dst)));
17947 
17948 			/*
17949 			 * Check if our address is present more than
17950 			 * once as consecutive hops in source route.
17951 			 * XXX verify per-interface ip_forwarding
17952 			 * for source route?
17953 			 */
17954 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17955 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17956 
17957 			if (ire != NULL) {
17958 				ire_refrele(ire);
17959 				off += IP_ADDR_LEN;
17960 				goto redo_srr;
17961 			}
17962 
17963 			if (dst == htonl(INADDR_LOOPBACK)) {
17964 				ip1dbg(("ip_rput_options: loopback addr in "
17965 				    "source route!\n"));
17966 				goto bad_src_route;
17967 			}
17968 			/*
17969 			 * For strict: verify that dst is directly
17970 			 * reachable.
17971 			 */
17972 			if (optval == IPOPT_SSRR) {
17973 				ire = ire_ftable_lookup(dst, 0, 0,
17974 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
17975 				    MBLK_GETLABEL(mp),
17976 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
17977 				if (ire == NULL) {
17978 					ip1dbg(("ip_rput_options: SSRR not "
17979 					    "directly reachable: 0x%x\n",
17980 					    ntohl(dst)));
17981 					goto bad_src_route;
17982 				}
17983 				ire_refrele(ire);
17984 			}
17985 			/*
17986 			 * Defer update of the offset and the record route
17987 			 * until the packet is forwarded.
17988 			 */
17989 			break;
17990 		case IPOPT_RR:
17991 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17992 				ip1dbg((
17993 				    "ip_rput_options: bad option offset\n"));
17994 				code = (char *)&opt[IPOPT_OLEN] -
17995 				    (char *)ipha;
17996 				goto param_prob;
17997 			}
17998 			break;
17999 		case IPOPT_TS:
18000 			/*
18001 			 * Verify that length >= 5 and that there is either
18002 			 * room for another timestamp or that the overflow
18003 			 * counter is not maxed out.
18004 			 */
18005 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
18006 			if (optlen < IPOPT_MINLEN_IT) {
18007 				goto param_prob;
18008 			}
18009 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18010 				ip1dbg((
18011 				    "ip_rput_options: bad option offset\n"));
18012 				code = (char *)&opt[IPOPT_OFFSET] -
18013 				    (char *)ipha;
18014 				goto param_prob;
18015 			}
18016 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18017 			case IPOPT_TS_TSONLY:
18018 				off = IPOPT_TS_TIMELEN;
18019 				break;
18020 			case IPOPT_TS_TSANDADDR:
18021 			case IPOPT_TS_PRESPEC:
18022 			case IPOPT_TS_PRESPEC_RFC791:
18023 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18024 				break;
18025 			default:
18026 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
18027 				    (char *)ipha;
18028 				goto param_prob;
18029 			}
18030 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
18031 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
18032 				/*
18033 				 * No room and the overflow counter is 15
18034 				 * already.
18035 				 */
18036 				goto param_prob;
18037 			}
18038 			break;
18039 		}
18040 	}
18041 
18042 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
18043 		*dstp = dst;
18044 		return (0);
18045 	}
18046 
18047 	ip1dbg(("ip_rput_options: error processing IP options."));
18048 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
18049 
18050 param_prob:
18051 	q = WR(q);
18052 	if (q->q_next != NULL)
18053 		ill = q->q_ptr;
18054 	else
18055 		ill = NULL;
18056 
18057 	/* make sure we clear any indication of a hardware checksum */
18058 	DB_CKSUMFLAGS(mp) = 0;
18059 	/* Don't know whether this is for non-global or global/forwarding */
18060 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18061 	if (zoneid == ALL_ZONES)
18062 		freemsg(mp);
18063 	else
18064 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
18065 	return (-1);
18066 
18067 bad_src_route:
18068 	q = WR(q);
18069 	if (q->q_next != NULL)
18070 		ill = q->q_ptr;
18071 	else
18072 		ill = NULL;
18073 
18074 	/* make sure we clear any indication of a hardware checksum */
18075 	DB_CKSUMFLAGS(mp) = 0;
18076 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18077 	if (zoneid == ALL_ZONES)
18078 		freemsg(mp);
18079 	else
18080 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18081 	return (-1);
18082 }
18083 
18084 /*
18085  * IP & ICMP info in >=14 msg's ...
18086  *  - ip fixed part (mib2_ip_t)
18087  *  - icmp fixed part (mib2_icmp_t)
18088  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18089  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18090  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18091  *  - ipRouteAttributeTable (ip 102)	labeled routes
18092  *  - ip multicast membership (ip_member_t)
18093  *  - ip multicast source filtering (ip_grpsrc_t)
18094  *  - igmp fixed part (struct igmpstat)
18095  *  - multicast routing stats (struct mrtstat)
18096  *  - multicast routing vifs (array of struct vifctl)
18097  *  - multicast routing routes (array of struct mfcctl)
18098  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18099  *					One per ill plus one generic
18100  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18101  *					One per ill plus one generic
18102  *  - ipv6RouteEntry			all IPv6 IREs
18103  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18104  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18105  *  - ipv6AddrEntry			all IPv6 ipifs
18106  *  - ipv6 multicast membership (ipv6_member_t)
18107  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18108  *
18109  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18110  *
18111  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18112  * already filled in by the caller.
18113  * Return value of 0 indicates that no messages were sent and caller
18114  * should free mpctl.
18115  */
18116 int
18117 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
18118 {
18119 	ip_stack_t *ipst;
18120 	sctp_stack_t *sctps;
18121 
18122 	if (q->q_next != NULL) {
18123 		ipst = ILLQ_TO_IPST(q);
18124 	} else {
18125 		ipst = CONNQ_TO_IPST(q);
18126 	}
18127 	ASSERT(ipst != NULL);
18128 	sctps = ipst->ips_netstack->netstack_sctp;
18129 
18130 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18131 		return (0);
18132 	}
18133 
18134 	/*
18135 	 * For the purposes of the (broken) packet shell use
18136 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
18137 	 * to make TCP and UDP appear first in the list of mib items.
18138 	 * TBD: We could expand this and use it in netstat so that
18139 	 * the kernel doesn't have to produce large tables (connections,
18140 	 * routes, etc) when netstat only wants the statistics or a particular
18141 	 * table.
18142 	 */
18143 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
18144 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
18145 			return (1);
18146 		}
18147 	}
18148 
18149 	if (level != MIB2_TCP) {
18150 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
18151 			return (1);
18152 		}
18153 	}
18154 
18155 	if (level != MIB2_UDP) {
18156 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
18157 			return (1);
18158 		}
18159 	}
18160 
18161 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18162 	    ipst)) == NULL) {
18163 		return (1);
18164 	}
18165 
18166 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18167 		return (1);
18168 	}
18169 
18170 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18171 		return (1);
18172 	}
18173 
18174 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18175 		return (1);
18176 	}
18177 
18178 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18179 		return (1);
18180 	}
18181 
18182 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18183 		return (1);
18184 	}
18185 
18186 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18187 		return (1);
18188 	}
18189 
18190 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18191 		return (1);
18192 	}
18193 
18194 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18195 		return (1);
18196 	}
18197 
18198 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18199 		return (1);
18200 	}
18201 
18202 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18203 		return (1);
18204 	}
18205 
18206 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18207 		return (1);
18208 	}
18209 
18210 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18211 		return (1);
18212 	}
18213 
18214 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18215 		return (1);
18216 	}
18217 
18218 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, ipst)) == NULL) {
18219 		return (1);
18220 	}
18221 
18222 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, ipst);
18223 	if (mpctl == NULL) {
18224 		return (1);
18225 	}
18226 
18227 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18228 		return (1);
18229 	}
18230 	freemsg(mpctl);
18231 	return (1);
18232 }
18233 
18234 
18235 /* Get global (legacy) IPv4 statistics */
18236 static mblk_t *
18237 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18238     ip_stack_t *ipst)
18239 {
18240 	mib2_ip_t		old_ip_mib;
18241 	struct opthdr		*optp;
18242 	mblk_t			*mp2ctl;
18243 
18244 	/*
18245 	 * make a copy of the original message
18246 	 */
18247 	mp2ctl = copymsg(mpctl);
18248 
18249 	/* fixed length IP structure... */
18250 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18251 	optp->level = MIB2_IP;
18252 	optp->name = 0;
18253 	SET_MIB(old_ip_mib.ipForwarding,
18254 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18255 	SET_MIB(old_ip_mib.ipDefaultTTL,
18256 	    (uint32_t)ipst->ips_ip_def_ttl);
18257 	SET_MIB(old_ip_mib.ipReasmTimeout,
18258 	    ipst->ips_ip_g_frag_timeout);
18259 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18260 	    sizeof (mib2_ipAddrEntry_t));
18261 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18262 	    sizeof (mib2_ipRouteEntry_t));
18263 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18264 	    sizeof (mib2_ipNetToMediaEntry_t));
18265 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18266 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18267 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18268 	    sizeof (mib2_ipAttributeEntry_t));
18269 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18270 
18271 	/*
18272 	 * Grab the statistics from the new IP MIB
18273 	 */
18274 	SET_MIB(old_ip_mib.ipInReceives,
18275 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18276 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18277 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18278 	SET_MIB(old_ip_mib.ipForwDatagrams,
18279 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18280 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18281 	    ipmib->ipIfStatsInUnknownProtos);
18282 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18283 	SET_MIB(old_ip_mib.ipInDelivers,
18284 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18285 	SET_MIB(old_ip_mib.ipOutRequests,
18286 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18287 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18288 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18289 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18290 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18291 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18292 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18293 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18294 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18295 
18296 	/* ipRoutingDiscards is not being used */
18297 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18298 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18299 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18300 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18301 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18302 	    ipmib->ipIfStatsReasmDuplicates);
18303 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18304 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18305 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18306 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18307 	SET_MIB(old_ip_mib.rawipInOverflows,
18308 	    ipmib->rawipIfStatsInOverflows);
18309 
18310 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18311 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18312 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18313 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18314 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18315 	    ipmib->ipIfStatsOutSwitchIPVersion);
18316 
18317 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18318 	    (int)sizeof (old_ip_mib))) {
18319 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18320 		    (uint_t)sizeof (old_ip_mib)));
18321 	}
18322 
18323 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18324 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18325 	    (int)optp->level, (int)optp->name, (int)optp->len));
18326 	qreply(q, mpctl);
18327 	return (mp2ctl);
18328 }
18329 
18330 /* Per interface IPv4 statistics */
18331 static mblk_t *
18332 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18333 {
18334 	struct opthdr		*optp;
18335 	mblk_t			*mp2ctl;
18336 	ill_t			*ill;
18337 	ill_walk_context_t	ctx;
18338 	mblk_t			*mp_tail = NULL;
18339 	mib2_ipIfStatsEntry_t	global_ip_mib;
18340 
18341 	/*
18342 	 * Make a copy of the original message
18343 	 */
18344 	mp2ctl = copymsg(mpctl);
18345 
18346 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18347 	optp->level = MIB2_IP;
18348 	optp->name = MIB2_IP_TRAFFIC_STATS;
18349 	/* Include "unknown interface" ip_mib */
18350 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18351 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18352 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18353 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18354 	    (ipst->ips_ip_g_forward ? 1 : 2));
18355 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18356 	    (uint32_t)ipst->ips_ip_def_ttl);
18357 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18358 	    sizeof (mib2_ipIfStatsEntry_t));
18359 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18360 	    sizeof (mib2_ipAddrEntry_t));
18361 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18362 	    sizeof (mib2_ipRouteEntry_t));
18363 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18364 	    sizeof (mib2_ipNetToMediaEntry_t));
18365 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18366 	    sizeof (ip_member_t));
18367 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18368 	    sizeof (ip_grpsrc_t));
18369 
18370 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18371 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18372 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18373 		    "failed to allocate %u bytes\n",
18374 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18375 	}
18376 
18377 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18378 
18379 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18380 	ill = ILL_START_WALK_V4(&ctx, ipst);
18381 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18382 		ill->ill_ip_mib->ipIfStatsIfIndex =
18383 		    ill->ill_phyint->phyint_ifindex;
18384 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18385 		    (ipst->ips_ip_g_forward ? 1 : 2));
18386 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18387 		    (uint32_t)ipst->ips_ip_def_ttl);
18388 
18389 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18390 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18391 		    (char *)ill->ill_ip_mib,
18392 		    (int)sizeof (*ill->ill_ip_mib))) {
18393 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18394 			    "failed to allocate %u bytes\n",
18395 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18396 		}
18397 	}
18398 	rw_exit(&ipst->ips_ill_g_lock);
18399 
18400 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18401 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18402 	    "level %d, name %d, len %d\n",
18403 	    (int)optp->level, (int)optp->name, (int)optp->len));
18404 	qreply(q, mpctl);
18405 
18406 	if (mp2ctl == NULL)
18407 		return (NULL);
18408 
18409 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18410 }
18411 
18412 /* Global IPv4 ICMP statistics */
18413 static mblk_t *
18414 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18415 {
18416 	struct opthdr		*optp;
18417 	mblk_t			*mp2ctl;
18418 
18419 	/*
18420 	 * Make a copy of the original message
18421 	 */
18422 	mp2ctl = copymsg(mpctl);
18423 
18424 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18425 	optp->level = MIB2_ICMP;
18426 	optp->name = 0;
18427 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18428 	    (int)sizeof (ipst->ips_icmp_mib))) {
18429 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18430 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18431 	}
18432 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18433 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18434 	    (int)optp->level, (int)optp->name, (int)optp->len));
18435 	qreply(q, mpctl);
18436 	return (mp2ctl);
18437 }
18438 
18439 /* Global IPv4 IGMP statistics */
18440 static mblk_t *
18441 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18442 {
18443 	struct opthdr		*optp;
18444 	mblk_t			*mp2ctl;
18445 
18446 	/*
18447 	 * make a copy of the original message
18448 	 */
18449 	mp2ctl = copymsg(mpctl);
18450 
18451 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18452 	optp->level = EXPER_IGMP;
18453 	optp->name = 0;
18454 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18455 	    (int)sizeof (ipst->ips_igmpstat))) {
18456 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18457 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18458 	}
18459 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18460 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18461 	    (int)optp->level, (int)optp->name, (int)optp->len));
18462 	qreply(q, mpctl);
18463 	return (mp2ctl);
18464 }
18465 
18466 /* Global IPv4 Multicast Routing statistics */
18467 static mblk_t *
18468 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18469 {
18470 	struct opthdr		*optp;
18471 	mblk_t			*mp2ctl;
18472 
18473 	/*
18474 	 * make a copy of the original message
18475 	 */
18476 	mp2ctl = copymsg(mpctl);
18477 
18478 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18479 	optp->level = EXPER_DVMRP;
18480 	optp->name = 0;
18481 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18482 		ip0dbg(("ip_mroute_stats: failed\n"));
18483 	}
18484 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18485 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18486 	    (int)optp->level, (int)optp->name, (int)optp->len));
18487 	qreply(q, mpctl);
18488 	return (mp2ctl);
18489 }
18490 
18491 /* IPv4 address information */
18492 static mblk_t *
18493 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18494 {
18495 	struct opthdr		*optp;
18496 	mblk_t			*mp2ctl;
18497 	mblk_t			*mp_tail = NULL;
18498 	ill_t			*ill;
18499 	ipif_t			*ipif;
18500 	uint_t			bitval;
18501 	mib2_ipAddrEntry_t	mae;
18502 	zoneid_t		zoneid;
18503 	ill_walk_context_t ctx;
18504 
18505 	/*
18506 	 * make a copy of the original message
18507 	 */
18508 	mp2ctl = copymsg(mpctl);
18509 
18510 	/* ipAddrEntryTable */
18511 
18512 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18513 	optp->level = MIB2_IP;
18514 	optp->name = MIB2_IP_ADDR;
18515 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18516 
18517 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18518 	ill = ILL_START_WALK_V4(&ctx, ipst);
18519 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18520 		for (ipif = ill->ill_ipif; ipif != NULL;
18521 		    ipif = ipif->ipif_next) {
18522 			if (ipif->ipif_zoneid != zoneid &&
18523 			    ipif->ipif_zoneid != ALL_ZONES)
18524 				continue;
18525 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18526 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18527 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18528 
18529 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18530 			    OCTET_LENGTH);
18531 			mae.ipAdEntIfIndex.o_length =
18532 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18533 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18534 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18535 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18536 			mae.ipAdEntInfo.ae_subnet_len =
18537 			    ip_mask_to_plen(ipif->ipif_net_mask);
18538 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18539 			for (bitval = 1;
18540 			    bitval &&
18541 			    !(bitval & ipif->ipif_brd_addr);
18542 			    bitval <<= 1)
18543 				noop;
18544 			mae.ipAdEntBcastAddr = bitval;
18545 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18546 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18547 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18548 			mae.ipAdEntInfo.ae_broadcast_addr =
18549 			    ipif->ipif_brd_addr;
18550 			mae.ipAdEntInfo.ae_pp_dst_addr =
18551 			    ipif->ipif_pp_dst_addr;
18552 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18553 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18554 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18555 
18556 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18557 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18558 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18559 				    "allocate %u bytes\n",
18560 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18561 			}
18562 		}
18563 	}
18564 	rw_exit(&ipst->ips_ill_g_lock);
18565 
18566 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18567 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18568 	    (int)optp->level, (int)optp->name, (int)optp->len));
18569 	qreply(q, mpctl);
18570 	return (mp2ctl);
18571 }
18572 
18573 /* IPv6 address information */
18574 static mblk_t *
18575 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18576 {
18577 	struct opthdr		*optp;
18578 	mblk_t			*mp2ctl;
18579 	mblk_t			*mp_tail = NULL;
18580 	ill_t			*ill;
18581 	ipif_t			*ipif;
18582 	mib2_ipv6AddrEntry_t	mae6;
18583 	zoneid_t		zoneid;
18584 	ill_walk_context_t	ctx;
18585 
18586 	/*
18587 	 * make a copy of the original message
18588 	 */
18589 	mp2ctl = copymsg(mpctl);
18590 
18591 	/* ipv6AddrEntryTable */
18592 
18593 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18594 	optp->level = MIB2_IP6;
18595 	optp->name = MIB2_IP6_ADDR;
18596 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18597 
18598 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18599 	ill = ILL_START_WALK_V6(&ctx, ipst);
18600 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18601 		for (ipif = ill->ill_ipif; ipif != NULL;
18602 		    ipif = ipif->ipif_next) {
18603 			if (ipif->ipif_zoneid != zoneid &&
18604 			    ipif->ipif_zoneid != ALL_ZONES)
18605 				continue;
18606 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18607 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18608 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18609 
18610 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18611 			    OCTET_LENGTH);
18612 			mae6.ipv6AddrIfIndex.o_length =
18613 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18614 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18615 			mae6.ipv6AddrPfxLength =
18616 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18617 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18618 			mae6.ipv6AddrInfo.ae_subnet_len =
18619 			    mae6.ipv6AddrPfxLength;
18620 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18621 
18622 			/* Type: stateless(1), stateful(2), unknown(3) */
18623 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18624 				mae6.ipv6AddrType = 1;
18625 			else
18626 				mae6.ipv6AddrType = 2;
18627 			/* Anycast: true(1), false(2) */
18628 			if (ipif->ipif_flags & IPIF_ANYCAST)
18629 				mae6.ipv6AddrAnycastFlag = 1;
18630 			else
18631 				mae6.ipv6AddrAnycastFlag = 2;
18632 
18633 			/*
18634 			 * Address status: preferred(1), deprecated(2),
18635 			 * invalid(3), inaccessible(4), unknown(5)
18636 			 */
18637 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18638 				mae6.ipv6AddrStatus = 3;
18639 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18640 				mae6.ipv6AddrStatus = 2;
18641 			else
18642 				mae6.ipv6AddrStatus = 1;
18643 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18644 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18645 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18646 			    ipif->ipif_v6pp_dst_addr;
18647 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18648 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18649 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18650 			mae6.ipv6AddrIdentifier = ill->ill_token;
18651 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18652 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18653 			mae6.ipv6AddrRetransmitTime =
18654 			    ill->ill_reachable_retrans_time;
18655 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18656 			    (char *)&mae6,
18657 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18658 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18659 				    "allocate %u bytes\n",
18660 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18661 			}
18662 		}
18663 	}
18664 	rw_exit(&ipst->ips_ill_g_lock);
18665 
18666 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18667 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18668 	    (int)optp->level, (int)optp->name, (int)optp->len));
18669 	qreply(q, mpctl);
18670 	return (mp2ctl);
18671 }
18672 
18673 /* IPv4 multicast group membership. */
18674 static mblk_t *
18675 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18676 {
18677 	struct opthdr		*optp;
18678 	mblk_t			*mp2ctl;
18679 	ill_t			*ill;
18680 	ipif_t			*ipif;
18681 	ilm_t			*ilm;
18682 	ip_member_t		ipm;
18683 	mblk_t			*mp_tail = NULL;
18684 	ill_walk_context_t	ctx;
18685 	zoneid_t		zoneid;
18686 
18687 	/*
18688 	 * make a copy of the original message
18689 	 */
18690 	mp2ctl = copymsg(mpctl);
18691 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18692 
18693 	/* ipGroupMember table */
18694 	optp = (struct opthdr *)&mpctl->b_rptr[
18695 	    sizeof (struct T_optmgmt_ack)];
18696 	optp->level = MIB2_IP;
18697 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18698 
18699 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18700 	ill = ILL_START_WALK_V4(&ctx, ipst);
18701 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18702 		ILM_WALKER_HOLD(ill);
18703 		for (ipif = ill->ill_ipif; ipif != NULL;
18704 		    ipif = ipif->ipif_next) {
18705 			if (ipif->ipif_zoneid != zoneid &&
18706 			    ipif->ipif_zoneid != ALL_ZONES)
18707 				continue;	/* not this zone */
18708 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
18709 			    OCTET_LENGTH);
18710 			ipm.ipGroupMemberIfIndex.o_length =
18711 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18712 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18713 				ASSERT(ilm->ilm_ipif != NULL);
18714 				ASSERT(ilm->ilm_ill == NULL);
18715 				if (ilm->ilm_ipif != ipif)
18716 					continue;
18717 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18718 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18719 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18720 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18721 				    (char *)&ipm, (int)sizeof (ipm))) {
18722 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18723 					    "failed to allocate %u bytes\n",
18724 					    (uint_t)sizeof (ipm)));
18725 				}
18726 			}
18727 		}
18728 		ILM_WALKER_RELE(ill);
18729 	}
18730 	rw_exit(&ipst->ips_ill_g_lock);
18731 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18732 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18733 	    (int)optp->level, (int)optp->name, (int)optp->len));
18734 	qreply(q, mpctl);
18735 	return (mp2ctl);
18736 }
18737 
18738 /* IPv6 multicast group membership. */
18739 static mblk_t *
18740 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18741 {
18742 	struct opthdr		*optp;
18743 	mblk_t			*mp2ctl;
18744 	ill_t			*ill;
18745 	ilm_t			*ilm;
18746 	ipv6_member_t		ipm6;
18747 	mblk_t			*mp_tail = NULL;
18748 	ill_walk_context_t	ctx;
18749 	zoneid_t		zoneid;
18750 
18751 	/*
18752 	 * make a copy of the original message
18753 	 */
18754 	mp2ctl = copymsg(mpctl);
18755 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18756 
18757 	/* ip6GroupMember table */
18758 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18759 	optp->level = MIB2_IP6;
18760 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18761 
18762 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18763 	ill = ILL_START_WALK_V6(&ctx, ipst);
18764 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18765 		ILM_WALKER_HOLD(ill);
18766 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18767 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18768 			ASSERT(ilm->ilm_ipif == NULL);
18769 			ASSERT(ilm->ilm_ill != NULL);
18770 			if (ilm->ilm_zoneid != zoneid)
18771 				continue;	/* not this zone */
18772 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18773 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18774 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18775 			if (!snmp_append_data2(mpctl->b_cont,
18776 			    &mp_tail,
18777 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18778 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18779 				    "failed to allocate %u bytes\n",
18780 				    (uint_t)sizeof (ipm6)));
18781 			}
18782 		}
18783 		ILM_WALKER_RELE(ill);
18784 	}
18785 	rw_exit(&ipst->ips_ill_g_lock);
18786 
18787 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18788 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18789 	    (int)optp->level, (int)optp->name, (int)optp->len));
18790 	qreply(q, mpctl);
18791 	return (mp2ctl);
18792 }
18793 
18794 /* IP multicast filtered sources */
18795 static mblk_t *
18796 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18797 {
18798 	struct opthdr		*optp;
18799 	mblk_t			*mp2ctl;
18800 	ill_t			*ill;
18801 	ipif_t			*ipif;
18802 	ilm_t			*ilm;
18803 	ip_grpsrc_t		ips;
18804 	mblk_t			*mp_tail = NULL;
18805 	ill_walk_context_t	ctx;
18806 	zoneid_t		zoneid;
18807 	int			i;
18808 	slist_t			*sl;
18809 
18810 	/*
18811 	 * make a copy of the original message
18812 	 */
18813 	mp2ctl = copymsg(mpctl);
18814 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18815 
18816 	/* ipGroupSource table */
18817 	optp = (struct opthdr *)&mpctl->b_rptr[
18818 	    sizeof (struct T_optmgmt_ack)];
18819 	optp->level = MIB2_IP;
18820 	optp->name = EXPER_IP_GROUP_SOURCES;
18821 
18822 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18823 	ill = ILL_START_WALK_V4(&ctx, ipst);
18824 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18825 		ILM_WALKER_HOLD(ill);
18826 		for (ipif = ill->ill_ipif; ipif != NULL;
18827 		    ipif = ipif->ipif_next) {
18828 			if (ipif->ipif_zoneid != zoneid)
18829 				continue;	/* not this zone */
18830 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
18831 			    OCTET_LENGTH);
18832 			ips.ipGroupSourceIfIndex.o_length =
18833 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18834 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18835 				ASSERT(ilm->ilm_ipif != NULL);
18836 				ASSERT(ilm->ilm_ill == NULL);
18837 				sl = ilm->ilm_filter;
18838 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18839 					continue;
18840 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18841 				for (i = 0; i < sl->sl_numsrc; i++) {
18842 					if (!IN6_IS_ADDR_V4MAPPED(
18843 					    &sl->sl_addr[i]))
18844 						continue;
18845 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18846 					    ips.ipGroupSourceAddress);
18847 					if (snmp_append_data2(mpctl->b_cont,
18848 					    &mp_tail, (char *)&ips,
18849 					    (int)sizeof (ips)) == 0) {
18850 						ip1dbg(("ip_snmp_get_mib2_"
18851 						    "ip_group_src: failed to "
18852 						    "allocate %u bytes\n",
18853 						    (uint_t)sizeof (ips)));
18854 					}
18855 				}
18856 			}
18857 		}
18858 		ILM_WALKER_RELE(ill);
18859 	}
18860 	rw_exit(&ipst->ips_ill_g_lock);
18861 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18862 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18863 	    (int)optp->level, (int)optp->name, (int)optp->len));
18864 	qreply(q, mpctl);
18865 	return (mp2ctl);
18866 }
18867 
18868 /* IPv6 multicast filtered sources. */
18869 static mblk_t *
18870 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18871 {
18872 	struct opthdr		*optp;
18873 	mblk_t			*mp2ctl;
18874 	ill_t			*ill;
18875 	ilm_t			*ilm;
18876 	ipv6_grpsrc_t		ips6;
18877 	mblk_t			*mp_tail = NULL;
18878 	ill_walk_context_t	ctx;
18879 	zoneid_t		zoneid;
18880 	int			i;
18881 	slist_t			*sl;
18882 
18883 	/*
18884 	 * make a copy of the original message
18885 	 */
18886 	mp2ctl = copymsg(mpctl);
18887 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18888 
18889 	/* ip6GroupMember table */
18890 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18891 	optp->level = MIB2_IP6;
18892 	optp->name = EXPER_IP6_GROUP_SOURCES;
18893 
18894 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18895 	ill = ILL_START_WALK_V6(&ctx, ipst);
18896 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18897 		ILM_WALKER_HOLD(ill);
18898 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18899 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18900 			ASSERT(ilm->ilm_ipif == NULL);
18901 			ASSERT(ilm->ilm_ill != NULL);
18902 			sl = ilm->ilm_filter;
18903 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18904 				continue;
18905 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18906 			for (i = 0; i < sl->sl_numsrc; i++) {
18907 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18908 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18909 				    (char *)&ips6, (int)sizeof (ips6))) {
18910 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18911 					    "group_src: failed to allocate "
18912 					    "%u bytes\n",
18913 					    (uint_t)sizeof (ips6)));
18914 				}
18915 			}
18916 		}
18917 		ILM_WALKER_RELE(ill);
18918 	}
18919 	rw_exit(&ipst->ips_ill_g_lock);
18920 
18921 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18922 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18923 	    (int)optp->level, (int)optp->name, (int)optp->len));
18924 	qreply(q, mpctl);
18925 	return (mp2ctl);
18926 }
18927 
18928 /* Multicast routing virtual interface table. */
18929 static mblk_t *
18930 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18931 {
18932 	struct opthdr		*optp;
18933 	mblk_t			*mp2ctl;
18934 
18935 	/*
18936 	 * make a copy of the original message
18937 	 */
18938 	mp2ctl = copymsg(mpctl);
18939 
18940 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18941 	optp->level = EXPER_DVMRP;
18942 	optp->name = EXPER_DVMRP_VIF;
18943 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
18944 		ip0dbg(("ip_mroute_vif: failed\n"));
18945 	}
18946 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18947 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
18948 	    (int)optp->level, (int)optp->name, (int)optp->len));
18949 	qreply(q, mpctl);
18950 	return (mp2ctl);
18951 }
18952 
18953 /* Multicast routing table. */
18954 static mblk_t *
18955 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18956 {
18957 	struct opthdr		*optp;
18958 	mblk_t			*mp2ctl;
18959 
18960 	/*
18961 	 * make a copy of the original message
18962 	 */
18963 	mp2ctl = copymsg(mpctl);
18964 
18965 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18966 	optp->level = EXPER_DVMRP;
18967 	optp->name = EXPER_DVMRP_MRT;
18968 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
18969 		ip0dbg(("ip_mroute_mrt: failed\n"));
18970 	}
18971 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18972 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
18973 	    (int)optp->level, (int)optp->name, (int)optp->len));
18974 	qreply(q, mpctl);
18975 	return (mp2ctl);
18976 }
18977 
18978 /*
18979  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
18980  * in one IRE walk.
18981  */
18982 static mblk_t *
18983 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18984 {
18985 	struct opthdr	*optp;
18986 	mblk_t		*mp2ctl;	/* Returned */
18987 	mblk_t		*mp3ctl;	/* nettomedia */
18988 	mblk_t		*mp4ctl;	/* routeattrs */
18989 	iproutedata_t	ird;
18990 	zoneid_t	zoneid;
18991 
18992 	/*
18993 	 * make copies of the original message
18994 	 *	- mp2ctl is returned unchanged to the caller for his use
18995 	 *	- mpctl is sent upstream as ipRouteEntryTable
18996 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
18997 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
18998 	 */
18999 	mp2ctl = copymsg(mpctl);
19000 	mp3ctl = copymsg(mpctl);
19001 	mp4ctl = copymsg(mpctl);
19002 	if (mp3ctl == NULL || mp4ctl == NULL) {
19003 		freemsg(mp4ctl);
19004 		freemsg(mp3ctl);
19005 		freemsg(mp2ctl);
19006 		freemsg(mpctl);
19007 		return (NULL);
19008 	}
19009 
19010 	bzero(&ird, sizeof (ird));
19011 
19012 	ird.ird_route.lp_head = mpctl->b_cont;
19013 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19014 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19015 
19016 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19017 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
19018 
19019 	/* ipRouteEntryTable in mpctl */
19020 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19021 	optp->level = MIB2_IP;
19022 	optp->name = MIB2_IP_ROUTE;
19023 	optp->len = msgdsize(ird.ird_route.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, mpctl);
19027 
19028 	/* ipNetToMediaEntryTable in mp3ctl */
19029 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19030 	optp->level = MIB2_IP;
19031 	optp->name = MIB2_IP_MEDIA;
19032 	optp->len = msgdsize(ird.ird_netmedia.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 	qreply(q, mp3ctl);
19036 
19037 	/* ipRouteAttributeTable in mp4ctl */
19038 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19039 	optp->level = MIB2_IP;
19040 	optp->name = EXPER_IP_RTATTR;
19041 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19042 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19043 	    (int)optp->level, (int)optp->name, (int)optp->len));
19044 	if (optp->len == 0)
19045 		freemsg(mp4ctl);
19046 	else
19047 		qreply(q, mp4ctl);
19048 
19049 	return (mp2ctl);
19050 }
19051 
19052 /*
19053  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
19054  * ipv6NetToMediaEntryTable in an NDP walk.
19055  */
19056 static mblk_t *
19057 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19058 {
19059 	struct opthdr	*optp;
19060 	mblk_t		*mp2ctl;	/* Returned */
19061 	mblk_t		*mp3ctl;	/* nettomedia */
19062 	mblk_t		*mp4ctl;	/* routeattrs */
19063 	iproutedata_t	ird;
19064 	zoneid_t	zoneid;
19065 
19066 	/*
19067 	 * make copies of the original message
19068 	 *	- mp2ctl is returned unchanged to the caller for his use
19069 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19070 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19071 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19072 	 */
19073 	mp2ctl = copymsg(mpctl);
19074 	mp3ctl = copymsg(mpctl);
19075 	mp4ctl = copymsg(mpctl);
19076 	if (mp3ctl == NULL || mp4ctl == NULL) {
19077 		freemsg(mp4ctl);
19078 		freemsg(mp3ctl);
19079 		freemsg(mp2ctl);
19080 		freemsg(mpctl);
19081 		return (NULL);
19082 	}
19083 
19084 	bzero(&ird, sizeof (ird));
19085 
19086 	ird.ird_route.lp_head = mpctl->b_cont;
19087 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19088 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19089 
19090 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19091 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19092 
19093 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19094 	optp->level = MIB2_IP6;
19095 	optp->name = MIB2_IP6_ROUTE;
19096 	optp->len = msgdsize(ird.ird_route.lp_head);
19097 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19098 	    (int)optp->level, (int)optp->name, (int)optp->len));
19099 	qreply(q, mpctl);
19100 
19101 	/* ipv6NetToMediaEntryTable in mp3ctl */
19102 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19103 
19104 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19105 	optp->level = MIB2_IP6;
19106 	optp->name = MIB2_IP6_MEDIA;
19107 	optp->len = msgdsize(ird.ird_netmedia.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 	qreply(q, mp3ctl);
19111 
19112 	/* ipv6RouteAttributeTable in mp4ctl */
19113 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19114 	optp->level = MIB2_IP6;
19115 	optp->name = EXPER_IP_RTATTR;
19116 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19117 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19118 	    (int)optp->level, (int)optp->name, (int)optp->len));
19119 	if (optp->len == 0)
19120 		freemsg(mp4ctl);
19121 	else
19122 		qreply(q, mp4ctl);
19123 
19124 	return (mp2ctl);
19125 }
19126 
19127 /*
19128  * IPv6 mib: One per ill
19129  */
19130 static mblk_t *
19131 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19132 {
19133 	struct opthdr		*optp;
19134 	mblk_t			*mp2ctl;
19135 	ill_t			*ill;
19136 	ill_walk_context_t	ctx;
19137 	mblk_t			*mp_tail = NULL;
19138 
19139 	/*
19140 	 * Make a copy of the original message
19141 	 */
19142 	mp2ctl = copymsg(mpctl);
19143 
19144 	/* fixed length IPv6 structure ... */
19145 
19146 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19147 	optp->level = MIB2_IP6;
19148 	optp->name = 0;
19149 	/* Include "unknown interface" ip6_mib */
19150 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19151 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19152 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19153 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19154 	    ipst->ips_ipv6_forward ? 1 : 2);
19155 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19156 	    ipst->ips_ipv6_def_hops);
19157 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19158 	    sizeof (mib2_ipIfStatsEntry_t));
19159 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19160 	    sizeof (mib2_ipv6AddrEntry_t));
19161 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19162 	    sizeof (mib2_ipv6RouteEntry_t));
19163 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19164 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19165 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19166 	    sizeof (ipv6_member_t));
19167 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19168 	    sizeof (ipv6_grpsrc_t));
19169 
19170 	/*
19171 	 * Synchronize 64- and 32-bit counters
19172 	 */
19173 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19174 	    ipIfStatsHCInReceives);
19175 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19176 	    ipIfStatsHCInDelivers);
19177 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19178 	    ipIfStatsHCOutRequests);
19179 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19180 	    ipIfStatsHCOutForwDatagrams);
19181 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19182 	    ipIfStatsHCOutMcastPkts);
19183 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19184 	    ipIfStatsHCInMcastPkts);
19185 
19186 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19187 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19188 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19189 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19190 	}
19191 
19192 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19193 	ill = ILL_START_WALK_V6(&ctx, ipst);
19194 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19195 		ill->ill_ip_mib->ipIfStatsIfIndex =
19196 		    ill->ill_phyint->phyint_ifindex;
19197 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19198 		    ipst->ips_ipv6_forward ? 1 : 2);
19199 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19200 		    ill->ill_max_hops);
19201 
19202 		/*
19203 		 * Synchronize 64- and 32-bit counters
19204 		 */
19205 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19206 		    ipIfStatsHCInReceives);
19207 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19208 		    ipIfStatsHCInDelivers);
19209 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19210 		    ipIfStatsHCOutRequests);
19211 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19212 		    ipIfStatsHCOutForwDatagrams);
19213 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19214 		    ipIfStatsHCOutMcastPkts);
19215 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19216 		    ipIfStatsHCInMcastPkts);
19217 
19218 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19219 		    (char *)ill->ill_ip_mib,
19220 		    (int)sizeof (*ill->ill_ip_mib))) {
19221 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19222 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19223 		}
19224 	}
19225 	rw_exit(&ipst->ips_ill_g_lock);
19226 
19227 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19228 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19229 	    (int)optp->level, (int)optp->name, (int)optp->len));
19230 	qreply(q, mpctl);
19231 	return (mp2ctl);
19232 }
19233 
19234 /*
19235  * ICMPv6 mib: One per ill
19236  */
19237 static mblk_t *
19238 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19239 {
19240 	struct opthdr		*optp;
19241 	mblk_t			*mp2ctl;
19242 	ill_t			*ill;
19243 	ill_walk_context_t	ctx;
19244 	mblk_t			*mp_tail = NULL;
19245 	/*
19246 	 * Make a copy of the original message
19247 	 */
19248 	mp2ctl = copymsg(mpctl);
19249 
19250 	/* fixed length ICMPv6 structure ... */
19251 
19252 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19253 	optp->level = MIB2_ICMP6;
19254 	optp->name = 0;
19255 	/* Include "unknown interface" icmp6_mib */
19256 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19257 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19258 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19259 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19260 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19261 	    (char *)&ipst->ips_icmp6_mib,
19262 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19263 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19264 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19265 	}
19266 
19267 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19268 	ill = ILL_START_WALK_V6(&ctx, ipst);
19269 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19270 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19271 		    ill->ill_phyint->phyint_ifindex;
19272 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19273 		    (char *)ill->ill_icmp6_mib,
19274 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19275 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19276 			    "%u bytes\n",
19277 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19278 		}
19279 	}
19280 	rw_exit(&ipst->ips_ill_g_lock);
19281 
19282 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19283 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19284 	    (int)optp->level, (int)optp->name, (int)optp->len));
19285 	qreply(q, mpctl);
19286 	return (mp2ctl);
19287 }
19288 
19289 /*
19290  * ire_walk routine to create both ipRouteEntryTable and
19291  * ipRouteAttributeTable in one IRE walk
19292  */
19293 static void
19294 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19295 {
19296 	ill_t				*ill;
19297 	ipif_t				*ipif;
19298 	mib2_ipRouteEntry_t		*re;
19299 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19300 	ipaddr_t			gw_addr;
19301 	tsol_ire_gw_secattr_t		*attrp;
19302 	tsol_gc_t			*gc = NULL;
19303 	tsol_gcgrp_t			*gcgrp = NULL;
19304 	uint_t				sacnt = 0;
19305 	int				i;
19306 
19307 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19308 
19309 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19310 		return;
19311 
19312 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19313 		mutex_enter(&attrp->igsa_lock);
19314 		if ((gc = attrp->igsa_gc) != NULL) {
19315 			gcgrp = gc->gc_grp;
19316 			ASSERT(gcgrp != NULL);
19317 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19318 			sacnt = 1;
19319 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19320 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19321 			gc = gcgrp->gcgrp_head;
19322 			sacnt = gcgrp->gcgrp_count;
19323 		}
19324 		mutex_exit(&attrp->igsa_lock);
19325 
19326 		/* do nothing if there's no gc to report */
19327 		if (gc == NULL) {
19328 			ASSERT(sacnt == 0);
19329 			if (gcgrp != NULL) {
19330 				/* we might as well drop the lock now */
19331 				rw_exit(&gcgrp->gcgrp_rwlock);
19332 				gcgrp = NULL;
19333 			}
19334 			attrp = NULL;
19335 		}
19336 
19337 		ASSERT(gc == NULL || (gcgrp != NULL &&
19338 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19339 	}
19340 	ASSERT(sacnt == 0 || gc != NULL);
19341 
19342 	if (sacnt != 0 &&
19343 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19344 		kmem_free(re, sizeof (*re));
19345 		rw_exit(&gcgrp->gcgrp_rwlock);
19346 		return;
19347 	}
19348 
19349 	/*
19350 	 * Return all IRE types for route table... let caller pick and choose
19351 	 */
19352 	re->ipRouteDest = ire->ire_addr;
19353 	ipif = ire->ire_ipif;
19354 	re->ipRouteIfIndex.o_length = 0;
19355 	if (ire->ire_type == IRE_CACHE) {
19356 		ill = (ill_t *)ire->ire_stq->q_ptr;
19357 		re->ipRouteIfIndex.o_length =
19358 		    ill->ill_name_length == 0 ? 0 :
19359 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19360 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19361 		    re->ipRouteIfIndex.o_length);
19362 	} else if (ipif != NULL) {
19363 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19364 		re->ipRouteIfIndex.o_length =
19365 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19366 	}
19367 	re->ipRouteMetric1 = -1;
19368 	re->ipRouteMetric2 = -1;
19369 	re->ipRouteMetric3 = -1;
19370 	re->ipRouteMetric4 = -1;
19371 
19372 	gw_addr = ire->ire_gateway_addr;
19373 
19374 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19375 		re->ipRouteNextHop = ire->ire_src_addr;
19376 	else
19377 		re->ipRouteNextHop = gw_addr;
19378 	/* indirect(4), direct(3), or invalid(2) */
19379 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19380 		re->ipRouteType = 2;
19381 	else
19382 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19383 	re->ipRouteProto = -1;
19384 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19385 	re->ipRouteMask = ire->ire_mask;
19386 	re->ipRouteMetric5 = -1;
19387 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19388 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19389 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19390 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19391 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19392 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19393 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19394 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19395 
19396 	if (ire->ire_flags & RTF_DYNAMIC) {
19397 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19398 	} else {
19399 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19400 	}
19401 
19402 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19403 	    (char *)re, (int)sizeof (*re))) {
19404 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19405 		    (uint_t)sizeof (*re)));
19406 	}
19407 
19408 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19409 		iaeptr->iae_routeidx = ird->ird_idx;
19410 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19411 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19412 	}
19413 
19414 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19415 	    (char *)iae, sacnt * sizeof (*iae))) {
19416 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19417 		    (unsigned)(sacnt * sizeof (*iae))));
19418 	}
19419 
19420 	/* bump route index for next pass */
19421 	ird->ird_idx++;
19422 
19423 	kmem_free(re, sizeof (*re));
19424 	if (sacnt != 0)
19425 		kmem_free(iae, sacnt * sizeof (*iae));
19426 
19427 	if (gcgrp != NULL)
19428 		rw_exit(&gcgrp->gcgrp_rwlock);
19429 }
19430 
19431 /*
19432  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19433  */
19434 static void
19435 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19436 {
19437 	ill_t				*ill;
19438 	ipif_t				*ipif;
19439 	mib2_ipv6RouteEntry_t		*re;
19440 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19441 	in6_addr_t			gw_addr_v6;
19442 	tsol_ire_gw_secattr_t		*attrp;
19443 	tsol_gc_t			*gc = NULL;
19444 	tsol_gcgrp_t			*gcgrp = NULL;
19445 	uint_t				sacnt = 0;
19446 	int				i;
19447 
19448 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19449 
19450 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19451 		return;
19452 
19453 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19454 		mutex_enter(&attrp->igsa_lock);
19455 		if ((gc = attrp->igsa_gc) != NULL) {
19456 			gcgrp = gc->gc_grp;
19457 			ASSERT(gcgrp != NULL);
19458 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19459 			sacnt = 1;
19460 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19461 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19462 			gc = gcgrp->gcgrp_head;
19463 			sacnt = gcgrp->gcgrp_count;
19464 		}
19465 		mutex_exit(&attrp->igsa_lock);
19466 
19467 		/* do nothing if there's no gc to report */
19468 		if (gc == NULL) {
19469 			ASSERT(sacnt == 0);
19470 			if (gcgrp != NULL) {
19471 				/* we might as well drop the lock now */
19472 				rw_exit(&gcgrp->gcgrp_rwlock);
19473 				gcgrp = NULL;
19474 			}
19475 			attrp = NULL;
19476 		}
19477 
19478 		ASSERT(gc == NULL || (gcgrp != NULL &&
19479 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19480 	}
19481 	ASSERT(sacnt == 0 || gc != NULL);
19482 
19483 	if (sacnt != 0 &&
19484 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19485 		kmem_free(re, sizeof (*re));
19486 		rw_exit(&gcgrp->gcgrp_rwlock);
19487 		return;
19488 	}
19489 
19490 	/*
19491 	 * Return all IRE types for route table... let caller pick and choose
19492 	 */
19493 	re->ipv6RouteDest = ire->ire_addr_v6;
19494 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19495 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19496 	re->ipv6RouteIfIndex.o_length = 0;
19497 	ipif = ire->ire_ipif;
19498 	if (ire->ire_type == IRE_CACHE) {
19499 		ill = (ill_t *)ire->ire_stq->q_ptr;
19500 		re->ipv6RouteIfIndex.o_length =
19501 		    ill->ill_name_length == 0 ? 0 :
19502 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19503 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19504 		    re->ipv6RouteIfIndex.o_length);
19505 	} else if (ipif != NULL) {
19506 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19507 		re->ipv6RouteIfIndex.o_length =
19508 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19509 	}
19510 
19511 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19512 
19513 	mutex_enter(&ire->ire_lock);
19514 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19515 	mutex_exit(&ire->ire_lock);
19516 
19517 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19518 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19519 	else
19520 		re->ipv6RouteNextHop = gw_addr_v6;
19521 
19522 	/* remote(4), local(3), or discard(2) */
19523 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19524 		re->ipv6RouteType = 2;
19525 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19526 		re->ipv6RouteType = 3;
19527 	else
19528 		re->ipv6RouteType = 4;
19529 
19530 	re->ipv6RouteProtocol	= -1;
19531 	re->ipv6RoutePolicy	= 0;
19532 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19533 	re->ipv6RouteNextHopRDI	= 0;
19534 	re->ipv6RouteWeight	= 0;
19535 	re->ipv6RouteMetric	= 0;
19536 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19537 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19538 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19539 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19540 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19541 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19542 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19543 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19544 
19545 	if (ire->ire_flags & RTF_DYNAMIC) {
19546 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19547 	} else {
19548 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19549 	}
19550 
19551 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19552 	    (char *)re, (int)sizeof (*re))) {
19553 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19554 		    (uint_t)sizeof (*re)));
19555 	}
19556 
19557 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19558 		iaeptr->iae_routeidx = ird->ird_idx;
19559 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19560 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19561 	}
19562 
19563 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19564 	    (char *)iae, sacnt * sizeof (*iae))) {
19565 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19566 		    (unsigned)(sacnt * sizeof (*iae))));
19567 	}
19568 
19569 	/* bump route index for next pass */
19570 	ird->ird_idx++;
19571 
19572 	kmem_free(re, sizeof (*re));
19573 	if (sacnt != 0)
19574 		kmem_free(iae, sacnt * sizeof (*iae));
19575 
19576 	if (gcgrp != NULL)
19577 		rw_exit(&gcgrp->gcgrp_rwlock);
19578 }
19579 
19580 /*
19581  * ndp_walk routine to create ipv6NetToMediaEntryTable
19582  */
19583 static int
19584 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19585 {
19586 	ill_t				*ill;
19587 	mib2_ipv6NetToMediaEntry_t	ntme;
19588 	dl_unitdata_req_t		*dl;
19589 
19590 	ill = nce->nce_ill;
19591 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19592 		return (0);
19593 
19594 	/*
19595 	 * Neighbor cache entry attached to IRE with on-link
19596 	 * destination.
19597 	 */
19598 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19599 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19600 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19601 	    (nce->nce_res_mp != NULL)) {
19602 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19603 		ntme.ipv6NetToMediaPhysAddress.o_length =
19604 		    dl->dl_dest_addr_length;
19605 	} else {
19606 		ntme.ipv6NetToMediaPhysAddress.o_length =
19607 		    ill->ill_phys_addr_length;
19608 	}
19609 	if (nce->nce_res_mp != NULL) {
19610 		bcopy((char *)nce->nce_res_mp->b_rptr +
19611 		    NCE_LL_ADDR_OFFSET(ill),
19612 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19613 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19614 	} else {
19615 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19616 		    ill->ill_phys_addr_length);
19617 	}
19618 	/*
19619 	 * Note: Returns ND_* states. Should be:
19620 	 * reachable(1), stale(2), delay(3), probe(4),
19621 	 * invalid(5), unknown(6)
19622 	 */
19623 	ntme.ipv6NetToMediaState = nce->nce_state;
19624 	ntme.ipv6NetToMediaLastUpdated = 0;
19625 
19626 	/* other(1), dynamic(2), static(3), local(4) */
19627 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19628 		ntme.ipv6NetToMediaType = 4;
19629 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19630 		ntme.ipv6NetToMediaType = 1;
19631 	} else {
19632 		ntme.ipv6NetToMediaType = 2;
19633 	}
19634 
19635 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19636 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19637 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19638 		    (uint_t)sizeof (ntme)));
19639 	}
19640 	return (0);
19641 }
19642 
19643 /*
19644  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19645  */
19646 /* ARGSUSED */
19647 int
19648 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19649 {
19650 	switch (level) {
19651 	case MIB2_IP:
19652 	case MIB2_ICMP:
19653 		switch (name) {
19654 		default:
19655 			break;
19656 		}
19657 		return (1);
19658 	default:
19659 		return (1);
19660 	}
19661 }
19662 
19663 /*
19664  * When there exists both a 64- and 32-bit counter of a particular type
19665  * (i.e., InReceives), only the 64-bit counters are added.
19666  */
19667 void
19668 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19669 {
19670 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19671 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19672 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19673 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19674 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19675 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19676 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19677 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19678 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19679 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19680 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19681 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19682 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19683 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19684 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19685 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19686 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19687 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19688 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19689 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19690 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19691 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19692 	    o2->ipIfStatsInWrongIPVersion);
19693 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19694 	    o2->ipIfStatsInWrongIPVersion);
19695 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19696 	    o2->ipIfStatsOutSwitchIPVersion);
19697 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19698 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19699 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19700 	    o2->ipIfStatsHCInForwDatagrams);
19701 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19702 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19703 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19704 	    o2->ipIfStatsHCOutForwDatagrams);
19705 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19706 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19707 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19708 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19709 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19710 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19711 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19712 	    o2->ipIfStatsHCOutMcastOctets);
19713 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19714 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19715 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19716 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19717 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19718 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19719 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19720 }
19721 
19722 void
19723 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19724 {
19725 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19726 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19727 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19728 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19729 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19730 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19731 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19732 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19733 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19734 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19735 	    o2->ipv6IfIcmpInRouterSolicits);
19736 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19737 	    o2->ipv6IfIcmpInRouterAdvertisements);
19738 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19739 	    o2->ipv6IfIcmpInNeighborSolicits);
19740 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19741 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19742 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19743 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19744 	    o2->ipv6IfIcmpInGroupMembQueries);
19745 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19746 	    o2->ipv6IfIcmpInGroupMembResponses);
19747 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19748 	    o2->ipv6IfIcmpInGroupMembReductions);
19749 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19750 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19751 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19752 	    o2->ipv6IfIcmpOutDestUnreachs);
19753 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19754 	    o2->ipv6IfIcmpOutAdminProhibs);
19755 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19756 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19757 	    o2->ipv6IfIcmpOutParmProblems);
19758 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19759 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19760 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19761 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19762 	    o2->ipv6IfIcmpOutRouterSolicits);
19763 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19764 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19765 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19766 	    o2->ipv6IfIcmpOutNeighborSolicits);
19767 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19768 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19769 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19770 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19771 	    o2->ipv6IfIcmpOutGroupMembQueries);
19772 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19773 	    o2->ipv6IfIcmpOutGroupMembResponses);
19774 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19775 	    o2->ipv6IfIcmpOutGroupMembReductions);
19776 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19777 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19778 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19779 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19780 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19781 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19782 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19783 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19784 	    o2->ipv6IfIcmpInGroupMembTotal);
19785 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19786 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19787 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19788 	    o2->ipv6IfIcmpInGroupMembBadReports);
19789 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19790 	    o2->ipv6IfIcmpInGroupMembOurReports);
19791 }
19792 
19793 /*
19794  * Called before the options are updated to check if this packet will
19795  * be source routed from here.
19796  * This routine assumes that the options are well formed i.e. that they
19797  * have already been checked.
19798  */
19799 static boolean_t
19800 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
19801 {
19802 	ipoptp_t	opts;
19803 	uchar_t		*opt;
19804 	uint8_t		optval;
19805 	uint8_t		optlen;
19806 	ipaddr_t	dst;
19807 	ire_t		*ire;
19808 
19809 	if (IS_SIMPLE_IPH(ipha)) {
19810 		ip2dbg(("not source routed\n"));
19811 		return (B_FALSE);
19812 	}
19813 	dst = ipha->ipha_dst;
19814 	for (optval = ipoptp_first(&opts, ipha);
19815 	    optval != IPOPT_EOL;
19816 	    optval = ipoptp_next(&opts)) {
19817 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19818 		opt = opts.ipoptp_cur;
19819 		optlen = opts.ipoptp_len;
19820 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19821 		    optval, optlen));
19822 		switch (optval) {
19823 			uint32_t off;
19824 		case IPOPT_SSRR:
19825 		case IPOPT_LSRR:
19826 			/*
19827 			 * If dst is one of our addresses and there are some
19828 			 * entries left in the source route return (true).
19829 			 */
19830 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19831 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
19832 			if (ire == NULL) {
19833 				ip2dbg(("ip_source_routed: not next"
19834 				    " source route 0x%x\n",
19835 				    ntohl(dst)));
19836 				return (B_FALSE);
19837 			}
19838 			ire_refrele(ire);
19839 			off = opt[IPOPT_OFFSET];
19840 			off--;
19841 			if (optlen < IP_ADDR_LEN ||
19842 			    off > optlen - IP_ADDR_LEN) {
19843 				/* End of source route */
19844 				ip1dbg(("ip_source_routed: end of SR\n"));
19845 				return (B_FALSE);
19846 			}
19847 			return (B_TRUE);
19848 		}
19849 	}
19850 	ip2dbg(("not source routed\n"));
19851 	return (B_FALSE);
19852 }
19853 
19854 /*
19855  * Check if the packet contains any source route.
19856  */
19857 static boolean_t
19858 ip_source_route_included(ipha_t *ipha)
19859 {
19860 	ipoptp_t	opts;
19861 	uint8_t		optval;
19862 
19863 	if (IS_SIMPLE_IPH(ipha))
19864 		return (B_FALSE);
19865 	for (optval = ipoptp_first(&opts, ipha);
19866 	    optval != IPOPT_EOL;
19867 	    optval = ipoptp_next(&opts)) {
19868 		switch (optval) {
19869 		case IPOPT_SSRR:
19870 		case IPOPT_LSRR:
19871 			return (B_TRUE);
19872 		}
19873 	}
19874 	return (B_FALSE);
19875 }
19876 
19877 /*
19878  * Called when the IRE expiration timer fires.
19879  */
19880 void
19881 ip_trash_timer_expire(void *args)
19882 {
19883 	int			flush_flag = 0;
19884 	ire_expire_arg_t	iea;
19885 	ip_stack_t		*ipst = (ip_stack_t *)args;
19886 
19887 	iea.iea_ipst = ipst;	/* No netstack_hold */
19888 
19889 	/*
19890 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19891 	 * This lock makes sure that a new invocation of this function
19892 	 * that occurs due to an almost immediate timer firing will not
19893 	 * progress beyond this point until the current invocation is done
19894 	 */
19895 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19896 	ipst->ips_ip_ire_expire_id = 0;
19897 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19898 
19899 	/* Periodic timer */
19900 	if (ipst->ips_ip_ire_arp_time_elapsed >=
19901 	    ipst->ips_ip_ire_arp_interval) {
19902 		/*
19903 		 * Remove all IRE_CACHE entries since they might
19904 		 * contain arp information.
19905 		 */
19906 		flush_flag |= FLUSH_ARP_TIME;
19907 		ipst->ips_ip_ire_arp_time_elapsed = 0;
19908 		IP_STAT(ipst, ip_ire_arp_timer_expired);
19909 	}
19910 	if (ipst->ips_ip_ire_rd_time_elapsed >=
19911 	    ipst->ips_ip_ire_redir_interval) {
19912 		/* Remove all redirects */
19913 		flush_flag |= FLUSH_REDIRECT_TIME;
19914 		ipst->ips_ip_ire_rd_time_elapsed = 0;
19915 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
19916 	}
19917 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
19918 	    ipst->ips_ip_ire_pathmtu_interval) {
19919 		/* Increase path mtu */
19920 		flush_flag |= FLUSH_MTU_TIME;
19921 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
19922 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
19923 	}
19924 
19925 	/*
19926 	 * Optimize for the case when there are no redirects in the
19927 	 * ftable, that is, no need to walk the ftable in that case.
19928 	 */
19929 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
19930 		iea.iea_flush_flag = flush_flag;
19931 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
19932 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
19933 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
19934 		    NULL, ALL_ZONES, ipst);
19935 	}
19936 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
19937 	    ipst->ips_ip_redirect_cnt > 0) {
19938 		iea.iea_flush_flag = flush_flag;
19939 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
19940 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
19941 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
19942 	}
19943 	if (flush_flag & FLUSH_MTU_TIME) {
19944 		/*
19945 		 * Walk all IPv6 IRE's and update them
19946 		 * Note that ARP and redirect timers are not
19947 		 * needed since NUD handles stale entries.
19948 		 */
19949 		flush_flag = FLUSH_MTU_TIME;
19950 		iea.iea_flush_flag = flush_flag;
19951 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
19952 		    ALL_ZONES, ipst);
19953 	}
19954 
19955 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
19956 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
19957 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
19958 
19959 	/*
19960 	 * Hold the lock to serialize timeout calls and prevent
19961 	 * stale values in ip_ire_expire_id. Otherwise it is possible
19962 	 * for the timer to fire and a new invocation of this function
19963 	 * to start before the return value of timeout has been stored
19964 	 * in ip_ire_expire_id by the current invocation.
19965 	 */
19966 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19967 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
19968 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
19969 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19970 }
19971 
19972 /*
19973  * Called by the memory allocator subsystem directly, when the system
19974  * is running low on memory.
19975  */
19976 /* ARGSUSED */
19977 void
19978 ip_trash_ire_reclaim(void *args)
19979 {
19980 	netstack_handle_t nh;
19981 	netstack_t *ns;
19982 
19983 	netstack_next_init(&nh);
19984 	while ((ns = netstack_next(&nh)) != NULL) {
19985 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
19986 		netstack_rele(ns);
19987 	}
19988 	netstack_next_fini(&nh);
19989 }
19990 
19991 static void
19992 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
19993 {
19994 	ire_cache_count_t icc;
19995 	ire_cache_reclaim_t icr;
19996 	ncc_cache_count_t ncc;
19997 	nce_cache_reclaim_t ncr;
19998 	uint_t delete_cnt;
19999 	/*
20000 	 * Memory reclaim call back.
20001 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
20002 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
20003 	 * entries, determine what fraction to free for
20004 	 * each category of IRE_CACHE entries giving absolute priority
20005 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
20006 	 * entry will be freed unless all offlink entries are freed).
20007 	 */
20008 	icc.icc_total = 0;
20009 	icc.icc_unused = 0;
20010 	icc.icc_offlink = 0;
20011 	icc.icc_pmtu = 0;
20012 	icc.icc_onlink = 0;
20013 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20014 
20015 	/*
20016 	 * Free NCEs for IPv6 like the onlink ires.
20017 	 */
20018 	ncc.ncc_total = 0;
20019 	ncc.ncc_host = 0;
20020 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
20021 
20022 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
20023 	    icc.icc_pmtu + icc.icc_onlink);
20024 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
20025 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
20026 	if (delete_cnt == 0)
20027 		return;
20028 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
20029 	/* Always delete all unused offlink entries */
20030 	icr.icr_ipst = ipst;
20031 	icr.icr_unused = 1;
20032 	if (delete_cnt <= icc.icc_unused) {
20033 		/*
20034 		 * Only need to free unused entries.  In other words,
20035 		 * there are enough unused entries to free to meet our
20036 		 * target number of freed ire cache entries.
20037 		 */
20038 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
20039 		ncr.ncr_host = 0;
20040 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
20041 		/*
20042 		 * Only need to free unused entries, plus a fraction of offlink
20043 		 * entries.  It follows from the first if statement that
20044 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
20045 		 */
20046 		delete_cnt -= icc.icc_unused;
20047 		/* Round up # deleted by truncating fraction */
20048 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
20049 		icr.icr_pmtu = icr.icr_onlink = 0;
20050 		ncr.ncr_host = 0;
20051 	} else if (delete_cnt <=
20052 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
20053 		/*
20054 		 * Free all unused and offlink entries, plus a fraction of
20055 		 * pmtu entries.  It follows from the previous if statement
20056 		 * that icc_pmtu is non-zero, and that
20057 		 * delete_cnt != icc_unused + icc_offlink.
20058 		 */
20059 		icr.icr_offlink = 1;
20060 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
20061 		/* Round up # deleted by truncating fraction */
20062 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20063 		icr.icr_onlink = 0;
20064 		ncr.ncr_host = 0;
20065 	} else {
20066 		/*
20067 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20068 		 * of onlink entries.  If we're here, then we know that
20069 		 * icc_onlink is non-zero, and that
20070 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20071 		 */
20072 		icr.icr_offlink = icr.icr_pmtu = 1;
20073 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20074 		    icc.icc_pmtu;
20075 		/* Round up # deleted by truncating fraction */
20076 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20077 		/* Using the same delete fraction as for onlink IREs */
20078 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20079 	}
20080 #ifdef DEBUG
20081 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20082 	    "fractions %d/%d/%d/%d\n",
20083 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20084 	    icc.icc_unused, icc.icc_offlink,
20085 	    icc.icc_pmtu, icc.icc_onlink,
20086 	    icr.icr_unused, icr.icr_offlink,
20087 	    icr.icr_pmtu, icr.icr_onlink));
20088 #endif
20089 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20090 	if (ncr.ncr_host != 0)
20091 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20092 		    (uchar_t *)&ncr, ipst);
20093 #ifdef DEBUG
20094 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20095 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20096 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20097 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20098 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20099 	    icc.icc_pmtu, icc.icc_onlink));
20100 #endif
20101 }
20102 
20103 /*
20104  * ip_unbind is called when a copy of an unbind request is received from the
20105  * upper level protocol.  We remove this conn from any fanout hash list it is
20106  * on, and zero out the bind information.  No reply is expected up above.
20107  */
20108 mblk_t *
20109 ip_unbind(queue_t *q, mblk_t *mp)
20110 {
20111 	conn_t	*connp = Q_TO_CONN(q);
20112 
20113 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20114 
20115 	if (is_system_labeled() && connp->conn_anon_port) {
20116 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20117 		    connp->conn_mlp_type, connp->conn_ulp,
20118 		    ntohs(connp->conn_lport), B_FALSE);
20119 		connp->conn_anon_port = 0;
20120 	}
20121 	connp->conn_mlp_type = mlptSingle;
20122 
20123 	ipcl_hash_remove(connp);
20124 
20125 	ASSERT(mp->b_cont == NULL);
20126 	/*
20127 	 * Convert mp into a T_OK_ACK
20128 	 */
20129 	mp = mi_tpi_ok_ack_alloc(mp);
20130 
20131 	/*
20132 	 * should not happen in practice... T_OK_ACK is smaller than the
20133 	 * original message.
20134 	 */
20135 	if (mp == NULL)
20136 		return (NULL);
20137 
20138 	return (mp);
20139 }
20140 
20141 /*
20142  * Write side put procedure.  Outbound data, IOCTLs, responses from
20143  * resolvers, etc, come down through here.
20144  *
20145  * arg2 is always a queue_t *.
20146  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20147  * the zoneid.
20148  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20149  */
20150 void
20151 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20152 {
20153 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20154 }
20155 
20156 void
20157 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20158     ip_opt_info_t *infop)
20159 {
20160 	conn_t		*connp = NULL;
20161 	queue_t		*q = (queue_t *)arg2;
20162 	ipha_t		*ipha;
20163 #define	rptr	((uchar_t *)ipha)
20164 	ire_t		*ire = NULL;
20165 	ire_t		*sctp_ire = NULL;
20166 	uint32_t	v_hlen_tos_len;
20167 	ipaddr_t	dst;
20168 	mblk_t		*first_mp = NULL;
20169 	boolean_t	mctl_present;
20170 	ipsec_out_t	*io;
20171 	int		match_flags;
20172 	ill_t		*attach_ill = NULL;
20173 					/* Bind to IPIF_NOFAILOVER ill etc. */
20174 	ill_t		*xmit_ill = NULL;	/* IP_PKTINFO etc. */
20175 	ipif_t		*dst_ipif;
20176 	boolean_t	multirt_need_resolve = B_FALSE;
20177 	mblk_t		*copy_mp = NULL;
20178 	int		err;
20179 	zoneid_t	zoneid;
20180 	boolean_t	need_decref = B_FALSE;
20181 	boolean_t	ignore_dontroute = B_FALSE;
20182 	boolean_t	ignore_nexthop = B_FALSE;
20183 	boolean_t	ip_nexthop = B_FALSE;
20184 	ipaddr_t	nexthop_addr;
20185 	ip_stack_t	*ipst;
20186 
20187 #ifdef	_BIG_ENDIAN
20188 #define	V_HLEN	(v_hlen_tos_len >> 24)
20189 #else
20190 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20191 #endif
20192 
20193 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20194 	    "ip_wput_start: q %p", q);
20195 
20196 	/*
20197 	 * ip_wput fast path
20198 	 */
20199 
20200 	/* is packet from ARP ? */
20201 	if (q->q_next != NULL) {
20202 		zoneid = (zoneid_t)(uintptr_t)arg;
20203 		goto qnext;
20204 	}
20205 
20206 	connp = (conn_t *)arg;
20207 	ASSERT(connp != NULL);
20208 	zoneid = connp->conn_zoneid;
20209 	ipst = connp->conn_netstack->netstack_ip;
20210 
20211 	/* is queue flow controlled? */
20212 	if ((q->q_first != NULL || connp->conn_draining) &&
20213 	    (caller == IP_WPUT)) {
20214 		ASSERT(!need_decref);
20215 		(void) putq(q, mp);
20216 		return;
20217 	}
20218 
20219 	/* Multidata transmit? */
20220 	if (DB_TYPE(mp) == M_MULTIDATA) {
20221 		/*
20222 		 * We should never get here, since all Multidata messages
20223 		 * originating from tcp should have been directed over to
20224 		 * tcp_multisend() in the first place.
20225 		 */
20226 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20227 		freemsg(mp);
20228 		return;
20229 	} else if (DB_TYPE(mp) != M_DATA)
20230 		goto notdata;
20231 
20232 	if (mp->b_flag & MSGHASREF) {
20233 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20234 		mp->b_flag &= ~MSGHASREF;
20235 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20236 		need_decref = B_TRUE;
20237 	}
20238 	ipha = (ipha_t *)mp->b_rptr;
20239 
20240 	/* is IP header non-aligned or mblk smaller than basic IP header */
20241 #ifndef SAFETY_BEFORE_SPEED
20242 	if (!OK_32PTR(rptr) ||
20243 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20244 		goto hdrtoosmall;
20245 #endif
20246 
20247 	ASSERT(OK_32PTR(ipha));
20248 
20249 	/*
20250 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20251 	 * wrong version, we'll catch it again in ip_output_v6.
20252 	 *
20253 	 * Note that this is *only* locally-generated output here, and never
20254 	 * forwarded data, and that we need to deal only with transports that
20255 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20256 	 * label.)
20257 	 */
20258 	if (is_system_labeled() &&
20259 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20260 	    !connp->conn_ulp_labeled) {
20261 		err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20262 		    connp->conn_mac_exempt, ipst);
20263 		ipha = (ipha_t *)mp->b_rptr;
20264 		if (err != 0) {
20265 			first_mp = mp;
20266 			if (err == EINVAL)
20267 				goto icmp_parameter_problem;
20268 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20269 			goto discard_pkt;
20270 		}
20271 	}
20272 
20273 	ASSERT(infop != NULL);
20274 
20275 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20276 		/*
20277 		 * IP_PKTINFO ancillary option is present.
20278 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20279 		 * allows using address of any zone as the source address.
20280 		 */
20281 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20282 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20283 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20284 		if (ire == NULL)
20285 			goto drop_pkt;
20286 		ire_refrele(ire);
20287 		ire = NULL;
20288 	}
20289 
20290 	/*
20291 	 * IP_DONTFAILOVER_IF and IP_BOUND_IF have precedence over ill index
20292 	 * passed in IP_PKTINFO.
20293 	 */
20294 	if (infop->ip_opt_ill_index != 0 &&
20295 	    connp->conn_outgoing_ill == NULL &&
20296 	    connp->conn_nofailover_ill == NULL) {
20297 
20298 		xmit_ill = ill_lookup_on_ifindex(
20299 		    infop->ip_opt_ill_index, B_FALSE, NULL, NULL, NULL, NULL,
20300 		    ipst);
20301 
20302 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20303 			goto drop_pkt;
20304 		/*
20305 		 * check that there is an ipif belonging
20306 		 * to our zone. IPCL_ZONEID is not used because
20307 		 * IP_ALLZONES option is valid only when the ill is
20308 		 * accessible from all zones i.e has a valid ipif in
20309 		 * all zones.
20310 		 */
20311 		if (!ipif_lookup_zoneid_group(xmit_ill, zoneid, 0, NULL)) {
20312 			goto drop_pkt;
20313 		}
20314 	}
20315 
20316 	/*
20317 	 * If there is a policy, try to attach an ipsec_out in
20318 	 * the front. At the end, first_mp either points to a
20319 	 * M_DATA message or IPSEC_OUT message linked to a
20320 	 * M_DATA message. We have to do it now as we might
20321 	 * lose the "conn" if we go through ip_newroute.
20322 	 */
20323 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20324 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20325 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20326 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20327 			if (need_decref)
20328 				CONN_DEC_REF(connp);
20329 			return;
20330 		} else {
20331 			ASSERT(mp->b_datap->db_type == M_CTL);
20332 			first_mp = mp;
20333 			mp = mp->b_cont;
20334 			mctl_present = B_TRUE;
20335 		}
20336 	} else {
20337 		first_mp = mp;
20338 		mctl_present = B_FALSE;
20339 	}
20340 
20341 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20342 
20343 	/* is wrong version or IP options present */
20344 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20345 		goto version_hdrlen_check;
20346 	dst = ipha->ipha_dst;
20347 
20348 	if (connp->conn_nofailover_ill != NULL) {
20349 		attach_ill = conn_get_held_ill(connp,
20350 		    &connp->conn_nofailover_ill, &err);
20351 		if (err == ILL_LOOKUP_FAILED) {
20352 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20353 			if (need_decref)
20354 				CONN_DEC_REF(connp);
20355 			freemsg(first_mp);
20356 			return;
20357 		}
20358 	}
20359 
20360 	/* If IP_BOUND_IF has been set, use that ill. */
20361 	if (connp->conn_outgoing_ill != NULL) {
20362 		xmit_ill = conn_get_held_ill(connp,
20363 		    &connp->conn_outgoing_ill, &err);
20364 		if (err == ILL_LOOKUP_FAILED)
20365 			goto drop_pkt;
20366 
20367 		goto send_from_ill;
20368 	}
20369 
20370 	/* is packet multicast? */
20371 	if (CLASSD(dst))
20372 		goto multicast;
20373 
20374 	/*
20375 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20376 	 * takes precedence over conn_dontroute and conn_nexthop_set
20377 	 */
20378 	if (xmit_ill != NULL)
20379 		goto send_from_ill;
20380 
20381 	if (connp->conn_dontroute || connp->conn_nexthop_set) {
20382 		/*
20383 		 * If the destination is a broadcast, local, or loopback
20384 		 * address, SO_DONTROUTE and IP_NEXTHOP go through the
20385 		 * standard path.
20386 		 */
20387 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20388 		if ((ire == NULL) || (ire->ire_type &
20389 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK)) == 0) {
20390 			if (ire != NULL) {
20391 				ire_refrele(ire);
20392 				/* No more access to ire */
20393 				ire = NULL;
20394 			}
20395 			/*
20396 			 * bypass routing checks and go directly to interface.
20397 			 */
20398 			if (connp->conn_dontroute)
20399 				goto dontroute;
20400 
20401 			ASSERT(connp->conn_nexthop_set);
20402 			ip_nexthop = B_TRUE;
20403 			nexthop_addr = connp->conn_nexthop_v4;
20404 			goto send_from_ill;
20405 		}
20406 
20407 		/* Must be a broadcast, a loopback or a local ire */
20408 		ire_refrele(ire);
20409 		/* No more access to ire */
20410 		ire = NULL;
20411 	}
20412 
20413 	if (attach_ill != NULL)
20414 		goto send_from_ill;
20415 
20416 	/*
20417 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20418 	 * this for the tcp global queue and listen end point
20419 	 * as it does not really have a real destination to
20420 	 * talk to.  This is also true for SCTP.
20421 	 */
20422 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20423 	    !connp->conn_fully_bound) {
20424 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20425 		if (ire == NULL)
20426 			goto noirefound;
20427 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20428 		    "ip_wput_end: q %p (%S)", q, "end");
20429 
20430 		/*
20431 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20432 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20433 		 */
20434 		if (ire->ire_flags & RTF_MULTIRT) {
20435 
20436 			/*
20437 			 * Force the TTL of multirouted packets if required.
20438 			 * The TTL of such packets is bounded by the
20439 			 * ip_multirt_ttl ndd variable.
20440 			 */
20441 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20442 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20443 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20444 				    "(was %d), dst 0x%08x\n",
20445 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20446 				    ntohl(ire->ire_addr)));
20447 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20448 			}
20449 			/*
20450 			 * We look at this point if there are pending
20451 			 * unresolved routes. ire_multirt_resolvable()
20452 			 * checks in O(n) that all IRE_OFFSUBNET ire
20453 			 * entries for the packet's destination and
20454 			 * flagged RTF_MULTIRT are currently resolved.
20455 			 * If some remain unresolved, we make a copy
20456 			 * of the current message. It will be used
20457 			 * to initiate additional route resolutions.
20458 			 */
20459 			multirt_need_resolve =
20460 			    ire_multirt_need_resolve(ire->ire_addr,
20461 			    MBLK_GETLABEL(first_mp), ipst);
20462 			ip2dbg(("ip_wput[TCP]: ire %p, "
20463 			    "multirt_need_resolve %d, first_mp %p\n",
20464 			    (void *)ire, multirt_need_resolve,
20465 			    (void *)first_mp));
20466 			if (multirt_need_resolve) {
20467 				copy_mp = copymsg(first_mp);
20468 				if (copy_mp != NULL) {
20469 					MULTIRT_DEBUG_TAG(copy_mp);
20470 				}
20471 			}
20472 		}
20473 
20474 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20475 
20476 		/*
20477 		 * Try to resolve another multiroute if
20478 		 * ire_multirt_need_resolve() deemed it necessary.
20479 		 */
20480 		if (copy_mp != NULL)
20481 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20482 		if (need_decref)
20483 			CONN_DEC_REF(connp);
20484 		return;
20485 	}
20486 
20487 	/*
20488 	 * Access to conn_ire_cache. (protected by conn_lock)
20489 	 *
20490 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20491 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20492 	 * send a packet or two with the IRE_CACHE that is going away.
20493 	 * Access to the ire requires an ire refhold on the ire prior to
20494 	 * its use since an interface unplumb thread may delete the cached
20495 	 * ire and release the refhold at any time.
20496 	 *
20497 	 * Caching an ire in the conn_ire_cache
20498 	 *
20499 	 * o Caching an ire pointer in the conn requires a strict check for
20500 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20501 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20502 	 * in the conn is done after making sure under the bucket lock that the
20503 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20504 	 * caching an ire after the unplumb thread has cleaned up the conn.
20505 	 * If the conn does not send a packet subsequently the unplumb thread
20506 	 * will be hanging waiting for the ire count to drop to zero.
20507 	 *
20508 	 * o We also need to atomically test for a null conn_ire_cache and
20509 	 * set the conn_ire_cache under the the protection of the conn_lock
20510 	 * to avoid races among concurrent threads trying to simultaneously
20511 	 * cache an ire in the conn_ire_cache.
20512 	 */
20513 	mutex_enter(&connp->conn_lock);
20514 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20515 
20516 	if (ire != NULL && ire->ire_addr == dst &&
20517 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20518 
20519 		IRE_REFHOLD(ire);
20520 		mutex_exit(&connp->conn_lock);
20521 
20522 	} else {
20523 		boolean_t cached = B_FALSE;
20524 		connp->conn_ire_cache = NULL;
20525 		mutex_exit(&connp->conn_lock);
20526 		/* Release the old ire */
20527 		if (ire != NULL && sctp_ire == NULL)
20528 			IRE_REFRELE_NOTR(ire);
20529 
20530 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20531 		if (ire == NULL)
20532 			goto noirefound;
20533 		IRE_REFHOLD_NOTR(ire);
20534 
20535 		mutex_enter(&connp->conn_lock);
20536 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20537 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20538 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20539 				if (connp->conn_ulp == IPPROTO_TCP)
20540 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20541 				connp->conn_ire_cache = ire;
20542 				cached = B_TRUE;
20543 			}
20544 			rw_exit(&ire->ire_bucket->irb_lock);
20545 		}
20546 		mutex_exit(&connp->conn_lock);
20547 
20548 		/*
20549 		 * We can continue to use the ire but since it was
20550 		 * not cached, we should drop the extra reference.
20551 		 */
20552 		if (!cached)
20553 			IRE_REFRELE_NOTR(ire);
20554 	}
20555 
20556 
20557 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20558 	    "ip_wput_end: q %p (%S)", q, "end");
20559 
20560 	/*
20561 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20562 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20563 	 */
20564 	if (ire->ire_flags & RTF_MULTIRT) {
20565 
20566 		/*
20567 		 * Force the TTL of multirouted packets if required.
20568 		 * The TTL of such packets is bounded by the
20569 		 * ip_multirt_ttl ndd variable.
20570 		 */
20571 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20572 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20573 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20574 			    "(was %d), dst 0x%08x\n",
20575 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20576 			    ntohl(ire->ire_addr)));
20577 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20578 		}
20579 
20580 		/*
20581 		 * At this point, we check to see if there are any pending
20582 		 * unresolved routes. ire_multirt_resolvable()
20583 		 * checks in O(n) that all IRE_OFFSUBNET ire
20584 		 * entries for the packet's destination and
20585 		 * flagged RTF_MULTIRT are currently resolved.
20586 		 * If some remain unresolved, we make a copy
20587 		 * of the current message. It will be used
20588 		 * to initiate additional route resolutions.
20589 		 */
20590 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20591 		    MBLK_GETLABEL(first_mp), ipst);
20592 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20593 		    "multirt_need_resolve %d, first_mp %p\n",
20594 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20595 		if (multirt_need_resolve) {
20596 			copy_mp = copymsg(first_mp);
20597 			if (copy_mp != NULL) {
20598 				MULTIRT_DEBUG_TAG(copy_mp);
20599 			}
20600 		}
20601 	}
20602 
20603 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20604 
20605 	/*
20606 	 * Try to resolve another multiroute if
20607 	 * ire_multirt_resolvable() deemed it necessary
20608 	 */
20609 	if (copy_mp != NULL)
20610 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20611 	if (need_decref)
20612 		CONN_DEC_REF(connp);
20613 	return;
20614 
20615 qnext:
20616 	/*
20617 	 * Upper Level Protocols pass down complete IP datagrams
20618 	 * as M_DATA messages.	Everything else is a sideshow.
20619 	 *
20620 	 * 1) We could be re-entering ip_wput because of ip_neworute
20621 	 *    in which case we could have a IPSEC_OUT message. We
20622 	 *    need to pass through ip_wput like other datagrams and
20623 	 *    hence cannot branch to ip_wput_nondata.
20624 	 *
20625 	 * 2) ARP, AH, ESP, and other clients who are on the module
20626 	 *    instance of IP stream, give us something to deal with.
20627 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20628 	 *
20629 	 * 3) ICMP replies also could come here.
20630 	 */
20631 	ipst = ILLQ_TO_IPST(q);
20632 
20633 	if (DB_TYPE(mp) != M_DATA) {
20634 notdata:
20635 		if (DB_TYPE(mp) == M_CTL) {
20636 			/*
20637 			 * M_CTL messages are used by ARP, AH and ESP to
20638 			 * communicate with IP. We deal with IPSEC_IN and
20639 			 * IPSEC_OUT here. ip_wput_nondata handles other
20640 			 * cases.
20641 			 */
20642 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20643 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20644 				first_mp = mp->b_cont;
20645 				first_mp->b_flag &= ~MSGHASREF;
20646 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20647 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20648 				CONN_DEC_REF(connp);
20649 				connp = NULL;
20650 			}
20651 			if (ii->ipsec_info_type == IPSEC_IN) {
20652 				/*
20653 				 * Either this message goes back to
20654 				 * IPsec for further processing or to
20655 				 * ULP after policy checks.
20656 				 */
20657 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20658 				return;
20659 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20660 				io = (ipsec_out_t *)ii;
20661 				if (io->ipsec_out_proc_begin) {
20662 					/*
20663 					 * IPsec processing has already started.
20664 					 * Complete it.
20665 					 * IPQoS notes: We don't care what is
20666 					 * in ipsec_out_ill_index since this
20667 					 * won't be processed for IPQoS policies
20668 					 * in ipsec_out_process.
20669 					 */
20670 					ipsec_out_process(q, mp, NULL,
20671 					    io->ipsec_out_ill_index);
20672 					return;
20673 				} else {
20674 					connp = (q->q_next != NULL) ?
20675 					    NULL : Q_TO_CONN(q);
20676 					first_mp = mp;
20677 					mp = mp->b_cont;
20678 					mctl_present = B_TRUE;
20679 				}
20680 				zoneid = io->ipsec_out_zoneid;
20681 				ASSERT(zoneid != ALL_ZONES);
20682 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20683 				/*
20684 				 * It's an IPsec control message requesting
20685 				 * an SADB update to be sent to the IPsec
20686 				 * hardware acceleration capable ills.
20687 				 */
20688 				ipsec_ctl_t *ipsec_ctl =
20689 				    (ipsec_ctl_t *)mp->b_rptr;
20690 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20691 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20692 				mblk_t *cmp = mp->b_cont;
20693 
20694 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20695 				ASSERT(cmp != NULL);
20696 
20697 				freeb(mp);
20698 				ill_ipsec_capab_send_all(satype, cmp, sa,
20699 				    ipst->ips_netstack);
20700 				return;
20701 			} else {
20702 				/*
20703 				 * This must be ARP or special TSOL signaling.
20704 				 */
20705 				ip_wput_nondata(NULL, q, mp, NULL);
20706 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20707 				    "ip_wput_end: q %p (%S)", q, "nondata");
20708 				return;
20709 			}
20710 		} else {
20711 			/*
20712 			 * This must be non-(ARP/AH/ESP) messages.
20713 			 */
20714 			ASSERT(!need_decref);
20715 			ip_wput_nondata(NULL, q, mp, NULL);
20716 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20717 			    "ip_wput_end: q %p (%S)", q, "nondata");
20718 			return;
20719 		}
20720 	} else {
20721 		first_mp = mp;
20722 		mctl_present = B_FALSE;
20723 	}
20724 
20725 	ASSERT(first_mp != NULL);
20726 	/*
20727 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20728 	 * to make sure that this packet goes out on the same interface it
20729 	 * came in. We handle that here.
20730 	 */
20731 	if (mctl_present) {
20732 		uint_t ifindex;
20733 
20734 		io = (ipsec_out_t *)first_mp->b_rptr;
20735 		if (io->ipsec_out_attach_if || io->ipsec_out_ip_nexthop) {
20736 			/*
20737 			 * We may have lost the conn context if we are
20738 			 * coming here from ip_newroute(). Copy the
20739 			 * nexthop information.
20740 			 */
20741 			if (io->ipsec_out_ip_nexthop) {
20742 				ip_nexthop = B_TRUE;
20743 				nexthop_addr = io->ipsec_out_nexthop_addr;
20744 
20745 				ipha = (ipha_t *)mp->b_rptr;
20746 				dst = ipha->ipha_dst;
20747 				goto send_from_ill;
20748 			} else {
20749 				ASSERT(io->ipsec_out_ill_index != 0);
20750 				ifindex = io->ipsec_out_ill_index;
20751 				attach_ill = ill_lookup_on_ifindex(ifindex,
20752 				    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20753 				if (attach_ill == NULL) {
20754 					ASSERT(xmit_ill == NULL);
20755 					ip1dbg(("ip_output: bad ifindex for "
20756 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20757 					    ifindex));
20758 					freemsg(first_mp);
20759 					BUMP_MIB(&ipst->ips_ip_mib,
20760 					    ipIfStatsOutDiscards);
20761 					ASSERT(!need_decref);
20762 					return;
20763 				}
20764 			}
20765 		}
20766 	}
20767 
20768 	ASSERT(xmit_ill == NULL);
20769 
20770 	/* We have a complete IP datagram heading outbound. */
20771 	ipha = (ipha_t *)mp->b_rptr;
20772 
20773 #ifndef SPEED_BEFORE_SAFETY
20774 	/*
20775 	 * Make sure we have a full-word aligned message and that at least
20776 	 * a simple IP header is accessible in the first message.  If not,
20777 	 * try a pullup.  For labeled systems we need to always take this
20778 	 * path as M_CTLs are "notdata" but have trailing data to process.
20779 	 */
20780 	if (!OK_32PTR(rptr) ||
20781 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH || is_system_labeled()) {
20782 hdrtoosmall:
20783 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20784 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20785 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20786 			if (first_mp == NULL)
20787 				first_mp = mp;
20788 			goto discard_pkt;
20789 		}
20790 
20791 		/* This function assumes that mp points to an IPv4 packet. */
20792 		if (is_system_labeled() && q->q_next == NULL &&
20793 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20794 		    !connp->conn_ulp_labeled) {
20795 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20796 			    connp->conn_mac_exempt, ipst);
20797 			ipha = (ipha_t *)mp->b_rptr;
20798 			if (first_mp != NULL)
20799 				first_mp->b_cont = mp;
20800 			if (err != 0) {
20801 				if (first_mp == NULL)
20802 					first_mp = mp;
20803 				if (err == EINVAL)
20804 					goto icmp_parameter_problem;
20805 				ip2dbg(("ip_wput: label check failed (%d)\n",
20806 				    err));
20807 				goto discard_pkt;
20808 			}
20809 		}
20810 
20811 		ipha = (ipha_t *)mp->b_rptr;
20812 		if (first_mp == NULL) {
20813 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20814 			/*
20815 			 * If we got here because of "goto hdrtoosmall"
20816 			 * We need to attach a IPSEC_OUT.
20817 			 */
20818 			if (connp->conn_out_enforce_policy) {
20819 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
20820 				    NULL, ipha->ipha_protocol,
20821 				    ipst->ips_netstack)) == NULL)) {
20822 					BUMP_MIB(&ipst->ips_ip_mib,
20823 					    ipIfStatsOutDiscards);
20824 					if (need_decref)
20825 						CONN_DEC_REF(connp);
20826 					return;
20827 				} else {
20828 					ASSERT(mp->b_datap->db_type == M_CTL);
20829 					first_mp = mp;
20830 					mp = mp->b_cont;
20831 					mctl_present = B_TRUE;
20832 				}
20833 			} else {
20834 				first_mp = mp;
20835 				mctl_present = B_FALSE;
20836 			}
20837 		}
20838 	}
20839 #endif
20840 
20841 	/* Most of the code below is written for speed, not readability */
20842 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20843 
20844 	/*
20845 	 * If ip_newroute() fails, we're going to need a full
20846 	 * header for the icmp wraparound.
20847 	 */
20848 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20849 		uint_t	v_hlen;
20850 version_hdrlen_check:
20851 		ASSERT(first_mp != NULL);
20852 		v_hlen = V_HLEN;
20853 		/*
20854 		 * siphon off IPv6 packets coming down from transport
20855 		 * layer modules here.
20856 		 * Note: high-order bit carries NUD reachability confirmation
20857 		 */
20858 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20859 			/*
20860 			 * FIXME: assume that callers of ip_output* call
20861 			 * the right version?
20862 			 */
20863 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
20864 			ASSERT(xmit_ill == NULL);
20865 			if (attach_ill != NULL)
20866 				ill_refrele(attach_ill);
20867 			if (need_decref)
20868 				mp->b_flag |= MSGHASREF;
20869 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20870 			return;
20871 		}
20872 
20873 		if ((v_hlen >> 4) != IP_VERSION) {
20874 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20875 			    "ip_wput_end: q %p (%S)", q, "badvers");
20876 			goto discard_pkt;
20877 		}
20878 		/*
20879 		 * Is the header length at least 20 bytes?
20880 		 *
20881 		 * Are there enough bytes accessible in the header?  If
20882 		 * not, try a pullup.
20883 		 */
20884 		v_hlen &= 0xF;
20885 		v_hlen <<= 2;
20886 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20887 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20888 			    "ip_wput_end: q %p (%S)", q, "badlen");
20889 			goto discard_pkt;
20890 		}
20891 		if (v_hlen > (mp->b_wptr - rptr)) {
20892 			if (!pullupmsg(mp, v_hlen)) {
20893 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20894 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20895 				goto discard_pkt;
20896 			}
20897 			ipha = (ipha_t *)mp->b_rptr;
20898 		}
20899 		/*
20900 		 * Move first entry from any source route into ipha_dst and
20901 		 * verify the options
20902 		 */
20903 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
20904 		    zoneid, ipst)) {
20905 			ASSERT(xmit_ill == NULL);
20906 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20907 			if (attach_ill != NULL)
20908 				ill_refrele(attach_ill);
20909 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20910 			    "ip_wput_end: q %p (%S)", q, "badopts");
20911 			if (need_decref)
20912 				CONN_DEC_REF(connp);
20913 			return;
20914 		}
20915 	}
20916 	dst = ipha->ipha_dst;
20917 
20918 	/*
20919 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20920 	 * we have to run the packet through ip_newroute which will take
20921 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
20922 	 * a resolver, or assigning a default gateway, etc.
20923 	 */
20924 	if (CLASSD(dst)) {
20925 		ipif_t	*ipif;
20926 		uint32_t setsrc = 0;
20927 
20928 multicast:
20929 		ASSERT(first_mp != NULL);
20930 		ip2dbg(("ip_wput: CLASSD\n"));
20931 		if (connp == NULL) {
20932 			/*
20933 			 * Use the first good ipif on the ill.
20934 			 * XXX Should this ever happen? (Appears
20935 			 * to show up with just ppp and no ethernet due
20936 			 * to in.rdisc.)
20937 			 * However, ire_send should be able to
20938 			 * call ip_wput_ire directly.
20939 			 *
20940 			 * XXX Also, this can happen for ICMP and other packets
20941 			 * with multicast source addresses.  Perhaps we should
20942 			 * fix things so that we drop the packet in question,
20943 			 * but for now, just run with it.
20944 			 */
20945 			ill_t *ill = (ill_t *)q->q_ptr;
20946 
20947 			/*
20948 			 * Don't honor attach_if for this case. If ill
20949 			 * is part of the group, ipif could belong to
20950 			 * any ill and we cannot maintain attach_ill
20951 			 * and ipif_ill same anymore and the assert
20952 			 * below would fail.
20953 			 */
20954 			if (mctl_present && io->ipsec_out_attach_if) {
20955 				io->ipsec_out_ill_index = 0;
20956 				io->ipsec_out_attach_if = B_FALSE;
20957 				ASSERT(attach_ill != NULL);
20958 				ill_refrele(attach_ill);
20959 				attach_ill = NULL;
20960 			}
20961 
20962 			ASSERT(attach_ill == NULL);
20963 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
20964 			if (ipif == NULL) {
20965 				if (need_decref)
20966 					CONN_DEC_REF(connp);
20967 				freemsg(first_mp);
20968 				return;
20969 			}
20970 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
20971 			    ntohl(dst), ill->ill_name));
20972 		} else {
20973 			/*
20974 			 * The order of precedence is IP_BOUND_IF, IP_PKTINFO
20975 			 * and IP_MULTICAST_IF.  The block comment above this
20976 			 * function explains the locking mechanism used here.
20977 			 */
20978 			if (xmit_ill == NULL) {
20979 				xmit_ill = conn_get_held_ill(connp,
20980 				    &connp->conn_outgoing_ill, &err);
20981 				if (err == ILL_LOOKUP_FAILED) {
20982 					ip1dbg(("ip_wput: No ill for "
20983 					    "IP_BOUND_IF\n"));
20984 					BUMP_MIB(&ipst->ips_ip_mib,
20985 					    ipIfStatsOutNoRoutes);
20986 					goto drop_pkt;
20987 				}
20988 			}
20989 
20990 			if (xmit_ill == NULL) {
20991 				ipif = conn_get_held_ipif(connp,
20992 				    &connp->conn_multicast_ipif, &err);
20993 				if (err == IPIF_LOOKUP_FAILED) {
20994 					ip1dbg(("ip_wput: No ipif for "
20995 					    "multicast\n"));
20996 					BUMP_MIB(&ipst->ips_ip_mib,
20997 					    ipIfStatsOutNoRoutes);
20998 					goto drop_pkt;
20999 				}
21000 			}
21001 			if (xmit_ill != NULL) {
21002 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21003 				if (ipif == NULL) {
21004 					ip1dbg(("ip_wput: No ipif for "
21005 					    "xmit_ill\n"));
21006 					BUMP_MIB(&ipst->ips_ip_mib,
21007 					    ipIfStatsOutNoRoutes);
21008 					goto drop_pkt;
21009 				}
21010 			} else if (ipif == NULL || ipif->ipif_isv6) {
21011 				/*
21012 				 * We must do this ipif determination here
21013 				 * else we could pass through ip_newroute
21014 				 * and come back here without the conn context.
21015 				 *
21016 				 * Note: we do late binding i.e. we bind to
21017 				 * the interface when the first packet is sent.
21018 				 * For performance reasons we do not rebind on
21019 				 * each packet but keep the binding until the
21020 				 * next IP_MULTICAST_IF option.
21021 				 *
21022 				 * conn_multicast_{ipif,ill} are shared between
21023 				 * IPv4 and IPv6 and AF_INET6 sockets can
21024 				 * send both IPv4 and IPv6 packets. Hence
21025 				 * we have to check that "isv6" matches above.
21026 				 */
21027 				if (ipif != NULL)
21028 					ipif_refrele(ipif);
21029 				ipif = ipif_lookup_group(dst, zoneid, ipst);
21030 				if (ipif == NULL) {
21031 					ip1dbg(("ip_wput: No ipif for "
21032 					    "multicast\n"));
21033 					BUMP_MIB(&ipst->ips_ip_mib,
21034 					    ipIfStatsOutNoRoutes);
21035 					goto drop_pkt;
21036 				}
21037 				err = conn_set_held_ipif(connp,
21038 				    &connp->conn_multicast_ipif, ipif);
21039 				if (err == IPIF_LOOKUP_FAILED) {
21040 					ipif_refrele(ipif);
21041 					ip1dbg(("ip_wput: No ipif for "
21042 					    "multicast\n"));
21043 					BUMP_MIB(&ipst->ips_ip_mib,
21044 					    ipIfStatsOutNoRoutes);
21045 					goto drop_pkt;
21046 				}
21047 			}
21048 		}
21049 		ASSERT(!ipif->ipif_isv6);
21050 		/*
21051 		 * As we may lose the conn by the time we reach ip_wput_ire,
21052 		 * we copy conn_multicast_loop and conn_dontroute on to an
21053 		 * ipsec_out. In case if this datagram goes out secure,
21054 		 * we need the ill_index also. Copy that also into the
21055 		 * ipsec_out.
21056 		 */
21057 		if (mctl_present) {
21058 			io = (ipsec_out_t *)first_mp->b_rptr;
21059 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21060 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21061 		} else {
21062 			ASSERT(mp == first_mp);
21063 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21064 			    BPRI_HI)) == NULL) {
21065 				ipif_refrele(ipif);
21066 				first_mp = mp;
21067 				goto discard_pkt;
21068 			}
21069 			first_mp->b_datap->db_type = M_CTL;
21070 			first_mp->b_wptr += sizeof (ipsec_info_t);
21071 			/* ipsec_out_secure is B_FALSE now */
21072 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21073 			io = (ipsec_out_t *)first_mp->b_rptr;
21074 			io->ipsec_out_type = IPSEC_OUT;
21075 			io->ipsec_out_len = sizeof (ipsec_out_t);
21076 			io->ipsec_out_use_global_policy = B_TRUE;
21077 			io->ipsec_out_ns = ipst->ips_netstack;
21078 			first_mp->b_cont = mp;
21079 			mctl_present = B_TRUE;
21080 		}
21081 		if (attach_ill != NULL) {
21082 			ASSERT(attach_ill == ipif->ipif_ill);
21083 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21084 
21085 			/*
21086 			 * Check if we need an ire that will not be
21087 			 * looked up by anybody else i.e. HIDDEN.
21088 			 */
21089 			if (ill_is_probeonly(attach_ill)) {
21090 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21091 			}
21092 			io->ipsec_out_ill_index =
21093 			    attach_ill->ill_phyint->phyint_ifindex;
21094 			io->ipsec_out_attach_if = B_TRUE;
21095 		} else {
21096 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21097 			io->ipsec_out_ill_index =
21098 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21099 		}
21100 		if (connp != NULL) {
21101 			io->ipsec_out_multicast_loop =
21102 			    connp->conn_multicast_loop;
21103 			io->ipsec_out_dontroute = connp->conn_dontroute;
21104 			io->ipsec_out_zoneid = connp->conn_zoneid;
21105 		}
21106 		/*
21107 		 * If the application uses IP_MULTICAST_IF with
21108 		 * different logical addresses of the same ILL, we
21109 		 * need to make sure that the soruce address of
21110 		 * the packet matches the logical IP address used
21111 		 * in the option. We do it by initializing ipha_src
21112 		 * here. This should keep IPsec also happy as
21113 		 * when we return from IPsec processing, we don't
21114 		 * have to worry about getting the right address on
21115 		 * the packet. Thus it is sufficient to look for
21116 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21117 		 * MATCH_IRE_IPIF.
21118 		 *
21119 		 * NOTE : We need to do it for non-secure case also as
21120 		 * this might go out secure if there is a global policy
21121 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
21122 		 * address, the source should be initialized already and
21123 		 * hence we won't be initializing here.
21124 		 *
21125 		 * As we do not have the ire yet, it is possible that
21126 		 * we set the source address here and then later discover
21127 		 * that the ire implies the source address to be assigned
21128 		 * through the RTF_SETSRC flag.
21129 		 * In that case, the setsrc variable will remind us
21130 		 * that overwritting the source address by the one
21131 		 * of the RTF_SETSRC-flagged ire is allowed.
21132 		 */
21133 		if (ipha->ipha_src == INADDR_ANY &&
21134 		    (connp == NULL || !connp->conn_unspec_src)) {
21135 			ipha->ipha_src = ipif->ipif_src_addr;
21136 			setsrc = RTF_SETSRC;
21137 		}
21138 		/*
21139 		 * Find an IRE which matches the destination and the outgoing
21140 		 * queue (i.e. the outgoing interface.)
21141 		 * For loopback use a unicast IP address for
21142 		 * the ire lookup.
21143 		 */
21144 		if (IS_LOOPBACK(ipif->ipif_ill))
21145 			dst = ipif->ipif_lcl_addr;
21146 
21147 		/*
21148 		 * If xmit_ill is set, we branch out to ip_newroute_ipif.
21149 		 * We don't need to lookup ire in ctable as the packet
21150 		 * needs to be sent to the destination through the specified
21151 		 * ill irrespective of ires in the cache table.
21152 		 */
21153 		ire = NULL;
21154 		if (xmit_ill == NULL) {
21155 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21156 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21157 		}
21158 
21159 		/*
21160 		 * refrele attach_ill as its not needed anymore.
21161 		 */
21162 		if (attach_ill != NULL) {
21163 			ill_refrele(attach_ill);
21164 			attach_ill = NULL;
21165 		}
21166 
21167 		if (ire == NULL) {
21168 			/*
21169 			 * Multicast loopback and multicast forwarding is
21170 			 * done in ip_wput_ire.
21171 			 *
21172 			 * Mark this packet to make it be delivered to
21173 			 * ip_wput_ire after the new ire has been
21174 			 * created.
21175 			 *
21176 			 * The call to ip_newroute_ipif takes into account
21177 			 * the setsrc reminder. In any case, we take care
21178 			 * of the RTF_MULTIRT flag.
21179 			 */
21180 			mp->b_prev = mp->b_next = NULL;
21181 			if (xmit_ill == NULL ||
21182 			    xmit_ill->ill_ipif_up_count > 0) {
21183 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21184 				    setsrc | RTF_MULTIRT, zoneid, infop);
21185 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21186 				    "ip_wput_end: q %p (%S)", q, "noire");
21187 			} else {
21188 				freemsg(first_mp);
21189 			}
21190 			ipif_refrele(ipif);
21191 			if (xmit_ill != NULL)
21192 				ill_refrele(xmit_ill);
21193 			if (need_decref)
21194 				CONN_DEC_REF(connp);
21195 			return;
21196 		}
21197 
21198 		ipif_refrele(ipif);
21199 		ipif = NULL;
21200 		ASSERT(xmit_ill == NULL);
21201 
21202 		/*
21203 		 * Honor the RTF_SETSRC flag for multicast packets,
21204 		 * if allowed by the setsrc reminder.
21205 		 */
21206 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21207 			ipha->ipha_src = ire->ire_src_addr;
21208 		}
21209 
21210 		/*
21211 		 * Unconditionally force the TTL to 1 for
21212 		 * multirouted multicast packets:
21213 		 * multirouted multicast should not cross
21214 		 * multicast routers.
21215 		 */
21216 		if (ire->ire_flags & RTF_MULTIRT) {
21217 			if (ipha->ipha_ttl > 1) {
21218 				ip2dbg(("ip_wput: forcing multicast "
21219 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21220 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21221 				ipha->ipha_ttl = 1;
21222 			}
21223 		}
21224 	} else {
21225 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
21226 		if ((ire != NULL) && (ire->ire_type &
21227 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21228 			ignore_dontroute = B_TRUE;
21229 			ignore_nexthop = B_TRUE;
21230 		}
21231 		if (ire != NULL) {
21232 			ire_refrele(ire);
21233 			ire = NULL;
21234 		}
21235 		/*
21236 		 * Guard against coming in from arp in which case conn is NULL.
21237 		 * Also guard against non M_DATA with dontroute set but
21238 		 * destined to local, loopback or broadcast addresses.
21239 		 */
21240 		if (connp != NULL && connp->conn_dontroute &&
21241 		    !ignore_dontroute) {
21242 dontroute:
21243 			/*
21244 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21245 			 * routing protocols from seeing false direct
21246 			 * connectivity.
21247 			 */
21248 			ipha->ipha_ttl = 1;
21249 
21250 			/* If suitable ipif not found, drop packet */
21251 			dst_ipif = ipif_lookup_onlink_addr(dst, zoneid, ipst);
21252 			if (dst_ipif == NULL) {
21253 noroute:
21254 				ip1dbg(("ip_wput: no route for dst using"
21255 				    " SO_DONTROUTE\n"));
21256 				BUMP_MIB(&ipst->ips_ip_mib,
21257 				    ipIfStatsOutNoRoutes);
21258 				mp->b_prev = mp->b_next = NULL;
21259 				if (first_mp == NULL)
21260 					first_mp = mp;
21261 				goto drop_pkt;
21262 			} else {
21263 				/*
21264 				 * If suitable ipif has been found, set
21265 				 * xmit_ill to the corresponding
21266 				 * ipif_ill because we'll be using the
21267 				 * send_from_ill logic below.
21268 				 */
21269 				ASSERT(xmit_ill == NULL);
21270 				xmit_ill = dst_ipif->ipif_ill;
21271 				mutex_enter(&xmit_ill->ill_lock);
21272 				if (!ILL_CAN_LOOKUP(xmit_ill)) {
21273 					mutex_exit(&xmit_ill->ill_lock);
21274 					xmit_ill = NULL;
21275 					ipif_refrele(dst_ipif);
21276 					goto noroute;
21277 				}
21278 				ill_refhold_locked(xmit_ill);
21279 				mutex_exit(&xmit_ill->ill_lock);
21280 				ipif_refrele(dst_ipif);
21281 			}
21282 		}
21283 		/*
21284 		 * If we are bound to IPIF_NOFAILOVER address, look for
21285 		 * an IRE_CACHE matching the ill.
21286 		 */
21287 send_from_ill:
21288 		if (attach_ill != NULL) {
21289 			ipif_t	*attach_ipif;
21290 
21291 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21292 
21293 			/*
21294 			 * Check if we need an ire that will not be
21295 			 * looked up by anybody else i.e. HIDDEN.
21296 			 */
21297 			if (ill_is_probeonly(attach_ill)) {
21298 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21299 			}
21300 
21301 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
21302 			if (attach_ipif == NULL) {
21303 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
21304 				goto discard_pkt;
21305 			}
21306 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
21307 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21308 			ipif_refrele(attach_ipif);
21309 		} else if (xmit_ill != NULL) {
21310 			ipif_t *ipif;
21311 
21312 			/*
21313 			 * Mark this packet as originated locally
21314 			 */
21315 			mp->b_prev = mp->b_next = NULL;
21316 
21317 			/*
21318 			 * Could be SO_DONTROUTE case also.
21319 			 * Verify that at least one ipif is up on the ill.
21320 			 */
21321 			if (xmit_ill->ill_ipif_up_count == 0) {
21322 				ip1dbg(("ip_output: xmit_ill %s is down\n",
21323 				    xmit_ill->ill_name));
21324 				goto drop_pkt;
21325 			}
21326 
21327 			ipif = ipif_get_next_ipif(NULL, xmit_ill);
21328 			if (ipif == NULL) {
21329 				ip1dbg(("ip_output: xmit_ill %s NULL ipif\n",
21330 				    xmit_ill->ill_name));
21331 				goto drop_pkt;
21332 			}
21333 
21334 			/*
21335 			 * Look for a ire that is part of the group,
21336 			 * if found use it else call ip_newroute_ipif.
21337 			 * IPCL_ZONEID is not used for matching because
21338 			 * IP_ALLZONES option is valid only when the
21339 			 * ill is accessible from all zones i.e has a
21340 			 * valid ipif in all zones.
21341 			 */
21342 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21343 			ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21344 			    MBLK_GETLABEL(mp), match_flags, ipst);
21345 			/*
21346 			 * If an ire exists use it or else create
21347 			 * an ire but don't add it to the cache.
21348 			 * Adding an ire may cause issues with
21349 			 * asymmetric routing.
21350 			 * In case of multiroute always act as if
21351 			 * ire does not exist.
21352 			 */
21353 			if (ire == NULL || ire->ire_flags & RTF_MULTIRT) {
21354 				if (ire != NULL)
21355 					ire_refrele(ire);
21356 				ip_newroute_ipif(q, first_mp, ipif,
21357 				    dst, connp, 0, zoneid, infop);
21358 				ipif_refrele(ipif);
21359 				ip1dbg(("ip_output: xmit_ill via %s\n",
21360 				    xmit_ill->ill_name));
21361 				ill_refrele(xmit_ill);
21362 				if (need_decref)
21363 					CONN_DEC_REF(connp);
21364 				return;
21365 			}
21366 			ipif_refrele(ipif);
21367 		} else if (ip_nexthop || (connp != NULL &&
21368 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21369 			if (!ip_nexthop) {
21370 				ip_nexthop = B_TRUE;
21371 				nexthop_addr = connp->conn_nexthop_v4;
21372 			}
21373 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21374 			    MATCH_IRE_GW;
21375 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21376 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21377 		} else {
21378 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp),
21379 			    ipst);
21380 		}
21381 		if (!ire) {
21382 			/*
21383 			 * Make sure we don't load spread if this
21384 			 * is IPIF_NOFAILOVER case.
21385 			 */
21386 			if ((attach_ill != NULL) ||
21387 			    (ip_nexthop && !ignore_nexthop)) {
21388 				if (mctl_present) {
21389 					io = (ipsec_out_t *)first_mp->b_rptr;
21390 					ASSERT(first_mp->b_datap->db_type ==
21391 					    M_CTL);
21392 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21393 				} else {
21394 					ASSERT(mp == first_mp);
21395 					first_mp = allocb(
21396 					    sizeof (ipsec_info_t), BPRI_HI);
21397 					if (first_mp == NULL) {
21398 						first_mp = mp;
21399 						goto discard_pkt;
21400 					}
21401 					first_mp->b_datap->db_type = M_CTL;
21402 					first_mp->b_wptr +=
21403 					    sizeof (ipsec_info_t);
21404 					/* ipsec_out_secure is B_FALSE now */
21405 					bzero(first_mp->b_rptr,
21406 					    sizeof (ipsec_info_t));
21407 					io = (ipsec_out_t *)first_mp->b_rptr;
21408 					io->ipsec_out_type = IPSEC_OUT;
21409 					io->ipsec_out_len =
21410 					    sizeof (ipsec_out_t);
21411 					io->ipsec_out_use_global_policy =
21412 					    B_TRUE;
21413 					io->ipsec_out_ns = ipst->ips_netstack;
21414 					first_mp->b_cont = mp;
21415 					mctl_present = B_TRUE;
21416 				}
21417 				if (attach_ill != NULL) {
21418 					io->ipsec_out_ill_index = attach_ill->
21419 					    ill_phyint->phyint_ifindex;
21420 					io->ipsec_out_attach_if = B_TRUE;
21421 				} else {
21422 					io->ipsec_out_ip_nexthop = ip_nexthop;
21423 					io->ipsec_out_nexthop_addr =
21424 					    nexthop_addr;
21425 				}
21426 			}
21427 noirefound:
21428 			/*
21429 			 * Mark this packet as having originated on
21430 			 * this machine.  This will be noted in
21431 			 * ire_add_then_send, which needs to know
21432 			 * whether to run it back through ip_wput or
21433 			 * ip_rput following successful resolution.
21434 			 */
21435 			mp->b_prev = NULL;
21436 			mp->b_next = NULL;
21437 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21438 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21439 			    "ip_wput_end: q %p (%S)", q, "newroute");
21440 			if (attach_ill != NULL)
21441 				ill_refrele(attach_ill);
21442 			if (xmit_ill != NULL)
21443 				ill_refrele(xmit_ill);
21444 			if (need_decref)
21445 				CONN_DEC_REF(connp);
21446 			return;
21447 		}
21448 	}
21449 
21450 	/* We now know where we are going with it. */
21451 
21452 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21453 	    "ip_wput_end: q %p (%S)", q, "end");
21454 
21455 	/*
21456 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21457 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21458 	 */
21459 	if (ire->ire_flags & RTF_MULTIRT) {
21460 		/*
21461 		 * Force the TTL of multirouted packets if required.
21462 		 * The TTL of such packets is bounded by the
21463 		 * ip_multirt_ttl ndd variable.
21464 		 */
21465 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21466 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21467 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21468 			    "(was %d), dst 0x%08x\n",
21469 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21470 			    ntohl(ire->ire_addr)));
21471 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21472 		}
21473 		/*
21474 		 * At this point, we check to see if there are any pending
21475 		 * unresolved routes. ire_multirt_resolvable()
21476 		 * checks in O(n) that all IRE_OFFSUBNET ire
21477 		 * entries for the packet's destination and
21478 		 * flagged RTF_MULTIRT are currently resolved.
21479 		 * If some remain unresolved, we make a copy
21480 		 * of the current message. It will be used
21481 		 * to initiate additional route resolutions.
21482 		 */
21483 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21484 		    MBLK_GETLABEL(first_mp), ipst);
21485 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21486 		    "multirt_need_resolve %d, first_mp %p\n",
21487 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21488 		if (multirt_need_resolve) {
21489 			copy_mp = copymsg(first_mp);
21490 			if (copy_mp != NULL) {
21491 				MULTIRT_DEBUG_TAG(copy_mp);
21492 			}
21493 		}
21494 	}
21495 
21496 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21497 	/*
21498 	 * Try to resolve another multiroute if
21499 	 * ire_multirt_resolvable() deemed it necessary.
21500 	 * At this point, we need to distinguish
21501 	 * multicasts from other packets. For multicasts,
21502 	 * we call ip_newroute_ipif() and request that both
21503 	 * multirouting and setsrc flags are checked.
21504 	 */
21505 	if (copy_mp != NULL) {
21506 		if (CLASSD(dst)) {
21507 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21508 			if (ipif) {
21509 				ASSERT(infop->ip_opt_ill_index == 0);
21510 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21511 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21512 				ipif_refrele(ipif);
21513 			} else {
21514 				MULTIRT_DEBUG_UNTAG(copy_mp);
21515 				freemsg(copy_mp);
21516 				copy_mp = NULL;
21517 			}
21518 		} else {
21519 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21520 		}
21521 	}
21522 	if (attach_ill != NULL)
21523 		ill_refrele(attach_ill);
21524 	if (xmit_ill != NULL)
21525 		ill_refrele(xmit_ill);
21526 	if (need_decref)
21527 		CONN_DEC_REF(connp);
21528 	return;
21529 
21530 icmp_parameter_problem:
21531 	/* could not have originated externally */
21532 	ASSERT(mp->b_prev == NULL);
21533 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21534 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21535 		/* it's the IP header length that's in trouble */
21536 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21537 		first_mp = NULL;
21538 	}
21539 
21540 discard_pkt:
21541 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21542 drop_pkt:
21543 	ip1dbg(("ip_wput: dropped packet\n"));
21544 	if (ire != NULL)
21545 		ire_refrele(ire);
21546 	if (need_decref)
21547 		CONN_DEC_REF(connp);
21548 	freemsg(first_mp);
21549 	if (attach_ill != NULL)
21550 		ill_refrele(attach_ill);
21551 	if (xmit_ill != NULL)
21552 		ill_refrele(xmit_ill);
21553 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21554 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21555 }
21556 
21557 /*
21558  * If this is a conn_t queue, then we pass in the conn. This includes the
21559  * zoneid.
21560  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21561  * in which case we use the global zoneid since those are all part of
21562  * the global zone.
21563  */
21564 void
21565 ip_wput(queue_t *q, mblk_t *mp)
21566 {
21567 	if (CONN_Q(q))
21568 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21569 	else
21570 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21571 }
21572 
21573 /*
21574  *
21575  * The following rules must be observed when accessing any ipif or ill
21576  * that has been cached in the conn. Typically conn_nofailover_ill,
21577  * conn_outgoing_ill, conn_multicast_ipif and conn_multicast_ill.
21578  *
21579  * Access: The ipif or ill pointed to from the conn can be accessed under
21580  * the protection of the conn_lock or after it has been refheld under the
21581  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21582  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21583  * The reason for this is that a concurrent unplumb could actually be
21584  * cleaning up these cached pointers by walking the conns and might have
21585  * finished cleaning up the conn in question. The macros check that an
21586  * unplumb has not yet started on the ipif or ill.
21587  *
21588  * Caching: An ipif or ill pointer may be cached in the conn only after
21589  * making sure that an unplumb has not started. So the caching is done
21590  * while holding both the conn_lock and the ill_lock and after using the
21591  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21592  * flag before starting the cleanup of conns.
21593  *
21594  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21595  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21596  * or a reference to the ipif or a reference to an ire that references the
21597  * ipif. An ipif does not change its ill except for failover/failback. Since
21598  * failover/failback happens only after bringing down the ipif and making sure
21599  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
21600  * the above holds.
21601  */
21602 ipif_t *
21603 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21604 {
21605 	ipif_t	*ipif;
21606 	ill_t	*ill;
21607 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21608 
21609 	*err = 0;
21610 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21611 	mutex_enter(&connp->conn_lock);
21612 	ipif = *ipifp;
21613 	if (ipif != NULL) {
21614 		ill = ipif->ipif_ill;
21615 		mutex_enter(&ill->ill_lock);
21616 		if (IPIF_CAN_LOOKUP(ipif)) {
21617 			ipif_refhold_locked(ipif);
21618 			mutex_exit(&ill->ill_lock);
21619 			mutex_exit(&connp->conn_lock);
21620 			rw_exit(&ipst->ips_ill_g_lock);
21621 			return (ipif);
21622 		} else {
21623 			*err = IPIF_LOOKUP_FAILED;
21624 		}
21625 		mutex_exit(&ill->ill_lock);
21626 	}
21627 	mutex_exit(&connp->conn_lock);
21628 	rw_exit(&ipst->ips_ill_g_lock);
21629 	return (NULL);
21630 }
21631 
21632 ill_t *
21633 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21634 {
21635 	ill_t	*ill;
21636 
21637 	*err = 0;
21638 	mutex_enter(&connp->conn_lock);
21639 	ill = *illp;
21640 	if (ill != NULL) {
21641 		mutex_enter(&ill->ill_lock);
21642 		if (ILL_CAN_LOOKUP(ill)) {
21643 			ill_refhold_locked(ill);
21644 			mutex_exit(&ill->ill_lock);
21645 			mutex_exit(&connp->conn_lock);
21646 			return (ill);
21647 		} else {
21648 			*err = ILL_LOOKUP_FAILED;
21649 		}
21650 		mutex_exit(&ill->ill_lock);
21651 	}
21652 	mutex_exit(&connp->conn_lock);
21653 	return (NULL);
21654 }
21655 
21656 static int
21657 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21658 {
21659 	ill_t	*ill;
21660 
21661 	ill = ipif->ipif_ill;
21662 	mutex_enter(&connp->conn_lock);
21663 	mutex_enter(&ill->ill_lock);
21664 	if (IPIF_CAN_LOOKUP(ipif)) {
21665 		*ipifp = ipif;
21666 		mutex_exit(&ill->ill_lock);
21667 		mutex_exit(&connp->conn_lock);
21668 		return (0);
21669 	}
21670 	mutex_exit(&ill->ill_lock);
21671 	mutex_exit(&connp->conn_lock);
21672 	return (IPIF_LOOKUP_FAILED);
21673 }
21674 
21675 /*
21676  * This is called if the outbound datagram needs fragmentation.
21677  *
21678  * NOTE : This function does not ire_refrele the ire argument passed in.
21679  */
21680 static void
21681 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21682     ip_stack_t *ipst)
21683 {
21684 	ipha_t		*ipha;
21685 	mblk_t		*mp;
21686 	uint32_t	v_hlen_tos_len;
21687 	uint32_t	max_frag;
21688 	uint32_t	frag_flag;
21689 	boolean_t	dont_use;
21690 
21691 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21692 		mp = ipsec_mp->b_cont;
21693 	} else {
21694 		mp = ipsec_mp;
21695 	}
21696 
21697 	ipha = (ipha_t *)mp->b_rptr;
21698 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21699 
21700 #ifdef	_BIG_ENDIAN
21701 #define	V_HLEN	(v_hlen_tos_len >> 24)
21702 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21703 #else
21704 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21705 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21706 #endif
21707 
21708 #ifndef SPEED_BEFORE_SAFETY
21709 	/*
21710 	 * Check that ipha_length is consistent with
21711 	 * the mblk length
21712 	 */
21713 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21714 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21715 		    LENGTH, msgdsize(mp)));
21716 		freemsg(ipsec_mp);
21717 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21718 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21719 		    "packet length mismatch");
21720 		return;
21721 	}
21722 #endif
21723 	/*
21724 	 * Don't use frag_flag if pre-built packet or source
21725 	 * routed or if multicast (since multicast packets do not solicit
21726 	 * ICMP "packet too big" messages). Get the values of
21727 	 * max_frag and frag_flag atomically by acquiring the
21728 	 * ire_lock.
21729 	 */
21730 	mutex_enter(&ire->ire_lock);
21731 	max_frag = ire->ire_max_frag;
21732 	frag_flag = ire->ire_frag_flag;
21733 	mutex_exit(&ire->ire_lock);
21734 
21735 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21736 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21737 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21738 
21739 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21740 	    (dont_use ? 0 : frag_flag), zoneid, ipst);
21741 }
21742 
21743 /*
21744  * Used for deciding the MSS size for the upper layer. Thus
21745  * we need to check the outbound policy values in the conn.
21746  */
21747 int
21748 conn_ipsec_length(conn_t *connp)
21749 {
21750 	ipsec_latch_t *ipl;
21751 
21752 	ipl = connp->conn_latch;
21753 	if (ipl == NULL)
21754 		return (0);
21755 
21756 	if (ipl->ipl_out_policy == NULL)
21757 		return (0);
21758 
21759 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21760 }
21761 
21762 /*
21763  * Returns an estimate of the IPsec headers size. This is used if
21764  * we don't want to call into IPsec to get the exact size.
21765  */
21766 int
21767 ipsec_out_extra_length(mblk_t *ipsec_mp)
21768 {
21769 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21770 	ipsec_action_t *a;
21771 
21772 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21773 	if (!io->ipsec_out_secure)
21774 		return (0);
21775 
21776 	a = io->ipsec_out_act;
21777 
21778 	if (a == NULL) {
21779 		ASSERT(io->ipsec_out_policy != NULL);
21780 		a = io->ipsec_out_policy->ipsp_act;
21781 	}
21782 	ASSERT(a != NULL);
21783 
21784 	return (a->ipa_ovhd);
21785 }
21786 
21787 /*
21788  * Returns an estimate of the IPsec headers size. This is used if
21789  * we don't want to call into IPsec to get the exact size.
21790  */
21791 int
21792 ipsec_in_extra_length(mblk_t *ipsec_mp)
21793 {
21794 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21795 	ipsec_action_t *a;
21796 
21797 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21798 
21799 	a = ii->ipsec_in_action;
21800 	return (a == NULL ? 0 : a->ipa_ovhd);
21801 }
21802 
21803 /*
21804  * If there are any source route options, return the true final
21805  * destination. Otherwise, return the destination.
21806  */
21807 ipaddr_t
21808 ip_get_dst(ipha_t *ipha)
21809 {
21810 	ipoptp_t	opts;
21811 	uchar_t		*opt;
21812 	uint8_t		optval;
21813 	uint8_t		optlen;
21814 	ipaddr_t	dst;
21815 	uint32_t off;
21816 
21817 	dst = ipha->ipha_dst;
21818 
21819 	if (IS_SIMPLE_IPH(ipha))
21820 		return (dst);
21821 
21822 	for (optval = ipoptp_first(&opts, ipha);
21823 	    optval != IPOPT_EOL;
21824 	    optval = ipoptp_next(&opts)) {
21825 		opt = opts.ipoptp_cur;
21826 		optlen = opts.ipoptp_len;
21827 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21828 		switch (optval) {
21829 		case IPOPT_SSRR:
21830 		case IPOPT_LSRR:
21831 			off = opt[IPOPT_OFFSET];
21832 			/*
21833 			 * If one of the conditions is true, it means
21834 			 * end of options and dst already has the right
21835 			 * value.
21836 			 */
21837 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21838 				off = optlen - IP_ADDR_LEN;
21839 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21840 			}
21841 			return (dst);
21842 		default:
21843 			break;
21844 		}
21845 	}
21846 
21847 	return (dst);
21848 }
21849 
21850 mblk_t *
21851 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21852     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21853 {
21854 	ipsec_out_t	*io;
21855 	mblk_t		*first_mp;
21856 	boolean_t policy_present;
21857 	ip_stack_t	*ipst;
21858 	ipsec_stack_t	*ipss;
21859 
21860 	ASSERT(ire != NULL);
21861 	ipst = ire->ire_ipst;
21862 	ipss = ipst->ips_netstack->netstack_ipsec;
21863 
21864 	first_mp = mp;
21865 	if (mp->b_datap->db_type == M_CTL) {
21866 		io = (ipsec_out_t *)first_mp->b_rptr;
21867 		/*
21868 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21869 		 *
21870 		 * 1) There is per-socket policy (including cached global
21871 		 *    policy) or a policy on the IP-in-IP tunnel.
21872 		 * 2) There is no per-socket policy, but it is
21873 		 *    a multicast packet that needs to go out
21874 		 *    on a specific interface. This is the case
21875 		 *    where (ip_wput and ip_wput_multicast) attaches
21876 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21877 		 *
21878 		 * In case (2) we check with global policy to
21879 		 * see if there is a match and set the ill_index
21880 		 * appropriately so that we can lookup the ire
21881 		 * properly in ip_wput_ipsec_out.
21882 		 */
21883 
21884 		/*
21885 		 * ipsec_out_use_global_policy is set to B_FALSE
21886 		 * in ipsec_in_to_out(). Refer to that function for
21887 		 * details.
21888 		 */
21889 		if ((io->ipsec_out_latch == NULL) &&
21890 		    (io->ipsec_out_use_global_policy)) {
21891 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21892 			    ire, connp, unspec_src, zoneid));
21893 		}
21894 		if (!io->ipsec_out_secure) {
21895 			/*
21896 			 * If this is not a secure packet, drop
21897 			 * the IPSEC_OUT mp and treat it as a clear
21898 			 * packet. This happens when we are sending
21899 			 * a ICMP reply back to a clear packet. See
21900 			 * ipsec_in_to_out() for details.
21901 			 */
21902 			mp = first_mp->b_cont;
21903 			freeb(first_mp);
21904 		}
21905 		return (mp);
21906 	}
21907 	/*
21908 	 * See whether we need to attach a global policy here. We
21909 	 * don't depend on the conn (as it could be null) for deciding
21910 	 * what policy this datagram should go through because it
21911 	 * should have happened in ip_wput if there was some
21912 	 * policy. This normally happens for connections which are not
21913 	 * fully bound preventing us from caching policies in
21914 	 * ip_bind. Packets coming from the TCP listener/global queue
21915 	 * - which are non-hard_bound - could also be affected by
21916 	 * applying policy here.
21917 	 *
21918 	 * If this packet is coming from tcp global queue or listener,
21919 	 * we will be applying policy here.  This may not be *right*
21920 	 * if these packets are coming from the detached connection as
21921 	 * it could have gone in clear before. This happens only if a
21922 	 * TCP connection started when there is no policy and somebody
21923 	 * added policy before it became detached. Thus packets of the
21924 	 * detached connection could go out secure and the other end
21925 	 * would drop it because it will be expecting in clear. The
21926 	 * converse is not true i.e if somebody starts a TCP
21927 	 * connection and deletes the policy, all the packets will
21928 	 * still go out with the policy that existed before deleting
21929 	 * because ip_unbind sends up policy information which is used
21930 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21931 	 * TCP to attach a dummy IPSEC_OUT and set
21932 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21933 	 * affect performance for normal cases, we are not doing it.
21934 	 * Thus, set policy before starting any TCP connections.
21935 	 *
21936 	 * NOTE - We might apply policy even for a hard bound connection
21937 	 * - for which we cached policy in ip_bind - if somebody added
21938 	 * global policy after we inherited the policy in ip_bind.
21939 	 * This means that the packets that were going out in clear
21940 	 * previously would start going secure and hence get dropped
21941 	 * on the other side. To fix this, TCP attaches a dummy
21942 	 * ipsec_out and make sure that we don't apply global policy.
21943 	 */
21944 	if (ipha != NULL)
21945 		policy_present = ipss->ipsec_outbound_v4_policy_present;
21946 	else
21947 		policy_present = ipss->ipsec_outbound_v6_policy_present;
21948 	if (!policy_present)
21949 		return (mp);
21950 
21951 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21952 	    zoneid));
21953 }
21954 
21955 ire_t *
21956 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
21957 {
21958 	ipaddr_t addr;
21959 	ire_t *save_ire;
21960 	irb_t *irb;
21961 	ill_group_t *illgrp;
21962 	int	err;
21963 
21964 	save_ire = ire;
21965 	addr = ire->ire_addr;
21966 
21967 	ASSERT(ire->ire_type == IRE_BROADCAST);
21968 
21969 	illgrp = connp->conn_outgoing_ill->ill_group;
21970 	if (illgrp == NULL) {
21971 		*conn_outgoing_ill = conn_get_held_ill(connp,
21972 		    &connp->conn_outgoing_ill, &err);
21973 		if (err == ILL_LOOKUP_FAILED) {
21974 			ire_refrele(save_ire);
21975 			return (NULL);
21976 		}
21977 		return (save_ire);
21978 	}
21979 	/*
21980 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
21981 	 * If it is part of the group, we need to send on the ire
21982 	 * that has been cleared of IRE_MARK_NORECV and that belongs
21983 	 * to this group. This is okay as IP_BOUND_IF really means
21984 	 * any ill in the group. We depend on the fact that the
21985 	 * first ire in the group is always cleared of IRE_MARK_NORECV
21986 	 * if such an ire exists. This is possible only if you have
21987 	 * at least one ill in the group that has not failed.
21988 	 *
21989 	 * First get to the ire that matches the address and group.
21990 	 *
21991 	 * We don't look for an ire with a matching zoneid because a given zone
21992 	 * won't always have broadcast ires on all ills in the group.
21993 	 */
21994 	irb = ire->ire_bucket;
21995 	rw_enter(&irb->irb_lock, RW_READER);
21996 	if (ire->ire_marks & IRE_MARK_NORECV) {
21997 		/*
21998 		 * If the current zone only has an ire broadcast for this
21999 		 * address marked NORECV, the ire we want is ahead in the
22000 		 * bucket, so we look it up deliberately ignoring the zoneid.
22001 		 */
22002 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
22003 			if (ire->ire_addr != addr)
22004 				continue;
22005 			/* skip over deleted ires */
22006 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
22007 				continue;
22008 		}
22009 	}
22010 	while (ire != NULL) {
22011 		/*
22012 		 * If a new interface is coming up, we could end up
22013 		 * seeing the loopback ire and the non-loopback ire
22014 		 * may not have been added yet. So check for ire_stq
22015 		 */
22016 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
22017 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
22018 			break;
22019 		}
22020 		ire = ire->ire_next;
22021 	}
22022 	if (ire != NULL && ire->ire_addr == addr &&
22023 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
22024 		IRE_REFHOLD(ire);
22025 		rw_exit(&irb->irb_lock);
22026 		ire_refrele(save_ire);
22027 		*conn_outgoing_ill = ire_to_ill(ire);
22028 		/*
22029 		 * Refhold the ill to make the conn_outgoing_ill
22030 		 * independent of the ire. ip_wput_ire goes in a loop
22031 		 * and may refrele the ire. Since we have an ire at this
22032 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
22033 		 */
22034 		ill_refhold(*conn_outgoing_ill);
22035 		return (ire);
22036 	}
22037 	rw_exit(&irb->irb_lock);
22038 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
22039 	/*
22040 	 * If we can't find a suitable ire, return the original ire.
22041 	 */
22042 	return (save_ire);
22043 }
22044 
22045 /*
22046  * This function does the ire_refrele of the ire passed in as the
22047  * argument. As this function looks up more ires i.e broadcast ires,
22048  * it needs to REFRELE them. Currently, for simplicity we don't
22049  * differentiate the one passed in and looked up here. We always
22050  * REFRELE.
22051  * IPQoS Notes:
22052  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
22053  * IPsec packets are done in ipsec_out_process.
22054  *
22055  */
22056 void
22057 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
22058     zoneid_t zoneid)
22059 {
22060 	ipha_t		*ipha;
22061 #define	rptr	((uchar_t *)ipha)
22062 	queue_t		*stq;
22063 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
22064 	uint32_t	v_hlen_tos_len;
22065 	uint32_t	ttl_protocol;
22066 	ipaddr_t	src;
22067 	ipaddr_t	dst;
22068 	uint32_t	cksum;
22069 	ipaddr_t	orig_src;
22070 	ire_t		*ire1;
22071 	mblk_t		*next_mp;
22072 	uint_t		hlen;
22073 	uint16_t	*up;
22074 	uint32_t	max_frag = ire->ire_max_frag;
22075 	ill_t		*ill = ire_to_ill(ire);
22076 	int		clusterwide;
22077 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
22078 	int		ipsec_len;
22079 	mblk_t		*first_mp;
22080 	ipsec_out_t	*io;
22081 	boolean_t	conn_dontroute;		/* conn value for multicast */
22082 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
22083 	boolean_t	multicast_forward;	/* Should we forward ? */
22084 	boolean_t	unspec_src;
22085 	ill_t		*conn_outgoing_ill = NULL;
22086 	ill_t		*ire_ill;
22087 	ill_t		*ire1_ill;
22088 	ill_t		*out_ill;
22089 	uint32_t 	ill_index = 0;
22090 	boolean_t	multirt_send = B_FALSE;
22091 	int		err;
22092 	ipxmit_state_t	pktxmit_state;
22093 	ip_stack_t	*ipst = ire->ire_ipst;
22094 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22095 
22096 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22097 	    "ip_wput_ire_start: q %p", q);
22098 
22099 	multicast_forward = B_FALSE;
22100 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22101 
22102 	if (ire->ire_flags & RTF_MULTIRT) {
22103 		/*
22104 		 * Multirouting case. The bucket where ire is stored
22105 		 * probably holds other RTF_MULTIRT flagged ire
22106 		 * to the destination. In this call to ip_wput_ire,
22107 		 * we attempt to send the packet through all
22108 		 * those ires. Thus, we first ensure that ire is the
22109 		 * first RTF_MULTIRT ire in the bucket,
22110 		 * before walking the ire list.
22111 		 */
22112 		ire_t *first_ire;
22113 		irb_t *irb = ire->ire_bucket;
22114 		ASSERT(irb != NULL);
22115 
22116 		/* Make sure we do not omit any multiroute ire. */
22117 		IRB_REFHOLD(irb);
22118 		for (first_ire = irb->irb_ire;
22119 		    first_ire != NULL;
22120 		    first_ire = first_ire->ire_next) {
22121 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22122 			    (first_ire->ire_addr == ire->ire_addr) &&
22123 			    !(first_ire->ire_marks &
22124 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
22125 				break;
22126 			}
22127 		}
22128 
22129 		if ((first_ire != NULL) && (first_ire != ire)) {
22130 			IRE_REFHOLD(first_ire);
22131 			ire_refrele(ire);
22132 			ire = first_ire;
22133 			ill = ire_to_ill(ire);
22134 		}
22135 		IRB_REFRELE(irb);
22136 	}
22137 
22138 	/*
22139 	 * conn_outgoing_ill variable is used only in the broadcast loop.
22140 	 * for performance we don't grab the mutexs in the fastpath
22141 	 */
22142 	if ((connp != NULL) &&
22143 	    (ire->ire_type == IRE_BROADCAST) &&
22144 	    ((connp->conn_nofailover_ill != NULL) ||
22145 	    (connp->conn_outgoing_ill != NULL))) {
22146 		/*
22147 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
22148 		 * option. So, see if this endpoint is bound to a
22149 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
22150 		 * that if the interface is failed, we will still send
22151 		 * the packet on the same ill which is what we want.
22152 		 */
22153 		conn_outgoing_ill = conn_get_held_ill(connp,
22154 		    &connp->conn_nofailover_ill, &err);
22155 		if (err == ILL_LOOKUP_FAILED) {
22156 			ire_refrele(ire);
22157 			freemsg(mp);
22158 			return;
22159 		}
22160 		if (conn_outgoing_ill == NULL) {
22161 			/*
22162 			 * Choose a good ill in the group to send the
22163 			 * packets on.
22164 			 */
22165 			ire = conn_set_outgoing_ill(connp, ire,
22166 			    &conn_outgoing_ill);
22167 			if (ire == NULL) {
22168 				freemsg(mp);
22169 				return;
22170 			}
22171 		}
22172 	}
22173 
22174 	if (mp->b_datap->db_type != M_CTL) {
22175 		ipha = (ipha_t *)mp->b_rptr;
22176 	} else {
22177 		io = (ipsec_out_t *)mp->b_rptr;
22178 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22179 		ASSERT(zoneid == io->ipsec_out_zoneid);
22180 		ASSERT(zoneid != ALL_ZONES);
22181 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22182 		dst = ipha->ipha_dst;
22183 		/*
22184 		 * For the multicast case, ipsec_out carries conn_dontroute and
22185 		 * conn_multicast_loop as conn may not be available here. We
22186 		 * need this for multicast loopback and forwarding which is done
22187 		 * later in the code.
22188 		 */
22189 		if (CLASSD(dst)) {
22190 			conn_dontroute = io->ipsec_out_dontroute;
22191 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22192 			/*
22193 			 * If conn_dontroute is not set or conn_multicast_loop
22194 			 * is set, we need to do forwarding/loopback. For
22195 			 * datagrams from ip_wput_multicast, conn_dontroute is
22196 			 * set to B_TRUE and conn_multicast_loop is set to
22197 			 * B_FALSE so that we neither do forwarding nor
22198 			 * loopback.
22199 			 */
22200 			if (!conn_dontroute || conn_multicast_loop)
22201 				multicast_forward = B_TRUE;
22202 		}
22203 	}
22204 
22205 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22206 	    ire->ire_zoneid != ALL_ZONES) {
22207 		/*
22208 		 * When a zone sends a packet to another zone, we try to deliver
22209 		 * the packet under the same conditions as if the destination
22210 		 * was a real node on the network. To do so, we look for a
22211 		 * matching route in the forwarding table.
22212 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22213 		 * ip_newroute() does.
22214 		 * Note that IRE_LOCAL are special, since they are used
22215 		 * when the zoneid doesn't match in some cases. This means that
22216 		 * we need to handle ipha_src differently since ire_src_addr
22217 		 * belongs to the receiving zone instead of the sending zone.
22218 		 * When ip_restrict_interzone_loopback is set, then
22219 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22220 		 * for loopback between zones when the logical "Ethernet" would
22221 		 * have looped them back.
22222 		 */
22223 		ire_t *src_ire;
22224 
22225 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22226 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22227 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22228 		if (src_ire != NULL &&
22229 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22230 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22231 		    ire_local_same_ill_group(ire, src_ire))) {
22232 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22233 				ipha->ipha_src = src_ire->ire_src_addr;
22234 			ire_refrele(src_ire);
22235 		} else {
22236 			ire_refrele(ire);
22237 			if (conn_outgoing_ill != NULL)
22238 				ill_refrele(conn_outgoing_ill);
22239 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22240 			if (src_ire != NULL) {
22241 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22242 					ire_refrele(src_ire);
22243 					freemsg(mp);
22244 					return;
22245 				}
22246 				ire_refrele(src_ire);
22247 			}
22248 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22249 				/* Failed */
22250 				freemsg(mp);
22251 				return;
22252 			}
22253 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22254 			    ipst);
22255 			return;
22256 		}
22257 	}
22258 
22259 	if (mp->b_datap->db_type == M_CTL ||
22260 	    ipss->ipsec_outbound_v4_policy_present) {
22261 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22262 		    unspec_src, zoneid);
22263 		if (mp == NULL) {
22264 			ire_refrele(ire);
22265 			if (conn_outgoing_ill != NULL)
22266 				ill_refrele(conn_outgoing_ill);
22267 			return;
22268 		}
22269 		/*
22270 		 * Trusted Extensions supports all-zones interfaces, so
22271 		 * zoneid == ALL_ZONES is valid, but IPsec maps ALL_ZONES to
22272 		 * the global zone.
22273 		 */
22274 		if (zoneid == ALL_ZONES && mp->b_datap->db_type == M_CTL) {
22275 			io = (ipsec_out_t *)mp->b_rptr;
22276 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
22277 			zoneid = io->ipsec_out_zoneid;
22278 		}
22279 	}
22280 
22281 	first_mp = mp;
22282 	ipsec_len = 0;
22283 
22284 	if (first_mp->b_datap->db_type == M_CTL) {
22285 		io = (ipsec_out_t *)first_mp->b_rptr;
22286 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22287 		mp = first_mp->b_cont;
22288 		ipsec_len = ipsec_out_extra_length(first_mp);
22289 		ASSERT(ipsec_len >= 0);
22290 		/* We already picked up the zoneid from the M_CTL above */
22291 		ASSERT(zoneid == io->ipsec_out_zoneid);
22292 		ASSERT(zoneid != ALL_ZONES);
22293 
22294 		/*
22295 		 * Drop M_CTL here if IPsec processing is not needed.
22296 		 * (Non-IPsec use of M_CTL extracted any information it
22297 		 * needed above).
22298 		 */
22299 		if (ipsec_len == 0) {
22300 			freeb(first_mp);
22301 			first_mp = mp;
22302 		}
22303 	}
22304 
22305 	/*
22306 	 * Fast path for ip_wput_ire
22307 	 */
22308 
22309 	ipha = (ipha_t *)mp->b_rptr;
22310 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22311 	dst = ipha->ipha_dst;
22312 
22313 	/*
22314 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22315 	 * if the socket is a SOCK_RAW type. The transport checksum should
22316 	 * be provided in the pre-built packet, so we don't need to compute it.
22317 	 * Also, other application set flags, like DF, should not be altered.
22318 	 * Other transport MUST pass down zero.
22319 	 */
22320 	ip_hdr_included = ipha->ipha_ident;
22321 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22322 
22323 	if (CLASSD(dst)) {
22324 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22325 		    ntohl(dst),
22326 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22327 		    ntohl(ire->ire_addr)));
22328 	}
22329 
22330 /* Macros to extract header fields from data already in registers */
22331 #ifdef	_BIG_ENDIAN
22332 #define	V_HLEN	(v_hlen_tos_len >> 24)
22333 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22334 #define	PROTO	(ttl_protocol & 0xFF)
22335 #else
22336 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22337 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22338 #define	PROTO	(ttl_protocol >> 8)
22339 #endif
22340 
22341 
22342 	orig_src = src = ipha->ipha_src;
22343 	/* (The loop back to "another" is explained down below.) */
22344 another:;
22345 	/*
22346 	 * Assign an ident value for this packet.  We assign idents on
22347 	 * a per destination basis out of the IRE.  There could be
22348 	 * other threads targeting the same destination, so we have to
22349 	 * arrange for a atomic increment.  Note that we use a 32-bit
22350 	 * atomic add because it has better performance than its
22351 	 * 16-bit sibling.
22352 	 *
22353 	 * If running in cluster mode and if the source address
22354 	 * belongs to a replicated service then vector through
22355 	 * cl_inet_ipident vector to allocate ip identifier
22356 	 * NOTE: This is a contract private interface with the
22357 	 * clustering group.
22358 	 */
22359 	clusterwide = 0;
22360 	if (cl_inet_ipident) {
22361 		ASSERT(cl_inet_isclusterwide);
22362 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
22363 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
22364 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
22365 			    AF_INET, (uint8_t *)(uintptr_t)src,
22366 			    (uint8_t *)(uintptr_t)dst);
22367 			clusterwide = 1;
22368 		}
22369 	}
22370 	if (!clusterwide) {
22371 		ipha->ipha_ident =
22372 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22373 	}
22374 
22375 #ifndef _BIG_ENDIAN
22376 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22377 #endif
22378 
22379 	/*
22380 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22381 	 * This is needed to obey conn_unspec_src when packets go through
22382 	 * ip_newroute + arp.
22383 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22384 	 */
22385 	if (src == INADDR_ANY && !unspec_src) {
22386 		/*
22387 		 * Assign the appropriate source address from the IRE if none
22388 		 * was specified.
22389 		 */
22390 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22391 
22392 		/*
22393 		 * With IP multipathing, broadcast packets are sent on the ire
22394 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
22395 		 * the group. However, this ire might not be in the same zone so
22396 		 * we can't always use its source address. We look for a
22397 		 * broadcast ire in the same group and in the right zone.
22398 		 */
22399 		if (ire->ire_type == IRE_BROADCAST &&
22400 		    ire->ire_zoneid != zoneid) {
22401 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
22402 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
22403 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
22404 			if (src_ire != NULL) {
22405 				src = src_ire->ire_src_addr;
22406 				ire_refrele(src_ire);
22407 			} else {
22408 				ire_refrele(ire);
22409 				if (conn_outgoing_ill != NULL)
22410 					ill_refrele(conn_outgoing_ill);
22411 				freemsg(first_mp);
22412 				if (ill != NULL) {
22413 					BUMP_MIB(ill->ill_ip_mib,
22414 					    ipIfStatsOutDiscards);
22415 				} else {
22416 					BUMP_MIB(&ipst->ips_ip_mib,
22417 					    ipIfStatsOutDiscards);
22418 				}
22419 				return;
22420 			}
22421 		} else {
22422 			src = ire->ire_src_addr;
22423 		}
22424 
22425 		if (connp == NULL) {
22426 			ip1dbg(("ip_wput_ire: no connp and no src "
22427 			    "address for dst 0x%x, using src 0x%x\n",
22428 			    ntohl(dst),
22429 			    ntohl(src)));
22430 		}
22431 		ipha->ipha_src = src;
22432 	}
22433 	stq = ire->ire_stq;
22434 
22435 	/*
22436 	 * We only allow ire chains for broadcasts since there will
22437 	 * be multiple IRE_CACHE entries for the same multicast
22438 	 * address (one per ipif).
22439 	 */
22440 	next_mp = NULL;
22441 
22442 	/* broadcast packet */
22443 	if (ire->ire_type == IRE_BROADCAST)
22444 		goto broadcast;
22445 
22446 	/* loopback ? */
22447 	if (stq == NULL)
22448 		goto nullstq;
22449 
22450 	/* The ill_index for outbound ILL */
22451 	ill_index = Q_TO_INDEX(stq);
22452 
22453 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22454 	ttl_protocol = ((uint16_t *)ipha)[4];
22455 
22456 	/* pseudo checksum (do it in parts for IP header checksum) */
22457 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22458 
22459 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22460 		queue_t *dev_q = stq->q_next;
22461 
22462 		/* flow controlled */
22463 		if ((dev_q->q_next || dev_q->q_first) &&
22464 		    !canput(dev_q))
22465 			goto blocked;
22466 		if ((PROTO == IPPROTO_UDP) &&
22467 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22468 			hlen = (V_HLEN & 0xF) << 2;
22469 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22470 			if (*up != 0) {
22471 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22472 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22473 				/* Software checksum? */
22474 				if (DB_CKSUMFLAGS(mp) == 0) {
22475 					IP_STAT(ipst, ip_out_sw_cksum);
22476 					IP_STAT_UPDATE(ipst,
22477 					    ip_udp_out_sw_cksum_bytes,
22478 					    LENGTH - hlen);
22479 				}
22480 			}
22481 		}
22482 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22483 		hlen = (V_HLEN & 0xF) << 2;
22484 		if (PROTO == IPPROTO_TCP) {
22485 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22486 			/*
22487 			 * The packet header is processed once and for all, even
22488 			 * in the multirouting case. We disable hardware
22489 			 * checksum if the packet is multirouted, as it will be
22490 			 * replicated via several interfaces, and not all of
22491 			 * them may have this capability.
22492 			 */
22493 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22494 			    LENGTH, max_frag, ipsec_len, cksum);
22495 			/* Software checksum? */
22496 			if (DB_CKSUMFLAGS(mp) == 0) {
22497 				IP_STAT(ipst, ip_out_sw_cksum);
22498 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22499 				    LENGTH - hlen);
22500 			}
22501 		} else {
22502 			sctp_hdr_t	*sctph;
22503 
22504 			ASSERT(PROTO == IPPROTO_SCTP);
22505 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22506 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22507 			/*
22508 			 * Zero out the checksum field to ensure proper
22509 			 * checksum calculation.
22510 			 */
22511 			sctph->sh_chksum = 0;
22512 #ifdef	DEBUG
22513 			if (!skip_sctp_cksum)
22514 #endif
22515 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22516 		}
22517 	}
22518 
22519 	/*
22520 	 * If this is a multicast packet and originated from ip_wput
22521 	 * we need to do loopback and forwarding checks. If it comes
22522 	 * from ip_wput_multicast, we SHOULD not do this.
22523 	 */
22524 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22525 
22526 	/* checksum */
22527 	cksum += ttl_protocol;
22528 
22529 	/* fragment the packet */
22530 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22531 		goto fragmentit;
22532 	/*
22533 	 * Don't use frag_flag if packet is pre-built or source
22534 	 * routed or if multicast (since multicast packets do
22535 	 * not solicit ICMP "packet too big" messages).
22536 	 */
22537 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22538 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22539 	    !ip_source_route_included(ipha)) &&
22540 	    !CLASSD(ipha->ipha_dst))
22541 		ipha->ipha_fragment_offset_and_flags |=
22542 		    htons(ire->ire_frag_flag);
22543 
22544 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22545 		/* calculate IP header checksum */
22546 		cksum += ipha->ipha_ident;
22547 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22548 		cksum += ipha->ipha_fragment_offset_and_flags;
22549 
22550 		/* IP options present */
22551 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22552 		if (hlen)
22553 			goto checksumoptions;
22554 
22555 		/* calculate hdr checksum */
22556 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22557 		cksum = ~(cksum + (cksum >> 16));
22558 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22559 	}
22560 	if (ipsec_len != 0) {
22561 		/*
22562 		 * We will do the rest of the processing after
22563 		 * we come back from IPsec in ip_wput_ipsec_out().
22564 		 */
22565 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22566 
22567 		io = (ipsec_out_t *)first_mp->b_rptr;
22568 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
22569 		    ill_phyint->phyint_ifindex;
22570 
22571 		ipsec_out_process(q, first_mp, ire, ill_index);
22572 		ire_refrele(ire);
22573 		if (conn_outgoing_ill != NULL)
22574 			ill_refrele(conn_outgoing_ill);
22575 		return;
22576 	}
22577 
22578 	/*
22579 	 * In most cases, the emission loop below is entered only
22580 	 * once. Only in the case where the ire holds the
22581 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22582 	 * flagged ires in the bucket, and send the packet
22583 	 * through all crossed RTF_MULTIRT routes.
22584 	 */
22585 	if (ire->ire_flags & RTF_MULTIRT) {
22586 		multirt_send = B_TRUE;
22587 	}
22588 	do {
22589 		if (multirt_send) {
22590 			irb_t *irb;
22591 			/*
22592 			 * We are in a multiple send case, need to get
22593 			 * the next ire and make a duplicate of the packet.
22594 			 * ire1 holds here the next ire to process in the
22595 			 * bucket. If multirouting is expected,
22596 			 * any non-RTF_MULTIRT ire that has the
22597 			 * right destination address is ignored.
22598 			 */
22599 			irb = ire->ire_bucket;
22600 			ASSERT(irb != NULL);
22601 
22602 			IRB_REFHOLD(irb);
22603 			for (ire1 = ire->ire_next;
22604 			    ire1 != NULL;
22605 			    ire1 = ire1->ire_next) {
22606 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22607 					continue;
22608 				if (ire1->ire_addr != ire->ire_addr)
22609 					continue;
22610 				if (ire1->ire_marks &
22611 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22612 					continue;
22613 
22614 				/* Got one */
22615 				IRE_REFHOLD(ire1);
22616 				break;
22617 			}
22618 			IRB_REFRELE(irb);
22619 
22620 			if (ire1 != NULL) {
22621 				next_mp = copyb(mp);
22622 				if ((next_mp == NULL) ||
22623 				    ((mp->b_cont != NULL) &&
22624 				    ((next_mp->b_cont =
22625 				    dupmsg(mp->b_cont)) == NULL))) {
22626 					freemsg(next_mp);
22627 					next_mp = NULL;
22628 					ire_refrele(ire1);
22629 					ire1 = NULL;
22630 				}
22631 			}
22632 
22633 			/* Last multiroute ire; don't loop anymore. */
22634 			if (ire1 == NULL) {
22635 				multirt_send = B_FALSE;
22636 			}
22637 		}
22638 
22639 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22640 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22641 		    mblk_t *, mp);
22642 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22643 		    ipst->ips_ipv4firewall_physical_out,
22644 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, 0, ipst);
22645 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22646 		if (mp == NULL)
22647 			goto release_ire_and_ill;
22648 
22649 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22650 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22651 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
22652 		if ((pktxmit_state == SEND_FAILED) ||
22653 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22654 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22655 			    "- packet dropped\n"));
22656 release_ire_and_ill:
22657 			ire_refrele(ire);
22658 			if (next_mp != NULL) {
22659 				freemsg(next_mp);
22660 				ire_refrele(ire1);
22661 			}
22662 			if (conn_outgoing_ill != NULL)
22663 				ill_refrele(conn_outgoing_ill);
22664 			return;
22665 		}
22666 
22667 		if (CLASSD(dst)) {
22668 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22669 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22670 			    LENGTH);
22671 		}
22672 
22673 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22674 		    "ip_wput_ire_end: q %p (%S)",
22675 		    q, "last copy out");
22676 		IRE_REFRELE(ire);
22677 
22678 		if (multirt_send) {
22679 			ASSERT(ire1);
22680 			/*
22681 			 * Proceed with the next RTF_MULTIRT ire,
22682 			 * Also set up the send-to queue accordingly.
22683 			 */
22684 			ire = ire1;
22685 			ire1 = NULL;
22686 			stq = ire->ire_stq;
22687 			mp = next_mp;
22688 			next_mp = NULL;
22689 			ipha = (ipha_t *)mp->b_rptr;
22690 			ill_index = Q_TO_INDEX(stq);
22691 			ill = (ill_t *)stq->q_ptr;
22692 		}
22693 	} while (multirt_send);
22694 	if (conn_outgoing_ill != NULL)
22695 		ill_refrele(conn_outgoing_ill);
22696 	return;
22697 
22698 	/*
22699 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22700 	 */
22701 broadcast:
22702 	{
22703 		/*
22704 		 * To avoid broadcast storms, we usually set the TTL to 1 for
22705 		 * broadcasts.  However, if SO_DONTROUTE isn't set, this value
22706 		 * can be overridden stack-wide through the ip_broadcast_ttl
22707 		 * ndd tunable, or on a per-connection basis through the
22708 		 * IP_BROADCAST_TTL socket option.
22709 		 *
22710 		 * In the event that we are replying to incoming ICMP packets,
22711 		 * connp could be NULL.
22712 		 */
22713 		ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22714 		if (connp != NULL) {
22715 			if (connp->conn_dontroute)
22716 				ipha->ipha_ttl = 1;
22717 			else if (connp->conn_broadcast_ttl != 0)
22718 				ipha->ipha_ttl = connp->conn_broadcast_ttl;
22719 		}
22720 
22721 		/*
22722 		 * Note that we are not doing a IRB_REFHOLD here.
22723 		 * Actually we don't care if the list changes i.e
22724 		 * if somebody deletes an IRE from the list while
22725 		 * we drop the lock, the next time we come around
22726 		 * ire_next will be NULL and hence we won't send
22727 		 * out multiple copies which is fine.
22728 		 */
22729 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22730 		ire1 = ire->ire_next;
22731 		if (conn_outgoing_ill != NULL) {
22732 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22733 				ASSERT(ire1 == ire->ire_next);
22734 				if (ire1 != NULL && ire1->ire_addr == dst) {
22735 					ire_refrele(ire);
22736 					ire = ire1;
22737 					IRE_REFHOLD(ire);
22738 					ire1 = ire->ire_next;
22739 					continue;
22740 				}
22741 				rw_exit(&ire->ire_bucket->irb_lock);
22742 				/* Did not find a matching ill */
22743 				ip1dbg(("ip_wput_ire: broadcast with no "
22744 				    "matching IP_BOUND_IF ill %s dst %x\n",
22745 				    conn_outgoing_ill->ill_name, dst));
22746 				freemsg(first_mp);
22747 				if (ire != NULL)
22748 					ire_refrele(ire);
22749 				ill_refrele(conn_outgoing_ill);
22750 				return;
22751 			}
22752 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22753 			/*
22754 			 * If the next IRE has the same address and is not one
22755 			 * of the two copies that we need to send, try to see
22756 			 * whether this copy should be sent at all. This
22757 			 * assumes that we insert loopbacks first and then
22758 			 * non-loopbacks. This is acheived by inserting the
22759 			 * loopback always before non-loopback.
22760 			 * This is used to send a single copy of a broadcast
22761 			 * packet out all physical interfaces that have an
22762 			 * matching IRE_BROADCAST while also looping
22763 			 * back one copy (to ip_wput_local) for each
22764 			 * matching physical interface. However, we avoid
22765 			 * sending packets out different logical that match by
22766 			 * having ipif_up/ipif_down supress duplicate
22767 			 * IRE_BROADCASTS.
22768 			 *
22769 			 * This feature is currently used to get broadcasts
22770 			 * sent to multiple interfaces, when the broadcast
22771 			 * address being used applies to multiple interfaces.
22772 			 * For example, a whole net broadcast will be
22773 			 * replicated on every connected subnet of
22774 			 * the target net.
22775 			 *
22776 			 * Each zone has its own set of IRE_BROADCASTs, so that
22777 			 * we're able to distribute inbound packets to multiple
22778 			 * zones who share a broadcast address. We avoid looping
22779 			 * back outbound packets in different zones but on the
22780 			 * same ill, as the application would see duplicates.
22781 			 *
22782 			 * If the interfaces are part of the same group,
22783 			 * we would want to send only one copy out for
22784 			 * whole group.
22785 			 *
22786 			 * This logic assumes that ire_add_v4() groups the
22787 			 * IRE_BROADCAST entries so that those with the same
22788 			 * ire_addr and ill_group are kept together.
22789 			 */
22790 			ire_ill = ire->ire_ipif->ipif_ill;
22791 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22792 				if (ire_ill->ill_group != NULL &&
22793 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22794 					/*
22795 					 * If the current zone only has an ire
22796 					 * broadcast for this address marked
22797 					 * NORECV, the ire we want is ahead in
22798 					 * the bucket, so we look it up
22799 					 * deliberately ignoring the zoneid.
22800 					 */
22801 					for (ire1 = ire->ire_bucket->irb_ire;
22802 					    ire1 != NULL;
22803 					    ire1 = ire1->ire_next) {
22804 						ire1_ill =
22805 						    ire1->ire_ipif->ipif_ill;
22806 						if (ire1->ire_addr != dst)
22807 							continue;
22808 						/* skip over the current ire */
22809 						if (ire1 == ire)
22810 							continue;
22811 						/* skip over deleted ires */
22812 						if (ire1->ire_marks &
22813 						    IRE_MARK_CONDEMNED)
22814 							continue;
22815 						/*
22816 						 * non-loopback ire in our
22817 						 * group: use it for the next
22818 						 * pass in the loop
22819 						 */
22820 						if (ire1->ire_stq != NULL &&
22821 						    ire1_ill->ill_group ==
22822 						    ire_ill->ill_group)
22823 							break;
22824 					}
22825 				}
22826 			} else {
22827 				while (ire1 != NULL && ire1->ire_addr == dst) {
22828 					ire1_ill = ire1->ire_ipif->ipif_ill;
22829 					/*
22830 					 * We can have two broadcast ires on the
22831 					 * same ill in different zones; here
22832 					 * we'll send a copy of the packet on
22833 					 * each ill and the fanout code will
22834 					 * call conn_wantpacket() to check that
22835 					 * the zone has the broadcast address
22836 					 * configured on the ill. If the two
22837 					 * ires are in the same group we only
22838 					 * send one copy up.
22839 					 */
22840 					if (ire1_ill != ire_ill &&
22841 					    (ire1_ill->ill_group == NULL ||
22842 					    ire_ill->ill_group == NULL ||
22843 					    ire1_ill->ill_group !=
22844 					    ire_ill->ill_group)) {
22845 						break;
22846 					}
22847 					ire1 = ire1->ire_next;
22848 				}
22849 			}
22850 		}
22851 		ASSERT(multirt_send == B_FALSE);
22852 		if (ire1 != NULL && ire1->ire_addr == dst) {
22853 			if ((ire->ire_flags & RTF_MULTIRT) &&
22854 			    (ire1->ire_flags & RTF_MULTIRT)) {
22855 				/*
22856 				 * We are in the multirouting case.
22857 				 * The message must be sent at least
22858 				 * on both ires. These ires have been
22859 				 * inserted AFTER the standard ones
22860 				 * in ip_rt_add(). There are thus no
22861 				 * other ire entries for the destination
22862 				 * address in the rest of the bucket
22863 				 * that do not have the RTF_MULTIRT
22864 				 * flag. We don't process a copy
22865 				 * of the message here. This will be
22866 				 * done in the final sending loop.
22867 				 */
22868 				multirt_send = B_TRUE;
22869 			} else {
22870 				next_mp = ip_copymsg(first_mp);
22871 				if (next_mp != NULL)
22872 					IRE_REFHOLD(ire1);
22873 			}
22874 		}
22875 		rw_exit(&ire->ire_bucket->irb_lock);
22876 	}
22877 
22878 	if (stq) {
22879 		/*
22880 		 * A non-NULL send-to queue means this packet is going
22881 		 * out of this machine.
22882 		 */
22883 		out_ill = (ill_t *)stq->q_ptr;
22884 
22885 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22886 		ttl_protocol = ((uint16_t *)ipha)[4];
22887 		/*
22888 		 * We accumulate the pseudo header checksum in cksum.
22889 		 * This is pretty hairy code, so watch close.  One
22890 		 * thing to keep in mind is that UDP and TCP have
22891 		 * stored their respective datagram lengths in their
22892 		 * checksum fields.  This lines things up real nice.
22893 		 */
22894 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22895 		    (src >> 16) + (src & 0xFFFF);
22896 		/*
22897 		 * We assume the udp checksum field contains the
22898 		 * length, so to compute the pseudo header checksum,
22899 		 * all we need is the protocol number and src/dst.
22900 		 */
22901 		/* Provide the checksums for UDP and TCP. */
22902 		if ((PROTO == IPPROTO_TCP) &&
22903 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22904 			/* hlen gets the number of uchar_ts in the IP header */
22905 			hlen = (V_HLEN & 0xF) << 2;
22906 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22907 			IP_STAT(ipst, ip_out_sw_cksum);
22908 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22909 			    LENGTH - hlen);
22910 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22911 		} else if (PROTO == IPPROTO_SCTP &&
22912 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22913 			sctp_hdr_t	*sctph;
22914 
22915 			hlen = (V_HLEN & 0xF) << 2;
22916 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22917 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22918 			sctph->sh_chksum = 0;
22919 #ifdef	DEBUG
22920 			if (!skip_sctp_cksum)
22921 #endif
22922 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22923 		} else {
22924 			queue_t *dev_q = stq->q_next;
22925 
22926 			if ((dev_q->q_next || dev_q->q_first) &&
22927 			    !canput(dev_q)) {
22928 blocked:
22929 				ipha->ipha_ident = ip_hdr_included;
22930 				/*
22931 				 * If we don't have a conn to apply
22932 				 * backpressure, free the message.
22933 				 * In the ire_send path, we don't know
22934 				 * the position to requeue the packet. Rather
22935 				 * than reorder packets, we just drop this
22936 				 * packet.
22937 				 */
22938 				if (ipst->ips_ip_output_queue &&
22939 				    connp != NULL &&
22940 				    caller != IRE_SEND) {
22941 					if (caller == IP_WSRV) {
22942 						connp->conn_did_putbq = 1;
22943 						(void) putbq(connp->conn_wq,
22944 						    first_mp);
22945 						conn_drain_insert(connp);
22946 						/*
22947 						 * This is the service thread,
22948 						 * and the queue is already
22949 						 * noenabled. The check for
22950 						 * canput and the putbq is not
22951 						 * atomic. So we need to check
22952 						 * again.
22953 						 */
22954 						if (canput(stq->q_next))
22955 							connp->conn_did_putbq
22956 							    = 0;
22957 						IP_STAT(ipst, ip_conn_flputbq);
22958 					} else {
22959 						/*
22960 						 * We are not the service proc.
22961 						 * ip_wsrv will be scheduled or
22962 						 * is already running.
22963 						 */
22964 						(void) putq(connp->conn_wq,
22965 						    first_mp);
22966 					}
22967 				} else {
22968 					out_ill = (ill_t *)stq->q_ptr;
22969 					BUMP_MIB(out_ill->ill_ip_mib,
22970 					    ipIfStatsOutDiscards);
22971 					freemsg(first_mp);
22972 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22973 					    "ip_wput_ire_end: q %p (%S)",
22974 					    q, "discard");
22975 				}
22976 				ire_refrele(ire);
22977 				if (next_mp) {
22978 					ire_refrele(ire1);
22979 					freemsg(next_mp);
22980 				}
22981 				if (conn_outgoing_ill != NULL)
22982 					ill_refrele(conn_outgoing_ill);
22983 				return;
22984 			}
22985 			if ((PROTO == IPPROTO_UDP) &&
22986 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22987 				/*
22988 				 * hlen gets the number of uchar_ts in the
22989 				 * IP header
22990 				 */
22991 				hlen = (V_HLEN & 0xF) << 2;
22992 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22993 				max_frag = ire->ire_max_frag;
22994 				if (*up != 0) {
22995 					IP_CKSUM_XMIT(out_ill, ire, mp, ipha,
22996 					    up, PROTO, hlen, LENGTH, max_frag,
22997 					    ipsec_len, cksum);
22998 					/* Software checksum? */
22999 					if (DB_CKSUMFLAGS(mp) == 0) {
23000 						IP_STAT(ipst, ip_out_sw_cksum);
23001 						IP_STAT_UPDATE(ipst,
23002 						    ip_udp_out_sw_cksum_bytes,
23003 						    LENGTH - hlen);
23004 					}
23005 				}
23006 			}
23007 		}
23008 		/*
23009 		 * Need to do this even when fragmenting. The local
23010 		 * loopback can be done without computing checksums
23011 		 * but forwarding out other interface must be done
23012 		 * after the IP checksum (and ULP checksums) have been
23013 		 * computed.
23014 		 *
23015 		 * NOTE : multicast_forward is set only if this packet
23016 		 * originated from ip_wput. For packets originating from
23017 		 * ip_wput_multicast, it is not set.
23018 		 */
23019 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
23020 multi_loopback:
23021 			ip2dbg(("ip_wput: multicast, loop %d\n",
23022 			    conn_multicast_loop));
23023 
23024 			/*  Forget header checksum offload */
23025 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
23026 
23027 			/*
23028 			 * Local loopback of multicasts?  Check the
23029 			 * ill.
23030 			 *
23031 			 * Note that the loopback function will not come
23032 			 * in through ip_rput - it will only do the
23033 			 * client fanout thus we need to do an mforward
23034 			 * as well.  The is different from the BSD
23035 			 * logic.
23036 			 */
23037 			if (ill != NULL) {
23038 				ilm_t	*ilm;
23039 
23040 				ILM_WALKER_HOLD(ill);
23041 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
23042 				    ALL_ZONES);
23043 				ILM_WALKER_RELE(ill);
23044 				if (ilm != NULL) {
23045 					/*
23046 					 * Pass along the virtual output q.
23047 					 * ip_wput_local() will distribute the
23048 					 * packet to all the matching zones,
23049 					 * except the sending zone when
23050 					 * IP_MULTICAST_LOOP is false.
23051 					 */
23052 					ip_multicast_loopback(q, ill, first_mp,
23053 					    conn_multicast_loop ? 0 :
23054 					    IP_FF_NO_MCAST_LOOP, zoneid);
23055 				}
23056 			}
23057 			if (ipha->ipha_ttl == 0) {
23058 				/*
23059 				 * 0 => only to this host i.e. we are
23060 				 * done. We are also done if this was the
23061 				 * loopback interface since it is sufficient
23062 				 * to loopback one copy of a multicast packet.
23063 				 */
23064 				freemsg(first_mp);
23065 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23066 				    "ip_wput_ire_end: q %p (%S)",
23067 				    q, "loopback");
23068 				ire_refrele(ire);
23069 				if (conn_outgoing_ill != NULL)
23070 					ill_refrele(conn_outgoing_ill);
23071 				return;
23072 			}
23073 			/*
23074 			 * ILLF_MULTICAST is checked in ip_newroute
23075 			 * i.e. we don't need to check it here since
23076 			 * all IRE_CACHEs come from ip_newroute.
23077 			 * For multicast traffic, SO_DONTROUTE is interpreted
23078 			 * to mean only send the packet out the interface
23079 			 * (optionally specified with IP_MULTICAST_IF)
23080 			 * and do not forward it out additional interfaces.
23081 			 * RSVP and the rsvp daemon is an example of a
23082 			 * protocol and user level process that
23083 			 * handles it's own routing. Hence, it uses the
23084 			 * SO_DONTROUTE option to accomplish this.
23085 			 */
23086 
23087 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
23088 			    ill != NULL) {
23089 				/* Unconditionally redo the checksum */
23090 				ipha->ipha_hdr_checksum = 0;
23091 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23092 
23093 				/*
23094 				 * If this needs to go out secure, we need
23095 				 * to wait till we finish the IPsec
23096 				 * processing.
23097 				 */
23098 				if (ipsec_len == 0 &&
23099 				    ip_mforward(ill, ipha, mp)) {
23100 					freemsg(first_mp);
23101 					ip1dbg(("ip_wput: mforward failed\n"));
23102 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23103 					    "ip_wput_ire_end: q %p (%S)",
23104 					    q, "mforward failed");
23105 					ire_refrele(ire);
23106 					if (conn_outgoing_ill != NULL)
23107 						ill_refrele(conn_outgoing_ill);
23108 					return;
23109 				}
23110 			}
23111 		}
23112 		max_frag = ire->ire_max_frag;
23113 		cksum += ttl_protocol;
23114 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23115 			/* No fragmentation required for this one. */
23116 			/*
23117 			 * Don't use frag_flag if packet is pre-built or source
23118 			 * routed or if multicast (since multicast packets do
23119 			 * not solicit ICMP "packet too big" messages).
23120 			 */
23121 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23122 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23123 			    !ip_source_route_included(ipha)) &&
23124 			    !CLASSD(ipha->ipha_dst))
23125 				ipha->ipha_fragment_offset_and_flags |=
23126 				    htons(ire->ire_frag_flag);
23127 
23128 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23129 				/* Complete the IP header checksum. */
23130 				cksum += ipha->ipha_ident;
23131 				cksum += (v_hlen_tos_len >> 16)+
23132 				    (v_hlen_tos_len & 0xFFFF);
23133 				cksum += ipha->ipha_fragment_offset_and_flags;
23134 				hlen = (V_HLEN & 0xF) -
23135 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23136 				if (hlen) {
23137 checksumoptions:
23138 					/*
23139 					 * Account for the IP Options in the IP
23140 					 * header checksum.
23141 					 */
23142 					up = (uint16_t *)(rptr+
23143 					    IP_SIMPLE_HDR_LENGTH);
23144 					do {
23145 						cksum += up[0];
23146 						cksum += up[1];
23147 						up += 2;
23148 					} while (--hlen);
23149 				}
23150 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23151 				cksum = ~(cksum + (cksum >> 16));
23152 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23153 			}
23154 			if (ipsec_len != 0) {
23155 				ipsec_out_process(q, first_mp, ire, ill_index);
23156 				if (!next_mp) {
23157 					ire_refrele(ire);
23158 					if (conn_outgoing_ill != NULL)
23159 						ill_refrele(conn_outgoing_ill);
23160 					return;
23161 				}
23162 				goto next;
23163 			}
23164 
23165 			/*
23166 			 * multirt_send has already been handled
23167 			 * for broadcast, but not yet for multicast
23168 			 * or IP options.
23169 			 */
23170 			if (next_mp == NULL) {
23171 				if (ire->ire_flags & RTF_MULTIRT) {
23172 					multirt_send = B_TRUE;
23173 				}
23174 			}
23175 
23176 			/*
23177 			 * In most cases, the emission loop below is
23178 			 * entered only once. Only in the case where
23179 			 * the ire holds the RTF_MULTIRT flag, do we loop
23180 			 * to process all RTF_MULTIRT ires in the bucket,
23181 			 * and send the packet through all crossed
23182 			 * RTF_MULTIRT routes.
23183 			 */
23184 			do {
23185 				if (multirt_send) {
23186 					irb_t *irb;
23187 
23188 					irb = ire->ire_bucket;
23189 					ASSERT(irb != NULL);
23190 					/*
23191 					 * We are in a multiple send case,
23192 					 * need to get the next IRE and make
23193 					 * a duplicate of the packet.
23194 					 */
23195 					IRB_REFHOLD(irb);
23196 					for (ire1 = ire->ire_next;
23197 					    ire1 != NULL;
23198 					    ire1 = ire1->ire_next) {
23199 						if (!(ire1->ire_flags &
23200 						    RTF_MULTIRT)) {
23201 							continue;
23202 						}
23203 						if (ire1->ire_addr !=
23204 						    ire->ire_addr) {
23205 							continue;
23206 						}
23207 						if (ire1->ire_marks &
23208 						    (IRE_MARK_CONDEMNED|
23209 						    IRE_MARK_HIDDEN)) {
23210 							continue;
23211 						}
23212 
23213 						/* Got one */
23214 						IRE_REFHOLD(ire1);
23215 						break;
23216 					}
23217 					IRB_REFRELE(irb);
23218 
23219 					if (ire1 != NULL) {
23220 						next_mp = copyb(mp);
23221 						if ((next_mp == NULL) ||
23222 						    ((mp->b_cont != NULL) &&
23223 						    ((next_mp->b_cont =
23224 						    dupmsg(mp->b_cont))
23225 						    == NULL))) {
23226 							freemsg(next_mp);
23227 							next_mp = NULL;
23228 							ire_refrele(ire1);
23229 							ire1 = NULL;
23230 						}
23231 					}
23232 
23233 					/*
23234 					 * Last multiroute ire; don't loop
23235 					 * anymore. The emission is over
23236 					 * and next_mp is NULL.
23237 					 */
23238 					if (ire1 == NULL) {
23239 						multirt_send = B_FALSE;
23240 					}
23241 				}
23242 
23243 				out_ill = ire_to_ill(ire);
23244 				DTRACE_PROBE4(ip4__physical__out__start,
23245 				    ill_t *, NULL,
23246 				    ill_t *, out_ill,
23247 				    ipha_t *, ipha, mblk_t *, mp);
23248 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23249 				    ipst->ips_ipv4firewall_physical_out,
23250 				    NULL, out_ill, ipha, mp, mp, 0, ipst);
23251 				DTRACE_PROBE1(ip4__physical__out__end,
23252 				    mblk_t *, mp);
23253 				if (mp == NULL)
23254 					goto release_ire_and_ill_2;
23255 
23256 				ASSERT(ipsec_len == 0);
23257 				mp->b_prev =
23258 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23259 				DTRACE_PROBE2(ip__xmit__2,
23260 				    mblk_t *, mp, ire_t *, ire);
23261 				pktxmit_state = ip_xmit_v4(mp, ire,
23262 				    NULL, B_TRUE);
23263 				if ((pktxmit_state == SEND_FAILED) ||
23264 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23265 release_ire_and_ill_2:
23266 					if (next_mp) {
23267 						freemsg(next_mp);
23268 						ire_refrele(ire1);
23269 					}
23270 					ire_refrele(ire);
23271 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23272 					    "ip_wput_ire_end: q %p (%S)",
23273 					    q, "discard MDATA");
23274 					if (conn_outgoing_ill != NULL)
23275 						ill_refrele(conn_outgoing_ill);
23276 					return;
23277 				}
23278 
23279 				if (CLASSD(dst)) {
23280 					BUMP_MIB(out_ill->ill_ip_mib,
23281 					    ipIfStatsHCOutMcastPkts);
23282 					UPDATE_MIB(out_ill->ill_ip_mib,
23283 					    ipIfStatsHCOutMcastOctets,
23284 					    LENGTH);
23285 				} else if (ire->ire_type == IRE_BROADCAST) {
23286 					BUMP_MIB(out_ill->ill_ip_mib,
23287 					    ipIfStatsHCOutBcastPkts);
23288 				}
23289 
23290 				if (multirt_send) {
23291 					/*
23292 					 * We are in a multiple send case,
23293 					 * need to re-enter the sending loop
23294 					 * using the next ire.
23295 					 */
23296 					ire_refrele(ire);
23297 					ire = ire1;
23298 					stq = ire->ire_stq;
23299 					mp = next_mp;
23300 					next_mp = NULL;
23301 					ipha = (ipha_t *)mp->b_rptr;
23302 					ill_index = Q_TO_INDEX(stq);
23303 				}
23304 			} while (multirt_send);
23305 
23306 			if (!next_mp) {
23307 				/*
23308 				 * Last copy going out (the ultra-common
23309 				 * case).  Note that we intentionally replicate
23310 				 * the putnext rather than calling it before
23311 				 * the next_mp check in hopes of a little
23312 				 * tail-call action out of the compiler.
23313 				 */
23314 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23315 				    "ip_wput_ire_end: q %p (%S)",
23316 				    q, "last copy out(1)");
23317 				ire_refrele(ire);
23318 				if (conn_outgoing_ill != NULL)
23319 					ill_refrele(conn_outgoing_ill);
23320 				return;
23321 			}
23322 			/* More copies going out below. */
23323 		} else {
23324 			int offset;
23325 fragmentit:
23326 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23327 			/*
23328 			 * If this would generate a icmp_frag_needed message,
23329 			 * we need to handle it before we do the IPsec
23330 			 * processing. Otherwise, we need to strip the IPsec
23331 			 * headers before we send up the message to the ULPs
23332 			 * which becomes messy and difficult.
23333 			 */
23334 			if (ipsec_len != 0) {
23335 				if ((max_frag < (unsigned int)(LENGTH +
23336 				    ipsec_len)) && (offset & IPH_DF)) {
23337 					out_ill = (ill_t *)stq->q_ptr;
23338 					BUMP_MIB(out_ill->ill_ip_mib,
23339 					    ipIfStatsOutFragFails);
23340 					BUMP_MIB(out_ill->ill_ip_mib,
23341 					    ipIfStatsOutFragReqds);
23342 					ipha->ipha_hdr_checksum = 0;
23343 					ipha->ipha_hdr_checksum =
23344 					    (uint16_t)ip_csum_hdr(ipha);
23345 					icmp_frag_needed(ire->ire_stq, first_mp,
23346 					    max_frag, zoneid, ipst);
23347 					if (!next_mp) {
23348 						ire_refrele(ire);
23349 						if (conn_outgoing_ill != NULL) {
23350 							ill_refrele(
23351 							    conn_outgoing_ill);
23352 						}
23353 						return;
23354 					}
23355 				} else {
23356 					/*
23357 					 * This won't cause a icmp_frag_needed
23358 					 * message. to be generated. Send it on
23359 					 * the wire. Note that this could still
23360 					 * cause fragmentation and all we
23361 					 * do is the generation of the message
23362 					 * to the ULP if needed before IPsec.
23363 					 */
23364 					if (!next_mp) {
23365 						ipsec_out_process(q, first_mp,
23366 						    ire, ill_index);
23367 						TRACE_2(TR_FAC_IP,
23368 						    TR_IP_WPUT_IRE_END,
23369 						    "ip_wput_ire_end: q %p "
23370 						    "(%S)", q,
23371 						    "last ipsec_out_process");
23372 						ire_refrele(ire);
23373 						if (conn_outgoing_ill != NULL) {
23374 							ill_refrele(
23375 							    conn_outgoing_ill);
23376 						}
23377 						return;
23378 					}
23379 					ipsec_out_process(q, first_mp,
23380 					    ire, ill_index);
23381 				}
23382 			} else {
23383 				/*
23384 				 * Initiate IPPF processing. For
23385 				 * fragmentable packets we finish
23386 				 * all QOS packet processing before
23387 				 * calling:
23388 				 * ip_wput_ire_fragmentit->ip_wput_frag
23389 				 */
23390 
23391 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23392 					ip_process(IPP_LOCAL_OUT, &mp,
23393 					    ill_index);
23394 					if (mp == NULL) {
23395 						out_ill = (ill_t *)stq->q_ptr;
23396 						BUMP_MIB(out_ill->ill_ip_mib,
23397 						    ipIfStatsOutDiscards);
23398 						if (next_mp != NULL) {
23399 							freemsg(next_mp);
23400 							ire_refrele(ire1);
23401 						}
23402 						ire_refrele(ire);
23403 						TRACE_2(TR_FAC_IP,
23404 						    TR_IP_WPUT_IRE_END,
23405 						    "ip_wput_ire: q %p (%S)",
23406 						    q, "discard MDATA");
23407 						if (conn_outgoing_ill != NULL) {
23408 							ill_refrele(
23409 							    conn_outgoing_ill);
23410 						}
23411 						return;
23412 					}
23413 				}
23414 				if (!next_mp) {
23415 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23416 					    "ip_wput_ire_end: q %p (%S)",
23417 					    q, "last fragmentation");
23418 					ip_wput_ire_fragmentit(mp, ire,
23419 					    zoneid, ipst);
23420 					ire_refrele(ire);
23421 					if (conn_outgoing_ill != NULL)
23422 						ill_refrele(conn_outgoing_ill);
23423 					return;
23424 				}
23425 				ip_wput_ire_fragmentit(mp, ire, zoneid, ipst);
23426 			}
23427 		}
23428 	} else {
23429 nullstq:
23430 		/* A NULL stq means the destination address is local. */
23431 		UPDATE_OB_PKT_COUNT(ire);
23432 		ire->ire_last_used_time = lbolt;
23433 		ASSERT(ire->ire_ipif != NULL);
23434 		if (!next_mp) {
23435 			/*
23436 			 * Is there an "in" and "out" for traffic local
23437 			 * to a host (loopback)?  The code in Solaris doesn't
23438 			 * explicitly draw a line in its code for in vs out,
23439 			 * so we've had to draw a line in the sand: ip_wput_ire
23440 			 * is considered to be the "output" side and
23441 			 * ip_wput_local to be the "input" side.
23442 			 */
23443 			out_ill = ire_to_ill(ire);
23444 
23445 			/*
23446 			 * DTrace this as ip:::send.  A blocked packet will
23447 			 * fire the send probe, but not the receive probe.
23448 			 */
23449 			DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23450 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23451 			    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23452 
23453 			DTRACE_PROBE4(ip4__loopback__out__start,
23454 			    ill_t *, NULL, ill_t *, out_ill,
23455 			    ipha_t *, ipha, mblk_t *, first_mp);
23456 
23457 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23458 			    ipst->ips_ipv4firewall_loopback_out,
23459 			    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23460 
23461 			DTRACE_PROBE1(ip4__loopback__out_end,
23462 			    mblk_t *, first_mp);
23463 
23464 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23465 			    "ip_wput_ire_end: q %p (%S)",
23466 			    q, "local address");
23467 
23468 			if (first_mp != NULL)
23469 				ip_wput_local(q, out_ill, ipha,
23470 				    first_mp, ire, 0, ire->ire_zoneid);
23471 			ire_refrele(ire);
23472 			if (conn_outgoing_ill != NULL)
23473 				ill_refrele(conn_outgoing_ill);
23474 			return;
23475 		}
23476 
23477 		out_ill = ire_to_ill(ire);
23478 
23479 		/*
23480 		 * DTrace this as ip:::send.  A blocked packet will fire the
23481 		 * send probe, but not the receive probe.
23482 		 */
23483 		DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23484 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23485 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23486 
23487 		DTRACE_PROBE4(ip4__loopback__out__start,
23488 		    ill_t *, NULL, ill_t *, out_ill,
23489 		    ipha_t *, ipha, mblk_t *, first_mp);
23490 
23491 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23492 		    ipst->ips_ipv4firewall_loopback_out,
23493 		    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23494 
23495 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23496 
23497 		if (first_mp != NULL)
23498 			ip_wput_local(q, out_ill, ipha,
23499 			    first_mp, ire, 0, ire->ire_zoneid);
23500 	}
23501 next:
23502 	/*
23503 	 * More copies going out to additional interfaces.
23504 	 * ire1 has already been held. We don't need the
23505 	 * "ire" anymore.
23506 	 */
23507 	ire_refrele(ire);
23508 	ire = ire1;
23509 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23510 	mp = next_mp;
23511 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23512 	ill = ire_to_ill(ire);
23513 	first_mp = mp;
23514 	if (ipsec_len != 0) {
23515 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23516 		mp = mp->b_cont;
23517 	}
23518 	dst = ire->ire_addr;
23519 	ipha = (ipha_t *)mp->b_rptr;
23520 	/*
23521 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23522 	 * Restore ipha_ident "no checksum" flag.
23523 	 */
23524 	src = orig_src;
23525 	ipha->ipha_ident = ip_hdr_included;
23526 	goto another;
23527 
23528 #undef	rptr
23529 #undef	Q_TO_INDEX
23530 }
23531 
23532 /*
23533  * Routine to allocate a message that is used to notify the ULP about MDT.
23534  * The caller may provide a pointer to the link-layer MDT capabilities,
23535  * or NULL if MDT is to be disabled on the stream.
23536  */
23537 mblk_t *
23538 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23539 {
23540 	mblk_t *mp;
23541 	ip_mdt_info_t *mdti;
23542 	ill_mdt_capab_t *idst;
23543 
23544 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23545 		DB_TYPE(mp) = M_CTL;
23546 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23547 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23548 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23549 		idst = &(mdti->mdt_capab);
23550 
23551 		/*
23552 		 * If the caller provides us with the capability, copy
23553 		 * it over into our notification message; otherwise
23554 		 * we zero out the capability portion.
23555 		 */
23556 		if (isrc != NULL)
23557 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23558 		else
23559 			bzero((caddr_t)idst, sizeof (*idst));
23560 	}
23561 	return (mp);
23562 }
23563 
23564 /*
23565  * Routine which determines whether MDT can be enabled on the destination
23566  * IRE and IPC combination, and if so, allocates and returns the MDT
23567  * notification mblk that may be used by ULP.  We also check if we need to
23568  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23569  * MDT usage in the past have been lifted.  This gets called during IP
23570  * and ULP binding.
23571  */
23572 mblk_t *
23573 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23574     ill_mdt_capab_t *mdt_cap)
23575 {
23576 	mblk_t *mp;
23577 	boolean_t rc = B_FALSE;
23578 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23579 
23580 	ASSERT(dst_ire != NULL);
23581 	ASSERT(connp != NULL);
23582 	ASSERT(mdt_cap != NULL);
23583 
23584 	/*
23585 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23586 	 * Multidata, which is handled in tcp_multisend().  This
23587 	 * is the reason why we do all these checks here, to ensure
23588 	 * that we don't enable Multidata for the cases which we
23589 	 * can't handle at the moment.
23590 	 */
23591 	do {
23592 		/* Only do TCP at the moment */
23593 		if (connp->conn_ulp != IPPROTO_TCP)
23594 			break;
23595 
23596 		/*
23597 		 * IPsec outbound policy present?  Note that we get here
23598 		 * after calling ipsec_conn_cache_policy() where the global
23599 		 * policy checking is performed.  conn_latch will be
23600 		 * non-NULL as long as there's a policy defined,
23601 		 * i.e. conn_out_enforce_policy may be NULL in such case
23602 		 * when the connection is non-secure, and hence we check
23603 		 * further if the latch refers to an outbound policy.
23604 		 */
23605 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23606 			break;
23607 
23608 		/* CGTP (multiroute) is enabled? */
23609 		if (dst_ire->ire_flags & RTF_MULTIRT)
23610 			break;
23611 
23612 		/* Outbound IPQoS enabled? */
23613 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23614 			/*
23615 			 * In this case, we disable MDT for this and all
23616 			 * future connections going over the interface.
23617 			 */
23618 			mdt_cap->ill_mdt_on = 0;
23619 			break;
23620 		}
23621 
23622 		/* socket option(s) present? */
23623 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23624 			break;
23625 
23626 		rc = B_TRUE;
23627 	/* CONSTCOND */
23628 	} while (0);
23629 
23630 	/* Remember the result */
23631 	connp->conn_mdt_ok = rc;
23632 
23633 	if (!rc)
23634 		return (NULL);
23635 	else if (!mdt_cap->ill_mdt_on) {
23636 		/*
23637 		 * If MDT has been previously turned off in the past, and we
23638 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23639 		 * then enable it for this interface.
23640 		 */
23641 		mdt_cap->ill_mdt_on = 1;
23642 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23643 		    "interface %s\n", ill_name));
23644 	}
23645 
23646 	/* Allocate the MDT info mblk */
23647 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23648 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23649 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23650 		return (NULL);
23651 	}
23652 	return (mp);
23653 }
23654 
23655 /*
23656  * Routine to allocate a message that is used to notify the ULP about LSO.
23657  * The caller may provide a pointer to the link-layer LSO capabilities,
23658  * or NULL if LSO is to be disabled on the stream.
23659  */
23660 mblk_t *
23661 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23662 {
23663 	mblk_t *mp;
23664 	ip_lso_info_t *lsoi;
23665 	ill_lso_capab_t *idst;
23666 
23667 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23668 		DB_TYPE(mp) = M_CTL;
23669 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23670 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23671 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23672 		idst = &(lsoi->lso_capab);
23673 
23674 		/*
23675 		 * If the caller provides us with the capability, copy
23676 		 * it over into our notification message; otherwise
23677 		 * we zero out the capability portion.
23678 		 */
23679 		if (isrc != NULL)
23680 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23681 		else
23682 			bzero((caddr_t)idst, sizeof (*idst));
23683 	}
23684 	return (mp);
23685 }
23686 
23687 /*
23688  * Routine which determines whether LSO can be enabled on the destination
23689  * IRE and IPC combination, and if so, allocates and returns the LSO
23690  * notification mblk that may be used by ULP.  We also check if we need to
23691  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23692  * LSO usage in the past have been lifted.  This gets called during IP
23693  * and ULP binding.
23694  */
23695 mblk_t *
23696 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23697     ill_lso_capab_t *lso_cap)
23698 {
23699 	mblk_t *mp;
23700 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23701 
23702 	ASSERT(dst_ire != NULL);
23703 	ASSERT(connp != NULL);
23704 	ASSERT(lso_cap != NULL);
23705 
23706 	connp->conn_lso_ok = B_TRUE;
23707 
23708 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23709 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23710 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23711 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23712 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23713 		connp->conn_lso_ok = B_FALSE;
23714 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23715 			/*
23716 			 * Disable LSO for this and all future connections going
23717 			 * over the interface.
23718 			 */
23719 			lso_cap->ill_lso_on = 0;
23720 		}
23721 	}
23722 
23723 	if (!connp->conn_lso_ok)
23724 		return (NULL);
23725 	else if (!lso_cap->ill_lso_on) {
23726 		/*
23727 		 * If LSO has been previously turned off in the past, and we
23728 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23729 		 * then enable it for this interface.
23730 		 */
23731 		lso_cap->ill_lso_on = 1;
23732 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23733 		    ill_name));
23734 	}
23735 
23736 	/* Allocate the LSO info mblk */
23737 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23738 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23739 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23740 
23741 	return (mp);
23742 }
23743 
23744 /*
23745  * Create destination address attribute, and fill it with the physical
23746  * destination address and SAP taken from the template DL_UNITDATA_REQ
23747  * message block.
23748  */
23749 boolean_t
23750 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23751 {
23752 	dl_unitdata_req_t *dlurp;
23753 	pattr_t *pa;
23754 	pattrinfo_t pa_info;
23755 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23756 	uint_t das_len, das_off;
23757 
23758 	ASSERT(dlmp != NULL);
23759 
23760 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23761 	das_len = dlurp->dl_dest_addr_length;
23762 	das_off = dlurp->dl_dest_addr_offset;
23763 
23764 	pa_info.type = PATTR_DSTADDRSAP;
23765 	pa_info.len = sizeof (**das) + das_len - 1;
23766 
23767 	/* create and associate the attribute */
23768 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23769 	if (pa != NULL) {
23770 		ASSERT(*das != NULL);
23771 		(*das)->addr_is_group = 0;
23772 		(*das)->addr_len = (uint8_t)das_len;
23773 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23774 	}
23775 
23776 	return (pa != NULL);
23777 }
23778 
23779 /*
23780  * Create hardware checksum attribute and fill it with the values passed.
23781  */
23782 boolean_t
23783 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23784     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23785 {
23786 	pattr_t *pa;
23787 	pattrinfo_t pa_info;
23788 
23789 	ASSERT(mmd != NULL);
23790 
23791 	pa_info.type = PATTR_HCKSUM;
23792 	pa_info.len = sizeof (pattr_hcksum_t);
23793 
23794 	/* create and associate the attribute */
23795 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23796 	if (pa != NULL) {
23797 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23798 
23799 		hck->hcksum_start_offset = start_offset;
23800 		hck->hcksum_stuff_offset = stuff_offset;
23801 		hck->hcksum_end_offset = end_offset;
23802 		hck->hcksum_flags = flags;
23803 	}
23804 	return (pa != NULL);
23805 }
23806 
23807 /*
23808  * Create zerocopy attribute and fill it with the specified flags
23809  */
23810 boolean_t
23811 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23812 {
23813 	pattr_t *pa;
23814 	pattrinfo_t pa_info;
23815 
23816 	ASSERT(mmd != NULL);
23817 	pa_info.type = PATTR_ZCOPY;
23818 	pa_info.len = sizeof (pattr_zcopy_t);
23819 
23820 	/* create and associate the attribute */
23821 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23822 	if (pa != NULL) {
23823 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23824 
23825 		zcopy->zcopy_flags = flags;
23826 	}
23827 	return (pa != NULL);
23828 }
23829 
23830 /*
23831  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23832  * block chain. We could rewrite to handle arbitrary message block chains but
23833  * that would make the code complicated and slow. Right now there three
23834  * restrictions:
23835  *
23836  *   1. The first message block must contain the complete IP header and
23837  *	at least 1 byte of payload data.
23838  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23839  *	so that we can use a single Multidata message.
23840  *   3. No frag must be distributed over two or more message blocks so
23841  *	that we don't need more than two packet descriptors per frag.
23842  *
23843  * The above restrictions allow us to support userland applications (which
23844  * will send down a single message block) and NFS over UDP (which will
23845  * send down a chain of at most three message blocks).
23846  *
23847  * We also don't use MDT for payloads with less than or equal to
23848  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23849  */
23850 boolean_t
23851 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23852 {
23853 	int	blocks;
23854 	ssize_t	total, missing, size;
23855 
23856 	ASSERT(mp != NULL);
23857 	ASSERT(hdr_len > 0);
23858 
23859 	size = MBLKL(mp) - hdr_len;
23860 	if (size <= 0)
23861 		return (B_FALSE);
23862 
23863 	/* The first mblk contains the header and some payload. */
23864 	blocks = 1;
23865 	total = size;
23866 	size %= len;
23867 	missing = (size == 0) ? 0 : (len - size);
23868 	mp = mp->b_cont;
23869 
23870 	while (mp != NULL) {
23871 		/*
23872 		 * Give up if we encounter a zero length message block.
23873 		 * In practice, this should rarely happen and therefore
23874 		 * not worth the trouble of freeing and re-linking the
23875 		 * mblk from the chain to handle such case.
23876 		 */
23877 		if ((size = MBLKL(mp)) == 0)
23878 			return (B_FALSE);
23879 
23880 		/* Too many payload buffers for a single Multidata message? */
23881 		if (++blocks > MULTIDATA_MAX_PBUFS)
23882 			return (B_FALSE);
23883 
23884 		total += size;
23885 		/* Is a frag distributed over two or more message blocks? */
23886 		if (missing > size)
23887 			return (B_FALSE);
23888 		size -= missing;
23889 
23890 		size %= len;
23891 		missing = (size == 0) ? 0 : (len - size);
23892 
23893 		mp = mp->b_cont;
23894 	}
23895 
23896 	return (total > ip_wput_frag_mdt_min);
23897 }
23898 
23899 /*
23900  * Outbound IPv4 fragmentation routine using MDT.
23901  */
23902 static void
23903 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23904     uint32_t frag_flag, int offset)
23905 {
23906 	ipha_t		*ipha_orig;
23907 	int		i1, ip_data_end;
23908 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23909 	mblk_t		*hdr_mp, *md_mp = NULL;
23910 	unsigned char	*hdr_ptr, *pld_ptr;
23911 	multidata_t	*mmd;
23912 	ip_pdescinfo_t	pdi;
23913 	ill_t		*ill;
23914 	ip_stack_t	*ipst = ire->ire_ipst;
23915 
23916 	ASSERT(DB_TYPE(mp) == M_DATA);
23917 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23918 
23919 	ill = ire_to_ill(ire);
23920 	ASSERT(ill != NULL);
23921 
23922 	ipha_orig = (ipha_t *)mp->b_rptr;
23923 	mp->b_rptr += sizeof (ipha_t);
23924 
23925 	/* Calculate how many packets we will send out */
23926 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23927 	pkts = (i1 + len - 1) / len;
23928 	ASSERT(pkts > 1);
23929 
23930 	/* Allocate a message block which will hold all the IP Headers. */
23931 	wroff = ipst->ips_ip_wroff_extra;
23932 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23933 
23934 	i1 = pkts * hdr_chunk_len;
23935 	/*
23936 	 * Create the header buffer, Multidata and destination address
23937 	 * and SAP attribute that should be associated with it.
23938 	 */
23939 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23940 	    ((hdr_mp->b_wptr += i1),
23941 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23942 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23943 		freemsg(mp);
23944 		if (md_mp == NULL) {
23945 			freemsg(hdr_mp);
23946 		} else {
23947 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
23948 			freemsg(md_mp);
23949 		}
23950 		IP_STAT(ipst, ip_frag_mdt_allocfail);
23951 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
23952 		return;
23953 	}
23954 	IP_STAT(ipst, ip_frag_mdt_allocd);
23955 
23956 	/*
23957 	 * Add a payload buffer to the Multidata; this operation must not
23958 	 * fail, or otherwise our logic in this routine is broken.  There
23959 	 * is no memory allocation done by the routine, so any returned
23960 	 * failure simply tells us that we've done something wrong.
23961 	 *
23962 	 * A failure tells us that either we're adding the same payload
23963 	 * buffer more than once, or we're trying to add more buffers than
23964 	 * allowed.  None of the above cases should happen, and we panic
23965 	 * because either there's horrible heap corruption, and/or
23966 	 * programming mistake.
23967 	 */
23968 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23969 		goto pbuf_panic;
23970 
23971 	hdr_ptr = hdr_mp->b_rptr;
23972 	pld_ptr = mp->b_rptr;
23973 
23974 	/* Establish the ending byte offset, based on the starting offset. */
23975 	offset <<= 3;
23976 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23977 	    IP_SIMPLE_HDR_LENGTH;
23978 
23979 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23980 
23981 	while (pld_ptr < mp->b_wptr) {
23982 		ipha_t		*ipha;
23983 		uint16_t	offset_and_flags;
23984 		uint16_t	ip_len;
23985 		int		error;
23986 
23987 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23988 		ipha = (ipha_t *)(hdr_ptr + wroff);
23989 		ASSERT(OK_32PTR(ipha));
23990 		*ipha = *ipha_orig;
23991 
23992 		if (ip_data_end - offset > len) {
23993 			offset_and_flags = IPH_MF;
23994 		} else {
23995 			/*
23996 			 * Last frag. Set len to the length of this last piece.
23997 			 */
23998 			len = ip_data_end - offset;
23999 			/* A frag of a frag might have IPH_MF non-zero */
24000 			offset_and_flags =
24001 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24002 			    IPH_MF;
24003 		}
24004 		offset_and_flags |= (uint16_t)(offset >> 3);
24005 		offset_and_flags |= (uint16_t)frag_flag;
24006 		/* Store the offset and flags in the IP header. */
24007 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24008 
24009 		/* Store the length in the IP header. */
24010 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
24011 		ipha->ipha_length = htons(ip_len);
24012 
24013 		/*
24014 		 * Set the IP header checksum.  Note that mp is just
24015 		 * the header, so this is easy to pass to ip_csum.
24016 		 */
24017 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24018 
24019 		DTRACE_IP7(send, mblk_t *, md_mp, conn_t *, NULL, void_ip_t *,
24020 		    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *,
24021 		    NULL, int, 0);
24022 
24023 		/*
24024 		 * Record offset and size of header and data of the next packet
24025 		 * in the multidata message.
24026 		 */
24027 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
24028 		PDESC_PLD_INIT(&pdi);
24029 		i1 = MIN(mp->b_wptr - pld_ptr, len);
24030 		ASSERT(i1 > 0);
24031 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
24032 		if (i1 == len) {
24033 			pld_ptr += len;
24034 		} else {
24035 			i1 = len - i1;
24036 			mp = mp->b_cont;
24037 			ASSERT(mp != NULL);
24038 			ASSERT(MBLKL(mp) >= i1);
24039 			/*
24040 			 * Attach the next payload message block to the
24041 			 * multidata message.
24042 			 */
24043 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24044 				goto pbuf_panic;
24045 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
24046 			pld_ptr = mp->b_rptr + i1;
24047 		}
24048 
24049 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
24050 		    KM_NOSLEEP)) == NULL) {
24051 			/*
24052 			 * Any failure other than ENOMEM indicates that we
24053 			 * have passed in invalid pdesc info or parameters
24054 			 * to mmd_addpdesc, which must not happen.
24055 			 *
24056 			 * EINVAL is a result of failure on boundary checks
24057 			 * against the pdesc info contents.  It should not
24058 			 * happen, and we panic because either there's
24059 			 * horrible heap corruption, and/or programming
24060 			 * mistake.
24061 			 */
24062 			if (error != ENOMEM) {
24063 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
24064 				    "pdesc logic error detected for "
24065 				    "mmd %p pinfo %p (%d)\n",
24066 				    (void *)mmd, (void *)&pdi, error);
24067 				/* NOTREACHED */
24068 			}
24069 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
24070 			/* Free unattached payload message blocks as well */
24071 			md_mp->b_cont = mp->b_cont;
24072 			goto free_mmd;
24073 		}
24074 
24075 		/* Advance fragment offset. */
24076 		offset += len;
24077 
24078 		/* Advance to location for next header in the buffer. */
24079 		hdr_ptr += hdr_chunk_len;
24080 
24081 		/* Did we reach the next payload message block? */
24082 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
24083 			mp = mp->b_cont;
24084 			/*
24085 			 * Attach the next message block with payload
24086 			 * data to the multidata message.
24087 			 */
24088 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24089 				goto pbuf_panic;
24090 			pld_ptr = mp->b_rptr;
24091 		}
24092 	}
24093 
24094 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
24095 	ASSERT(mp->b_wptr == pld_ptr);
24096 
24097 	/* Update IP statistics */
24098 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
24099 
24100 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
24101 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
24102 
24103 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
24104 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
24105 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
24106 
24107 	if (pkt_type == OB_PKT) {
24108 		ire->ire_ob_pkt_count += pkts;
24109 		if (ire->ire_ipif != NULL)
24110 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
24111 	} else {
24112 		/* The type is IB_PKT in the forwarding path. */
24113 		ire->ire_ib_pkt_count += pkts;
24114 		ASSERT(!IRE_IS_LOCAL(ire));
24115 		if (ire->ire_type & IRE_BROADCAST) {
24116 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
24117 		} else {
24118 			UPDATE_MIB(ill->ill_ip_mib,
24119 			    ipIfStatsHCOutForwDatagrams, pkts);
24120 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
24121 		}
24122 	}
24123 	ire->ire_last_used_time = lbolt;
24124 	/* Send it down */
24125 	putnext(ire->ire_stq, md_mp);
24126 	return;
24127 
24128 pbuf_panic:
24129 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
24130 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
24131 	    pbuf_idx);
24132 	/* NOTREACHED */
24133 }
24134 
24135 /*
24136  * Outbound IP fragmentation routine.
24137  *
24138  * NOTE : This routine does not ire_refrele the ire that is passed in
24139  * as the argument.
24140  */
24141 static void
24142 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
24143     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst)
24144 {
24145 	int		i1;
24146 	mblk_t		*ll_hdr_mp;
24147 	int 		ll_hdr_len;
24148 	int		hdr_len;
24149 	mblk_t		*hdr_mp;
24150 	ipha_t		*ipha;
24151 	int		ip_data_end;
24152 	int		len;
24153 	mblk_t		*mp = mp_orig, *mp1;
24154 	int		offset;
24155 	queue_t		*q;
24156 	uint32_t	v_hlen_tos_len;
24157 	mblk_t		*first_mp;
24158 	boolean_t	mctl_present;
24159 	ill_t		*ill;
24160 	ill_t		*out_ill;
24161 	mblk_t		*xmit_mp;
24162 	mblk_t		*carve_mp;
24163 	ire_t		*ire1 = NULL;
24164 	ire_t		*save_ire = NULL;
24165 	mblk_t  	*next_mp = NULL;
24166 	boolean_t	last_frag = B_FALSE;
24167 	boolean_t	multirt_send = B_FALSE;
24168 	ire_t		*first_ire = NULL;
24169 	irb_t		*irb = NULL;
24170 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24171 
24172 	ill = ire_to_ill(ire);
24173 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24174 
24175 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24176 
24177 	if (max_frag == 0) {
24178 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24179 		    " -  dropping packet\n"));
24180 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24181 		freemsg(mp);
24182 		return;
24183 	}
24184 
24185 	/*
24186 	 * IPsec does not allow hw accelerated packets to be fragmented
24187 	 * This check is made in ip_wput_ipsec_out prior to coming here
24188 	 * via ip_wput_ire_fragmentit.
24189 	 *
24190 	 * If at this point we have an ire whose ARP request has not
24191 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24192 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24193 	 * This packet and all fragmentable packets for this ire will
24194 	 * continue to get dropped while ire_nce->nce_state remains in
24195 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24196 	 * ND_REACHABLE, all subsquent large packets for this ire will
24197 	 * get fragemented and sent out by this function.
24198 	 */
24199 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24200 		/* If nce_state is ND_INITIAL, trigger ARP query */
24201 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
24202 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24203 		    " -  dropping packet\n"));
24204 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24205 		freemsg(mp);
24206 		return;
24207 	}
24208 
24209 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24210 	    "ip_wput_frag_start:");
24211 
24212 	if (mp->b_datap->db_type == M_CTL) {
24213 		first_mp = mp;
24214 		mp_orig = mp = mp->b_cont;
24215 		mctl_present = B_TRUE;
24216 	} else {
24217 		first_mp = mp;
24218 		mctl_present = B_FALSE;
24219 	}
24220 
24221 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24222 	ipha = (ipha_t *)mp->b_rptr;
24223 
24224 	/*
24225 	 * If the Don't Fragment flag is on, generate an ICMP destination
24226 	 * unreachable, fragmentation needed.
24227 	 */
24228 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24229 	if (offset & IPH_DF) {
24230 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24231 		if (is_system_labeled()) {
24232 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24233 			    ire->ire_max_frag - max_frag, AF_INET);
24234 		}
24235 		/*
24236 		 * Need to compute hdr checksum if called from ip_wput_ire.
24237 		 * Note that ip_rput_forward verifies the checksum before
24238 		 * calling this routine so in that case this is a noop.
24239 		 */
24240 		ipha->ipha_hdr_checksum = 0;
24241 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24242 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24243 		    ipst);
24244 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24245 		    "ip_wput_frag_end:(%S)",
24246 		    "don't fragment");
24247 		return;
24248 	}
24249 	/*
24250 	 * Labeled systems adjust max_frag if they add a label
24251 	 * to send the correct path mtu.  We need the real mtu since we
24252 	 * are fragmenting the packet after label adjustment.
24253 	 */
24254 	if (is_system_labeled())
24255 		max_frag = ire->ire_max_frag;
24256 	if (mctl_present)
24257 		freeb(first_mp);
24258 	/*
24259 	 * Establish the starting offset.  May not be zero if we are fragging
24260 	 * a fragment that is being forwarded.
24261 	 */
24262 	offset = offset & IPH_OFFSET;
24263 
24264 	/* TODO why is this test needed? */
24265 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24266 	if (((max_frag - LENGTH) & ~7) < 8) {
24267 		/* TODO: notify ulp somehow */
24268 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24269 		freemsg(mp);
24270 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24271 		    "ip_wput_frag_end:(%S)",
24272 		    "len < 8");
24273 		return;
24274 	}
24275 
24276 	hdr_len = (V_HLEN & 0xF) << 2;
24277 
24278 	ipha->ipha_hdr_checksum = 0;
24279 
24280 	/*
24281 	 * Establish the number of bytes maximum per frag, after putting
24282 	 * in the header.
24283 	 */
24284 	len = (max_frag - hdr_len) & ~7;
24285 
24286 	/* Check if we can use MDT to send out the frags. */
24287 	ASSERT(!IRE_IS_LOCAL(ire));
24288 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24289 	    ipst->ips_ip_multidata_outbound &&
24290 	    !(ire->ire_flags & RTF_MULTIRT) &&
24291 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24292 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24293 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24294 		ASSERT(ill->ill_mdt_capab != NULL);
24295 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24296 			/*
24297 			 * If MDT has been previously turned off in the past,
24298 			 * and we currently can do MDT (due to IPQoS policy
24299 			 * removal, etc.) then enable it for this interface.
24300 			 */
24301 			ill->ill_mdt_capab->ill_mdt_on = 1;
24302 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24303 			    ill->ill_name));
24304 		}
24305 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24306 		    offset);
24307 		return;
24308 	}
24309 
24310 	/* Get a copy of the header for the trailing frags */
24311 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst);
24312 	if (!hdr_mp) {
24313 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24314 		freemsg(mp);
24315 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24316 		    "ip_wput_frag_end:(%S)",
24317 		    "couldn't copy hdr");
24318 		return;
24319 	}
24320 	if (DB_CRED(mp) != NULL)
24321 		mblk_setcred(hdr_mp, DB_CRED(mp));
24322 
24323 	/* Store the starting offset, with the MoreFrags flag. */
24324 	i1 = offset | IPH_MF | frag_flag;
24325 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24326 
24327 	/* Establish the ending byte offset, based on the starting offset. */
24328 	offset <<= 3;
24329 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24330 
24331 	/* Store the length of the first fragment in the IP header. */
24332 	i1 = len + hdr_len;
24333 	ASSERT(i1 <= IP_MAXPACKET);
24334 	ipha->ipha_length = htons((uint16_t)i1);
24335 
24336 	/*
24337 	 * Compute the IP header checksum for the first frag.  We have to
24338 	 * watch out that we stop at the end of the header.
24339 	 */
24340 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24341 
24342 	/*
24343 	 * Now carve off the first frag.  Note that this will include the
24344 	 * original IP header.
24345 	 */
24346 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24347 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24348 		freeb(hdr_mp);
24349 		freemsg(mp_orig);
24350 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24351 		    "ip_wput_frag_end:(%S)",
24352 		    "couldn't carve first");
24353 		return;
24354 	}
24355 
24356 	/*
24357 	 * Multirouting case. Each fragment is replicated
24358 	 * via all non-condemned RTF_MULTIRT routes
24359 	 * currently resolved.
24360 	 * We ensure that first_ire is the first RTF_MULTIRT
24361 	 * ire in the bucket.
24362 	 */
24363 	if (ire->ire_flags & RTF_MULTIRT) {
24364 		irb = ire->ire_bucket;
24365 		ASSERT(irb != NULL);
24366 
24367 		multirt_send = B_TRUE;
24368 
24369 		/* Make sure we do not omit any multiroute ire. */
24370 		IRB_REFHOLD(irb);
24371 		for (first_ire = irb->irb_ire;
24372 		    first_ire != NULL;
24373 		    first_ire = first_ire->ire_next) {
24374 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24375 			    (first_ire->ire_addr == ire->ire_addr) &&
24376 			    !(first_ire->ire_marks &
24377 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
24378 				break;
24379 			}
24380 		}
24381 
24382 		if (first_ire != NULL) {
24383 			if (first_ire != ire) {
24384 				IRE_REFHOLD(first_ire);
24385 				/*
24386 				 * Do not release the ire passed in
24387 				 * as the argument.
24388 				 */
24389 				ire = first_ire;
24390 			} else {
24391 				first_ire = NULL;
24392 			}
24393 		}
24394 		IRB_REFRELE(irb);
24395 
24396 		/*
24397 		 * Save the first ire; we will need to restore it
24398 		 * for the trailing frags.
24399 		 * We REFHOLD save_ire, as each iterated ire will be
24400 		 * REFRELEd.
24401 		 */
24402 		save_ire = ire;
24403 		IRE_REFHOLD(save_ire);
24404 	}
24405 
24406 	/*
24407 	 * First fragment emission loop.
24408 	 * In most cases, the emission loop below is entered only
24409 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24410 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24411 	 * bucket, and send the fragment through all crossed
24412 	 * RTF_MULTIRT routes.
24413 	 */
24414 	do {
24415 		if (ire->ire_flags & RTF_MULTIRT) {
24416 			/*
24417 			 * We are in a multiple send case, need to get
24418 			 * the next ire and make a copy of the packet.
24419 			 * ire1 holds here the next ire to process in the
24420 			 * bucket. If multirouting is expected,
24421 			 * any non-RTF_MULTIRT ire that has the
24422 			 * right destination address is ignored.
24423 			 *
24424 			 * We have to take into account the MTU of
24425 			 * each walked ire. max_frag is set by the
24426 			 * the caller and generally refers to
24427 			 * the primary ire entry. Here we ensure that
24428 			 * no route with a lower MTU will be used, as
24429 			 * fragments are carved once for all ires,
24430 			 * then replicated.
24431 			 */
24432 			ASSERT(irb != NULL);
24433 			IRB_REFHOLD(irb);
24434 			for (ire1 = ire->ire_next;
24435 			    ire1 != NULL;
24436 			    ire1 = ire1->ire_next) {
24437 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24438 					continue;
24439 				if (ire1->ire_addr != ire->ire_addr)
24440 					continue;
24441 				if (ire1->ire_marks &
24442 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24443 					continue;
24444 				/*
24445 				 * Ensure we do not exceed the MTU
24446 				 * of the next route.
24447 				 */
24448 				if (ire1->ire_max_frag < max_frag) {
24449 					ip_multirt_bad_mtu(ire1, max_frag);
24450 					continue;
24451 				}
24452 
24453 				/* Got one. */
24454 				IRE_REFHOLD(ire1);
24455 				break;
24456 			}
24457 			IRB_REFRELE(irb);
24458 
24459 			if (ire1 != NULL) {
24460 				next_mp = copyb(mp);
24461 				if ((next_mp == NULL) ||
24462 				    ((mp->b_cont != NULL) &&
24463 				    ((next_mp->b_cont =
24464 				    dupmsg(mp->b_cont)) == NULL))) {
24465 					freemsg(next_mp);
24466 					next_mp = NULL;
24467 					ire_refrele(ire1);
24468 					ire1 = NULL;
24469 				}
24470 			}
24471 
24472 			/* Last multiroute ire; don't loop anymore. */
24473 			if (ire1 == NULL) {
24474 				multirt_send = B_FALSE;
24475 			}
24476 		}
24477 
24478 		ll_hdr_len = 0;
24479 		LOCK_IRE_FP_MP(ire);
24480 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24481 		if (ll_hdr_mp != NULL) {
24482 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24483 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24484 		} else {
24485 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24486 		}
24487 
24488 		/* If there is a transmit header, get a copy for this frag. */
24489 		/*
24490 		 * TODO: should check db_ref before calling ip_carve_mp since
24491 		 * it might give us a dup.
24492 		 */
24493 		if (!ll_hdr_mp) {
24494 			/* No xmit header. */
24495 			xmit_mp = mp;
24496 
24497 		/* We have a link-layer header that can fit in our mblk. */
24498 		} else if (mp->b_datap->db_ref == 1 &&
24499 		    ll_hdr_len != 0 &&
24500 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24501 			/* M_DATA fastpath */
24502 			mp->b_rptr -= ll_hdr_len;
24503 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24504 			xmit_mp = mp;
24505 
24506 		/* Corner case if copyb has failed */
24507 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24508 			UNLOCK_IRE_FP_MP(ire);
24509 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24510 			freeb(hdr_mp);
24511 			freemsg(mp);
24512 			freemsg(mp_orig);
24513 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24514 			    "ip_wput_frag_end:(%S)",
24515 			    "discard");
24516 
24517 			if (multirt_send) {
24518 				ASSERT(ire1);
24519 				ASSERT(next_mp);
24520 
24521 				freemsg(next_mp);
24522 				ire_refrele(ire1);
24523 			}
24524 			if (save_ire != NULL)
24525 				IRE_REFRELE(save_ire);
24526 
24527 			if (first_ire != NULL)
24528 				ire_refrele(first_ire);
24529 			return;
24530 
24531 		/*
24532 		 * Case of res_mp OR the fastpath mp can't fit
24533 		 * in the mblk
24534 		 */
24535 		} else {
24536 			xmit_mp->b_cont = mp;
24537 			if (DB_CRED(mp) != NULL)
24538 				mblk_setcred(xmit_mp, DB_CRED(mp));
24539 			/*
24540 			 * Get priority marking, if any.
24541 			 * We propagate the CoS marking from the
24542 			 * original packet that went to QoS processing
24543 			 * in ip_wput_ire to the newly carved mp.
24544 			 */
24545 			if (DB_TYPE(xmit_mp) == M_DATA)
24546 				xmit_mp->b_band = mp->b_band;
24547 		}
24548 		UNLOCK_IRE_FP_MP(ire);
24549 
24550 		q = ire->ire_stq;
24551 		out_ill = (ill_t *)q->q_ptr;
24552 
24553 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24554 
24555 		DTRACE_PROBE4(ip4__physical__out__start,
24556 		    ill_t *, NULL, ill_t *, out_ill,
24557 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24558 
24559 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24560 		    ipst->ips_ipv4firewall_physical_out,
24561 		    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24562 
24563 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24564 
24565 		if (xmit_mp != NULL) {
24566 			DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *, NULL,
24567 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
24568 			    ipha_t *, ipha, ip6_t *, NULL, int, 0);
24569 
24570 			putnext(q, xmit_mp);
24571 
24572 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24573 			UPDATE_MIB(out_ill->ill_ip_mib,
24574 			    ipIfStatsHCOutOctets, i1);
24575 
24576 			if (pkt_type != OB_PKT) {
24577 				/*
24578 				 * Update the packet count and MIB stats
24579 				 * of trailing RTF_MULTIRT ires.
24580 				 */
24581 				UPDATE_OB_PKT_COUNT(ire);
24582 				BUMP_MIB(out_ill->ill_ip_mib,
24583 				    ipIfStatsOutFragReqds);
24584 			}
24585 		}
24586 
24587 		if (multirt_send) {
24588 			/*
24589 			 * We are in a multiple send case; look for
24590 			 * the next ire and re-enter the loop.
24591 			 */
24592 			ASSERT(ire1);
24593 			ASSERT(next_mp);
24594 			/* REFRELE the current ire before looping */
24595 			ire_refrele(ire);
24596 			ire = ire1;
24597 			ire1 = NULL;
24598 			mp = next_mp;
24599 			next_mp = NULL;
24600 		}
24601 	} while (multirt_send);
24602 
24603 	ASSERT(ire1 == NULL);
24604 
24605 	/* Restore the original ire; we need it for the trailing frags */
24606 	if (save_ire != NULL) {
24607 		/* REFRELE the last iterated ire */
24608 		ire_refrele(ire);
24609 		/* save_ire has been REFHOLDed */
24610 		ire = save_ire;
24611 		save_ire = NULL;
24612 		q = ire->ire_stq;
24613 	}
24614 
24615 	if (pkt_type == OB_PKT) {
24616 		UPDATE_OB_PKT_COUNT(ire);
24617 	} else {
24618 		out_ill = (ill_t *)q->q_ptr;
24619 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24620 		UPDATE_IB_PKT_COUNT(ire);
24621 	}
24622 
24623 	/* Advance the offset to the second frag starting point. */
24624 	offset += len;
24625 	/*
24626 	 * Update hdr_len from the copied header - there might be less options
24627 	 * in the later fragments.
24628 	 */
24629 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24630 	/* Loop until done. */
24631 	for (;;) {
24632 		uint16_t	offset_and_flags;
24633 		uint16_t	ip_len;
24634 
24635 		if (ip_data_end - offset > len) {
24636 			/*
24637 			 * Carve off the appropriate amount from the original
24638 			 * datagram.
24639 			 */
24640 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24641 				mp = NULL;
24642 				break;
24643 			}
24644 			/*
24645 			 * More frags after this one.  Get another copy
24646 			 * of the header.
24647 			 */
24648 			if (carve_mp->b_datap->db_ref == 1 &&
24649 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24650 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24651 				/* Inline IP header */
24652 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24653 				    hdr_mp->b_rptr;
24654 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24655 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24656 				mp = carve_mp;
24657 			} else {
24658 				if (!(mp = copyb(hdr_mp))) {
24659 					freemsg(carve_mp);
24660 					break;
24661 				}
24662 				/* Get priority marking, if any. */
24663 				mp->b_band = carve_mp->b_band;
24664 				mp->b_cont = carve_mp;
24665 			}
24666 			ipha = (ipha_t *)mp->b_rptr;
24667 			offset_and_flags = IPH_MF;
24668 		} else {
24669 			/*
24670 			 * Last frag.  Consume the header. Set len to
24671 			 * the length of this last piece.
24672 			 */
24673 			len = ip_data_end - offset;
24674 
24675 			/*
24676 			 * Carve off the appropriate amount from the original
24677 			 * datagram.
24678 			 */
24679 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24680 				mp = NULL;
24681 				break;
24682 			}
24683 			if (carve_mp->b_datap->db_ref == 1 &&
24684 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24685 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24686 				/* Inline IP header */
24687 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24688 				    hdr_mp->b_rptr;
24689 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24690 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24691 				mp = carve_mp;
24692 				freeb(hdr_mp);
24693 				hdr_mp = mp;
24694 			} else {
24695 				mp = hdr_mp;
24696 				/* Get priority marking, if any. */
24697 				mp->b_band = carve_mp->b_band;
24698 				mp->b_cont = carve_mp;
24699 			}
24700 			ipha = (ipha_t *)mp->b_rptr;
24701 			/* A frag of a frag might have IPH_MF non-zero */
24702 			offset_and_flags =
24703 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24704 			    IPH_MF;
24705 		}
24706 		offset_and_flags |= (uint16_t)(offset >> 3);
24707 		offset_and_flags |= (uint16_t)frag_flag;
24708 		/* Store the offset and flags in the IP header. */
24709 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24710 
24711 		/* Store the length in the IP header. */
24712 		ip_len = (uint16_t)(len + hdr_len);
24713 		ipha->ipha_length = htons(ip_len);
24714 
24715 		/*
24716 		 * Set the IP header checksum.	Note that mp is just
24717 		 * the header, so this is easy to pass to ip_csum.
24718 		 */
24719 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24720 
24721 		/* Attach a transmit header, if any, and ship it. */
24722 		if (pkt_type == OB_PKT) {
24723 			UPDATE_OB_PKT_COUNT(ire);
24724 		} else {
24725 			out_ill = (ill_t *)q->q_ptr;
24726 			BUMP_MIB(out_ill->ill_ip_mib,
24727 			    ipIfStatsHCOutForwDatagrams);
24728 			UPDATE_IB_PKT_COUNT(ire);
24729 		}
24730 
24731 		if (ire->ire_flags & RTF_MULTIRT) {
24732 			irb = ire->ire_bucket;
24733 			ASSERT(irb != NULL);
24734 
24735 			multirt_send = B_TRUE;
24736 
24737 			/*
24738 			 * Save the original ire; we will need to restore it
24739 			 * for the tailing frags.
24740 			 */
24741 			save_ire = ire;
24742 			IRE_REFHOLD(save_ire);
24743 		}
24744 		/*
24745 		 * Emission loop for this fragment, similar
24746 		 * to what is done for the first fragment.
24747 		 */
24748 		do {
24749 			if (multirt_send) {
24750 				/*
24751 				 * We are in a multiple send case, need to get
24752 				 * the next ire and make a copy of the packet.
24753 				 */
24754 				ASSERT(irb != NULL);
24755 				IRB_REFHOLD(irb);
24756 				for (ire1 = ire->ire_next;
24757 				    ire1 != NULL;
24758 				    ire1 = ire1->ire_next) {
24759 					if (!(ire1->ire_flags & RTF_MULTIRT))
24760 						continue;
24761 					if (ire1->ire_addr != ire->ire_addr)
24762 						continue;
24763 					if (ire1->ire_marks &
24764 					    (IRE_MARK_CONDEMNED|
24765 					    IRE_MARK_HIDDEN)) {
24766 						continue;
24767 					}
24768 					/*
24769 					 * Ensure we do not exceed the MTU
24770 					 * of the next route.
24771 					 */
24772 					if (ire1->ire_max_frag < max_frag) {
24773 						ip_multirt_bad_mtu(ire1,
24774 						    max_frag);
24775 						continue;
24776 					}
24777 
24778 					/* Got one. */
24779 					IRE_REFHOLD(ire1);
24780 					break;
24781 				}
24782 				IRB_REFRELE(irb);
24783 
24784 				if (ire1 != NULL) {
24785 					next_mp = copyb(mp);
24786 					if ((next_mp == NULL) ||
24787 					    ((mp->b_cont != NULL) &&
24788 					    ((next_mp->b_cont =
24789 					    dupmsg(mp->b_cont)) == NULL))) {
24790 						freemsg(next_mp);
24791 						next_mp = NULL;
24792 						ire_refrele(ire1);
24793 						ire1 = NULL;
24794 					}
24795 				}
24796 
24797 				/* Last multiroute ire; don't loop anymore. */
24798 				if (ire1 == NULL) {
24799 					multirt_send = B_FALSE;
24800 				}
24801 			}
24802 
24803 			/* Update transmit header */
24804 			ll_hdr_len = 0;
24805 			LOCK_IRE_FP_MP(ire);
24806 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24807 			if (ll_hdr_mp != NULL) {
24808 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24809 				ll_hdr_len = MBLKL(ll_hdr_mp);
24810 			} else {
24811 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24812 			}
24813 
24814 			if (!ll_hdr_mp) {
24815 				xmit_mp = mp;
24816 
24817 			/*
24818 			 * We have link-layer header that can fit in
24819 			 * our mblk.
24820 			 */
24821 			} else if (mp->b_datap->db_ref == 1 &&
24822 			    ll_hdr_len != 0 &&
24823 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24824 				/* M_DATA fastpath */
24825 				mp->b_rptr -= ll_hdr_len;
24826 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24827 				    ll_hdr_len);
24828 				xmit_mp = mp;
24829 
24830 			/*
24831 			 * Case of res_mp OR the fastpath mp can't fit
24832 			 * in the mblk
24833 			 */
24834 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24835 				xmit_mp->b_cont = mp;
24836 				if (DB_CRED(mp) != NULL)
24837 					mblk_setcred(xmit_mp, DB_CRED(mp));
24838 				/* Get priority marking, if any. */
24839 				if (DB_TYPE(xmit_mp) == M_DATA)
24840 					xmit_mp->b_band = mp->b_band;
24841 
24842 			/* Corner case if copyb failed */
24843 			} else {
24844 				/*
24845 				 * Exit both the replication and
24846 				 * fragmentation loops.
24847 				 */
24848 				UNLOCK_IRE_FP_MP(ire);
24849 				goto drop_pkt;
24850 			}
24851 			UNLOCK_IRE_FP_MP(ire);
24852 
24853 			mp1 = mp;
24854 			out_ill = (ill_t *)q->q_ptr;
24855 
24856 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24857 
24858 			DTRACE_PROBE4(ip4__physical__out__start,
24859 			    ill_t *, NULL, ill_t *, out_ill,
24860 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24861 
24862 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24863 			    ipst->ips_ipv4firewall_physical_out,
24864 			    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24865 
24866 			DTRACE_PROBE1(ip4__physical__out__end,
24867 			    mblk_t *, xmit_mp);
24868 
24869 			if (mp != mp1 && hdr_mp == mp1)
24870 				hdr_mp = mp;
24871 			if (mp != mp1 && mp_orig == mp1)
24872 				mp_orig = mp;
24873 
24874 			if (xmit_mp != NULL) {
24875 				DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *,
24876 				    NULL, void_ip_t *, ipha,
24877 				    __dtrace_ipsr_ill_t *, out_ill, ipha_t *,
24878 				    ipha, ip6_t *, NULL, int, 0);
24879 
24880 				putnext(q, xmit_mp);
24881 
24882 				BUMP_MIB(out_ill->ill_ip_mib,
24883 				    ipIfStatsHCOutTransmits);
24884 				UPDATE_MIB(out_ill->ill_ip_mib,
24885 				    ipIfStatsHCOutOctets, ip_len);
24886 
24887 				if (pkt_type != OB_PKT) {
24888 					/*
24889 					 * Update the packet count of trailing
24890 					 * RTF_MULTIRT ires.
24891 					 */
24892 					UPDATE_OB_PKT_COUNT(ire);
24893 				}
24894 			}
24895 
24896 			/* All done if we just consumed the hdr_mp. */
24897 			if (mp == hdr_mp) {
24898 				last_frag = B_TRUE;
24899 				BUMP_MIB(out_ill->ill_ip_mib,
24900 				    ipIfStatsOutFragOKs);
24901 			}
24902 
24903 			if (multirt_send) {
24904 				/*
24905 				 * We are in a multiple send case; look for
24906 				 * the next ire and re-enter the loop.
24907 				 */
24908 				ASSERT(ire1);
24909 				ASSERT(next_mp);
24910 				/* REFRELE the current ire before looping */
24911 				ire_refrele(ire);
24912 				ire = ire1;
24913 				ire1 = NULL;
24914 				q = ire->ire_stq;
24915 				mp = next_mp;
24916 				next_mp = NULL;
24917 			}
24918 		} while (multirt_send);
24919 		/*
24920 		 * Restore the original ire; we need it for the
24921 		 * trailing frags
24922 		 */
24923 		if (save_ire != NULL) {
24924 			ASSERT(ire1 == NULL);
24925 			/* REFRELE the last iterated ire */
24926 			ire_refrele(ire);
24927 			/* save_ire has been REFHOLDed */
24928 			ire = save_ire;
24929 			q = ire->ire_stq;
24930 			save_ire = NULL;
24931 		}
24932 
24933 		if (last_frag) {
24934 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24935 			    "ip_wput_frag_end:(%S)",
24936 			    "consumed hdr_mp");
24937 
24938 			if (first_ire != NULL)
24939 				ire_refrele(first_ire);
24940 			return;
24941 		}
24942 		/* Otherwise, advance and loop. */
24943 		offset += len;
24944 	}
24945 
24946 drop_pkt:
24947 	/* Clean up following allocation failure. */
24948 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24949 	freemsg(mp);
24950 	if (mp != hdr_mp)
24951 		freeb(hdr_mp);
24952 	if (mp != mp_orig)
24953 		freemsg(mp_orig);
24954 
24955 	if (save_ire != NULL)
24956 		IRE_REFRELE(save_ire);
24957 	if (first_ire != NULL)
24958 		ire_refrele(first_ire);
24959 
24960 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24961 	    "ip_wput_frag_end:(%S)",
24962 	    "end--alloc failure");
24963 }
24964 
24965 /*
24966  * Copy the header plus those options which have the copy bit set
24967  */
24968 static mblk_t *
24969 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst)
24970 {
24971 	mblk_t	*mp;
24972 	uchar_t	*up;
24973 
24974 	/*
24975 	 * Quick check if we need to look for options without the copy bit
24976 	 * set
24977 	 */
24978 	mp = allocb(ipst->ips_ip_wroff_extra + hdr_len, BPRI_HI);
24979 	if (!mp)
24980 		return (mp);
24981 	mp->b_rptr += ipst->ips_ip_wroff_extra;
24982 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24983 		bcopy(rptr, mp->b_rptr, hdr_len);
24984 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
24985 		return (mp);
24986 	}
24987 	up  = mp->b_rptr;
24988 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24989 	up += IP_SIMPLE_HDR_LENGTH;
24990 	rptr += IP_SIMPLE_HDR_LENGTH;
24991 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24992 	while (hdr_len > 0) {
24993 		uint32_t optval;
24994 		uint32_t optlen;
24995 
24996 		optval = *rptr;
24997 		if (optval == IPOPT_EOL)
24998 			break;
24999 		if (optval == IPOPT_NOP)
25000 			optlen = 1;
25001 		else
25002 			optlen = rptr[1];
25003 		if (optval & IPOPT_COPY) {
25004 			bcopy(rptr, up, optlen);
25005 			up += optlen;
25006 		}
25007 		rptr += optlen;
25008 		hdr_len -= optlen;
25009 	}
25010 	/*
25011 	 * Make sure that we drop an even number of words by filling
25012 	 * with EOL to the next word boundary.
25013 	 */
25014 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
25015 	    hdr_len & 0x3; hdr_len++)
25016 		*up++ = IPOPT_EOL;
25017 	mp->b_wptr = up;
25018 	/* Update header length */
25019 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
25020 	return (mp);
25021 }
25022 
25023 /*
25024  * Delivery to local recipients including fanout to multiple recipients.
25025  * Does not do checksumming of UDP/TCP.
25026  * Note: q should be the read side queue for either the ill or conn.
25027  * Note: rq should be the read side q for the lower (ill) stream.
25028  * We don't send packets to IPPF processing, thus the last argument
25029  * to all the fanout calls are B_FALSE.
25030  */
25031 void
25032 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
25033     int fanout_flags, zoneid_t zoneid)
25034 {
25035 	uint32_t	protocol;
25036 	mblk_t		*first_mp;
25037 	boolean_t	mctl_present;
25038 	int		ire_type;
25039 #define	rptr	((uchar_t *)ipha)
25040 	ip_stack_t	*ipst = ill->ill_ipst;
25041 
25042 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
25043 	    "ip_wput_local_start: q %p", q);
25044 
25045 	if (ire != NULL) {
25046 		ire_type = ire->ire_type;
25047 	} else {
25048 		/*
25049 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
25050 		 * packet is not multicast, we can't tell the ire type.
25051 		 */
25052 		ASSERT(CLASSD(ipha->ipha_dst));
25053 		ire_type = IRE_BROADCAST;
25054 	}
25055 
25056 	first_mp = mp;
25057 	if (first_mp->b_datap->db_type == M_CTL) {
25058 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
25059 		if (!io->ipsec_out_secure) {
25060 			/*
25061 			 * This ipsec_out_t was allocated in ip_wput
25062 			 * for multicast packets to store the ill_index.
25063 			 * As this is being delivered locally, we don't
25064 			 * need this anymore.
25065 			 */
25066 			mp = first_mp->b_cont;
25067 			freeb(first_mp);
25068 			first_mp = mp;
25069 			mctl_present = B_FALSE;
25070 		} else {
25071 			/*
25072 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
25073 			 * security properties for the looped-back packet.
25074 			 */
25075 			mctl_present = B_TRUE;
25076 			mp = first_mp->b_cont;
25077 			ASSERT(mp != NULL);
25078 			ipsec_out_to_in(first_mp);
25079 		}
25080 	} else {
25081 		mctl_present = B_FALSE;
25082 	}
25083 
25084 	DTRACE_PROBE4(ip4__loopback__in__start,
25085 	    ill_t *, ill, ill_t *, NULL,
25086 	    ipha_t *, ipha, mblk_t *, first_mp);
25087 
25088 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
25089 	    ipst->ips_ipv4firewall_loopback_in,
25090 	    ill, NULL, ipha, first_mp, mp, 0, ipst);
25091 
25092 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
25093 
25094 	if (first_mp == NULL)
25095 		return;
25096 
25097 	DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL, void_ip_t *,
25098 	    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *, NULL,
25099 	    int, 1);
25100 
25101 	ipst->ips_loopback_packets++;
25102 
25103 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
25104 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
25105 	if (!IS_SIMPLE_IPH(ipha)) {
25106 		ip_wput_local_options(ipha, ipst);
25107 	}
25108 
25109 	protocol = ipha->ipha_protocol;
25110 	switch (protocol) {
25111 	case IPPROTO_ICMP: {
25112 		ire_t		*ire_zone;
25113 		ilm_t		*ilm;
25114 		mblk_t		*mp1;
25115 		zoneid_t	last_zoneid;
25116 
25117 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
25118 			ASSERT(ire_type == IRE_BROADCAST);
25119 			/*
25120 			 * In the multicast case, applications may have joined
25121 			 * the group from different zones, so we need to deliver
25122 			 * the packet to each of them. Loop through the
25123 			 * multicast memberships structures (ilm) on the receive
25124 			 * ill and send a copy of the packet up each matching
25125 			 * one. However, we don't do this for multicasts sent on
25126 			 * the loopback interface (PHYI_LOOPBACK flag set) as
25127 			 * they must stay in the sender's zone.
25128 			 *
25129 			 * ilm_add_v6() ensures that ilms in the same zone are
25130 			 * contiguous in the ill_ilm list. We use this property
25131 			 * to avoid sending duplicates needed when two
25132 			 * applications in the same zone join the same group on
25133 			 * different logical interfaces: we ignore the ilm if
25134 			 * it's zoneid is the same as the last matching one.
25135 			 * In addition, the sending of the packet for
25136 			 * ire_zoneid is delayed until all of the other ilms
25137 			 * have been exhausted.
25138 			 */
25139 			last_zoneid = -1;
25140 			ILM_WALKER_HOLD(ill);
25141 			for (ilm = ill->ill_ilm; ilm != NULL;
25142 			    ilm = ilm->ilm_next) {
25143 				if ((ilm->ilm_flags & ILM_DELETED) ||
25144 				    ipha->ipha_dst != ilm->ilm_addr ||
25145 				    ilm->ilm_zoneid == last_zoneid ||
25146 				    ilm->ilm_zoneid == zoneid ||
25147 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25148 					continue;
25149 				mp1 = ip_copymsg(first_mp);
25150 				if (mp1 == NULL)
25151 					continue;
25152 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25153 				    mctl_present, B_FALSE, ill,
25154 				    ilm->ilm_zoneid);
25155 				last_zoneid = ilm->ilm_zoneid;
25156 			}
25157 			ILM_WALKER_RELE(ill);
25158 			/*
25159 			 * Loopback case: the sending endpoint has
25160 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25161 			 * dispatch the multicast packet to the sending zone.
25162 			 */
25163 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25164 				freemsg(first_mp);
25165 				return;
25166 			}
25167 		} else if (ire_type == IRE_BROADCAST) {
25168 			/*
25169 			 * In the broadcast case, there may be many zones
25170 			 * which need a copy of the packet delivered to them.
25171 			 * There is one IRE_BROADCAST per broadcast address
25172 			 * and per zone; we walk those using a helper function.
25173 			 * In addition, the sending of the packet for zoneid is
25174 			 * delayed until all of the other ires have been
25175 			 * processed.
25176 			 */
25177 			IRB_REFHOLD(ire->ire_bucket);
25178 			ire_zone = NULL;
25179 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25180 			    ire)) != NULL) {
25181 				mp1 = ip_copymsg(first_mp);
25182 				if (mp1 == NULL)
25183 					continue;
25184 
25185 				UPDATE_IB_PKT_COUNT(ire_zone);
25186 				ire_zone->ire_last_used_time = lbolt;
25187 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25188 				    mctl_present, B_FALSE, ill,
25189 				    ire_zone->ire_zoneid);
25190 			}
25191 			IRB_REFRELE(ire->ire_bucket);
25192 		}
25193 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25194 		    0, mctl_present, B_FALSE, ill, zoneid);
25195 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25196 		    "ip_wput_local_end: q %p (%S)",
25197 		    q, "icmp");
25198 		return;
25199 	}
25200 	case IPPROTO_IGMP:
25201 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25202 			/* Bad packet - discarded by igmp_input */
25203 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25204 			    "ip_wput_local_end: q %p (%S)",
25205 			    q, "igmp_input--bad packet");
25206 			if (mctl_present)
25207 				freeb(first_mp);
25208 			return;
25209 		}
25210 		/*
25211 		 * igmp_input() may have returned the pulled up message.
25212 		 * So first_mp and ipha need to be reinitialized.
25213 		 */
25214 		ipha = (ipha_t *)mp->b_rptr;
25215 		if (mctl_present)
25216 			first_mp->b_cont = mp;
25217 		else
25218 			first_mp = mp;
25219 		/* deliver to local raw users */
25220 		break;
25221 	case IPPROTO_ENCAP:
25222 		/*
25223 		 * This case is covered by either ip_fanout_proto, or by
25224 		 * the above security processing for self-tunneled packets.
25225 		 */
25226 		break;
25227 	case IPPROTO_UDP: {
25228 		uint16_t	*up;
25229 		uint32_t	ports;
25230 
25231 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25232 		    UDP_PORTS_OFFSET);
25233 		/* Force a 'valid' checksum. */
25234 		up[3] = 0;
25235 
25236 		ports = *(uint32_t *)up;
25237 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25238 		    (ire_type == IRE_BROADCAST),
25239 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25240 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25241 		    ill, zoneid);
25242 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25243 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25244 		return;
25245 	}
25246 	case IPPROTO_TCP: {
25247 
25248 		/*
25249 		 * For TCP, discard broadcast packets.
25250 		 */
25251 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25252 			freemsg(first_mp);
25253 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25254 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25255 			return;
25256 		}
25257 
25258 		if (mp->b_datap->db_type == M_DATA) {
25259 			/*
25260 			 * M_DATA mblk, so init mblk (chain) for no struio().
25261 			 */
25262 			mblk_t	*mp1 = mp;
25263 
25264 			do {
25265 				mp1->b_datap->db_struioflag = 0;
25266 			} while ((mp1 = mp1->b_cont) != NULL);
25267 		}
25268 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25269 		    <= mp->b_wptr);
25270 		ip_fanout_tcp(q, first_mp, ill, ipha,
25271 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25272 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25273 		    mctl_present, B_FALSE, zoneid);
25274 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25275 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25276 		return;
25277 	}
25278 	case IPPROTO_SCTP:
25279 	{
25280 		uint32_t	ports;
25281 
25282 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25283 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25284 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25285 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25286 		return;
25287 	}
25288 
25289 	default:
25290 		break;
25291 	}
25292 	/*
25293 	 * Find a client for some other protocol.  We give
25294 	 * copies to multiple clients, if more than one is
25295 	 * bound.
25296 	 */
25297 	ip_fanout_proto(q, first_mp, ill, ipha,
25298 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25299 	    mctl_present, B_FALSE, ill, zoneid);
25300 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25301 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25302 #undef	rptr
25303 }
25304 
25305 /*
25306  * Update any source route, record route, or timestamp options.
25307  * Check that we are at end of strict source route.
25308  * The options have been sanity checked by ip_wput_options().
25309  */
25310 static void
25311 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25312 {
25313 	ipoptp_t	opts;
25314 	uchar_t		*opt;
25315 	uint8_t		optval;
25316 	uint8_t		optlen;
25317 	ipaddr_t	dst;
25318 	uint32_t	ts;
25319 	ire_t		*ire;
25320 	timestruc_t	now;
25321 
25322 	ip2dbg(("ip_wput_local_options\n"));
25323 	for (optval = ipoptp_first(&opts, ipha);
25324 	    optval != IPOPT_EOL;
25325 	    optval = ipoptp_next(&opts)) {
25326 		opt = opts.ipoptp_cur;
25327 		optlen = opts.ipoptp_len;
25328 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25329 		switch (optval) {
25330 			uint32_t off;
25331 		case IPOPT_SSRR:
25332 		case IPOPT_LSRR:
25333 			off = opt[IPOPT_OFFSET];
25334 			off--;
25335 			if (optlen < IP_ADDR_LEN ||
25336 			    off > optlen - IP_ADDR_LEN) {
25337 				/* End of source route */
25338 				break;
25339 			}
25340 			/*
25341 			 * This will only happen if two consecutive entries
25342 			 * in the source route contains our address or if
25343 			 * it is a packet with a loose source route which
25344 			 * reaches us before consuming the whole source route
25345 			 */
25346 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25347 			if (optval == IPOPT_SSRR) {
25348 				return;
25349 			}
25350 			/*
25351 			 * Hack: instead of dropping the packet truncate the
25352 			 * source route to what has been used by filling the
25353 			 * rest with IPOPT_NOP.
25354 			 */
25355 			opt[IPOPT_OLEN] = (uint8_t)off;
25356 			while (off < optlen) {
25357 				opt[off++] = IPOPT_NOP;
25358 			}
25359 			break;
25360 		case IPOPT_RR:
25361 			off = opt[IPOPT_OFFSET];
25362 			off--;
25363 			if (optlen < IP_ADDR_LEN ||
25364 			    off > optlen - IP_ADDR_LEN) {
25365 				/* No more room - ignore */
25366 				ip1dbg((
25367 				    "ip_wput_forward_options: end of RR\n"));
25368 				break;
25369 			}
25370 			dst = htonl(INADDR_LOOPBACK);
25371 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25372 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25373 			break;
25374 		case IPOPT_TS:
25375 			/* Insert timestamp if there is romm */
25376 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25377 			case IPOPT_TS_TSONLY:
25378 				off = IPOPT_TS_TIMELEN;
25379 				break;
25380 			case IPOPT_TS_PRESPEC:
25381 			case IPOPT_TS_PRESPEC_RFC791:
25382 				/* Verify that the address matched */
25383 				off = opt[IPOPT_OFFSET] - 1;
25384 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25385 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25386 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25387 				    ipst);
25388 				if (ire == NULL) {
25389 					/* Not for us */
25390 					break;
25391 				}
25392 				ire_refrele(ire);
25393 				/* FALLTHRU */
25394 			case IPOPT_TS_TSANDADDR:
25395 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25396 				break;
25397 			default:
25398 				/*
25399 				 * ip_*put_options should have already
25400 				 * dropped this packet.
25401 				 */
25402 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25403 				    "unknown IT - bug in ip_wput_options?\n");
25404 				return;	/* Keep "lint" happy */
25405 			}
25406 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25407 				/* Increase overflow counter */
25408 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25409 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25410 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25411 				    (off << 4);
25412 				break;
25413 			}
25414 			off = opt[IPOPT_OFFSET] - 1;
25415 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25416 			case IPOPT_TS_PRESPEC:
25417 			case IPOPT_TS_PRESPEC_RFC791:
25418 			case IPOPT_TS_TSANDADDR:
25419 				dst = htonl(INADDR_LOOPBACK);
25420 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25421 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25422 				/* FALLTHRU */
25423 			case IPOPT_TS_TSONLY:
25424 				off = opt[IPOPT_OFFSET] - 1;
25425 				/* Compute # of milliseconds since midnight */
25426 				gethrestime(&now);
25427 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25428 				    now.tv_nsec / (NANOSEC / MILLISEC);
25429 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25430 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25431 				break;
25432 			}
25433 			break;
25434 		}
25435 	}
25436 }
25437 
25438 /*
25439  * Send out a multicast packet on interface ipif.
25440  * The sender does not have an conn.
25441  * Caller verifies that this isn't a PHYI_LOOPBACK.
25442  */
25443 void
25444 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25445 {
25446 	ipha_t	*ipha;
25447 	ire_t	*ire;
25448 	ipaddr_t	dst;
25449 	mblk_t		*first_mp;
25450 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25451 
25452 	/* igmp_sendpkt always allocates a ipsec_out_t */
25453 	ASSERT(mp->b_datap->db_type == M_CTL);
25454 	ASSERT(!ipif->ipif_isv6);
25455 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25456 
25457 	first_mp = mp;
25458 	mp = first_mp->b_cont;
25459 	ASSERT(mp->b_datap->db_type == M_DATA);
25460 	ipha = (ipha_t *)mp->b_rptr;
25461 
25462 	/*
25463 	 * Find an IRE which matches the destination and the outgoing
25464 	 * queue (i.e. the outgoing interface.)
25465 	 */
25466 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25467 		dst = ipif->ipif_pp_dst_addr;
25468 	else
25469 		dst = ipha->ipha_dst;
25470 	/*
25471 	 * The source address has already been initialized by the
25472 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25473 	 * be sufficient rather than MATCH_IRE_IPIF.
25474 	 *
25475 	 * This function is used for sending IGMP packets. We need
25476 	 * to make sure that we send the packet out of the interface
25477 	 * (ipif->ipif_ill) where we joined the group. This is to
25478 	 * prevent from switches doing IGMP snooping to send us multicast
25479 	 * packets for a given group on the interface we have joined.
25480 	 * If we can't find an ire, igmp_sendpkt has already initialized
25481 	 * ipsec_out_attach_if so that this will not be load spread in
25482 	 * ip_newroute_ipif.
25483 	 */
25484 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25485 	    MATCH_IRE_ILL, ipst);
25486 	if (!ire) {
25487 		/*
25488 		 * Mark this packet to make it be delivered to
25489 		 * ip_wput_ire after the new ire has been
25490 		 * created.
25491 		 */
25492 		mp->b_prev = NULL;
25493 		mp->b_next = NULL;
25494 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25495 		    zoneid, &zero_info);
25496 		return;
25497 	}
25498 
25499 	/*
25500 	 * Honor the RTF_SETSRC flag; this is the only case
25501 	 * where we force this addr whatever the current src addr is,
25502 	 * because this address is set by igmp_sendpkt(), and
25503 	 * cannot be specified by any user.
25504 	 */
25505 	if (ire->ire_flags & RTF_SETSRC) {
25506 		ipha->ipha_src = ire->ire_src_addr;
25507 	}
25508 
25509 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25510 }
25511 
25512 /*
25513  * NOTE : This function does not ire_refrele the ire argument passed in.
25514  *
25515  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25516  * failure. The nce_fp_mp can vanish any time in the case of
25517  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25518  * the ire_lock to access the nce_fp_mp in this case.
25519  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25520  * prepending a fastpath message IPQoS processing must precede it, we also set
25521  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25522  * (IPQoS might have set the b_band for CoS marking).
25523  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25524  * must follow it so that IPQoS can mark the dl_priority field for CoS
25525  * marking, if needed.
25526  */
25527 static mblk_t *
25528 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc,
25529     uint32_t ill_index, ipha_t **iphap)
25530 {
25531 	uint_t	hlen;
25532 	ipha_t *ipha;
25533 	mblk_t *mp1;
25534 	boolean_t qos_done = B_FALSE;
25535 	uchar_t	*ll_hdr;
25536 	ip_stack_t	*ipst = ire->ire_ipst;
25537 
25538 #define	rptr	((uchar_t *)ipha)
25539 
25540 	ipha = (ipha_t *)mp->b_rptr;
25541 	hlen = 0;
25542 	LOCK_IRE_FP_MP(ire);
25543 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25544 		ASSERT(DB_TYPE(mp1) == M_DATA);
25545 		/* Initiate IPPF processing */
25546 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25547 			UNLOCK_IRE_FP_MP(ire);
25548 			ip_process(proc, &mp, ill_index);
25549 			if (mp == NULL)
25550 				return (NULL);
25551 
25552 			ipha = (ipha_t *)mp->b_rptr;
25553 			LOCK_IRE_FP_MP(ire);
25554 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25555 				qos_done = B_TRUE;
25556 				goto no_fp_mp;
25557 			}
25558 			ASSERT(DB_TYPE(mp1) == M_DATA);
25559 		}
25560 		hlen = MBLKL(mp1);
25561 		/*
25562 		 * Check if we have enough room to prepend fastpath
25563 		 * header
25564 		 */
25565 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25566 			ll_hdr = rptr - hlen;
25567 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25568 			/*
25569 			 * Set the b_rptr to the start of the link layer
25570 			 * header
25571 			 */
25572 			mp->b_rptr = ll_hdr;
25573 			mp1 = mp;
25574 		} else {
25575 			mp1 = copyb(mp1);
25576 			if (mp1 == NULL)
25577 				goto unlock_err;
25578 			mp1->b_band = mp->b_band;
25579 			mp1->b_cont = mp;
25580 			/*
25581 			 * certain system generated traffic may not
25582 			 * have cred/label in ip header block. This
25583 			 * is true even for a labeled system. But for
25584 			 * labeled traffic, inherit the label in the
25585 			 * new header.
25586 			 */
25587 			if (DB_CRED(mp) != NULL)
25588 				mblk_setcred(mp1, DB_CRED(mp));
25589 			/*
25590 			 * XXX disable ICK_VALID and compute checksum
25591 			 * here; can happen if nce_fp_mp changes and
25592 			 * it can't be copied now due to insufficient
25593 			 * space. (unlikely, fp mp can change, but it
25594 			 * does not increase in length)
25595 			 */
25596 		}
25597 		UNLOCK_IRE_FP_MP(ire);
25598 	} else {
25599 no_fp_mp:
25600 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25601 		if (mp1 == NULL) {
25602 unlock_err:
25603 			UNLOCK_IRE_FP_MP(ire);
25604 			freemsg(mp);
25605 			return (NULL);
25606 		}
25607 		UNLOCK_IRE_FP_MP(ire);
25608 		mp1->b_cont = mp;
25609 		/*
25610 		 * certain system generated traffic may not
25611 		 * have cred/label in ip header block. This
25612 		 * is true even for a labeled system. But for
25613 		 * labeled traffic, inherit the label in the
25614 		 * new header.
25615 		 */
25616 		if (DB_CRED(mp) != NULL)
25617 			mblk_setcred(mp1, DB_CRED(mp));
25618 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25619 			ip_process(proc, &mp1, ill_index);
25620 			if (mp1 == NULL)
25621 				return (NULL);
25622 
25623 			if (mp1->b_cont == NULL)
25624 				ipha = NULL;
25625 			else
25626 				ipha = (ipha_t *)mp1->b_cont->b_rptr;
25627 		}
25628 	}
25629 
25630 	*iphap = ipha;
25631 	return (mp1);
25632 #undef rptr
25633 }
25634 
25635 /*
25636  * Finish the outbound IPsec processing for an IPv6 packet. This function
25637  * is called from ipsec_out_process() if the IPsec packet was processed
25638  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25639  * asynchronously.
25640  */
25641 void
25642 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25643     ire_t *ire_arg)
25644 {
25645 	in6_addr_t *v6dstp;
25646 	ire_t *ire;
25647 	mblk_t *mp;
25648 	ip6_t *ip6h1;
25649 	uint_t	ill_index;
25650 	ipsec_out_t *io;
25651 	boolean_t attach_if, hwaccel;
25652 	uint32_t flags = IP6_NO_IPPOLICY;
25653 	int match_flags;
25654 	zoneid_t zoneid;
25655 	boolean_t ill_need_rele = B_FALSE;
25656 	boolean_t ire_need_rele = B_FALSE;
25657 	ip_stack_t	*ipst;
25658 
25659 	mp = ipsec_mp->b_cont;
25660 	ip6h1 = (ip6_t *)mp->b_rptr;
25661 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25662 	ASSERT(io->ipsec_out_ns != NULL);
25663 	ipst = io->ipsec_out_ns->netstack_ip;
25664 	ill_index = io->ipsec_out_ill_index;
25665 	if (io->ipsec_out_reachable) {
25666 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25667 	}
25668 	attach_if = io->ipsec_out_attach_if;
25669 	hwaccel = io->ipsec_out_accelerated;
25670 	zoneid = io->ipsec_out_zoneid;
25671 	ASSERT(zoneid != ALL_ZONES);
25672 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25673 	/* Multicast addresses should have non-zero ill_index. */
25674 	v6dstp = &ip6h->ip6_dst;
25675 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25676 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25677 	ASSERT(!attach_if || ill_index != 0);
25678 	if (ill_index != 0) {
25679 		if (ill == NULL) {
25680 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
25681 			    B_TRUE, ipst);
25682 
25683 			/* Failure case frees things for us. */
25684 			if (ill == NULL)
25685 				return;
25686 
25687 			ill_need_rele = B_TRUE;
25688 		}
25689 		/*
25690 		 * If this packet needs to go out on a particular interface
25691 		 * honor it.
25692 		 */
25693 		if (attach_if) {
25694 			match_flags = MATCH_IRE_ILL;
25695 
25696 			/*
25697 			 * Check if we need an ire that will not be
25698 			 * looked up by anybody else i.e. HIDDEN.
25699 			 */
25700 			if (ill_is_probeonly(ill)) {
25701 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25702 			}
25703 		}
25704 	}
25705 	ASSERT(mp != NULL);
25706 
25707 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25708 		boolean_t unspec_src;
25709 		ipif_t	*ipif;
25710 
25711 		/*
25712 		 * Use the ill_index to get the right ill.
25713 		 */
25714 		unspec_src = io->ipsec_out_unspec_src;
25715 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25716 		if (ipif == NULL) {
25717 			if (ill_need_rele)
25718 				ill_refrele(ill);
25719 			freemsg(ipsec_mp);
25720 			return;
25721 		}
25722 
25723 		if (ire_arg != NULL) {
25724 			ire = ire_arg;
25725 		} else {
25726 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25727 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25728 			ire_need_rele = B_TRUE;
25729 		}
25730 		if (ire != NULL) {
25731 			ipif_refrele(ipif);
25732 			/*
25733 			 * XXX Do the multicast forwarding now, as the IPsec
25734 			 * processing has been done.
25735 			 */
25736 			goto send;
25737 		}
25738 
25739 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25740 		mp->b_prev = NULL;
25741 		mp->b_next = NULL;
25742 
25743 		/*
25744 		 * If the IPsec packet was processed asynchronously,
25745 		 * drop it now.
25746 		 */
25747 		if (q == NULL) {
25748 			if (ill_need_rele)
25749 				ill_refrele(ill);
25750 			freemsg(ipsec_mp);
25751 			return;
25752 		}
25753 
25754 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
25755 		    unspec_src, zoneid);
25756 		ipif_refrele(ipif);
25757 	} else {
25758 		if (attach_if) {
25759 			ipif_t	*ipif;
25760 
25761 			ipif = ipif_get_next_ipif(NULL, ill);
25762 			if (ipif == NULL) {
25763 				if (ill_need_rele)
25764 					ill_refrele(ill);
25765 				freemsg(ipsec_mp);
25766 				return;
25767 			}
25768 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25769 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25770 			ire_need_rele = B_TRUE;
25771 			ipif_refrele(ipif);
25772 		} else {
25773 			if (ire_arg != NULL) {
25774 				ire = ire_arg;
25775 			} else {
25776 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL,
25777 				    ipst);
25778 				ire_need_rele = B_TRUE;
25779 			}
25780 		}
25781 		if (ire != NULL)
25782 			goto send;
25783 		/*
25784 		 * ire disappeared underneath.
25785 		 *
25786 		 * What we need to do here is the ip_newroute
25787 		 * logic to get the ire without doing the IPsec
25788 		 * processing. Follow the same old path. But this
25789 		 * time, ip_wput or ire_add_then_send will call us
25790 		 * directly as all the IPsec operations are done.
25791 		 */
25792 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25793 		mp->b_prev = NULL;
25794 		mp->b_next = NULL;
25795 
25796 		/*
25797 		 * If the IPsec packet was processed asynchronously,
25798 		 * drop it now.
25799 		 */
25800 		if (q == NULL) {
25801 			if (ill_need_rele)
25802 				ill_refrele(ill);
25803 			freemsg(ipsec_mp);
25804 			return;
25805 		}
25806 
25807 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25808 		    zoneid, ipst);
25809 	}
25810 	if (ill != NULL && ill_need_rele)
25811 		ill_refrele(ill);
25812 	return;
25813 send:
25814 	if (ill != NULL && ill_need_rele)
25815 		ill_refrele(ill);
25816 
25817 	/* Local delivery */
25818 	if (ire->ire_stq == NULL) {
25819 		ill_t	*out_ill;
25820 		ASSERT(q != NULL);
25821 
25822 		/* PFHooks: LOOPBACK_OUT */
25823 		out_ill = ire_to_ill(ire);
25824 
25825 		/*
25826 		 * DTrace this as ip:::send.  A blocked packet will fire the
25827 		 * send probe, but not the receive probe.
25828 		 */
25829 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
25830 		    void_ip_t *, ip6h, __dtrace_ipsr_ill_t *, out_ill,
25831 		    ipha_t *, NULL, ip6_t *, ip6h, int, 1);
25832 
25833 		DTRACE_PROBE4(ip6__loopback__out__start,
25834 		    ill_t *, NULL, ill_t *, out_ill,
25835 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25836 
25837 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25838 		    ipst->ips_ipv6firewall_loopback_out,
25839 		    NULL, out_ill, ip6h1, ipsec_mp, mp, 0, ipst);
25840 
25841 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25842 
25843 		if (ipsec_mp != NULL)
25844 			ip_wput_local_v6(RD(q), out_ill,
25845 			    ip6h, ipsec_mp, ire, 0);
25846 		if (ire_need_rele)
25847 			ire_refrele(ire);
25848 		return;
25849 	}
25850 	/*
25851 	 * Everything is done. Send it out on the wire.
25852 	 * We force the insertion of a fragment header using the
25853 	 * IPH_FRAG_HDR flag in two cases:
25854 	 * - after reception of an ICMPv6 "packet too big" message
25855 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25856 	 * - for multirouted IPv6 packets, so that the receiver can
25857 	 *   discard duplicates according to their fragment identifier
25858 	 */
25859 	/* XXX fix flow control problems. */
25860 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25861 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25862 		if (hwaccel) {
25863 			/*
25864 			 * hardware acceleration does not handle these
25865 			 * "slow path" cases.
25866 			 */
25867 			/* IPsec KSTATS: should bump bean counter here. */
25868 			if (ire_need_rele)
25869 				ire_refrele(ire);
25870 			freemsg(ipsec_mp);
25871 			return;
25872 		}
25873 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25874 		    (mp->b_cont ? msgdsize(mp) :
25875 		    mp->b_wptr - (uchar_t *)ip6h)) {
25876 			/* IPsec KSTATS: should bump bean counter here. */
25877 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25878 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25879 			    msgdsize(mp)));
25880 			if (ire_need_rele)
25881 				ire_refrele(ire);
25882 			freemsg(ipsec_mp);
25883 			return;
25884 		}
25885 		ASSERT(mp->b_prev == NULL);
25886 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25887 		    ntohs(ip6h->ip6_plen) +
25888 		    IPV6_HDR_LEN, ire->ire_max_frag));
25889 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25890 		    ire->ire_max_frag);
25891 	} else {
25892 		UPDATE_OB_PKT_COUNT(ire);
25893 		ire->ire_last_used_time = lbolt;
25894 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25895 	}
25896 	if (ire_need_rele)
25897 		ire_refrele(ire);
25898 	freeb(ipsec_mp);
25899 }
25900 
25901 void
25902 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25903 {
25904 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25905 	da_ipsec_t *hada;	/* data attributes */
25906 	ill_t *ill = (ill_t *)q->q_ptr;
25907 
25908 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25909 
25910 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25911 		/* IPsec KSTATS: Bump lose counter here! */
25912 		freemsg(mp);
25913 		return;
25914 	}
25915 
25916 	/*
25917 	 * It's an IPsec packet that must be
25918 	 * accelerated by the Provider, and the
25919 	 * outbound ill is IPsec acceleration capable.
25920 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25921 	 * to the ill.
25922 	 * IPsec KSTATS: should bump packet counter here.
25923 	 */
25924 
25925 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25926 	if (hada_mp == NULL) {
25927 		/* IPsec KSTATS: should bump packet counter here. */
25928 		freemsg(mp);
25929 		return;
25930 	}
25931 
25932 	hada_mp->b_datap->db_type = M_CTL;
25933 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25934 	hada_mp->b_cont = mp;
25935 
25936 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25937 	bzero(hada, sizeof (da_ipsec_t));
25938 	hada->da_type = IPHADA_M_CTL;
25939 
25940 	putnext(q, hada_mp);
25941 }
25942 
25943 /*
25944  * Finish the outbound IPsec processing. This function is called from
25945  * ipsec_out_process() if the IPsec packet was processed
25946  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25947  * asynchronously.
25948  */
25949 void
25950 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25951     ire_t *ire_arg)
25952 {
25953 	uint32_t v_hlen_tos_len;
25954 	ipaddr_t	dst;
25955 	ipif_t	*ipif = NULL;
25956 	ire_t *ire;
25957 	ire_t *ire1 = NULL;
25958 	mblk_t *next_mp = NULL;
25959 	uint32_t max_frag;
25960 	boolean_t multirt_send = B_FALSE;
25961 	mblk_t *mp;
25962 	ipha_t *ipha1;
25963 	uint_t	ill_index;
25964 	ipsec_out_t *io;
25965 	boolean_t attach_if;
25966 	int match_flags;
25967 	irb_t *irb = NULL;
25968 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25969 	zoneid_t zoneid;
25970 	ipxmit_state_t	pktxmit_state;
25971 	ip_stack_t	*ipst;
25972 
25973 #ifdef	_BIG_ENDIAN
25974 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25975 #else
25976 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25977 #endif
25978 
25979 	mp = ipsec_mp->b_cont;
25980 	ipha1 = (ipha_t *)mp->b_rptr;
25981 	ASSERT(mp != NULL);
25982 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25983 	dst = ipha->ipha_dst;
25984 
25985 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25986 	ill_index = io->ipsec_out_ill_index;
25987 	attach_if = io->ipsec_out_attach_if;
25988 	zoneid = io->ipsec_out_zoneid;
25989 	ASSERT(zoneid != ALL_ZONES);
25990 	ipst = io->ipsec_out_ns->netstack_ip;
25991 	ASSERT(io->ipsec_out_ns != NULL);
25992 
25993 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25994 	if (ill_index != 0) {
25995 		if (ill == NULL) {
25996 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
25997 			    ill_index, B_FALSE, ipst);
25998 
25999 			/* Failure case frees things for us. */
26000 			if (ill == NULL)
26001 				return;
26002 
26003 			ill_need_rele = B_TRUE;
26004 		}
26005 		/*
26006 		 * If this packet needs to go out on a particular interface
26007 		 * honor it.
26008 		 */
26009 		if (attach_if) {
26010 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
26011 
26012 			/*
26013 			 * Check if we need an ire that will not be
26014 			 * looked up by anybody else i.e. HIDDEN.
26015 			 */
26016 			if (ill_is_probeonly(ill)) {
26017 				match_flags |= MATCH_IRE_MARK_HIDDEN;
26018 			}
26019 		}
26020 	}
26021 
26022 	if (CLASSD(dst)) {
26023 		boolean_t conn_dontroute;
26024 		/*
26025 		 * Use the ill_index to get the right ipif.
26026 		 */
26027 		conn_dontroute = io->ipsec_out_dontroute;
26028 		if (ill_index == 0)
26029 			ipif = ipif_lookup_group(dst, zoneid, ipst);
26030 		else
26031 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
26032 		if (ipif == NULL) {
26033 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
26034 			    " multicast\n"));
26035 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
26036 			freemsg(ipsec_mp);
26037 			goto done;
26038 		}
26039 		/*
26040 		 * ipha_src has already been intialized with the
26041 		 * value of the ipif in ip_wput. All we need now is
26042 		 * an ire to send this downstream.
26043 		 */
26044 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
26045 		    MBLK_GETLABEL(mp), match_flags, ipst);
26046 		if (ire != NULL) {
26047 			ill_t *ill1;
26048 			/*
26049 			 * Do the multicast forwarding now, as the IPsec
26050 			 * processing has been done.
26051 			 */
26052 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
26053 			    (ill1 = ire_to_ill(ire))) {
26054 				if (ip_mforward(ill1, ipha, mp)) {
26055 					freemsg(ipsec_mp);
26056 					ip1dbg(("ip_wput_ipsec_out: mforward "
26057 					    "failed\n"));
26058 					ire_refrele(ire);
26059 					goto done;
26060 				}
26061 			}
26062 			goto send;
26063 		}
26064 
26065 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
26066 		mp->b_prev = NULL;
26067 		mp->b_next = NULL;
26068 
26069 		/*
26070 		 * If the IPsec packet was processed asynchronously,
26071 		 * drop it now.
26072 		 */
26073 		if (q == NULL) {
26074 			freemsg(ipsec_mp);
26075 			goto done;
26076 		}
26077 
26078 		/*
26079 		 * We may be using a wrong ipif to create the ire.
26080 		 * But it is okay as the source address is assigned
26081 		 * for the packet already. Next outbound packet would
26082 		 * create the IRE with the right IPIF in ip_wput.
26083 		 *
26084 		 * Also handle RTF_MULTIRT routes.
26085 		 */
26086 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
26087 		    zoneid, &zero_info);
26088 	} else {
26089 		if (attach_if) {
26090 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
26091 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
26092 		} else {
26093 			if (ire_arg != NULL) {
26094 				ire = ire_arg;
26095 				ire_need_rele = B_FALSE;
26096 			} else {
26097 				ire = ire_cache_lookup(dst, zoneid,
26098 				    MBLK_GETLABEL(mp), ipst);
26099 			}
26100 		}
26101 		if (ire != NULL) {
26102 			goto send;
26103 		}
26104 
26105 		/*
26106 		 * ire disappeared underneath.
26107 		 *
26108 		 * What we need to do here is the ip_newroute
26109 		 * logic to get the ire without doing the IPsec
26110 		 * processing. Follow the same old path. But this
26111 		 * time, ip_wput or ire_add_then_put will call us
26112 		 * directly as all the IPsec operations are done.
26113 		 */
26114 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
26115 		mp->b_prev = NULL;
26116 		mp->b_next = NULL;
26117 
26118 		/*
26119 		 * If the IPsec packet was processed asynchronously,
26120 		 * drop it now.
26121 		 */
26122 		if (q == NULL) {
26123 			freemsg(ipsec_mp);
26124 			goto done;
26125 		}
26126 
26127 		/*
26128 		 * Since we're going through ip_newroute() again, we
26129 		 * need to make sure we don't:
26130 		 *
26131 		 *	1.) Trigger the ASSERT() with the ipha_ident
26132 		 *	    overloading.
26133 		 *	2.) Redo transport-layer checksumming, since we've
26134 		 *	    already done all that to get this far.
26135 		 *
26136 		 * The easiest way not do either of the above is to set
26137 		 * the ipha_ident field to IP_HDR_INCLUDED.
26138 		 */
26139 		ipha->ipha_ident = IP_HDR_INCLUDED;
26140 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
26141 		    zoneid, ipst);
26142 	}
26143 	goto done;
26144 send:
26145 	if (ire->ire_stq == NULL) {
26146 		ill_t	*out_ill;
26147 		/*
26148 		 * Loopbacks go through ip_wput_local except for one case.
26149 		 * We come here if we generate a icmp_frag_needed message
26150 		 * after IPsec processing is over. When this function calls
26151 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
26152 		 * icmp_frag_needed. The message generated comes back here
26153 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
26154 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
26155 		 * source address as it is usually set in ip_wput_ire. As
26156 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
26157 		 * and we end up here. We can't enter ip_wput_ire once the
26158 		 * IPsec processing is over and hence we need to do it here.
26159 		 */
26160 		ASSERT(q != NULL);
26161 		UPDATE_OB_PKT_COUNT(ire);
26162 		ire->ire_last_used_time = lbolt;
26163 		if (ipha->ipha_src == 0)
26164 			ipha->ipha_src = ire->ire_src_addr;
26165 
26166 		/* PFHooks: LOOPBACK_OUT */
26167 		out_ill = ire_to_ill(ire);
26168 
26169 		/*
26170 		 * DTrace this as ip:::send.  A blocked packet will fire the
26171 		 * send probe, but not the receive probe.
26172 		 */
26173 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
26174 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
26175 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
26176 
26177 		DTRACE_PROBE4(ip4__loopback__out__start,
26178 		    ill_t *, NULL, ill_t *, out_ill,
26179 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26180 
26181 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
26182 		    ipst->ips_ipv4firewall_loopback_out,
26183 		    NULL, out_ill, ipha1, ipsec_mp, mp, 0, ipst);
26184 
26185 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26186 
26187 		if (ipsec_mp != NULL)
26188 			ip_wput_local(RD(q), out_ill,
26189 			    ipha, ipsec_mp, ire, 0, zoneid);
26190 		if (ire_need_rele)
26191 			ire_refrele(ire);
26192 		goto done;
26193 	}
26194 
26195 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26196 		/*
26197 		 * We are through with IPsec processing.
26198 		 * Fragment this and send it on the wire.
26199 		 */
26200 		if (io->ipsec_out_accelerated) {
26201 			/*
26202 			 * The packet has been accelerated but must
26203 			 * be fragmented. This should not happen
26204 			 * since AH and ESP must not accelerate
26205 			 * packets that need fragmentation, however
26206 			 * the configuration could have changed
26207 			 * since the AH or ESP processing.
26208 			 * Drop packet.
26209 			 * IPsec KSTATS: bump bean counter here.
26210 			 */
26211 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26212 			    "fragmented accelerated packet!\n"));
26213 			freemsg(ipsec_mp);
26214 		} else {
26215 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid, ipst);
26216 		}
26217 		if (ire_need_rele)
26218 			ire_refrele(ire);
26219 		goto done;
26220 	}
26221 
26222 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26223 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26224 	    (void *)ire->ire_ipif, (void *)ipif));
26225 
26226 	/*
26227 	 * Multiroute the secured packet, unless IPsec really
26228 	 * requires the packet to go out only through a particular
26229 	 * interface.
26230 	 */
26231 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
26232 		ire_t *first_ire;
26233 		irb = ire->ire_bucket;
26234 		ASSERT(irb != NULL);
26235 		/*
26236 		 * This ire has been looked up as the one that
26237 		 * goes through the given ipif;
26238 		 * make sure we do not omit any other multiroute ire
26239 		 * that may be present in the bucket before this one.
26240 		 */
26241 		IRB_REFHOLD(irb);
26242 		for (first_ire = irb->irb_ire;
26243 		    first_ire != NULL;
26244 		    first_ire = first_ire->ire_next) {
26245 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26246 			    (first_ire->ire_addr == ire->ire_addr) &&
26247 			    !(first_ire->ire_marks &
26248 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
26249 				break;
26250 			}
26251 		}
26252 
26253 		if ((first_ire != NULL) && (first_ire != ire)) {
26254 			/*
26255 			 * Don't change the ire if the packet must
26256 			 * be fragmented if sent via this new one.
26257 			 */
26258 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26259 				IRE_REFHOLD(first_ire);
26260 				if (ire_need_rele)
26261 					ire_refrele(ire);
26262 				else
26263 					ire_need_rele = B_TRUE;
26264 				ire = first_ire;
26265 			}
26266 		}
26267 		IRB_REFRELE(irb);
26268 
26269 		multirt_send = B_TRUE;
26270 		max_frag = ire->ire_max_frag;
26271 	} else {
26272 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
26273 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
26274 			    "flag, attach_if %d\n", attach_if));
26275 		}
26276 	}
26277 
26278 	/*
26279 	 * In most cases, the emission loop below is entered only once.
26280 	 * Only in the case where the ire holds the RTF_MULTIRT
26281 	 * flag, we loop to process all RTF_MULTIRT ires in the
26282 	 * bucket, and send the packet through all crossed
26283 	 * RTF_MULTIRT routes.
26284 	 */
26285 	do {
26286 		if (multirt_send) {
26287 			/*
26288 			 * ire1 holds here the next ire to process in the
26289 			 * bucket. If multirouting is expected,
26290 			 * any non-RTF_MULTIRT ire that has the
26291 			 * right destination address is ignored.
26292 			 */
26293 			ASSERT(irb != NULL);
26294 			IRB_REFHOLD(irb);
26295 			for (ire1 = ire->ire_next;
26296 			    ire1 != NULL;
26297 			    ire1 = ire1->ire_next) {
26298 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26299 					continue;
26300 				if (ire1->ire_addr != ire->ire_addr)
26301 					continue;
26302 				if (ire1->ire_marks &
26303 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
26304 					continue;
26305 				/* No loopback here */
26306 				if (ire1->ire_stq == NULL)
26307 					continue;
26308 				/*
26309 				 * Ensure we do not exceed the MTU
26310 				 * of the next route.
26311 				 */
26312 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26313 					ip_multirt_bad_mtu(ire1, max_frag);
26314 					continue;
26315 				}
26316 
26317 				IRE_REFHOLD(ire1);
26318 				break;
26319 			}
26320 			IRB_REFRELE(irb);
26321 			if (ire1 != NULL) {
26322 				/*
26323 				 * We are in a multiple send case, need to
26324 				 * make a copy of the packet.
26325 				 */
26326 				next_mp = copymsg(ipsec_mp);
26327 				if (next_mp == NULL) {
26328 					ire_refrele(ire1);
26329 					ire1 = NULL;
26330 				}
26331 			}
26332 		}
26333 		/*
26334 		 * Everything is done. Send it out on the wire
26335 		 *
26336 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26337 		 * either send it on the wire or, in the case of
26338 		 * HW acceleration, call ipsec_hw_putnext.
26339 		 */
26340 		if (ire->ire_nce &&
26341 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26342 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26343 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26344 			/*
26345 			 * If ire's link-layer is unresolved (this
26346 			 * would only happen if the incomplete ire
26347 			 * was added to cachetable via forwarding path)
26348 			 * don't bother going to ip_xmit_v4. Just drop the
26349 			 * packet.
26350 			 * There is a slight risk here, in that, if we
26351 			 * have the forwarding path create an incomplete
26352 			 * IRE, then until the IRE is completed, any
26353 			 * transmitted IPsec packets will be dropped
26354 			 * instead of being queued waiting for resolution.
26355 			 *
26356 			 * But the likelihood of a forwarding packet and a wput
26357 			 * packet sending to the same dst at the same time
26358 			 * and there not yet be an ARP entry for it is small.
26359 			 * Furthermore, if this actually happens, it might
26360 			 * be likely that wput would generate multiple
26361 			 * packets (and forwarding would also have a train
26362 			 * of packets) for that destination. If this is
26363 			 * the case, some of them would have been dropped
26364 			 * anyway, since ARP only queues a few packets while
26365 			 * waiting for resolution
26366 			 *
26367 			 * NOTE: We should really call ip_xmit_v4,
26368 			 * and let it queue the packet and send the
26369 			 * ARP query and have ARP come back thus:
26370 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26371 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26372 			 * hw accel work. But it's too complex to get
26373 			 * the IPsec hw  acceleration approach to fit
26374 			 * well with ip_xmit_v4 doing ARP without
26375 			 * doing IPsec simplification. For now, we just
26376 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26377 			 * that we can continue with the send on the next
26378 			 * attempt.
26379 			 *
26380 			 * XXX THis should be revisited, when
26381 			 * the IPsec/IP interaction is cleaned up
26382 			 */
26383 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26384 			    " - dropping packet\n"));
26385 			freemsg(ipsec_mp);
26386 			/*
26387 			 * Call ip_xmit_v4() to trigger ARP query
26388 			 * in case the nce_state is ND_INITIAL
26389 			 */
26390 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26391 			goto drop_pkt;
26392 		}
26393 
26394 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26395 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26396 		    mblk_t *, ipsec_mp);
26397 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26398 		    ipst->ips_ipv4firewall_physical_out, NULL,
26399 		    ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, 0, ipst);
26400 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26401 		if (ipsec_mp == NULL)
26402 			goto drop_pkt;
26403 
26404 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26405 		pktxmit_state = ip_xmit_v4(mp, ire,
26406 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
26407 
26408 		if ((pktxmit_state ==  SEND_FAILED) ||
26409 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26410 
26411 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26412 drop_pkt:
26413 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26414 			    ipIfStatsOutDiscards);
26415 			if (ire_need_rele)
26416 				ire_refrele(ire);
26417 			if (ire1 != NULL) {
26418 				ire_refrele(ire1);
26419 				freemsg(next_mp);
26420 			}
26421 			goto done;
26422 		}
26423 
26424 		freeb(ipsec_mp);
26425 		if (ire_need_rele)
26426 			ire_refrele(ire);
26427 
26428 		if (ire1 != NULL) {
26429 			ire = ire1;
26430 			ire_need_rele = B_TRUE;
26431 			ASSERT(next_mp);
26432 			ipsec_mp = next_mp;
26433 			mp = ipsec_mp->b_cont;
26434 			ire1 = NULL;
26435 			next_mp = NULL;
26436 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26437 		} else {
26438 			multirt_send = B_FALSE;
26439 		}
26440 	} while (multirt_send);
26441 done:
26442 	if (ill != NULL && ill_need_rele)
26443 		ill_refrele(ill);
26444 	if (ipif != NULL)
26445 		ipif_refrele(ipif);
26446 }
26447 
26448 /*
26449  * Get the ill corresponding to the specified ire, and compare its
26450  * capabilities with the protocol and algorithms specified by the
26451  * the SA obtained from ipsec_out. If they match, annotate the
26452  * ipsec_out structure to indicate that the packet needs acceleration.
26453  *
26454  *
26455  * A packet is eligible for outbound hardware acceleration if the
26456  * following conditions are satisfied:
26457  *
26458  * 1. the packet will not be fragmented
26459  * 2. the provider supports the algorithm
26460  * 3. there is no pending control message being exchanged
26461  * 4. snoop is not attached
26462  * 5. the destination address is not a broadcast or multicast address.
26463  *
26464  * Rationale:
26465  *	- Hardware drivers do not support fragmentation with
26466  *	  the current interface.
26467  *	- snoop, multicast, and broadcast may result in exposure of
26468  *	  a cleartext datagram.
26469  * We check all five of these conditions here.
26470  *
26471  * XXX would like to nuke "ire_t *" parameter here; problem is that
26472  * IRE is only way to figure out if a v4 address is a broadcast and
26473  * thus ineligible for acceleration...
26474  */
26475 static void
26476 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26477 {
26478 	ipsec_out_t *io;
26479 	mblk_t *data_mp;
26480 	uint_t plen, overhead;
26481 	ip_stack_t	*ipst;
26482 
26483 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26484 		return;
26485 
26486 	if (ill == NULL)
26487 		return;
26488 	ipst = ill->ill_ipst;
26489 	/*
26490 	 * Destination address is a broadcast or multicast.  Punt.
26491 	 */
26492 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26493 	    IRE_LOCAL)))
26494 		return;
26495 
26496 	data_mp = ipsec_mp->b_cont;
26497 
26498 	if (ill->ill_isv6) {
26499 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26500 
26501 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26502 			return;
26503 
26504 		plen = ip6h->ip6_plen;
26505 	} else {
26506 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26507 
26508 		if (CLASSD(ipha->ipha_dst))
26509 			return;
26510 
26511 		plen = ipha->ipha_length;
26512 	}
26513 	/*
26514 	 * Is there a pending DLPI control message being exchanged
26515 	 * between IP/IPsec and the DLS Provider? If there is, it
26516 	 * could be a SADB update, and the state of the DLS Provider
26517 	 * SADB might not be in sync with the SADB maintained by
26518 	 * IPsec. To avoid dropping packets or using the wrong keying
26519 	 * material, we do not accelerate this packet.
26520 	 */
26521 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26522 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26523 		    "ill_dlpi_pending! don't accelerate packet\n"));
26524 		return;
26525 	}
26526 
26527 	/*
26528 	 * Is the Provider in promiscous mode? If it does, we don't
26529 	 * accelerate the packet since it will bounce back up to the
26530 	 * listeners in the clear.
26531 	 */
26532 	if (ill->ill_promisc_on_phys) {
26533 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26534 		    "ill in promiscous mode, don't accelerate packet\n"));
26535 		return;
26536 	}
26537 
26538 	/*
26539 	 * Will the packet require fragmentation?
26540 	 */
26541 
26542 	/*
26543 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26544 	 * as is used elsewhere.
26545 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26546 	 *	+ 2-byte trailer
26547 	 */
26548 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26549 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26550 
26551 	if ((plen + overhead) > ill->ill_max_mtu)
26552 		return;
26553 
26554 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26555 
26556 	/*
26557 	 * Can the ill accelerate this IPsec protocol and algorithm
26558 	 * specified by the SA?
26559 	 */
26560 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26561 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26562 		return;
26563 	}
26564 
26565 	/*
26566 	 * Tell AH or ESP that the outbound ill is capable of
26567 	 * accelerating this packet.
26568 	 */
26569 	io->ipsec_out_is_capab_ill = B_TRUE;
26570 }
26571 
26572 /*
26573  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26574  *
26575  * If this function returns B_TRUE, the requested SA's have been filled
26576  * into the ipsec_out_*_sa pointers.
26577  *
26578  * If the function returns B_FALSE, the packet has been "consumed", most
26579  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26580  *
26581  * The SA references created by the protocol-specific "select"
26582  * function will be released when the ipsec_mp is freed, thanks to the
26583  * ipsec_out_free destructor -- see spd.c.
26584  */
26585 static boolean_t
26586 ipsec_out_select_sa(mblk_t *ipsec_mp)
26587 {
26588 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26589 	ipsec_out_t *io;
26590 	ipsec_policy_t *pp;
26591 	ipsec_action_t *ap;
26592 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26593 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26594 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26595 
26596 	if (!io->ipsec_out_secure) {
26597 		/*
26598 		 * We came here by mistake.
26599 		 * Don't bother with ipsec processing
26600 		 * We should "discourage" this path in the future.
26601 		 */
26602 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26603 		return (B_FALSE);
26604 	}
26605 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26606 	ASSERT((io->ipsec_out_policy != NULL) ||
26607 	    (io->ipsec_out_act != NULL));
26608 
26609 	ASSERT(io->ipsec_out_failed == B_FALSE);
26610 
26611 	/*
26612 	 * IPsec processing has started.
26613 	 */
26614 	io->ipsec_out_proc_begin = B_TRUE;
26615 	ap = io->ipsec_out_act;
26616 	if (ap == NULL) {
26617 		pp = io->ipsec_out_policy;
26618 		ASSERT(pp != NULL);
26619 		ap = pp->ipsp_act;
26620 		ASSERT(ap != NULL);
26621 	}
26622 
26623 	/*
26624 	 * We have an action.  now, let's select SA's.
26625 	 * (In the future, we can cache this in the conn_t..)
26626 	 */
26627 	if (ap->ipa_want_esp) {
26628 		if (io->ipsec_out_esp_sa == NULL) {
26629 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26630 			    IPPROTO_ESP);
26631 		}
26632 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26633 	}
26634 
26635 	if (ap->ipa_want_ah) {
26636 		if (io->ipsec_out_ah_sa == NULL) {
26637 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26638 			    IPPROTO_AH);
26639 		}
26640 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26641 		/*
26642 		 * The ESP and AH processing order needs to be preserved
26643 		 * when both protocols are required (ESP should be applied
26644 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26645 		 * when both ESP and AH are required, and an AH ACQUIRE
26646 		 * is needed.
26647 		 */
26648 		if (ap->ipa_want_esp && need_ah_acquire)
26649 			need_esp_acquire = B_TRUE;
26650 	}
26651 
26652 	/*
26653 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26654 	 * Release SAs that got referenced, but will not be used until we
26655 	 * acquire _all_ of the SAs we need.
26656 	 */
26657 	if (need_ah_acquire || need_esp_acquire) {
26658 		if (io->ipsec_out_ah_sa != NULL) {
26659 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26660 			io->ipsec_out_ah_sa = NULL;
26661 		}
26662 		if (io->ipsec_out_esp_sa != NULL) {
26663 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26664 			io->ipsec_out_esp_sa = NULL;
26665 		}
26666 
26667 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26668 		return (B_FALSE);
26669 	}
26670 
26671 	return (B_TRUE);
26672 }
26673 
26674 /*
26675  * Process an IPSEC_OUT message and see what you can
26676  * do with it.
26677  * IPQoS Notes:
26678  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26679  * IPsec.
26680  * XXX would like to nuke ire_t.
26681  * XXX ill_index better be "real"
26682  */
26683 void
26684 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26685 {
26686 	ipsec_out_t *io;
26687 	ipsec_policy_t *pp;
26688 	ipsec_action_t *ap;
26689 	ipha_t *ipha;
26690 	ip6_t *ip6h;
26691 	mblk_t *mp;
26692 	ill_t *ill;
26693 	zoneid_t zoneid;
26694 	ipsec_status_t ipsec_rc;
26695 	boolean_t ill_need_rele = B_FALSE;
26696 	ip_stack_t	*ipst;
26697 	ipsec_stack_t	*ipss;
26698 
26699 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26700 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26701 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26702 	ipst = io->ipsec_out_ns->netstack_ip;
26703 	mp = ipsec_mp->b_cont;
26704 
26705 	/*
26706 	 * Initiate IPPF processing. We do it here to account for packets
26707 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26708 	 * We can check for ipsec_out_proc_begin even for such packets, as
26709 	 * they will always be false (asserted below).
26710 	 */
26711 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26712 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26713 		    io->ipsec_out_ill_index : ill_index);
26714 		if (mp == NULL) {
26715 			ip2dbg(("ipsec_out_process: packet dropped "\
26716 			    "during IPPF processing\n"));
26717 			freeb(ipsec_mp);
26718 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26719 			return;
26720 		}
26721 	}
26722 
26723 	if (!io->ipsec_out_secure) {
26724 		/*
26725 		 * We came here by mistake.
26726 		 * Don't bother with ipsec processing
26727 		 * Should "discourage" this path in the future.
26728 		 */
26729 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26730 		goto done;
26731 	}
26732 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26733 	ASSERT((io->ipsec_out_policy != NULL) ||
26734 	    (io->ipsec_out_act != NULL));
26735 	ASSERT(io->ipsec_out_failed == B_FALSE);
26736 
26737 	ipss = ipst->ips_netstack->netstack_ipsec;
26738 	if (!ipsec_loaded(ipss)) {
26739 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26740 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26741 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26742 		} else {
26743 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26744 		}
26745 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26746 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26747 		    &ipss->ipsec_dropper);
26748 		return;
26749 	}
26750 
26751 	/*
26752 	 * IPsec processing has started.
26753 	 */
26754 	io->ipsec_out_proc_begin = B_TRUE;
26755 	ap = io->ipsec_out_act;
26756 	if (ap == NULL) {
26757 		pp = io->ipsec_out_policy;
26758 		ASSERT(pp != NULL);
26759 		ap = pp->ipsp_act;
26760 		ASSERT(ap != NULL);
26761 	}
26762 
26763 	/*
26764 	 * Save the outbound ill index. When the packet comes back
26765 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26766 	 * before sending it the accelerated packet.
26767 	 */
26768 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26769 		int ifindex;
26770 		ill = ire_to_ill(ire);
26771 		ifindex = ill->ill_phyint->phyint_ifindex;
26772 		io->ipsec_out_capab_ill_index = ifindex;
26773 	}
26774 
26775 	/*
26776 	 * The order of processing is first insert a IP header if needed.
26777 	 * Then insert the ESP header and then the AH header.
26778 	 */
26779 	if ((io->ipsec_out_se_done == B_FALSE) &&
26780 	    (ap->ipa_want_se)) {
26781 		/*
26782 		 * First get the outer IP header before sending
26783 		 * it to ESP.
26784 		 */
26785 		ipha_t *oipha, *iipha;
26786 		mblk_t *outer_mp, *inner_mp;
26787 
26788 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26789 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26790 			    "ipsec_out_process: "
26791 			    "Self-Encapsulation failed: Out of memory\n");
26792 			freemsg(ipsec_mp);
26793 			if (ill != NULL) {
26794 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26795 			} else {
26796 				BUMP_MIB(&ipst->ips_ip_mib,
26797 				    ipIfStatsOutDiscards);
26798 			}
26799 			return;
26800 		}
26801 		inner_mp = ipsec_mp->b_cont;
26802 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26803 		oipha = (ipha_t *)outer_mp->b_rptr;
26804 		iipha = (ipha_t *)inner_mp->b_rptr;
26805 		*oipha = *iipha;
26806 		outer_mp->b_wptr += sizeof (ipha_t);
26807 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26808 		    sizeof (ipha_t));
26809 		oipha->ipha_protocol = IPPROTO_ENCAP;
26810 		oipha->ipha_version_and_hdr_length =
26811 		    IP_SIMPLE_HDR_VERSION;
26812 		oipha->ipha_hdr_checksum = 0;
26813 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26814 		outer_mp->b_cont = inner_mp;
26815 		ipsec_mp->b_cont = outer_mp;
26816 
26817 		io->ipsec_out_se_done = B_TRUE;
26818 		io->ipsec_out_tunnel = B_TRUE;
26819 	}
26820 
26821 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26822 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26823 	    !ipsec_out_select_sa(ipsec_mp))
26824 		return;
26825 
26826 	/*
26827 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26828 	 * to do the heavy lifting.
26829 	 */
26830 	zoneid = io->ipsec_out_zoneid;
26831 	ASSERT(zoneid != ALL_ZONES);
26832 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26833 		ASSERT(io->ipsec_out_esp_sa != NULL);
26834 		io->ipsec_out_esp_done = B_TRUE;
26835 		/*
26836 		 * Note that since hw accel can only apply one transform,
26837 		 * not two, we skip hw accel for ESP if we also have AH
26838 		 * This is an design limitation of the interface
26839 		 * which should be revisited.
26840 		 */
26841 		ASSERT(ire != NULL);
26842 		if (io->ipsec_out_ah_sa == NULL) {
26843 			ill = (ill_t *)ire->ire_stq->q_ptr;
26844 			ipsec_out_is_accelerated(ipsec_mp,
26845 			    io->ipsec_out_esp_sa, ill, ire);
26846 		}
26847 
26848 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26849 		switch (ipsec_rc) {
26850 		case IPSEC_STATUS_SUCCESS:
26851 			break;
26852 		case IPSEC_STATUS_FAILED:
26853 			if (ill != NULL) {
26854 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26855 			} else {
26856 				BUMP_MIB(&ipst->ips_ip_mib,
26857 				    ipIfStatsOutDiscards);
26858 			}
26859 			/* FALLTHRU */
26860 		case IPSEC_STATUS_PENDING:
26861 			return;
26862 		}
26863 	}
26864 
26865 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26866 		ASSERT(io->ipsec_out_ah_sa != NULL);
26867 		io->ipsec_out_ah_done = B_TRUE;
26868 		if (ire == NULL) {
26869 			int idx = io->ipsec_out_capab_ill_index;
26870 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26871 			    NULL, NULL, NULL, NULL, ipst);
26872 			ill_need_rele = B_TRUE;
26873 		} else {
26874 			ill = (ill_t *)ire->ire_stq->q_ptr;
26875 		}
26876 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26877 		    ire);
26878 
26879 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26880 		switch (ipsec_rc) {
26881 		case IPSEC_STATUS_SUCCESS:
26882 			break;
26883 		case IPSEC_STATUS_FAILED:
26884 			if (ill != NULL) {
26885 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26886 			} else {
26887 				BUMP_MIB(&ipst->ips_ip_mib,
26888 				    ipIfStatsOutDiscards);
26889 			}
26890 			/* FALLTHRU */
26891 		case IPSEC_STATUS_PENDING:
26892 			if (ill != NULL && ill_need_rele)
26893 				ill_refrele(ill);
26894 			return;
26895 		}
26896 	}
26897 	/*
26898 	 * We are done with IPsec processing. Send it over
26899 	 * the wire.
26900 	 */
26901 done:
26902 	mp = ipsec_mp->b_cont;
26903 	ipha = (ipha_t *)mp->b_rptr;
26904 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26905 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
26906 	} else {
26907 		ip6h = (ip6_t *)ipha;
26908 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
26909 	}
26910 	if (ill != NULL && ill_need_rele)
26911 		ill_refrele(ill);
26912 }
26913 
26914 /* ARGSUSED */
26915 void
26916 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26917 {
26918 	opt_restart_t	*or;
26919 	int	err;
26920 	conn_t	*connp;
26921 
26922 	ASSERT(CONN_Q(q));
26923 	connp = Q_TO_CONN(q);
26924 
26925 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26926 	or = (opt_restart_t *)first_mp->b_rptr;
26927 	/*
26928 	 * We don't need to pass any credentials here since this is just
26929 	 * a restart. The credentials are passed in when svr4_optcom_req
26930 	 * is called the first time (from ip_wput_nondata).
26931 	 */
26932 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26933 		err = svr4_optcom_req(q, first_mp, NULL,
26934 		    &ip_opt_obj, B_FALSE);
26935 	} else {
26936 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26937 		err = tpi_optcom_req(q, first_mp, NULL,
26938 		    &ip_opt_obj, B_FALSE);
26939 	}
26940 	if (err != EINPROGRESS) {
26941 		/* operation is done */
26942 		CONN_OPER_PENDING_DONE(connp);
26943 	}
26944 }
26945 
26946 /*
26947  * ioctls that go through a down/up sequence may need to wait for the down
26948  * to complete. This involves waiting for the ire and ipif refcnts to go down
26949  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26950  */
26951 /* ARGSUSED */
26952 void
26953 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26954 {
26955 	struct iocblk *iocp;
26956 	mblk_t *mp1;
26957 	ip_ioctl_cmd_t *ipip;
26958 	int err;
26959 	sin_t	*sin;
26960 	struct lifreq *lifr;
26961 	struct ifreq *ifr;
26962 
26963 	iocp = (struct iocblk *)mp->b_rptr;
26964 	ASSERT(ipsq != NULL);
26965 	/* Existence of mp1 verified in ip_wput_nondata */
26966 	mp1 = mp->b_cont->b_cont;
26967 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26968 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26969 		/*
26970 		 * Special case where ipsq_current_ipif is not set:
26971 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26972 		 * ill could also have become part of a ipmp group in the
26973 		 * process, we are here as were not able to complete the
26974 		 * operation in ipif_set_values because we could not become
26975 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
26976 		 * will not be set so we need to set it.
26977 		 */
26978 		ill_t *ill = q->q_ptr;
26979 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
26980 	}
26981 	ASSERT(ipsq->ipsq_current_ipif != NULL);
26982 
26983 	if (ipip->ipi_cmd_type == IF_CMD) {
26984 		/* This a old style SIOC[GS]IF* command */
26985 		ifr = (struct ifreq *)mp1->b_rptr;
26986 		sin = (sin_t *)&ifr->ifr_addr;
26987 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26988 		/* This a new style SIOC[GS]LIF* command */
26989 		lifr = (struct lifreq *)mp1->b_rptr;
26990 		sin = (sin_t *)&lifr->lifr_addr;
26991 	} else {
26992 		sin = NULL;
26993 	}
26994 
26995 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_current_ipif, sin, q, mp,
26996 	    ipip, mp1->b_rptr);
26997 
26998 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26999 }
27000 
27001 /*
27002  * ioctl processing
27003  *
27004  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
27005  * the ioctl command in the ioctl tables, determines the copyin data size
27006  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
27007  *
27008  * ioctl processing then continues when the M_IOCDATA makes its way down to
27009  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
27010  * associated 'conn' is refheld till the end of the ioctl and the general
27011  * ioctl processing function ip_process_ioctl() is called to extract the
27012  * arguments and process the ioctl.  To simplify extraction, ioctl commands
27013  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
27014  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
27015  * is used to extract the ioctl's arguments.
27016  *
27017  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
27018  * so goes thru the serialization primitive ipsq_try_enter. Then the
27019  * appropriate function to handle the ioctl is called based on the entry in
27020  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
27021  * which also refreleases the 'conn' that was refheld at the start of the
27022  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
27023  *
27024  * Many exclusive ioctls go thru an internal down up sequence as part of
27025  * the operation. For example an attempt to change the IP address of an
27026  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
27027  * does all the cleanup such as deleting all ires that use this address.
27028  * Then we need to wait till all references to the interface go away.
27029  */
27030 void
27031 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
27032 {
27033 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
27034 	ip_ioctl_cmd_t *ipip = arg;
27035 	ip_extract_func_t *extract_funcp;
27036 	cmd_info_t ci;
27037 	int err;
27038 
27039 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
27040 
27041 	if (ipip == NULL)
27042 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27043 
27044 	/*
27045 	 * SIOCLIFADDIF needs to go thru a special path since the
27046 	 * ill may not exist yet. This happens in the case of lo0
27047 	 * which is created using this ioctl.
27048 	 */
27049 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
27050 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
27051 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27052 		return;
27053 	}
27054 
27055 	ci.ci_ipif = NULL;
27056 	if (ipip->ipi_cmd_type == MISC_CMD) {
27057 		/*
27058 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
27059 		 */
27060 		if (ipip->ipi_cmd == IF_UNITSEL) {
27061 			/* ioctl comes down the ill */
27062 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
27063 			ipif_refhold(ci.ci_ipif);
27064 		}
27065 		err = 0;
27066 		ci.ci_sin = NULL;
27067 		ci.ci_sin6 = NULL;
27068 		ci.ci_lifr = NULL;
27069 	} else {
27070 		switch (ipip->ipi_cmd_type) {
27071 		case IF_CMD:
27072 		case LIF_CMD:
27073 			extract_funcp = ip_extract_lifreq;
27074 			break;
27075 
27076 		case ARP_CMD:
27077 		case XARP_CMD:
27078 			extract_funcp = ip_extract_arpreq;
27079 			break;
27080 
27081 		case TUN_CMD:
27082 			extract_funcp = ip_extract_tunreq;
27083 			break;
27084 
27085 		case MSFILT_CMD:
27086 			extract_funcp = ip_extract_msfilter;
27087 			break;
27088 
27089 		default:
27090 			ASSERT(0);
27091 		}
27092 
27093 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
27094 		if (err != 0) {
27095 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27096 			return;
27097 		}
27098 
27099 		/*
27100 		 * All of the extraction functions return a refheld ipif.
27101 		 */
27102 		ASSERT(ci.ci_ipif != NULL);
27103 	}
27104 
27105 	if (!(ipip->ipi_flags & IPI_WR)) {
27106 		/*
27107 		 * A return value of EINPROGRESS means the ioctl is
27108 		 * either queued and waiting for some reason or has
27109 		 * already completed.
27110 		 */
27111 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
27112 		    ci.ci_lifr);
27113 		if (ci.ci_ipif != NULL)
27114 			ipif_refrele(ci.ci_ipif);
27115 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27116 		return;
27117 	}
27118 
27119 	/*
27120 	 * If ipsq is non-null, we are already being called exclusively on an
27121 	 * ill but in the case of a failover in progress it is the "from" ill,
27122 	 *  rather than the "to" ill (which is the ill ptr passed in).
27123 	 * In order to ensure we are exclusive on both ILLs we rerun
27124 	 * ipsq_try_enter() here, ipsq's support recursive entry.
27125 	 */
27126 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
27127 	ASSERT(ci.ci_ipif != NULL);
27128 
27129 	ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
27130 	    NEW_OP, B_TRUE);
27131 
27132 	/*
27133 	 * Release the ipif so that ipif_down and friends that wait for
27134 	 * references to go away are not misled about the current ipif_refcnt
27135 	 * values. We are writer so we can access the ipif even after releasing
27136 	 * the ipif.
27137 	 */
27138 	ipif_refrele(ci.ci_ipif);
27139 	if (ipsq == NULL)
27140 		return;
27141 
27142 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
27143 
27144 	/*
27145 	 * For most set ioctls that come here, this serves as a single point
27146 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
27147 	 * be any new references to the ipif. This helps functions that go
27148 	 * through this path and end up trying to wait for the refcnts
27149 	 * associated with the ipif to go down to zero. Some exceptions are
27150 	 * Failover, Failback, and Groupname commands that operate on more than
27151 	 * just the ci.ci_ipif. These commands internally determine the
27152 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
27153 	 * flags on that set. Another exception is the Removeif command that
27154 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
27155 	 * ipif to operate on.
27156 	 */
27157 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
27158 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
27159 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
27160 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
27161 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
27162 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
27163 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
27164 
27165 	/*
27166 	 * A return value of EINPROGRESS means the ioctl is
27167 	 * either queued and waiting for some reason or has
27168 	 * already completed.
27169 	 */
27170 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
27171 
27172 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27173 
27174 	ipsq_exit(ipsq);
27175 }
27176 
27177 /*
27178  * Complete the ioctl. Typically ioctls use the mi package and need to
27179  * do mi_copyout/mi_copy_done.
27180  */
27181 void
27182 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
27183 {
27184 	conn_t	*connp = NULL;
27185 
27186 	if (err == EINPROGRESS)
27187 		return;
27188 
27189 	if (CONN_Q(q)) {
27190 		connp = Q_TO_CONN(q);
27191 		ASSERT(connp->conn_ref >= 2);
27192 	}
27193 
27194 	switch (mode) {
27195 	case COPYOUT:
27196 		if (err == 0)
27197 			mi_copyout(q, mp);
27198 		else
27199 			mi_copy_done(q, mp, err);
27200 		break;
27201 
27202 	case NO_COPYOUT:
27203 		mi_copy_done(q, mp, err);
27204 		break;
27205 
27206 	default:
27207 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27208 		break;
27209 	}
27210 
27211 	/*
27212 	 * The refhold placed at the start of the ioctl is released here.
27213 	 */
27214 	if (connp != NULL)
27215 		CONN_OPER_PENDING_DONE(connp);
27216 
27217 	if (ipsq != NULL)
27218 		ipsq_current_finish(ipsq);
27219 }
27220 
27221 /*
27222  * This is called from ip_wput_nondata to resume a deferred TCP bind.
27223  */
27224 /* ARGSUSED */
27225 void
27226 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
27227 {
27228 	conn_t *connp = arg;
27229 	tcp_t	*tcp;
27230 
27231 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
27232 	tcp = connp->conn_tcp;
27233 
27234 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
27235 		freemsg(mp);
27236 	else
27237 		tcp_rput_other(tcp, mp);
27238 	CONN_OPER_PENDING_DONE(connp);
27239 }
27240 
27241 /* Called from ip_wput for all non data messages */
27242 /* ARGSUSED */
27243 void
27244 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27245 {
27246 	mblk_t		*mp1;
27247 	ire_t		*ire, *fake_ire;
27248 	ill_t		*ill;
27249 	struct iocblk	*iocp;
27250 	ip_ioctl_cmd_t	*ipip;
27251 	cred_t		*cr;
27252 	conn_t		*connp;
27253 	int		err;
27254 	nce_t		*nce;
27255 	ipif_t		*ipif;
27256 	ip_stack_t	*ipst;
27257 	char		*proto_str;
27258 
27259 	if (CONN_Q(q)) {
27260 		connp = Q_TO_CONN(q);
27261 		ipst = connp->conn_netstack->netstack_ip;
27262 	} else {
27263 		connp = NULL;
27264 		ipst = ILLQ_TO_IPST(q);
27265 	}
27266 
27267 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
27268 
27269 	switch (DB_TYPE(mp)) {
27270 	case M_IOCTL:
27271 		/*
27272 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27273 		 * will arrange to copy in associated control structures.
27274 		 */
27275 		ip_sioctl_copyin_setup(q, mp);
27276 		return;
27277 	case M_IOCDATA:
27278 		/*
27279 		 * Ensure that this is associated with one of our trans-
27280 		 * parent ioctls.  If it's not ours, discard it if we're
27281 		 * running as a driver, or pass it on if we're a module.
27282 		 */
27283 		iocp = (struct iocblk *)mp->b_rptr;
27284 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27285 		if (ipip == NULL) {
27286 			if (q->q_next == NULL) {
27287 				goto nak;
27288 			} else {
27289 				putnext(q, mp);
27290 			}
27291 			return;
27292 		}
27293 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
27294 			/*
27295 			 * the ioctl is one we recognise, but is not
27296 			 * consumed by IP as a module, pass M_IOCDATA
27297 			 * for processing downstream, but only for
27298 			 * common Streams ioctls.
27299 			 */
27300 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27301 				putnext(q, mp);
27302 				return;
27303 			} else {
27304 				goto nak;
27305 			}
27306 		}
27307 
27308 		/* IOCTL continuation following copyin or copyout. */
27309 		if (mi_copy_state(q, mp, NULL) == -1) {
27310 			/*
27311 			 * The copy operation failed.  mi_copy_state already
27312 			 * cleaned up, so we're out of here.
27313 			 */
27314 			return;
27315 		}
27316 		/*
27317 		 * If we just completed a copy in, we become writer and
27318 		 * continue processing in ip_sioctl_copyin_done.  If it
27319 		 * was a copy out, we call mi_copyout again.  If there is
27320 		 * nothing more to copy out, it will complete the IOCTL.
27321 		 */
27322 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27323 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27324 				mi_copy_done(q, mp, EPROTO);
27325 				return;
27326 			}
27327 			/*
27328 			 * Check for cases that need more copying.  A return
27329 			 * value of 0 means a second copyin has been started,
27330 			 * so we return; a return value of 1 means no more
27331 			 * copying is needed, so we continue.
27332 			 */
27333 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27334 			    MI_COPY_COUNT(mp) == 1) {
27335 				if (ip_copyin_msfilter(q, mp) == 0)
27336 					return;
27337 			}
27338 			/*
27339 			 * Refhold the conn, till the ioctl completes. This is
27340 			 * needed in case the ioctl ends up in the pending mp
27341 			 * list. Every mp in the ill_pending_mp list and
27342 			 * the ipsq_pending_mp must have a refhold on the conn
27343 			 * to resume processing. The refhold is released when
27344 			 * the ioctl completes. (normally or abnormally)
27345 			 * In all cases ip_ioctl_finish is called to finish
27346 			 * the ioctl.
27347 			 */
27348 			if (connp != NULL) {
27349 				/* This is not a reentry */
27350 				ASSERT(ipsq == NULL);
27351 				CONN_INC_REF(connp);
27352 			} else {
27353 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27354 					mi_copy_done(q, mp, EINVAL);
27355 					return;
27356 				}
27357 			}
27358 
27359 			ip_process_ioctl(ipsq, q, mp, ipip);
27360 
27361 		} else {
27362 			mi_copyout(q, mp);
27363 		}
27364 		return;
27365 nak:
27366 		iocp->ioc_error = EINVAL;
27367 		mp->b_datap->db_type = M_IOCNAK;
27368 		iocp->ioc_count = 0;
27369 		qreply(q, mp);
27370 		return;
27371 
27372 	case M_IOCNAK:
27373 		/*
27374 		 * The only way we could get here is if a resolver didn't like
27375 		 * an IOCTL we sent it.	 This shouldn't happen.
27376 		 */
27377 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27378 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27379 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27380 		freemsg(mp);
27381 		return;
27382 	case M_IOCACK:
27383 		/* /dev/ip shouldn't see this */
27384 		if (CONN_Q(q))
27385 			goto nak;
27386 
27387 		/* Finish socket ioctls passed through to ARP. */
27388 		ip_sioctl_iocack(q, mp);
27389 		return;
27390 	case M_FLUSH:
27391 		if (*mp->b_rptr & FLUSHW)
27392 			flushq(q, FLUSHALL);
27393 		if (q->q_next) {
27394 			putnext(q, mp);
27395 			return;
27396 		}
27397 		if (*mp->b_rptr & FLUSHR) {
27398 			*mp->b_rptr &= ~FLUSHW;
27399 			qreply(q, mp);
27400 			return;
27401 		}
27402 		freemsg(mp);
27403 		return;
27404 	case IRE_DB_REQ_TYPE:
27405 		if (connp == NULL) {
27406 			proto_str = "IRE_DB_REQ_TYPE";
27407 			goto protonak;
27408 		}
27409 		/* An Upper Level Protocol wants a copy of an IRE. */
27410 		ip_ire_req(q, mp);
27411 		return;
27412 	case M_CTL:
27413 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27414 			break;
27415 
27416 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27417 		    TUN_HELLO) {
27418 			ASSERT(connp != NULL);
27419 			connp->conn_flags |= IPCL_IPTUN;
27420 			freeb(mp);
27421 			return;
27422 		}
27423 
27424 		/* M_CTL messages are used by ARP to tell us things. */
27425 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27426 			break;
27427 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27428 		case AR_ENTRY_SQUERY:
27429 			ip_wput_ctl(q, mp);
27430 			return;
27431 		case AR_CLIENT_NOTIFY:
27432 			ip_arp_news(q, mp);
27433 			return;
27434 		case AR_DLPIOP_DONE:
27435 			ASSERT(q->q_next != NULL);
27436 			ill = (ill_t *)q->q_ptr;
27437 			/* qwriter_ip releases the refhold */
27438 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27439 			ill_refhold(ill);
27440 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27441 			return;
27442 		case AR_ARP_CLOSING:
27443 			/*
27444 			 * ARP (above us) is closing. If no ARP bringup is
27445 			 * currently pending, ack the message so that ARP
27446 			 * can complete its close. Also mark ill_arp_closing
27447 			 * so that new ARP bringups will fail. If any
27448 			 * ARP bringup is currently in progress, we will
27449 			 * ack this when the current ARP bringup completes.
27450 			 */
27451 			ASSERT(q->q_next != NULL);
27452 			ill = (ill_t *)q->q_ptr;
27453 			mutex_enter(&ill->ill_lock);
27454 			ill->ill_arp_closing = 1;
27455 			if (!ill->ill_arp_bringup_pending) {
27456 				mutex_exit(&ill->ill_lock);
27457 				qreply(q, mp);
27458 			} else {
27459 				mutex_exit(&ill->ill_lock);
27460 				freemsg(mp);
27461 			}
27462 			return;
27463 		case AR_ARP_EXTEND:
27464 			/*
27465 			 * The ARP module above us is capable of duplicate
27466 			 * address detection.  Old ATM drivers will not send
27467 			 * this message.
27468 			 */
27469 			ASSERT(q->q_next != NULL);
27470 			ill = (ill_t *)q->q_ptr;
27471 			ill->ill_arp_extend = B_TRUE;
27472 			freemsg(mp);
27473 			return;
27474 		default:
27475 			break;
27476 		}
27477 		break;
27478 	case M_PROTO:
27479 	case M_PCPROTO:
27480 		/*
27481 		 * The only PROTO messages we expect are ULP binds and
27482 		 * copies of option negotiation acknowledgements.
27483 		 */
27484 		switch (((union T_primitives *)mp->b_rptr)->type) {
27485 		case O_T_BIND_REQ:
27486 		case T_BIND_REQ: {
27487 			/* Request can get queued in bind */
27488 			if (connp == NULL) {
27489 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27490 				goto protonak;
27491 			}
27492 			/*
27493 			 * The transports except SCTP call ip_bind_{v4,v6}()
27494 			 * directly instead of a a putnext. SCTP doesn't
27495 			 * generate any T_BIND_REQ since it has its own
27496 			 * fanout data structures. However, ESP and AH
27497 			 * come in for regular binds; all other cases are
27498 			 * bind retries.
27499 			 */
27500 			ASSERT(!IPCL_IS_SCTP(connp));
27501 
27502 			/* Don't increment refcnt if this is a re-entry */
27503 			if (ipsq == NULL)
27504 				CONN_INC_REF(connp);
27505 
27506 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27507 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27508 			if (mp == NULL)
27509 				return;
27510 			if (IPCL_IS_TCP(connp)) {
27511 				/*
27512 				 * In the case of TCP endpoint we
27513 				 * come here only for bind retries
27514 				 */
27515 				ASSERT(ipsq != NULL);
27516 				CONN_INC_REF(connp);
27517 				squeue_fill(connp->conn_sqp, mp,
27518 				    ip_resume_tcp_bind, connp,
27519 				    SQTAG_BIND_RETRY);
27520 			} else if (IPCL_IS_UDP(connp)) {
27521 				/*
27522 				 * In the case of UDP endpoint we
27523 				 * come here only for bind retries
27524 				 */
27525 				ASSERT(ipsq != NULL);
27526 				udp_resume_bind(connp, mp);
27527 			} else if (IPCL_IS_RAWIP(connp)) {
27528 				/*
27529 				 * In the case of RAWIP endpoint we
27530 				 * come here only for bind retries
27531 				 */
27532 				ASSERT(ipsq != NULL);
27533 				rawip_resume_bind(connp, mp);
27534 			} else {
27535 				/* The case of AH and ESP */
27536 				qreply(q, mp);
27537 				CONN_OPER_PENDING_DONE(connp);
27538 			}
27539 			return;
27540 		}
27541 		case T_SVR4_OPTMGMT_REQ:
27542 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27543 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27544 
27545 			if (connp == NULL) {
27546 				proto_str = "T_SVR4_OPTMGMT_REQ";
27547 				goto protonak;
27548 			}
27549 
27550 			if (!snmpcom_req(q, mp, ip_snmp_set,
27551 			    ip_snmp_get, cr)) {
27552 				/*
27553 				 * Call svr4_optcom_req so that it can
27554 				 * generate the ack. We don't come here
27555 				 * if this operation is being restarted.
27556 				 * ip_restart_optmgmt will drop the conn ref.
27557 				 * In the case of ipsec option after the ipsec
27558 				 * load is complete conn_restart_ipsec_waiter
27559 				 * drops the conn ref.
27560 				 */
27561 				ASSERT(ipsq == NULL);
27562 				CONN_INC_REF(connp);
27563 				if (ip_check_for_ipsec_opt(q, mp))
27564 					return;
27565 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj,
27566 				    B_FALSE);
27567 				if (err != EINPROGRESS) {
27568 					/* Operation is done */
27569 					CONN_OPER_PENDING_DONE(connp);
27570 				}
27571 			}
27572 			return;
27573 		case T_OPTMGMT_REQ:
27574 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27575 			/*
27576 			 * Note: No snmpcom_req support through new
27577 			 * T_OPTMGMT_REQ.
27578 			 * Call tpi_optcom_req so that it can
27579 			 * generate the ack.
27580 			 */
27581 			if (connp == NULL) {
27582 				proto_str = "T_OPTMGMT_REQ";
27583 				goto protonak;
27584 			}
27585 
27586 			ASSERT(ipsq == NULL);
27587 			/*
27588 			 * We don't come here for restart. ip_restart_optmgmt
27589 			 * will drop the conn ref. In the case of ipsec option
27590 			 * after the ipsec load is complete
27591 			 * conn_restart_ipsec_waiter drops the conn ref.
27592 			 */
27593 			CONN_INC_REF(connp);
27594 			if (ip_check_for_ipsec_opt(q, mp))
27595 				return;
27596 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj, B_FALSE);
27597 			if (err != EINPROGRESS) {
27598 				/* Operation is done */
27599 				CONN_OPER_PENDING_DONE(connp);
27600 			}
27601 			return;
27602 		case T_UNBIND_REQ:
27603 			if (connp == NULL) {
27604 				proto_str = "T_UNBIND_REQ";
27605 				goto protonak;
27606 			}
27607 			mp = ip_unbind(q, mp);
27608 			qreply(q, mp);
27609 			return;
27610 		default:
27611 			/*
27612 			 * Have to drop any DLPI messages coming down from
27613 			 * arp (such as an info_req which would cause ip
27614 			 * to receive an extra info_ack if it was passed
27615 			 * through.
27616 			 */
27617 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27618 			    (int)*(uint_t *)mp->b_rptr));
27619 			freemsg(mp);
27620 			return;
27621 		}
27622 		/* NOTREACHED */
27623 	case IRE_DB_TYPE: {
27624 		nce_t		*nce;
27625 		ill_t		*ill;
27626 		in6_addr_t	gw_addr_v6;
27627 
27628 
27629 		/*
27630 		 * This is a response back from a resolver.  It
27631 		 * consists of a message chain containing:
27632 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27633 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27634 		 * The LL_HDR_MBLK is the DLPI header to use to get
27635 		 * the attached packet, and subsequent ones for the
27636 		 * same destination, transmitted.
27637 		 */
27638 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27639 			break;
27640 		/*
27641 		 * First, check to make sure the resolution succeeded.
27642 		 * If it failed, the second mblk will be empty.
27643 		 * If it is, free the chain, dropping the packet.
27644 		 * (We must ire_delete the ire; that frees the ire mblk)
27645 		 * We're doing this now to support PVCs for ATM; it's
27646 		 * a partial xresolv implementation. When we fully implement
27647 		 * xresolv interfaces, instead of freeing everything here
27648 		 * we'll initiate neighbor discovery.
27649 		 *
27650 		 * For v4 (ARP and other external resolvers) the resolver
27651 		 * frees the message, so no check is needed. This check
27652 		 * is required, though, for a full xresolve implementation.
27653 		 * Including this code here now both shows how external
27654 		 * resolvers can NACK a resolution request using an
27655 		 * existing design that has no specific provisions for NACKs,
27656 		 * and also takes into account that the current non-ARP
27657 		 * external resolver has been coded to use this method of
27658 		 * NACKing for all IPv6 (xresolv) cases,
27659 		 * whether our xresolv implementation is complete or not.
27660 		 *
27661 		 */
27662 		ire = (ire_t *)mp->b_rptr;
27663 		ill = ire_to_ill(ire);
27664 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27665 		if (mp1->b_rptr == mp1->b_wptr) {
27666 			if (ire->ire_ipversion == IPV6_VERSION) {
27667 				/*
27668 				 * XRESOLV interface.
27669 				 */
27670 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27671 				mutex_enter(&ire->ire_lock);
27672 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27673 				mutex_exit(&ire->ire_lock);
27674 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27675 					nce = ndp_lookup_v6(ill,
27676 					    &ire->ire_addr_v6, B_FALSE);
27677 				} else {
27678 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
27679 					    B_FALSE);
27680 				}
27681 				if (nce != NULL) {
27682 					nce_resolv_failed(nce);
27683 					ndp_delete(nce);
27684 					NCE_REFRELE(nce);
27685 				}
27686 			}
27687 			mp->b_cont = NULL;
27688 			freemsg(mp1);		/* frees the pkt as well */
27689 			ASSERT(ire->ire_nce == NULL);
27690 			ire_delete((ire_t *)mp->b_rptr);
27691 			return;
27692 		}
27693 
27694 		/*
27695 		 * Split them into IRE_MBLK and pkt and feed it into
27696 		 * ire_add_then_send. Then in ire_add_then_send
27697 		 * the IRE will be added, and then the packet will be
27698 		 * run back through ip_wput. This time it will make
27699 		 * it to the wire.
27700 		 */
27701 		mp->b_cont = NULL;
27702 		mp = mp1->b_cont;		/* now, mp points to pkt */
27703 		mp1->b_cont = NULL;
27704 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27705 		if (ire->ire_ipversion == IPV6_VERSION) {
27706 			/*
27707 			 * XRESOLV interface. Find the nce and put a copy
27708 			 * of the dl_unitdata_req in nce_res_mp
27709 			 */
27710 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27711 			mutex_enter(&ire->ire_lock);
27712 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27713 			mutex_exit(&ire->ire_lock);
27714 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27715 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
27716 				    B_FALSE);
27717 			} else {
27718 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
27719 			}
27720 			if (nce != NULL) {
27721 				/*
27722 				 * We have to protect nce_res_mp here
27723 				 * from being accessed by other threads
27724 				 * while we change the mblk pointer.
27725 				 * Other functions will also lock the nce when
27726 				 * accessing nce_res_mp.
27727 				 *
27728 				 * The reason we change the mblk pointer
27729 				 * here rather than copying the resolved address
27730 				 * into the template is that, unlike with
27731 				 * ethernet, we have no guarantee that the
27732 				 * resolved address length will be
27733 				 * smaller than or equal to the lla length
27734 				 * with which the template was allocated,
27735 				 * (for ethernet, they're equal)
27736 				 * so we have to use the actual resolved
27737 				 * address mblk - which holds the real
27738 				 * dl_unitdata_req with the resolved address.
27739 				 *
27740 				 * Doing this is the same behavior as was
27741 				 * previously used in the v4 ARP case.
27742 				 */
27743 				mutex_enter(&nce->nce_lock);
27744 				if (nce->nce_res_mp != NULL)
27745 					freemsg(nce->nce_res_mp);
27746 				nce->nce_res_mp = mp1;
27747 				mutex_exit(&nce->nce_lock);
27748 				/*
27749 				 * We do a fastpath probe here because
27750 				 * we have resolved the address without
27751 				 * using Neighbor Discovery.
27752 				 * In the non-XRESOLV v6 case, the fastpath
27753 				 * probe is done right after neighbor
27754 				 * discovery completes.
27755 				 */
27756 				if (nce->nce_res_mp != NULL) {
27757 					int res;
27758 					nce_fastpath_list_add(nce);
27759 					res = ill_fastpath_probe(ill,
27760 					    nce->nce_res_mp);
27761 					if (res != 0 && res != EAGAIN)
27762 						nce_fastpath_list_delete(nce);
27763 				}
27764 
27765 				ire_add_then_send(q, ire, mp);
27766 				/*
27767 				 * Now we have to clean out any packets
27768 				 * that may have been queued on the nce
27769 				 * while it was waiting for address resolution
27770 				 * to complete.
27771 				 */
27772 				mutex_enter(&nce->nce_lock);
27773 				mp1 = nce->nce_qd_mp;
27774 				nce->nce_qd_mp = NULL;
27775 				mutex_exit(&nce->nce_lock);
27776 				while (mp1 != NULL) {
27777 					mblk_t *nxt_mp;
27778 					queue_t *fwdq = NULL;
27779 					ill_t   *inbound_ill;
27780 					uint_t ifindex;
27781 
27782 					nxt_mp = mp1->b_next;
27783 					mp1->b_next = NULL;
27784 					/*
27785 					 * Retrieve ifindex stored in
27786 					 * ip_rput_data_v6()
27787 					 */
27788 					ifindex =
27789 					    (uint_t)(uintptr_t)mp1->b_prev;
27790 					inbound_ill =
27791 					    ill_lookup_on_ifindex(ifindex,
27792 					    B_TRUE, NULL, NULL, NULL,
27793 					    NULL, ipst);
27794 					mp1->b_prev = NULL;
27795 					if (inbound_ill != NULL)
27796 						fwdq = inbound_ill->ill_rq;
27797 
27798 					if (fwdq != NULL) {
27799 						put(fwdq, mp1);
27800 						ill_refrele(inbound_ill);
27801 					} else
27802 						put(WR(ill->ill_rq), mp1);
27803 					mp1 = nxt_mp;
27804 				}
27805 				NCE_REFRELE(nce);
27806 			} else {	/* nce is NULL; clean up */
27807 				ire_delete(ire);
27808 				freemsg(mp);
27809 				freemsg(mp1);
27810 				return;
27811 			}
27812 		} else {
27813 			nce_t *arpce;
27814 			/*
27815 			 * Link layer resolution succeeded. Recompute the
27816 			 * ire_nce.
27817 			 */
27818 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27819 			if ((arpce = ndp_lookup_v4(ill,
27820 			    (ire->ire_gateway_addr != INADDR_ANY ?
27821 			    &ire->ire_gateway_addr : &ire->ire_addr),
27822 			    B_FALSE)) == NULL) {
27823 				freeb(ire->ire_mp);
27824 				freeb(mp1);
27825 				freemsg(mp);
27826 				return;
27827 			}
27828 			mutex_enter(&arpce->nce_lock);
27829 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27830 			if (arpce->nce_state == ND_REACHABLE) {
27831 				/*
27832 				 * Someone resolved this before us;
27833 				 * cleanup the res_mp. Since ire has
27834 				 * not been added yet, the call to ire_add_v4
27835 				 * from ire_add_then_send (when a dup is
27836 				 * detected) will clean up the ire.
27837 				 */
27838 				freeb(mp1);
27839 			} else {
27840 				ASSERT(arpce->nce_res_mp == NULL);
27841 				arpce->nce_res_mp = mp1;
27842 				arpce->nce_state = ND_REACHABLE;
27843 			}
27844 			mutex_exit(&arpce->nce_lock);
27845 			if (ire->ire_marks & IRE_MARK_NOADD) {
27846 				/*
27847 				 * this ire will not be added to the ire
27848 				 * cache table, so we can set the ire_nce
27849 				 * here, as there are no atomicity constraints.
27850 				 */
27851 				ire->ire_nce = arpce;
27852 				/*
27853 				 * We are associating this nce with the ire
27854 				 * so change the nce ref taken in
27855 				 * ndp_lookup_v4() from
27856 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27857 				 */
27858 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27859 			} else {
27860 				NCE_REFRELE(arpce);
27861 			}
27862 			ire_add_then_send(q, ire, mp);
27863 		}
27864 		return;	/* All is well, the packet has been sent. */
27865 	}
27866 	case IRE_ARPRESOLVE_TYPE: {
27867 
27868 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27869 			break;
27870 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27871 		mp->b_cont = NULL;
27872 		/*
27873 		 * First, check to make sure the resolution succeeded.
27874 		 * If it failed, the second mblk will be empty.
27875 		 */
27876 		if (mp1->b_rptr == mp1->b_wptr) {
27877 			/* cleanup  the incomplete ire, free queued packets */
27878 			freemsg(mp); /* fake ire */
27879 			freeb(mp1);  /* dl_unitdata response */
27880 			return;
27881 		}
27882 
27883 		/*
27884 		 * update any incomplete nce_t found. we lookup the ctable
27885 		 * and find the nce from the ire->ire_nce because we need
27886 		 * to pass the ire to ip_xmit_v4 later, and can find both
27887 		 * ire and nce in one lookup from the ctable.
27888 		 */
27889 		fake_ire = (ire_t *)mp->b_rptr;
27890 		/*
27891 		 * By the time we come back here from ARP
27892 		 * the logical outgoing interface  of the incomplete ire
27893 		 * we added in ire_forward could have disappeared,
27894 		 * causing the incomplete ire to also have
27895 		 * dissapeared. So we need to retreive the
27896 		 * proper ipif for the ire  before looking
27897 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
27898 		 */
27899 		ill = q->q_ptr;
27900 
27901 		/* Get the outgoing ipif */
27902 		mutex_enter(&ill->ill_lock);
27903 		if (ill->ill_state_flags & ILL_CONDEMNED) {
27904 			mutex_exit(&ill->ill_lock);
27905 			freemsg(mp); /* fake ire */
27906 			freeb(mp1);  /* dl_unitdata response */
27907 			return;
27908 		}
27909 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27910 
27911 		if (ipif == NULL) {
27912 			mutex_exit(&ill->ill_lock);
27913 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27914 			freemsg(mp);
27915 			freeb(mp1);
27916 			return;
27917 		}
27918 		ipif_refhold_locked(ipif);
27919 		mutex_exit(&ill->ill_lock);
27920 		ire = ire_ctable_lookup(fake_ire->ire_addr,
27921 		    fake_ire->ire_gateway_addr, IRE_CACHE,
27922 		    ipif, fake_ire->ire_zoneid, NULL,
27923 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY|
27924 		    MATCH_IRE_TYPE), ipst);
27925 		ipif_refrele(ipif);
27926 		if (ire == NULL) {
27927 			/*
27928 			 * no ire was found; check if there is an nce
27929 			 * for this lookup; if it has no ire's pointing at it
27930 			 * cleanup.
27931 			 */
27932 			if ((nce = ndp_lookup_v4(ill,
27933 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27934 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27935 			    B_FALSE)) != NULL) {
27936 				/*
27937 				 * cleanup:
27938 				 * We check for refcnt 2 (one for the nce
27939 				 * hash list + 1 for the ref taken by
27940 				 * ndp_lookup_v4) to check that there are
27941 				 * no ire's pointing at the nce.
27942 				 */
27943 				if (nce->nce_refcnt == 2)
27944 					ndp_delete(nce);
27945 				NCE_REFRELE(nce);
27946 			}
27947 			freeb(mp1);  /* dl_unitdata response */
27948 			freemsg(mp); /* fake ire */
27949 			return;
27950 		}
27951 		nce = ire->ire_nce;
27952 		DTRACE_PROBE2(ire__arpresolve__type,
27953 		    ire_t *, ire, nce_t *, nce);
27954 		ASSERT(nce->nce_state != ND_INITIAL);
27955 		mutex_enter(&nce->nce_lock);
27956 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27957 		if (nce->nce_state == ND_REACHABLE) {
27958 			/*
27959 			 * Someone resolved this before us;
27960 			 * our response is not needed any more.
27961 			 */
27962 			mutex_exit(&nce->nce_lock);
27963 			freeb(mp1);  /* dl_unitdata response */
27964 		} else {
27965 			ASSERT(nce->nce_res_mp == NULL);
27966 			nce->nce_res_mp = mp1;
27967 			nce->nce_state = ND_REACHABLE;
27968 			mutex_exit(&nce->nce_lock);
27969 			nce_fastpath(nce);
27970 		}
27971 		/*
27972 		 * The cached nce_t has been updated to be reachable;
27973 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
27974 		 */
27975 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27976 		freemsg(mp);
27977 		/*
27978 		 * send out queued packets.
27979 		 */
27980 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
27981 
27982 		IRE_REFRELE(ire);
27983 		return;
27984 	}
27985 	default:
27986 		break;
27987 	}
27988 	if (q->q_next) {
27989 		putnext(q, mp);
27990 	} else
27991 		freemsg(mp);
27992 	return;
27993 
27994 protonak:
27995 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
27996 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
27997 		qreply(q, mp);
27998 }
27999 
28000 /*
28001  * Process IP options in an outbound packet.  Modify the destination if there
28002  * is a source route option.
28003  * Returns non-zero if something fails in which case an ICMP error has been
28004  * sent and mp freed.
28005  */
28006 static int
28007 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
28008     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
28009 {
28010 	ipoptp_t	opts;
28011 	uchar_t		*opt;
28012 	uint8_t		optval;
28013 	uint8_t		optlen;
28014 	ipaddr_t	dst;
28015 	intptr_t	code = 0;
28016 	mblk_t		*mp;
28017 	ire_t		*ire = NULL;
28018 
28019 	ip2dbg(("ip_wput_options\n"));
28020 	mp = ipsec_mp;
28021 	if (mctl_present) {
28022 		mp = ipsec_mp->b_cont;
28023 	}
28024 
28025 	dst = ipha->ipha_dst;
28026 	for (optval = ipoptp_first(&opts, ipha);
28027 	    optval != IPOPT_EOL;
28028 	    optval = ipoptp_next(&opts)) {
28029 		opt = opts.ipoptp_cur;
28030 		optlen = opts.ipoptp_len;
28031 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
28032 		    optval, optlen));
28033 		switch (optval) {
28034 			uint32_t off;
28035 		case IPOPT_SSRR:
28036 		case IPOPT_LSRR:
28037 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28038 				ip1dbg((
28039 				    "ip_wput_options: bad option offset\n"));
28040 				code = (char *)&opt[IPOPT_OLEN] -
28041 				    (char *)ipha;
28042 				goto param_prob;
28043 			}
28044 			off = opt[IPOPT_OFFSET];
28045 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
28046 			    ntohl(dst)));
28047 			/*
28048 			 * For strict: verify that dst is directly
28049 			 * reachable.
28050 			 */
28051 			if (optval == IPOPT_SSRR) {
28052 				ire = ire_ftable_lookup(dst, 0, 0,
28053 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
28054 				    MBLK_GETLABEL(mp),
28055 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
28056 				if (ire == NULL) {
28057 					ip1dbg(("ip_wput_options: SSRR not"
28058 					    " directly reachable: 0x%x\n",
28059 					    ntohl(dst)));
28060 					goto bad_src_route;
28061 				}
28062 				ire_refrele(ire);
28063 			}
28064 			break;
28065 		case IPOPT_RR:
28066 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28067 				ip1dbg((
28068 				    "ip_wput_options: bad option offset\n"));
28069 				code = (char *)&opt[IPOPT_OLEN] -
28070 				    (char *)ipha;
28071 				goto param_prob;
28072 			}
28073 			break;
28074 		case IPOPT_TS:
28075 			/*
28076 			 * Verify that length >=5 and that there is either
28077 			 * room for another timestamp or that the overflow
28078 			 * counter is not maxed out.
28079 			 */
28080 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
28081 			if (optlen < IPOPT_MINLEN_IT) {
28082 				goto param_prob;
28083 			}
28084 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28085 				ip1dbg((
28086 				    "ip_wput_options: bad option offset\n"));
28087 				code = (char *)&opt[IPOPT_OFFSET] -
28088 				    (char *)ipha;
28089 				goto param_prob;
28090 			}
28091 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
28092 			case IPOPT_TS_TSONLY:
28093 				off = IPOPT_TS_TIMELEN;
28094 				break;
28095 			case IPOPT_TS_TSANDADDR:
28096 			case IPOPT_TS_PRESPEC:
28097 			case IPOPT_TS_PRESPEC_RFC791:
28098 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
28099 				break;
28100 			default:
28101 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
28102 				    (char *)ipha;
28103 				goto param_prob;
28104 			}
28105 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
28106 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
28107 				/*
28108 				 * No room and the overflow counter is 15
28109 				 * already.
28110 				 */
28111 				goto param_prob;
28112 			}
28113 			break;
28114 		}
28115 	}
28116 
28117 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
28118 		return (0);
28119 
28120 	ip1dbg(("ip_wput_options: error processing IP options."));
28121 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
28122 
28123 param_prob:
28124 	/*
28125 	 * Since ip_wput() isn't close to finished, we fill
28126 	 * in enough of the header for credible error reporting.
28127 	 */
28128 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28129 		/* Failed */
28130 		freemsg(ipsec_mp);
28131 		return (-1);
28132 	}
28133 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
28134 	return (-1);
28135 
28136 bad_src_route:
28137 	/*
28138 	 * Since ip_wput() isn't close to finished, we fill
28139 	 * in enough of the header for credible error reporting.
28140 	 */
28141 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28142 		/* Failed */
28143 		freemsg(ipsec_mp);
28144 		return (-1);
28145 	}
28146 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
28147 	return (-1);
28148 }
28149 
28150 /*
28151  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
28152  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
28153  * thru /etc/system.
28154  */
28155 #define	CONN_MAXDRAINCNT	64
28156 
28157 static void
28158 conn_drain_init(ip_stack_t *ipst)
28159 {
28160 	int i;
28161 
28162 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
28163 
28164 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
28165 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
28166 		/*
28167 		 * Default value of the number of drainers is the
28168 		 * number of cpus, subject to maximum of 8 drainers.
28169 		 */
28170 		if (boot_max_ncpus != -1)
28171 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
28172 		else
28173 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
28174 	}
28175 
28176 	ipst->ips_conn_drain_list = kmem_zalloc(ipst->ips_conn_drain_list_cnt *
28177 	    sizeof (idl_t), KM_SLEEP);
28178 
28179 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28180 		mutex_init(&ipst->ips_conn_drain_list[i].idl_lock, NULL,
28181 		    MUTEX_DEFAULT, NULL);
28182 	}
28183 }
28184 
28185 static void
28186 conn_drain_fini(ip_stack_t *ipst)
28187 {
28188 	int i;
28189 
28190 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++)
28191 		mutex_destroy(&ipst->ips_conn_drain_list[i].idl_lock);
28192 	kmem_free(ipst->ips_conn_drain_list,
28193 	    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28194 	ipst->ips_conn_drain_list = NULL;
28195 }
28196 
28197 /*
28198  * Note: For an overview of how flowcontrol is handled in IP please see the
28199  * IP Flowcontrol notes at the top of this file.
28200  *
28201  * Flow control has blocked us from proceeding. Insert the given conn in one
28202  * of the conn drain lists. These conn wq's will be qenabled later on when
28203  * STREAMS flow control does a backenable. conn_walk_drain will enable
28204  * the first conn in each of these drain lists. Each of these qenabled conns
28205  * in turn enables the next in the list, after it runs, or when it closes,
28206  * thus sustaining the drain process.
28207  *
28208  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
28209  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
28210  * running at any time, on a given conn, since there can be only 1 service proc
28211  * running on a queue at any time.
28212  */
28213 void
28214 conn_drain_insert(conn_t *connp)
28215 {
28216 	idl_t	*idl;
28217 	uint_t	index;
28218 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28219 
28220 	mutex_enter(&connp->conn_lock);
28221 	if (connp->conn_state_flags & CONN_CLOSING) {
28222 		/*
28223 		 * The conn is closing as a result of which CONN_CLOSING
28224 		 * is set. Return.
28225 		 */
28226 		mutex_exit(&connp->conn_lock);
28227 		return;
28228 	} else if (connp->conn_idl == NULL) {
28229 		/*
28230 		 * Assign the next drain list round robin. We dont' use
28231 		 * a lock, and thus it may not be strictly round robin.
28232 		 * Atomicity of load/stores is enough to make sure that
28233 		 * conn_drain_list_index is always within bounds.
28234 		 */
28235 		index = ipst->ips_conn_drain_list_index;
28236 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28237 		connp->conn_idl = &ipst->ips_conn_drain_list[index];
28238 		index++;
28239 		if (index == ipst->ips_conn_drain_list_cnt)
28240 			index = 0;
28241 		ipst->ips_conn_drain_list_index = index;
28242 	}
28243 	mutex_exit(&connp->conn_lock);
28244 
28245 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28246 	if ((connp->conn_drain_prev != NULL) ||
28247 	    (connp->conn_state_flags & CONN_CLOSING)) {
28248 		/*
28249 		 * The conn is already in the drain list, OR
28250 		 * the conn is closing. We need to check again for
28251 		 * the closing case again since close can happen
28252 		 * after we drop the conn_lock, and before we
28253 		 * acquire the CONN_DRAIN_LIST_LOCK.
28254 		 */
28255 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28256 		return;
28257 	} else {
28258 		idl = connp->conn_idl;
28259 	}
28260 
28261 	/*
28262 	 * The conn is not in the drain list. Insert it at the
28263 	 * tail of the drain list. The drain list is circular
28264 	 * and doubly linked. idl_conn points to the 1st element
28265 	 * in the list.
28266 	 */
28267 	if (idl->idl_conn == NULL) {
28268 		idl->idl_conn = connp;
28269 		connp->conn_drain_next = connp;
28270 		connp->conn_drain_prev = connp;
28271 	} else {
28272 		conn_t *head = idl->idl_conn;
28273 
28274 		connp->conn_drain_next = head;
28275 		connp->conn_drain_prev = head->conn_drain_prev;
28276 		head->conn_drain_prev->conn_drain_next = connp;
28277 		head->conn_drain_prev = connp;
28278 	}
28279 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28280 }
28281 
28282 /*
28283  * This conn is closing, and we are called from ip_close. OR
28284  * This conn has been serviced by ip_wsrv, and we need to do the tail
28285  * processing.
28286  * If this conn is part of the drain list, we may need to sustain the drain
28287  * process by qenabling the next conn in the drain list. We may also need to
28288  * remove this conn from the list, if it is done.
28289  */
28290 static void
28291 conn_drain_tail(conn_t *connp, boolean_t closing)
28292 {
28293 	idl_t *idl;
28294 
28295 	/*
28296 	 * connp->conn_idl is stable at this point, and no lock is needed
28297 	 * to check it. If we are called from ip_close, close has already
28298 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28299 	 * called us only because conn_idl is non-null. If we are called thru
28300 	 * service, conn_idl could be null, but it cannot change because
28301 	 * service is single-threaded per queue, and there cannot be another
28302 	 * instance of service trying to call conn_drain_insert on this conn
28303 	 * now.
28304 	 */
28305 	ASSERT(!closing || (connp->conn_idl != NULL));
28306 
28307 	/*
28308 	 * If connp->conn_idl is null, the conn has not been inserted into any
28309 	 * drain list even once since creation of the conn. Just return.
28310 	 */
28311 	if (connp->conn_idl == NULL)
28312 		return;
28313 
28314 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28315 
28316 	if (connp->conn_drain_prev == NULL) {
28317 		/* This conn is currently not in the drain list.  */
28318 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28319 		return;
28320 	}
28321 	idl = connp->conn_idl;
28322 	if (idl->idl_conn_draining == connp) {
28323 		/*
28324 		 * This conn is the current drainer. If this is the last conn
28325 		 * in the drain list, we need to do more checks, in the 'if'
28326 		 * below. Otherwwise we need to just qenable the next conn,
28327 		 * to sustain the draining, and is handled in the 'else'
28328 		 * below.
28329 		 */
28330 		if (connp->conn_drain_next == idl->idl_conn) {
28331 			/*
28332 			 * This conn is the last in this list. This round
28333 			 * of draining is complete. If idl_repeat is set,
28334 			 * it means another flow enabling has happened from
28335 			 * the driver/streams and we need to another round
28336 			 * of draining.
28337 			 * If there are more than 2 conns in the drain list,
28338 			 * do a left rotate by 1, so that all conns except the
28339 			 * conn at the head move towards the head by 1, and the
28340 			 * the conn at the head goes to the tail. This attempts
28341 			 * a more even share for all queues that are being
28342 			 * drained.
28343 			 */
28344 			if ((connp->conn_drain_next != connp) &&
28345 			    (idl->idl_conn->conn_drain_next != connp)) {
28346 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28347 			}
28348 			if (idl->idl_repeat) {
28349 				qenable(idl->idl_conn->conn_wq);
28350 				idl->idl_conn_draining = idl->idl_conn;
28351 				idl->idl_repeat = 0;
28352 			} else {
28353 				idl->idl_conn_draining = NULL;
28354 			}
28355 		} else {
28356 			/*
28357 			 * If the next queue that we are now qenable'ing,
28358 			 * is closing, it will remove itself from this list
28359 			 * and qenable the subsequent queue in ip_close().
28360 			 * Serialization is acheived thru idl_lock.
28361 			 */
28362 			qenable(connp->conn_drain_next->conn_wq);
28363 			idl->idl_conn_draining = connp->conn_drain_next;
28364 		}
28365 	}
28366 	if (!connp->conn_did_putbq || closing) {
28367 		/*
28368 		 * Remove ourself from the drain list, if we did not do
28369 		 * a putbq, or if the conn is closing.
28370 		 * Note: It is possible that q->q_first is non-null. It means
28371 		 * that these messages landed after we did a enableok() in
28372 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28373 		 * service them.
28374 		 */
28375 		if (connp->conn_drain_next == connp) {
28376 			/* Singleton in the list */
28377 			ASSERT(connp->conn_drain_prev == connp);
28378 			idl->idl_conn = NULL;
28379 			idl->idl_conn_draining = NULL;
28380 		} else {
28381 			connp->conn_drain_prev->conn_drain_next =
28382 			    connp->conn_drain_next;
28383 			connp->conn_drain_next->conn_drain_prev =
28384 			    connp->conn_drain_prev;
28385 			if (idl->idl_conn == connp)
28386 				idl->idl_conn = connp->conn_drain_next;
28387 			ASSERT(idl->idl_conn_draining != connp);
28388 
28389 		}
28390 		connp->conn_drain_next = NULL;
28391 		connp->conn_drain_prev = NULL;
28392 	}
28393 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28394 }
28395 
28396 /*
28397  * Write service routine. Shared perimeter entry point.
28398  * ip_wsrv can be called in any of the following ways.
28399  * 1. The device queue's messages has fallen below the low water mark
28400  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28401  *    the drain lists and backenable the first conn in each list.
28402  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28403  *    qenabled non-tcp upper layers. We start dequeing messages and call
28404  *    ip_wput for each message.
28405  */
28406 
28407 void
28408 ip_wsrv(queue_t *q)
28409 {
28410 	conn_t	*connp;
28411 	ill_t	*ill;
28412 	mblk_t	*mp;
28413 
28414 	if (q->q_next) {
28415 		ill = (ill_t *)q->q_ptr;
28416 		if (ill->ill_state_flags == 0) {
28417 			/*
28418 			 * The device flow control has opened up.
28419 			 * Walk through conn drain lists and qenable the
28420 			 * first conn in each list. This makes sense only
28421 			 * if the stream is fully plumbed and setup.
28422 			 * Hence the if check above.
28423 			 */
28424 			ip1dbg(("ip_wsrv: walking\n"));
28425 			conn_walk_drain(ill->ill_ipst);
28426 		}
28427 		return;
28428 	}
28429 
28430 	connp = Q_TO_CONN(q);
28431 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28432 
28433 	/*
28434 	 * 1. Set conn_draining flag to signal that service is active.
28435 	 *
28436 	 * 2. ip_output determines whether it has been called from service,
28437 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28438 	 *    has been called from service.
28439 	 *
28440 	 * 3. Message ordering is preserved by the following logic.
28441 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28442 	 *    the message at the tail, if conn_draining is set (i.e. service
28443 	 *    is running) or if q->q_first is non-null.
28444 	 *
28445 	 *    ii. If ip_output is called from service, and if ip_output cannot
28446 	 *    putnext due to flow control, it does a putbq.
28447 	 *
28448 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28449 	 *    (causing an infinite loop).
28450 	 */
28451 	ASSERT(!connp->conn_did_putbq);
28452 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28453 		connp->conn_draining = 1;
28454 		noenable(q);
28455 		while ((mp = getq(q)) != NULL) {
28456 			ASSERT(CONN_Q(q));
28457 
28458 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28459 			if (connp->conn_did_putbq) {
28460 				/* ip_wput did a putbq */
28461 				break;
28462 			}
28463 		}
28464 		/*
28465 		 * At this point, a thread coming down from top, calling
28466 		 * ip_wput, may end up queueing the message. We have not yet
28467 		 * enabled the queue, so ip_wsrv won't be called again.
28468 		 * To avoid this race, check q->q_first again (in the loop)
28469 		 * If the other thread queued the message before we call
28470 		 * enableok(), we will catch it in the q->q_first check.
28471 		 * If the other thread queues the message after we call
28472 		 * enableok(), ip_wsrv will be called again by STREAMS.
28473 		 */
28474 		connp->conn_draining = 0;
28475 		enableok(q);
28476 	}
28477 
28478 	/* Enable the next conn for draining */
28479 	conn_drain_tail(connp, B_FALSE);
28480 
28481 	connp->conn_did_putbq = 0;
28482 }
28483 
28484 /*
28485  * Walk the list of all conn's calling the function provided with the
28486  * specified argument for each.	 Note that this only walks conn's that
28487  * have been bound.
28488  * Applies to both IPv4 and IPv6.
28489  */
28490 static void
28491 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28492 {
28493 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28494 	    ipst->ips_ipcl_udp_fanout_size,
28495 	    func, arg, zoneid);
28496 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28497 	    ipst->ips_ipcl_conn_fanout_size,
28498 	    func, arg, zoneid);
28499 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28500 	    ipst->ips_ipcl_bind_fanout_size,
28501 	    func, arg, zoneid);
28502 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28503 	    IPPROTO_MAX, func, arg, zoneid);
28504 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28505 	    IPPROTO_MAX, func, arg, zoneid);
28506 }
28507 
28508 /*
28509  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28510  * of conns that need to be drained, check if drain is already in progress.
28511  * If so set the idl_repeat bit, indicating that the last conn in the list
28512  * needs to reinitiate the drain once again, for the list. If drain is not
28513  * in progress for the list, initiate the draining, by qenabling the 1st
28514  * conn in the list. The drain is self-sustaining, each qenabled conn will
28515  * in turn qenable the next conn, when it is done/blocked/closing.
28516  */
28517 static void
28518 conn_walk_drain(ip_stack_t *ipst)
28519 {
28520 	int i;
28521 	idl_t *idl;
28522 
28523 	IP_STAT(ipst, ip_conn_walk_drain);
28524 
28525 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28526 		idl = &ipst->ips_conn_drain_list[i];
28527 		mutex_enter(&idl->idl_lock);
28528 		if (idl->idl_conn == NULL) {
28529 			mutex_exit(&idl->idl_lock);
28530 			continue;
28531 		}
28532 		/*
28533 		 * If this list is not being drained currently by
28534 		 * an ip_wsrv thread, start the process.
28535 		 */
28536 		if (idl->idl_conn_draining == NULL) {
28537 			ASSERT(idl->idl_repeat == 0);
28538 			qenable(idl->idl_conn->conn_wq);
28539 			idl->idl_conn_draining = idl->idl_conn;
28540 		} else {
28541 			idl->idl_repeat = 1;
28542 		}
28543 		mutex_exit(&idl->idl_lock);
28544 	}
28545 }
28546 
28547 /*
28548  * Walk an conn hash table of `count' buckets, calling func for each entry.
28549  */
28550 static void
28551 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28552     zoneid_t zoneid)
28553 {
28554 	conn_t	*connp;
28555 
28556 	while (count-- > 0) {
28557 		mutex_enter(&connfp->connf_lock);
28558 		for (connp = connfp->connf_head; connp != NULL;
28559 		    connp = connp->conn_next) {
28560 			if (zoneid == GLOBAL_ZONEID ||
28561 			    zoneid == connp->conn_zoneid) {
28562 				CONN_INC_REF(connp);
28563 				mutex_exit(&connfp->connf_lock);
28564 				(*func)(connp, arg);
28565 				mutex_enter(&connfp->connf_lock);
28566 				CONN_DEC_REF(connp);
28567 			}
28568 		}
28569 		mutex_exit(&connfp->connf_lock);
28570 		connfp++;
28571 	}
28572 }
28573 
28574 /* conn_walk_fanout routine invoked for ip_conn_report for each conn. */
28575 static void
28576 conn_report1(conn_t *connp, void *mp)
28577 {
28578 	char	buf1[INET6_ADDRSTRLEN];
28579 	char	buf2[INET6_ADDRSTRLEN];
28580 	uint_t	print_len, buf_len;
28581 
28582 	ASSERT(connp != NULL);
28583 
28584 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28585 	if (buf_len <= 0)
28586 		return;
28587 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1));
28588 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2));
28589 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28590 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28591 	    "%5d %s/%05d %s/%05d\n",
28592 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28593 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28594 	    buf1, connp->conn_lport,
28595 	    buf2, connp->conn_fport);
28596 	if (print_len < buf_len) {
28597 		((mblk_t *)mp)->b_wptr += print_len;
28598 	} else {
28599 		((mblk_t *)mp)->b_wptr += buf_len;
28600 	}
28601 }
28602 
28603 /*
28604  * Named Dispatch routine to produce a formatted report on all conns
28605  * that are listed in one of the fanout tables.
28606  * This report is accessed by using the ndd utility to "get" ND variable
28607  * "ip_conn_status".
28608  */
28609 /* ARGSUSED */
28610 static int
28611 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28612 {
28613 	conn_t *connp = Q_TO_CONN(q);
28614 
28615 	(void) mi_mpprintf(mp,
28616 	    "CONN      " MI_COL_HDRPAD_STR
28617 	    "rfq      " MI_COL_HDRPAD_STR
28618 	    "stq      " MI_COL_HDRPAD_STR
28619 	    " zone local                 remote");
28620 
28621 	/*
28622 	 * Because of the ndd constraint, at most we can have 64K buffer
28623 	 * to put in all conn info.  So to be more efficient, just
28624 	 * allocate a 64K buffer here, assuming we need that large buffer.
28625 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28626 	 */
28627 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28628 		/* The following may work even if we cannot get a large buf. */
28629 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28630 		return (0);
28631 	}
28632 
28633 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
28634 	    connp->conn_netstack->netstack_ip);
28635 	return (0);
28636 }
28637 
28638 /*
28639  * Determine if the ill and multicast aspects of that packets
28640  * "matches" the conn.
28641  */
28642 boolean_t
28643 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28644     zoneid_t zoneid)
28645 {
28646 	ill_t *in_ill;
28647 	boolean_t found;
28648 	ipif_t *ipif;
28649 	ire_t *ire;
28650 	ipaddr_t dst, src;
28651 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28652 
28653 	dst = ipha->ipha_dst;
28654 	src = ipha->ipha_src;
28655 
28656 	/*
28657 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28658 	 * unicast, broadcast and multicast reception to
28659 	 * conn_incoming_ill. conn_wantpacket itself is called
28660 	 * only for BROADCAST and multicast.
28661 	 *
28662 	 * 1) ip_rput supresses duplicate broadcasts if the ill
28663 	 *    is part of a group. Hence, we should be receiving
28664 	 *    just one copy of broadcast for the whole group.
28665 	 *    Thus, if it is part of the group the packet could
28666 	 *    come on any ill of the group and hence we need a
28667 	 *    match on the group. Otherwise, match on ill should
28668 	 *    be sufficient.
28669 	 *
28670 	 * 2) ip_rput does not suppress duplicate multicast packets.
28671 	 *    If there are two interfaces in a ill group and we have
28672 	 *    2 applications (conns) joined a multicast group G on
28673 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
28674 	 *    will give us two packets because we join G on both the
28675 	 *    interfaces rather than nominating just one interface
28676 	 *    for receiving multicast like broadcast above. So,
28677 	 *    we have to call ilg_lookup_ill to filter out duplicate
28678 	 *    copies, if ill is part of a group.
28679 	 */
28680 	in_ill = connp->conn_incoming_ill;
28681 	if (in_ill != NULL) {
28682 		if (in_ill->ill_group == NULL) {
28683 			if (in_ill != ill)
28684 				return (B_FALSE);
28685 		} else if (in_ill->ill_group != ill->ill_group) {
28686 			return (B_FALSE);
28687 		}
28688 	}
28689 
28690 	if (!CLASSD(dst)) {
28691 		if (IPCL_ZONE_MATCH(connp, zoneid))
28692 			return (B_TRUE);
28693 		/*
28694 		 * The conn is in a different zone; we need to check that this
28695 		 * broadcast address is configured in the application's zone and
28696 		 * on one ill in the group.
28697 		 */
28698 		ipif = ipif_get_next_ipif(NULL, ill);
28699 		if (ipif == NULL)
28700 			return (B_FALSE);
28701 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28702 		    connp->conn_zoneid, NULL,
28703 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
28704 		ipif_refrele(ipif);
28705 		if (ire != NULL) {
28706 			ire_refrele(ire);
28707 			return (B_TRUE);
28708 		} else {
28709 			return (B_FALSE);
28710 		}
28711 	}
28712 
28713 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28714 	    connp->conn_zoneid == zoneid) {
28715 		/*
28716 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28717 		 * disabled, therefore we don't dispatch the multicast packet to
28718 		 * the sending zone.
28719 		 */
28720 		return (B_FALSE);
28721 	}
28722 
28723 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28724 		/*
28725 		 * Multicast packet on the loopback interface: we only match
28726 		 * conns who joined the group in the specified zone.
28727 		 */
28728 		return (B_FALSE);
28729 	}
28730 
28731 	if (connp->conn_multi_router) {
28732 		/* multicast packet and multicast router socket: send up */
28733 		return (B_TRUE);
28734 	}
28735 
28736 	mutex_enter(&connp->conn_lock);
28737 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28738 	mutex_exit(&connp->conn_lock);
28739 	return (found);
28740 }
28741 
28742 /*
28743  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28744  */
28745 /* ARGSUSED */
28746 static void
28747 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28748 {
28749 	ill_t *ill = (ill_t *)q->q_ptr;
28750 	mblk_t	*mp1, *mp2;
28751 	ipif_t  *ipif;
28752 	int err = 0;
28753 	conn_t *connp = NULL;
28754 	ipsq_t	*ipsq;
28755 	arc_t	*arc;
28756 
28757 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28758 
28759 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28760 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28761 
28762 	ASSERT(IAM_WRITER_ILL(ill));
28763 	mp2 = mp->b_cont;
28764 	mp->b_cont = NULL;
28765 
28766 	/*
28767 	 * We have now received the arp bringup completion message
28768 	 * from ARP. Mark the arp bringup as done. Also if the arp
28769 	 * stream has already started closing, send up the AR_ARP_CLOSING
28770 	 * ack now since ARP is waiting in close for this ack.
28771 	 */
28772 	mutex_enter(&ill->ill_lock);
28773 	ill->ill_arp_bringup_pending = 0;
28774 	if (ill->ill_arp_closing) {
28775 		mutex_exit(&ill->ill_lock);
28776 		/* Let's reuse the mp for sending the ack */
28777 		arc = (arc_t *)mp->b_rptr;
28778 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28779 		arc->arc_cmd = AR_ARP_CLOSING;
28780 		qreply(q, mp);
28781 	} else {
28782 		mutex_exit(&ill->ill_lock);
28783 		freeb(mp);
28784 	}
28785 
28786 	ipsq = ill->ill_phyint->phyint_ipsq;
28787 	ipif = ipsq->ipsq_pending_ipif;
28788 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28789 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28790 	if (mp1 == NULL) {
28791 		/* bringup was aborted by the user */
28792 		freemsg(mp2);
28793 		return;
28794 	}
28795 
28796 	/*
28797 	 * If an IOCTL is waiting on this (ipsq_current_ioctl != 0), then we
28798 	 * must have an associated conn_t.  Otherwise, we're bringing this
28799 	 * interface back up as part of handling an asynchronous event (e.g.,
28800 	 * physical address change).
28801 	 */
28802 	if (ipsq->ipsq_current_ioctl != 0) {
28803 		ASSERT(connp != NULL);
28804 		q = CONNP_TO_WQ(connp);
28805 	} else {
28806 		ASSERT(connp == NULL);
28807 		q = ill->ill_rq;
28808 	}
28809 
28810 	/*
28811 	 * If the DL_BIND_REQ fails, it is noted
28812 	 * in arc_name_offset.
28813 	 */
28814 	err = *((int *)mp2->b_rptr);
28815 	if (err == 0) {
28816 		if (ipif->ipif_isv6) {
28817 			if ((err = ipif_up_done_v6(ipif)) != 0)
28818 				ip0dbg(("ip_arp_done: init failed\n"));
28819 		} else {
28820 			if ((err = ipif_up_done(ipif)) != 0)
28821 				ip0dbg(("ip_arp_done: init failed\n"));
28822 		}
28823 	} else {
28824 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28825 	}
28826 
28827 	freemsg(mp2);
28828 
28829 	if ((err == 0) && (ill->ill_up_ipifs)) {
28830 		err = ill_up_ipifs(ill, q, mp1);
28831 		if (err == EINPROGRESS)
28832 			return;
28833 	}
28834 
28835 	if (ill->ill_up_ipifs)
28836 		ill_group_cleanup(ill);
28837 
28838 	/*
28839 	 * The operation must complete without EINPROGRESS since
28840 	 * ipsq_pending_mp_get() has removed the mblk from ipsq_pending_mp.
28841 	 * Otherwise, the operation will be stuck forever in the ipsq.
28842 	 */
28843 	ASSERT(err != EINPROGRESS);
28844 	if (ipsq->ipsq_current_ioctl != 0)
28845 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28846 	else
28847 		ipsq_current_finish(ipsq);
28848 }
28849 
28850 /* Allocate the private structure */
28851 static int
28852 ip_priv_alloc(void **bufp)
28853 {
28854 	void	*buf;
28855 
28856 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28857 		return (ENOMEM);
28858 
28859 	*bufp = buf;
28860 	return (0);
28861 }
28862 
28863 /* Function to delete the private structure */
28864 void
28865 ip_priv_free(void *buf)
28866 {
28867 	ASSERT(buf != NULL);
28868 	kmem_free(buf, sizeof (ip_priv_t));
28869 }
28870 
28871 /*
28872  * The entry point for IPPF processing.
28873  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28874  * routine just returns.
28875  *
28876  * When called, ip_process generates an ipp_packet_t structure
28877  * which holds the state information for this packet and invokes the
28878  * the classifier (via ipp_packet_process). The classification, depending on
28879  * configured filters, results in a list of actions for this packet. Invoking
28880  * an action may cause the packet to be dropped, in which case the resulting
28881  * mblk (*mpp) is NULL. proc indicates the callout position for
28882  * this packet and ill_index is the interface this packet on or will leave
28883  * on (inbound and outbound resp.).
28884  */
28885 void
28886 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28887 {
28888 	mblk_t		*mp;
28889 	ip_priv_t	*priv;
28890 	ipp_action_id_t	aid;
28891 	int		rc = 0;
28892 	ipp_packet_t	*pp;
28893 #define	IP_CLASS	"ip"
28894 
28895 	/* If the classifier is not loaded, return  */
28896 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28897 		return;
28898 	}
28899 
28900 	mp = *mpp;
28901 	ASSERT(mp != NULL);
28902 
28903 	/* Allocate the packet structure */
28904 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28905 	if (rc != 0) {
28906 		*mpp = NULL;
28907 		freemsg(mp);
28908 		return;
28909 	}
28910 
28911 	/* Allocate the private structure */
28912 	rc = ip_priv_alloc((void **)&priv);
28913 	if (rc != 0) {
28914 		*mpp = NULL;
28915 		freemsg(mp);
28916 		ipp_packet_free(pp);
28917 		return;
28918 	}
28919 	priv->proc = proc;
28920 	priv->ill_index = ill_index;
28921 	ipp_packet_set_private(pp, priv, ip_priv_free);
28922 	ipp_packet_set_data(pp, mp);
28923 
28924 	/* Invoke the classifier */
28925 	rc = ipp_packet_process(&pp);
28926 	if (pp != NULL) {
28927 		mp = ipp_packet_get_data(pp);
28928 		ipp_packet_free(pp);
28929 		if (rc != 0) {
28930 			freemsg(mp);
28931 			*mpp = NULL;
28932 		}
28933 	} else {
28934 		*mpp = NULL;
28935 	}
28936 #undef	IP_CLASS
28937 }
28938 
28939 /*
28940  * Propagate a multicast group membership operation (add/drop) on
28941  * all the interfaces crossed by the related multirt routes.
28942  * The call is considered successful if the operation succeeds
28943  * on at least one interface.
28944  */
28945 static int
28946 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28947     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28948     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28949     mblk_t *first_mp)
28950 {
28951 	ire_t		*ire_gw;
28952 	irb_t		*irb;
28953 	int		error = 0;
28954 	opt_restart_t	*or;
28955 	ip_stack_t	*ipst = ire->ire_ipst;
28956 
28957 	irb = ire->ire_bucket;
28958 	ASSERT(irb != NULL);
28959 
28960 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28961 
28962 	or = (opt_restart_t *)first_mp->b_rptr;
28963 	IRB_REFHOLD(irb);
28964 	for (; ire != NULL; ire = ire->ire_next) {
28965 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28966 			continue;
28967 		if (ire->ire_addr != group)
28968 			continue;
28969 
28970 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28971 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28972 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
28973 		/* No resolver exists for the gateway; skip this ire. */
28974 		if (ire_gw == NULL)
28975 			continue;
28976 
28977 		/*
28978 		 * This function can return EINPROGRESS. If so the operation
28979 		 * will be restarted from ip_restart_optmgmt which will
28980 		 * call ip_opt_set and option processing will restart for
28981 		 * this option. So we may end up calling 'fn' more than once.
28982 		 * This requires that 'fn' is idempotent except for the
28983 		 * return value. The operation is considered a success if
28984 		 * it succeeds at least once on any one interface.
28985 		 */
28986 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28987 		    NULL, fmode, src, first_mp);
28988 		if (error == 0)
28989 			or->or_private = CGTP_MCAST_SUCCESS;
28990 
28991 		if (ip_debug > 0) {
28992 			ulong_t	off;
28993 			char	*ksym;
28994 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28995 			ip2dbg(("ip_multirt_apply_membership: "
28996 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28997 			    "error %d [success %u]\n",
28998 			    ksym ? ksym : "?",
28999 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
29000 			    error, or->or_private));
29001 		}
29002 
29003 		ire_refrele(ire_gw);
29004 		if (error == EINPROGRESS) {
29005 			IRB_REFRELE(irb);
29006 			return (error);
29007 		}
29008 	}
29009 	IRB_REFRELE(irb);
29010 	/*
29011 	 * Consider the call as successful if we succeeded on at least
29012 	 * one interface. Otherwise, return the last encountered error.
29013 	 */
29014 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
29015 }
29016 
29017 
29018 /*
29019  * Issue a warning regarding a route crossing an interface with an
29020  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
29021  * amount of time is logged.
29022  */
29023 static void
29024 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
29025 {
29026 	hrtime_t	current = gethrtime();
29027 	char		buf[INET_ADDRSTRLEN];
29028 	ip_stack_t	*ipst = ire->ire_ipst;
29029 
29030 	/* Convert interval in ms to hrtime in ns */
29031 	if (ipst->ips_multirt_bad_mtu_last_time +
29032 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
29033 	    current) {
29034 		cmn_err(CE_WARN, "ip: ignoring multiroute "
29035 		    "to %s, incorrect MTU %u (expected %u)\n",
29036 		    ip_dot_addr(ire->ire_addr, buf),
29037 		    ire->ire_max_frag, max_frag);
29038 
29039 		ipst->ips_multirt_bad_mtu_last_time = current;
29040 	}
29041 }
29042 
29043 
29044 /*
29045  * Get the CGTP (multirouting) filtering status.
29046  * If 0, the CGTP hooks are transparent.
29047  */
29048 /* ARGSUSED */
29049 static int
29050 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
29051 {
29052 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29053 
29054 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
29055 	return (0);
29056 }
29057 
29058 
29059 /*
29060  * Set the CGTP (multirouting) filtering status.
29061  * If the status is changed from active to transparent
29062  * or from transparent to active, forward the new status
29063  * to the filtering module (if loaded).
29064  */
29065 /* ARGSUSED */
29066 static int
29067 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
29068     cred_t *ioc_cr)
29069 {
29070 	long		new_value;
29071 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29072 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29073 
29074 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
29075 		return (EPERM);
29076 
29077 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
29078 	    new_value < 0 || new_value > 1) {
29079 		return (EINVAL);
29080 	}
29081 
29082 	if ((!*ip_cgtp_filter_value) && new_value) {
29083 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
29084 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
29085 		    " (module not loaded)" : "");
29086 	}
29087 	if (*ip_cgtp_filter_value && (!new_value)) {
29088 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
29089 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
29090 		    " (module not loaded)" : "");
29091 	}
29092 
29093 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29094 		int	res;
29095 		netstackid_t stackid;
29096 
29097 		stackid = ipst->ips_netstack->netstack_stackid;
29098 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
29099 		    new_value);
29100 		if (res)
29101 			return (res);
29102 	}
29103 
29104 	*ip_cgtp_filter_value = (boolean_t)new_value;
29105 
29106 	return (0);
29107 }
29108 
29109 
29110 /*
29111  * Return the expected CGTP hooks version number.
29112  */
29113 int
29114 ip_cgtp_filter_supported(void)
29115 {
29116 	return (ip_cgtp_filter_rev);
29117 }
29118 
29119 
29120 /*
29121  * CGTP hooks can be registered by invoking this function.
29122  * Checks that the version number matches.
29123  */
29124 int
29125 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
29126 {
29127 	netstack_t *ns;
29128 	ip_stack_t *ipst;
29129 
29130 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
29131 		return (ENOTSUP);
29132 
29133 	ns = netstack_find_by_stackid(stackid);
29134 	if (ns == NULL)
29135 		return (EINVAL);
29136 	ipst = ns->netstack_ip;
29137 	ASSERT(ipst != NULL);
29138 
29139 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29140 		netstack_rele(ns);
29141 		return (EALREADY);
29142 	}
29143 
29144 	ipst->ips_ip_cgtp_filter_ops = ops;
29145 	netstack_rele(ns);
29146 	return (0);
29147 }
29148 
29149 /*
29150  * CGTP hooks can be unregistered by invoking this function.
29151  * Returns ENXIO if there was no registration.
29152  * Returns EBUSY if the ndd variable has not been turned off.
29153  */
29154 int
29155 ip_cgtp_filter_unregister(netstackid_t stackid)
29156 {
29157 	netstack_t *ns;
29158 	ip_stack_t *ipst;
29159 
29160 	ns = netstack_find_by_stackid(stackid);
29161 	if (ns == NULL)
29162 		return (EINVAL);
29163 	ipst = ns->netstack_ip;
29164 	ASSERT(ipst != NULL);
29165 
29166 	if (ipst->ips_ip_cgtp_filter) {
29167 		netstack_rele(ns);
29168 		return (EBUSY);
29169 	}
29170 
29171 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
29172 		netstack_rele(ns);
29173 		return (ENXIO);
29174 	}
29175 	ipst->ips_ip_cgtp_filter_ops = NULL;
29176 	netstack_rele(ns);
29177 	return (0);
29178 }
29179 
29180 /*
29181  * Check whether there is a CGTP filter registration.
29182  * Returns non-zero if there is a registration, otherwise returns zero.
29183  * Note: returns zero if bad stackid.
29184  */
29185 int
29186 ip_cgtp_filter_is_registered(netstackid_t stackid)
29187 {
29188 	netstack_t *ns;
29189 	ip_stack_t *ipst;
29190 	int ret;
29191 
29192 	ns = netstack_find_by_stackid(stackid);
29193 	if (ns == NULL)
29194 		return (0);
29195 	ipst = ns->netstack_ip;
29196 	ASSERT(ipst != NULL);
29197 
29198 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
29199 		ret = 1;
29200 	else
29201 		ret = 0;
29202 
29203 	netstack_rele(ns);
29204 	return (ret);
29205 }
29206 
29207 static squeue_func_t
29208 ip_squeue_switch(int val)
29209 {
29210 	squeue_func_t rval = squeue_fill;
29211 
29212 	switch (val) {
29213 	case IP_SQUEUE_ENTER_NODRAIN:
29214 		rval = squeue_enter_nodrain;
29215 		break;
29216 	case IP_SQUEUE_ENTER:
29217 		rval = squeue_enter;
29218 		break;
29219 	default:
29220 		break;
29221 	}
29222 	return (rval);
29223 }
29224 
29225 /* ARGSUSED */
29226 static int
29227 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29228     caddr_t addr, cred_t *cr)
29229 {
29230 	int *v = (int *)addr;
29231 	long new_value;
29232 
29233 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29234 		return (EPERM);
29235 
29236 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29237 		return (EINVAL);
29238 
29239 	ip_input_proc = ip_squeue_switch(new_value);
29240 	*v = new_value;
29241 	return (0);
29242 }
29243 
29244 /*
29245  * Handle ndd set of variables which require PRIV_SYS_NET_CONFIG such as
29246  * ip_debug.
29247  */
29248 /* ARGSUSED */
29249 static int
29250 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29251     caddr_t addr, cred_t *cr)
29252 {
29253 	int *v = (int *)addr;
29254 	long new_value;
29255 
29256 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29257 		return (EPERM);
29258 
29259 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29260 		return (EINVAL);
29261 
29262 	*v = new_value;
29263 	return (0);
29264 }
29265 
29266 /*
29267  * Handle changes to ipmp_hook_emulation ndd variable.
29268  * Need to update phyint_hook_ifindex.
29269  * Also generate a nic plumb event should a new ifidex be assigned to a group.
29270  */
29271 static void
29272 ipmp_hook_emulation_changed(ip_stack_t *ipst)
29273 {
29274 	phyint_t *phyi;
29275 	phyint_t *phyi_tmp;
29276 	char *groupname;
29277 	int namelen;
29278 	ill_t	*ill;
29279 	boolean_t new_group;
29280 
29281 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29282 	/*
29283 	 * Group indicies are stored in the phyint - a common structure
29284 	 * to both IPv4 and IPv6.
29285 	 */
29286 	phyi = avl_first(&ipst->ips_phyint_g_list->phyint_list_avl_by_index);
29287 	for (; phyi != NULL;
29288 	    phyi = avl_walk(&ipst->ips_phyint_g_list->phyint_list_avl_by_index,
29289 	    phyi, AVL_AFTER)) {
29290 		/* Ignore the ones that do not have a group */
29291 		if (phyi->phyint_groupname_len == 0)
29292 			continue;
29293 
29294 		/*
29295 		 * Look for other phyint in group.
29296 		 * Clear name/namelen so the lookup doesn't find ourselves.
29297 		 */
29298 		namelen = phyi->phyint_groupname_len;
29299 		groupname = phyi->phyint_groupname;
29300 		phyi->phyint_groupname_len = 0;
29301 		phyi->phyint_groupname = NULL;
29302 
29303 		phyi_tmp = phyint_lookup_group(groupname, B_FALSE, ipst);
29304 		/* Restore */
29305 		phyi->phyint_groupname_len = namelen;
29306 		phyi->phyint_groupname = groupname;
29307 
29308 		new_group = B_FALSE;
29309 		if (ipst->ips_ipmp_hook_emulation) {
29310 			/*
29311 			 * If the group already exists and has already
29312 			 * been assigned a group ifindex, we use the existing
29313 			 * group_ifindex, otherwise we pick a new group_ifindex
29314 			 * here.
29315 			 */
29316 			if (phyi_tmp != NULL &&
29317 			    phyi_tmp->phyint_group_ifindex != 0) {
29318 				phyi->phyint_group_ifindex =
29319 				    phyi_tmp->phyint_group_ifindex;
29320 			} else {
29321 				/* XXX We need a recovery strategy here. */
29322 				if (!ip_assign_ifindex(
29323 				    &phyi->phyint_group_ifindex, ipst))
29324 					cmn_err(CE_PANIC,
29325 					    "ip_assign_ifindex() failed");
29326 				new_group = B_TRUE;
29327 			}
29328 		} else {
29329 			phyi->phyint_group_ifindex = 0;
29330 		}
29331 		if (ipst->ips_ipmp_hook_emulation)
29332 			phyi->phyint_hook_ifindex = phyi->phyint_group_ifindex;
29333 		else
29334 			phyi->phyint_hook_ifindex = phyi->phyint_ifindex;
29335 
29336 		/*
29337 		 * For IP Filter to find out the relationship between
29338 		 * names and interface indicies, we need to generate
29339 		 * a NE_PLUMB event when a new group can appear.
29340 		 * We always generate events when a new interface appears
29341 		 * (even when ipmp_hook_emulation is set) so there
29342 		 * is no need to generate NE_PLUMB events when
29343 		 * ipmp_hook_emulation is turned off.
29344 		 * And since it isn't critical for IP Filter to get
29345 		 * the NE_UNPLUMB events we skip those here.
29346 		 */
29347 		if (new_group) {
29348 			/*
29349 			 * First phyint in group - generate group PLUMB event.
29350 			 * Since we are not running inside the ipsq we do
29351 			 * the dispatch immediately.
29352 			 */
29353 			if (phyi->phyint_illv4 != NULL)
29354 				ill = phyi->phyint_illv4;
29355 			else
29356 				ill = phyi->phyint_illv6;
29357 
29358 			if (ill != NULL) {
29359 				mutex_enter(&ill->ill_lock);
29360 				ill_nic_info_plumb(ill, B_TRUE);
29361 				ill_nic_info_dispatch(ill);
29362 				mutex_exit(&ill->ill_lock);
29363 			}
29364 		}
29365 	}
29366 	rw_exit(&ipst->ips_ill_g_lock);
29367 }
29368 
29369 /* ARGSUSED */
29370 static int
29371 ipmp_hook_emulation_set(queue_t *q, mblk_t *mp, char *value,
29372     caddr_t addr, cred_t *cr)
29373 {
29374 	int *v = (int *)addr;
29375 	long new_value;
29376 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29377 
29378 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29379 		return (EINVAL);
29380 
29381 	if (*v != new_value) {
29382 		*v = new_value;
29383 		ipmp_hook_emulation_changed(ipst);
29384 	}
29385 	return (0);
29386 }
29387 
29388 static void *
29389 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29390 {
29391 	kstat_t *ksp;
29392 
29393 	ip_stat_t template = {
29394 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29395 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29396 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29397 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29398 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29399 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29400 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29401 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29402 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29403 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29404 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29405 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29406 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29407 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29408 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29409 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29410 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29411 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29412 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29413 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29414 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29415 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29416 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29417 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29418 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29419 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29420 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29421 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29422 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29423 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29424 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29425 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29426 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29427 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29428 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29429 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29430 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29431 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29432 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29433 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29434 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29435 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29436 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29437 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29438 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29439 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29440 	};
29441 
29442 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29443 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29444 	    KSTAT_FLAG_VIRTUAL, stackid);
29445 
29446 	if (ksp == NULL)
29447 		return (NULL);
29448 
29449 	bcopy(&template, ip_statisticsp, sizeof (template));
29450 	ksp->ks_data = (void *)ip_statisticsp;
29451 	ksp->ks_private = (void *)(uintptr_t)stackid;
29452 
29453 	kstat_install(ksp);
29454 	return (ksp);
29455 }
29456 
29457 static void
29458 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29459 {
29460 	if (ksp != NULL) {
29461 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29462 		kstat_delete_netstack(ksp, stackid);
29463 	}
29464 }
29465 
29466 static void *
29467 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29468 {
29469 	kstat_t	*ksp;
29470 
29471 	ip_named_kstat_t template = {
29472 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29473 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29474 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29475 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29476 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29477 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29478 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29479 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29480 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29481 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29482 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29483 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29484 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29485 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29486 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29487 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29488 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29489 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29490 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29491 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29492 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29493 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29494 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29495 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29496 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29497 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29498 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29499 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29500 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29501 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29502 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29503 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29504 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29505 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29506 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29507 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29508 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29509 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29510 	};
29511 
29512 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29513 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29514 	if (ksp == NULL || ksp->ks_data == NULL)
29515 		return (NULL);
29516 
29517 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29518 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29519 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29520 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29521 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29522 
29523 	template.netToMediaEntrySize.value.i32 =
29524 	    sizeof (mib2_ipNetToMediaEntry_t);
29525 
29526 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29527 
29528 	bcopy(&template, ksp->ks_data, sizeof (template));
29529 	ksp->ks_update = ip_kstat_update;
29530 	ksp->ks_private = (void *)(uintptr_t)stackid;
29531 
29532 	kstat_install(ksp);
29533 	return (ksp);
29534 }
29535 
29536 static void
29537 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29538 {
29539 	if (ksp != NULL) {
29540 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29541 		kstat_delete_netstack(ksp, stackid);
29542 	}
29543 }
29544 
29545 static int
29546 ip_kstat_update(kstat_t *kp, int rw)
29547 {
29548 	ip_named_kstat_t *ipkp;
29549 	mib2_ipIfStatsEntry_t ipmib;
29550 	ill_walk_context_t ctx;
29551 	ill_t *ill;
29552 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29553 	netstack_t	*ns;
29554 	ip_stack_t	*ipst;
29555 
29556 	if (kp == NULL || kp->ks_data == NULL)
29557 		return (EIO);
29558 
29559 	if (rw == KSTAT_WRITE)
29560 		return (EACCES);
29561 
29562 	ns = netstack_find_by_stackid(stackid);
29563 	if (ns == NULL)
29564 		return (-1);
29565 	ipst = ns->netstack_ip;
29566 	if (ipst == NULL) {
29567 		netstack_rele(ns);
29568 		return (-1);
29569 	}
29570 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29571 
29572 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29573 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29574 	ill = ILL_START_WALK_V4(&ctx, ipst);
29575 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29576 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29577 	rw_exit(&ipst->ips_ill_g_lock);
29578 
29579 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29580 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29581 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29582 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29583 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29584 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29585 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29586 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29587 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29588 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29589 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29590 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29591 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29592 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29593 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29594 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29595 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29596 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29597 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29598 
29599 	ipkp->routingDiscards.value.ui32 =	0;
29600 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29601 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29602 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29603 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29604 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29605 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29606 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29607 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29608 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29609 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29610 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29611 
29612 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29613 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29614 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29615 
29616 	netstack_rele(ns);
29617 
29618 	return (0);
29619 }
29620 
29621 static void *
29622 icmp_kstat_init(netstackid_t stackid)
29623 {
29624 	kstat_t	*ksp;
29625 
29626 	icmp_named_kstat_t template = {
29627 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29628 		{ "inErrors",		KSTAT_DATA_UINT32 },
29629 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29630 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29631 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29632 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29633 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29634 		{ "inEchos",		KSTAT_DATA_UINT32 },
29635 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29636 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29637 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29638 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29639 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29640 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29641 		{ "outErrors",		KSTAT_DATA_UINT32 },
29642 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29643 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29644 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29645 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29646 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29647 		{ "outEchos",		KSTAT_DATA_UINT32 },
29648 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29649 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29650 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29651 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29652 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29653 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29654 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29655 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29656 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29657 		{ "outDrops",		KSTAT_DATA_UINT32 },
29658 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29659 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29660 	};
29661 
29662 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29663 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29664 	if (ksp == NULL || ksp->ks_data == NULL)
29665 		return (NULL);
29666 
29667 	bcopy(&template, ksp->ks_data, sizeof (template));
29668 
29669 	ksp->ks_update = icmp_kstat_update;
29670 	ksp->ks_private = (void *)(uintptr_t)stackid;
29671 
29672 	kstat_install(ksp);
29673 	return (ksp);
29674 }
29675 
29676 static void
29677 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29678 {
29679 	if (ksp != NULL) {
29680 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29681 		kstat_delete_netstack(ksp, stackid);
29682 	}
29683 }
29684 
29685 static int
29686 icmp_kstat_update(kstat_t *kp, int rw)
29687 {
29688 	icmp_named_kstat_t *icmpkp;
29689 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29690 	netstack_t	*ns;
29691 	ip_stack_t	*ipst;
29692 
29693 	if ((kp == NULL) || (kp->ks_data == NULL))
29694 		return (EIO);
29695 
29696 	if (rw == KSTAT_WRITE)
29697 		return (EACCES);
29698 
29699 	ns = netstack_find_by_stackid(stackid);
29700 	if (ns == NULL)
29701 		return (-1);
29702 	ipst = ns->netstack_ip;
29703 	if (ipst == NULL) {
29704 		netstack_rele(ns);
29705 		return (-1);
29706 	}
29707 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29708 
29709 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29710 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29711 	icmpkp->inDestUnreachs.value.ui32 =
29712 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29713 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29714 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29715 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29716 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29717 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29718 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29719 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29720 	icmpkp->inTimestampReps.value.ui32 =
29721 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29722 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29723 	icmpkp->inAddrMaskReps.value.ui32 =
29724 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29725 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29726 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29727 	icmpkp->outDestUnreachs.value.ui32 =
29728 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29729 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29730 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29731 	icmpkp->outSrcQuenchs.value.ui32 =
29732 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29733 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29734 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29735 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29736 	icmpkp->outTimestamps.value.ui32 =
29737 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29738 	icmpkp->outTimestampReps.value.ui32 =
29739 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29740 	icmpkp->outAddrMasks.value.ui32 =
29741 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29742 	icmpkp->outAddrMaskReps.value.ui32 =
29743 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29744 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29745 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29746 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29747 	icmpkp->outFragNeeded.value.ui32 =
29748 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29749 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29750 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29751 	icmpkp->inBadRedirects.value.ui32 =
29752 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29753 
29754 	netstack_rele(ns);
29755 	return (0);
29756 }
29757 
29758 /*
29759  * This is the fanout function for raw socket opened for SCTP.  Note
29760  * that it is called after SCTP checks that there is no socket which
29761  * wants a packet.  Then before SCTP handles this out of the blue packet,
29762  * this function is called to see if there is any raw socket for SCTP.
29763  * If there is and it is bound to the correct address, the packet will
29764  * be sent to that socket.  Note that only one raw socket can be bound to
29765  * a port.  This is assured in ipcl_sctp_hash_insert();
29766  */
29767 void
29768 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29769     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29770     zoneid_t zoneid)
29771 {
29772 	conn_t		*connp;
29773 	queue_t		*rq;
29774 	mblk_t		*first_mp;
29775 	boolean_t	secure;
29776 	ip6_t		*ip6h;
29777 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29778 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29779 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
29780 	boolean_t	sctp_csum_err = B_FALSE;
29781 
29782 	if (flags & IP_FF_SCTP_CSUM_ERR) {
29783 		sctp_csum_err = B_TRUE;
29784 		flags &= ~IP_FF_SCTP_CSUM_ERR;
29785 	}
29786 
29787 	first_mp = mp;
29788 	if (mctl_present) {
29789 		mp = first_mp->b_cont;
29790 		secure = ipsec_in_is_secure(first_mp);
29791 		ASSERT(mp != NULL);
29792 	} else {
29793 		secure = B_FALSE;
29794 	}
29795 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29796 
29797 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29798 	if (connp == NULL) {
29799 		/*
29800 		 * Although raw sctp is not summed, OOB chunks must be.
29801 		 * Drop the packet here if the sctp checksum failed.
29802 		 */
29803 		if (sctp_csum_err) {
29804 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
29805 			freemsg(first_mp);
29806 			return;
29807 		}
29808 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29809 		return;
29810 	}
29811 	rq = connp->conn_rq;
29812 	if (!canputnext(rq)) {
29813 		CONN_DEC_REF(connp);
29814 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29815 		freemsg(first_mp);
29816 		return;
29817 	}
29818 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29819 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29820 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29821 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29822 		if (first_mp == NULL) {
29823 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29824 			CONN_DEC_REF(connp);
29825 			return;
29826 		}
29827 	}
29828 	/*
29829 	 * We probably should not send M_CTL message up to
29830 	 * raw socket.
29831 	 */
29832 	if (mctl_present)
29833 		freeb(first_mp);
29834 
29835 	/* Initiate IPPF processing here if needed. */
29836 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29837 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29838 		ip_process(IPP_LOCAL_IN, &mp,
29839 		    recv_ill->ill_phyint->phyint_ifindex);
29840 		if (mp == NULL) {
29841 			CONN_DEC_REF(connp);
29842 			return;
29843 		}
29844 	}
29845 
29846 	if (connp->conn_recvif || connp->conn_recvslla ||
29847 	    ((connp->conn_ip_recvpktinfo ||
29848 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29849 	    (flags & IP_FF_IPINFO))) {
29850 		int in_flags = 0;
29851 
29852 		/*
29853 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29854 		 * IPF_RECVIF.
29855 		 */
29856 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29857 			in_flags = IPF_RECVIF;
29858 		}
29859 		if (connp->conn_recvslla) {
29860 			in_flags |= IPF_RECVSLLA;
29861 		}
29862 		if (isv4) {
29863 			mp = ip_add_info(mp, recv_ill, in_flags,
29864 			    IPCL_ZONEID(connp), ipst);
29865 		} else {
29866 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29867 			if (mp == NULL) {
29868 				BUMP_MIB(recv_ill->ill_ip_mib,
29869 				    ipIfStatsInDiscards);
29870 				CONN_DEC_REF(connp);
29871 				return;
29872 			}
29873 		}
29874 	}
29875 
29876 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29877 	/*
29878 	 * We are sending the IPSEC_IN message also up. Refer
29879 	 * to comments above this function.
29880 	 * This is the SOCK_RAW, IPPROTO_SCTP case.
29881 	 */
29882 	(connp->conn_recv)(connp, mp, NULL);
29883 	CONN_DEC_REF(connp);
29884 }
29885 
29886 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29887 {									\
29888 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29889 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29890 }
29891 /*
29892  * This function should be called only if all packet processing
29893  * including fragmentation is complete. Callers of this function
29894  * must set mp->b_prev to one of these values:
29895  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29896  * prior to handing over the mp as first argument to this function.
29897  *
29898  * If the ire passed by caller is incomplete, this function
29899  * queues the packet and if necessary, sends ARP request and bails.
29900  * If the ire passed is fully resolved, we simply prepend
29901  * the link-layer header to the packet, do ipsec hw acceleration
29902  * work if necessary, and send the packet out on the wire.
29903  *
29904  * NOTE: IPsec will only call this function with fully resolved
29905  * ires if hw acceleration is involved.
29906  * TODO list :
29907  * 	a Handle M_MULTIDATA so that
29908  *	  tcp_multisend->tcp_multisend_data can
29909  *	  call ip_xmit_v4 directly
29910  *	b Handle post-ARP work for fragments so that
29911  *	  ip_wput_frag can call this function.
29912  */
29913 ipxmit_state_t
29914 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
29915 {
29916 	nce_t		*arpce;
29917 	ipha_t		*ipha;
29918 	queue_t		*q;
29919 	int		ill_index;
29920 	mblk_t		*nxt_mp, *first_mp;
29921 	boolean_t	xmit_drop = B_FALSE;
29922 	ip_proc_t	proc;
29923 	ill_t		*out_ill;
29924 	int		pkt_len;
29925 
29926 	arpce = ire->ire_nce;
29927 	ASSERT(arpce != NULL);
29928 
29929 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29930 
29931 	mutex_enter(&arpce->nce_lock);
29932 	switch (arpce->nce_state) {
29933 	case ND_REACHABLE:
29934 		/* If there are other queued packets, queue this packet */
29935 		if (arpce->nce_qd_mp != NULL) {
29936 			if (mp != NULL)
29937 				nce_queue_mp_common(arpce, mp, B_FALSE);
29938 			mp = arpce->nce_qd_mp;
29939 		}
29940 		arpce->nce_qd_mp = NULL;
29941 		mutex_exit(&arpce->nce_lock);
29942 
29943 		/*
29944 		 * Flush the queue.  In the common case, where the
29945 		 * ARP is already resolved,  it will go through the
29946 		 * while loop only once.
29947 		 */
29948 		while (mp != NULL) {
29949 
29950 			nxt_mp = mp->b_next;
29951 			mp->b_next = NULL;
29952 			ASSERT(mp->b_datap->db_type != M_CTL);
29953 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29954 			/*
29955 			 * This info is needed for IPQOS to do COS marking
29956 			 * in ip_wput_attach_llhdr->ip_process.
29957 			 */
29958 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29959 			mp->b_prev = NULL;
29960 
29961 			/* set up ill index for outbound qos processing */
29962 			out_ill = ire_to_ill(ire);
29963 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29964 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29965 			    ill_index, &ipha);
29966 			if (first_mp == NULL) {
29967 				xmit_drop = B_TRUE;
29968 				BUMP_MIB(out_ill->ill_ip_mib,
29969 				    ipIfStatsOutDiscards);
29970 				goto next_mp;
29971 			}
29972 
29973 			/* non-ipsec hw accel case */
29974 			if (io == NULL || !io->ipsec_out_accelerated) {
29975 				/* send it */
29976 				q = ire->ire_stq;
29977 				if (proc == IPP_FWD_OUT) {
29978 					UPDATE_IB_PKT_COUNT(ire);
29979 				} else {
29980 					UPDATE_OB_PKT_COUNT(ire);
29981 				}
29982 				ire->ire_last_used_time = lbolt;
29983 
29984 				if (flow_ctl_enabled || canputnext(q)) {
29985 					if (proc == IPP_FWD_OUT) {
29986 
29987 					BUMP_MIB(out_ill->ill_ip_mib,
29988 					    ipIfStatsHCOutForwDatagrams);
29989 
29990 					}
29991 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29992 					    pkt_len);
29993 
29994 					DTRACE_IP7(send, mblk_t *, first_mp,
29995 					    conn_t *, NULL, void_ip_t *, ipha,
29996 					    __dtrace_ipsr_ill_t *, out_ill,
29997 					    ipha_t *, ipha, ip6_t *, NULL, int,
29998 					    0);
29999 
30000 					putnext(q, first_mp);
30001 				} else {
30002 					BUMP_MIB(out_ill->ill_ip_mib,
30003 					    ipIfStatsOutDiscards);
30004 					xmit_drop = B_TRUE;
30005 					freemsg(first_mp);
30006 				}
30007 			} else {
30008 				/*
30009 				 * Safety Pup says: make sure this
30010 				 *  is going to the right interface!
30011 				 */
30012 				ill_t *ill1 =
30013 				    (ill_t *)ire->ire_stq->q_ptr;
30014 				int ifindex =
30015 				    ill1->ill_phyint->phyint_ifindex;
30016 				if (ifindex !=
30017 				    io->ipsec_out_capab_ill_index) {
30018 					xmit_drop = B_TRUE;
30019 					freemsg(mp);
30020 				} else {
30021 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
30022 					    pkt_len);
30023 
30024 					DTRACE_IP7(send, mblk_t *, first_mp,
30025 					    conn_t *, NULL, void_ip_t *, ipha,
30026 					    __dtrace_ipsr_ill_t *, ill1,
30027 					    ipha_t *, ipha, ip6_t *, NULL,
30028 					    int, 0);
30029 
30030 					ipsec_hw_putnext(ire->ire_stq, mp);
30031 				}
30032 			}
30033 next_mp:
30034 			mp = nxt_mp;
30035 		} /* while (mp != NULL) */
30036 		if (xmit_drop)
30037 			return (SEND_FAILED);
30038 		else
30039 			return (SEND_PASSED);
30040 
30041 	case ND_INITIAL:
30042 	case ND_INCOMPLETE:
30043 
30044 		/*
30045 		 * While we do send off packets to dests that
30046 		 * use fully-resolved CGTP routes, we do not
30047 		 * handle unresolved CGTP routes.
30048 		 */
30049 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
30050 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
30051 
30052 		if (mp != NULL) {
30053 			/* queue the packet */
30054 			nce_queue_mp_common(arpce, mp, B_FALSE);
30055 		}
30056 
30057 		if (arpce->nce_state == ND_INCOMPLETE) {
30058 			mutex_exit(&arpce->nce_lock);
30059 			DTRACE_PROBE3(ip__xmit__incomplete,
30060 			    (ire_t *), ire, (mblk_t *), mp,
30061 			    (ipsec_out_t *), io);
30062 			return (LOOKUP_IN_PROGRESS);
30063 		}
30064 
30065 		arpce->nce_state = ND_INCOMPLETE;
30066 		mutex_exit(&arpce->nce_lock);
30067 		/*
30068 		 * Note that ire_add() (called from ire_forward())
30069 		 * holds a ref on the ire until ARP is completed.
30070 		 */
30071 
30072 		ire_arpresolve(ire, ire_to_ill(ire));
30073 		return (LOOKUP_IN_PROGRESS);
30074 	default:
30075 		ASSERT(0);
30076 		mutex_exit(&arpce->nce_lock);
30077 		return (LLHDR_RESLV_FAILED);
30078 	}
30079 }
30080 
30081 #undef	UPDATE_IP_MIB_OB_COUNTERS
30082 
30083 /*
30084  * Return B_TRUE if the buffers differ in length or content.
30085  * This is used for comparing extension header buffers.
30086  * Note that an extension header would be declared different
30087  * even if all that changed was the next header value in that header i.e.
30088  * what really changed is the next extension header.
30089  */
30090 boolean_t
30091 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
30092     uint_t blen)
30093 {
30094 	if (!b_valid)
30095 		blen = 0;
30096 
30097 	if (alen != blen)
30098 		return (B_TRUE);
30099 	if (alen == 0)
30100 		return (B_FALSE);	/* Both zero length */
30101 	return (bcmp(abuf, bbuf, alen));
30102 }
30103 
30104 /*
30105  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
30106  * Return B_FALSE if memory allocation fails - don't change any state!
30107  */
30108 boolean_t
30109 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30110     const void *src, uint_t srclen)
30111 {
30112 	void *dst;
30113 
30114 	if (!src_valid)
30115 		srclen = 0;
30116 
30117 	ASSERT(*dstlenp == 0);
30118 	if (src != NULL && srclen != 0) {
30119 		dst = mi_alloc(srclen, BPRI_MED);
30120 		if (dst == NULL)
30121 			return (B_FALSE);
30122 	} else {
30123 		dst = NULL;
30124 	}
30125 	if (*dstp != NULL)
30126 		mi_free(*dstp);
30127 	*dstp = dst;
30128 	*dstlenp = dst == NULL ? 0 : srclen;
30129 	return (B_TRUE);
30130 }
30131 
30132 /*
30133  * Replace what is in *dst, *dstlen with the source.
30134  * Assumes ip_allocbuf has already been called.
30135  */
30136 void
30137 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30138     const void *src, uint_t srclen)
30139 {
30140 	if (!src_valid)
30141 		srclen = 0;
30142 
30143 	ASSERT(*dstlenp == srclen);
30144 	if (src != NULL && srclen != 0)
30145 		bcopy(src, *dstp, srclen);
30146 }
30147 
30148 /*
30149  * Free the storage pointed to by the members of an ip6_pkt_t.
30150  */
30151 void
30152 ip6_pkt_free(ip6_pkt_t *ipp)
30153 {
30154 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
30155 
30156 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
30157 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
30158 		ipp->ipp_hopopts = NULL;
30159 		ipp->ipp_hopoptslen = 0;
30160 	}
30161 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
30162 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
30163 		ipp->ipp_rtdstopts = NULL;
30164 		ipp->ipp_rtdstoptslen = 0;
30165 	}
30166 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
30167 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
30168 		ipp->ipp_dstopts = NULL;
30169 		ipp->ipp_dstoptslen = 0;
30170 	}
30171 	if (ipp->ipp_fields & IPPF_RTHDR) {
30172 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
30173 		ipp->ipp_rthdr = NULL;
30174 		ipp->ipp_rthdrlen = 0;
30175 	}
30176 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
30177 	    IPPF_RTHDR);
30178 }
30179