xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision 257873cfc1dd3337766407f80397db60a56f2f5a)
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  * Hook function to generate cluster wide SPI.
201  */
202 void (*cl_inet_getspi)(uint8_t, uint8_t *, size_t) = NULL;
203 
204 /*
205  * Hook function to verify if the SPI is already utlized.
206  */
207 
208 int (*cl_inet_checkspi)(uint8_t, uint32_t) = NULL;
209 
210 /*
211  * Hook function to delete the SPI from the cluster wide repository.
212  */
213 
214 void (*cl_inet_deletespi)(uint8_t, uint32_t) = NULL;
215 
216 /*
217  * Hook function to inform the cluster when packet received on an IDLE SA
218  */
219 
220 void (*cl_inet_idlesa)(uint8_t, uint32_t, sa_family_t, in6_addr_t,
221     in6_addr_t) = NULL;
222 
223 /*
224  * Synchronization notes:
225  *
226  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
227  * MT level protection given by STREAMS. IP uses a combination of its own
228  * internal serialization mechanism and standard Solaris locking techniques.
229  * The internal serialization is per phyint (no IPMP) or per IPMP group.
230  * This is used to serialize plumbing operations, IPMP operations, certain
231  * multicast operations, most set ioctls, igmp/mld timers etc.
232  *
233  * Plumbing is a long sequence of operations involving message
234  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
235  * involved in plumbing operations. A natural model is to serialize these
236  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
237  * parallel without any interference. But various set ioctls on hme0 are best
238  * serialized. However if the system uses IPMP, the operations are easier if
239  * they are serialized on a per IPMP group basis since IPMP operations
240  * happen across ill's of a group. Thus the lowest common denominator is to
241  * serialize most set ioctls, multicast join/leave operations, IPMP operations
242  * igmp/mld timer operations, and processing of DLPI control messages received
243  * from drivers on a per IPMP group basis. If the system does not employ
244  * IPMP the serialization is on a per phyint basis. This serialization is
245  * provided by the ipsq_t and primitives operating on this. Details can
246  * be found in ip_if.c above the core primitives operating on ipsq_t.
247  *
248  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
249  * Simiarly lookup of an ire by a thread also returns a refheld ire.
250  * In addition ipif's and ill's referenced by the ire are also indirectly
251  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
252  * the ipif's address or netmask change as long as an ipif is refheld
253  * directly or indirectly. For example an SIOCLIFADDR ioctl that changes the
254  * address of an ipif has to go through the ipsq_t. This ensures that only
255  * 1 such exclusive operation proceeds at any time on the ipif. It then
256  * deletes all ires associated with this ipif, and waits for all refcnts
257  * associated with this ipif to come down to zero. The address is changed
258  * only after the ipif has been quiesced. Then the ipif is brought up again.
259  * More details are described above the comment in ip_sioctl_flags.
260  *
261  * Packet processing is based mostly on IREs and are fully multi-threaded
262  * using standard Solaris MT techniques.
263  *
264  * There are explicit locks in IP to handle:
265  * - The ip_g_head list maintained by mi_open_link() and friends.
266  *
267  * - The reassembly data structures (one lock per hash bucket)
268  *
269  * - conn_lock is meant to protect conn_t fields. The fields actually
270  *   protected by conn_lock are documented in the conn_t definition.
271  *
272  * - ire_lock to protect some of the fields of the ire, IRE tables
273  *   (one lock per hash bucket). Refer to ip_ire.c for details.
274  *
275  * - ndp_g_lock and nce_lock for protecting NCEs.
276  *
277  * - ill_lock protects fields of the ill and ipif. Details in ip.h
278  *
279  * - ill_g_lock: This is a global reader/writer lock. Protects the following
280  *	* The AVL tree based global multi list of all ills.
281  *	* The linked list of all ipifs of an ill
282  *	* The <ill-ipsq> mapping
283  *	* The ipsq->ipsq_phyint_list threaded by phyint_ipsq_next
284  *	* The illgroup list threaded by ill_group_next.
285  *	* <ill-phyint> association
286  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
287  *   into an ill, changing the <ill-ipsq> mapping of an ill, insertion/deletion
288  *   of an ill into the illgrp list, changing the <ill-phyint> assoc of an ill
289  *   will all have to hold the ill_g_lock as writer for the actual duration
290  *   of the insertion/deletion/change. More details about the <ill-ipsq> mapping
291  *   may be found in the IPMP section.
292  *
293  * - ill_lock:  This is a per ill mutex.
294  *   It protects some members of the ill and is documented below.
295  *   It also protects the <ill-ipsq> mapping
296  *   It also protects the illgroup list threaded by ill_group_next.
297  *   It also protects the <ill-phyint> assoc.
298  *   It also protects the list of ipifs hanging off the ill.
299  *
300  * - ipsq_lock: This is a per ipsq_t mutex lock.
301  *   This protects all the other members of the ipsq struct except
302  *   ipsq_refs and ipsq_phyint_list which are protected by ill_g_lock
303  *
304  * - illgrp_lock: This is a per ill_group mutex lock.
305  *   The only thing it protects is the illgrp_ill_schednext member of ill_group
306  *   which dictates which is the next ill in an ill_group that is to be chosen
307  *   for sending outgoing packets, through creation of an IRE_CACHE that
308  *   references this ill.
309  *
310  * - phyint_lock: This is a per phyint mutex lock. Protects just the
311  *   phyint_flags
312  *
313  * - ip_g_nd_lock: This is a global reader/writer lock.
314  *   Any call to nd_load to load a new parameter to the ND table must hold the
315  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
316  *   as reader.
317  *
318  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
319  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
320  *   uniqueness check also done atomically.
321  *
322  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
323  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
324  *   as a writer when adding or deleting elements from these lists, and
325  *   as a reader when walking these lists to send a SADB update to the
326  *   IPsec capable ills.
327  *
328  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
329  *   group list linked by ill_usesrc_grp_next. It also protects the
330  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
331  *   group is being added or deleted.  This lock is taken as a reader when
332  *   walking the list/group(eg: to get the number of members in a usesrc group).
333  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
334  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
335  *   example, it is not necessary to take this lock in the initial portion
336  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_groupname and
337  *   ip_sioctl_flags since the these operations are executed exclusively and
338  *   that ensures that the "usesrc group state" cannot change. The "usesrc
339  *   group state" change can happen only in the latter part of
340  *   ip_sioctl_slifusesrc and in ill_delete.
341  *
342  * Changing <ill-phyint>, <ill-ipsq>, <ill-illgroup> assocications.
343  *
344  * To change the <ill-phyint> association, the ill_g_lock must be held
345  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
346  * must be held.
347  *
348  * To change the <ill-ipsq> association the ill_g_lock must be held as writer
349  * and the ill_lock of the ill in question must be held.
350  *
351  * To change the <ill-illgroup> association the ill_g_lock must be held as
352  * writer and the ill_lock of the ill in question must be held.
353  *
354  * To add or delete an ipif from the list of ipifs hanging off the ill,
355  * ill_g_lock (writer) and ill_lock must be held and the thread must be
356  * a writer on the associated ipsq,.
357  *
358  * To add or delete an ill to the system, the ill_g_lock must be held as
359  * writer and the thread must be a writer on the associated ipsq.
360  *
361  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
362  * must be a writer on the associated ipsq.
363  *
364  * Lock hierarchy
365  *
366  * Some lock hierarchy scenarios are listed below.
367  *
368  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock
369  * ill_g_lock -> illgrp_lock -> ill_lock
370  * ill_g_lock -> ill_lock(s) -> phyint_lock
371  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
372  * ill_g_lock -> ip_addr_avail_lock
373  * conn_lock -> irb_lock -> ill_lock -> ire_lock
374  * ill_g_lock -> ip_g_nd_lock
375  *
376  * When more than 1 ill lock is needed to be held, all ill lock addresses
377  * are sorted on address and locked starting from highest addressed lock
378  * downward.
379  *
380  * IPsec scenarios
381  *
382  * ipsa_lock -> ill_g_lock -> ill_lock
383  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
384  * ipsec_capab_ills_lock -> ipsa_lock
385  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
386  *
387  * Trusted Solaris scenarios
388  *
389  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
390  * igsa_lock -> gcdb_lock
391  * gcgrp_rwlock -> ire_lock
392  * gcgrp_rwlock -> gcdb_lock
393  *
394  *
395  * Routing/forwarding table locking notes:
396  *
397  * Lock acquisition order: Radix tree lock, irb_lock.
398  * Requirements:
399  * i.  Walker must not hold any locks during the walker callback.
400  * ii  Walker must not see a truncated tree during the walk because of any node
401  *     deletion.
402  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
403  *     in many places in the code to walk the irb list. Thus even if all the
404  *     ires in a bucket have been deleted, we still can't free the radix node
405  *     until the ires have actually been inactive'd (freed).
406  *
407  * Tree traversal - Need to hold the global tree lock in read mode.
408  * Before dropping the global tree lock, need to either increment the ire_refcnt
409  * to ensure that the radix node can't be deleted.
410  *
411  * Tree add - Need to hold the global tree lock in write mode to add a
412  * radix node. To prevent the node from being deleted, increment the
413  * irb_refcnt, after the node is added to the tree. The ire itself is
414  * added later while holding the irb_lock, but not the tree lock.
415  *
416  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
417  * All associated ires must be inactive (i.e. freed), and irb_refcnt
418  * must be zero.
419  *
420  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
421  * global tree lock (read mode) for traversal.
422  *
423  * IPsec notes :
424  *
425  * IP interacts with the IPsec code (AH/ESP) by tagging a M_CTL message
426  * in front of the actual packet. For outbound datagrams, the M_CTL
427  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
428  * information used by the IPsec code for applying the right level of
429  * protection. The information initialized by IP in the ipsec_out_t
430  * is determined by the per-socket policy or global policy in the system.
431  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
432  * ipsec_info.h) which starts out with nothing in it. It gets filled
433  * with the right information if it goes through the AH/ESP code, which
434  * happens if the incoming packet is secure. The information initialized
435  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
436  * the policy requirements needed by per-socket policy or global policy
437  * is met or not.
438  *
439  * If there is both per-socket policy (set using setsockopt) and there
440  * is also global policy match for the 5 tuples of the socket,
441  * ipsec_override_policy() makes the decision of which one to use.
442  *
443  * For fully connected sockets i.e dst, src [addr, port] is known,
444  * conn_policy_cached is set indicating that policy has been cached.
445  * conn_in_enforce_policy may or may not be set depending on whether
446  * there is a global policy match or per-socket policy match.
447  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
448  * Once the right policy is set on the conn_t, policy cannot change for
449  * this socket. This makes life simpler for TCP (UDP ?) where
450  * re-transmissions go out with the same policy. For symmetry, policy
451  * is cached for fully connected UDP sockets also. Thus if policy is cached,
452  * it also implies that policy is latched i.e policy cannot change
453  * on these sockets. As we have the right policy on the conn, we don't
454  * have to lookup global policy for every outbound and inbound datagram
455  * and thus serving as an optimization. Note that a global policy change
456  * does not affect fully connected sockets if they have policy. If fully
457  * connected sockets did not have any policy associated with it, global
458  * policy change may affect them.
459  *
460  * IP Flow control notes:
461  *
462  * Non-TCP streams are flow controlled by IP. On the send side, if the packet
463  * cannot be sent down to the driver by IP, because of a canput failure, IP
464  * does a putq on the conn_wq. This will cause ip_wsrv to run on the conn_wq.
465  * ip_wsrv in turn, inserts the conn in a list of conn's that need to be drained
466  * when the flowcontrol condition subsides. Ultimately STREAMS backenables the
467  * ip_wsrv on the IP module, which in turn does a qenable of the conn_wq of the
468  * first conn in the list of conn's to be drained. ip_wsrv on this conn drains
469  * the queued messages, and removes the conn from the drain list, if all
470  * messages were drained. It also qenables the next conn in the drain list to
471  * continue the drain process.
472  *
473  * In reality the drain list is not a single list, but a configurable number
474  * of lists. The ip_wsrv on the IP module, qenables the first conn in each
475  * list. If the ip_wsrv of the next qenabled conn does not run, because the
476  * stream closes, ip_close takes responsibility to qenable the next conn in
477  * the drain list. The directly called ip_wput path always does a putq, if
478  * it cannot putnext. Thus synchronization problems are handled between
479  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
480  * functions that manipulate this drain list. Furthermore conn_drain_insert
481  * is called only from ip_wsrv, and there can be only 1 instance of ip_wsrv
482  * running on a queue at any time. conn_drain_tail can be simultaneously called
483  * from both ip_wsrv and ip_close.
484  *
485  * IPQOS notes:
486  *
487  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
488  * and IPQoS modules. IPPF includes hooks in IP at different control points
489  * (callout positions) which direct packets to IPQoS modules for policy
490  * processing. Policies, if present, are global.
491  *
492  * The callout positions are located in the following paths:
493  *		o local_in (packets destined for this host)
494  *		o local_out (packets orginating from this host )
495  *		o fwd_in  (packets forwarded by this m/c - inbound)
496  *		o fwd_out (packets forwarded by this m/c - outbound)
497  * Hooks at these callout points can be enabled/disabled using the ndd variable
498  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
499  * By default all the callout positions are enabled.
500  *
501  * Outbound (local_out)
502  * Hooks are placed in ip_wput_ire and ipsec_out_process.
503  *
504  * Inbound (local_in)
505  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
506  * TCP and UDP fanout routines.
507  *
508  * Forwarding (in and out)
509  * Hooks are placed in ip_rput_forward.
510  *
511  * IP Policy Framework processing (IPPF processing)
512  * Policy processing for a packet is initiated by ip_process, which ascertains
513  * that the classifier (ipgpc) is loaded and configured, failing which the
514  * packet resumes normal processing in IP. If the clasifier is present, the
515  * packet is acted upon by one or more IPQoS modules (action instances), per
516  * filters configured in ipgpc and resumes normal IP processing thereafter.
517  * An action instance can drop a packet in course of its processing.
518  *
519  * A boolean variable, ip_policy, is used in all the fanout routines that can
520  * invoke ip_process for a packet. This variable indicates if the packet should
521  * to be sent for policy processing. The variable is set to B_TRUE by default,
522  * i.e. when the routines are invoked in the normal ip procesing path for a
523  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
524  * ip_policy is set to B_FALSE for all the routines called in these two
525  * functions because, in the former case,  we don't process loopback traffic
526  * currently while in the latter, the packets have already been processed in
527  * icmp_inbound.
528  *
529  * Zones notes:
530  *
531  * The partitioning rules for networking are as follows:
532  * 1) Packets coming from a zone must have a source address belonging to that
533  * zone.
534  * 2) Packets coming from a zone can only be sent on a physical interface on
535  * which the zone has an IP address.
536  * 3) Between two zones on the same machine, packet delivery is only allowed if
537  * there's a matching route for the destination and zone in the forwarding
538  * table.
539  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
540  * different zones can bind to the same port with the wildcard address
541  * (INADDR_ANY).
542  *
543  * The granularity of interface partitioning is at the logical interface level.
544  * Therefore, every zone has its own IP addresses, and incoming packets can be
545  * attributed to a zone unambiguously. A logical interface is placed into a zone
546  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
547  * structure. Rule (1) is implemented by modifying the source address selection
548  * algorithm so that the list of eligible addresses is filtered based on the
549  * sending process zone.
550  *
551  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
552  * across all zones, depending on their type. Here is the break-up:
553  *
554  * IRE type				Shared/exclusive
555  * --------				----------------
556  * IRE_BROADCAST			Exclusive
557  * IRE_DEFAULT (default routes)		Shared (*)
558  * IRE_LOCAL				Exclusive (x)
559  * IRE_LOOPBACK				Exclusive
560  * IRE_PREFIX (net routes)		Shared (*)
561  * IRE_CACHE				Exclusive
562  * IRE_IF_NORESOLVER (interface routes)	Exclusive
563  * IRE_IF_RESOLVER (interface routes)	Exclusive
564  * IRE_HOST (host routes)		Shared (*)
565  *
566  * (*) A zone can only use a default or off-subnet route if the gateway is
567  * directly reachable from the zone, that is, if the gateway's address matches
568  * one of the zone's logical interfaces.
569  *
570  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
571  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
572  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
573  * address of the zone itself (the destination). Since IRE_LOCAL is used
574  * for communication between zones, ip_wput_ire has special logic to set
575  * the right source address when sending using an IRE_LOCAL.
576  *
577  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
578  * ire_cache_lookup restricts loopback using an IRE_LOCAL
579  * between zone to the case when L2 would have conceptually looped the packet
580  * back, i.e. the loopback which is required since neither Ethernet drivers
581  * nor Ethernet hardware loops them back. This is the case when the normal
582  * routes (ignoring IREs with different zoneids) would send out the packet on
583  * the same ill (or ill group) as the ill with which is IRE_LOCAL is
584  * associated.
585  *
586  * Multiple zones can share a common broadcast address; typically all zones
587  * share the 255.255.255.255 address. Incoming as well as locally originated
588  * broadcast packets must be dispatched to all the zones on the broadcast
589  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
590  * since some zones may not be on the 10.16.72/24 network. To handle this, each
591  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
592  * sent to every zone that has an IRE_BROADCAST entry for the destination
593  * address on the input ill, see conn_wantpacket().
594  *
595  * Applications in different zones can join the same multicast group address.
596  * For IPv4, group memberships are per-logical interface, so they're already
597  * inherently part of a zone. For IPv6, group memberships are per-physical
598  * interface, so we distinguish IPv6 group memberships based on group address,
599  * interface and zoneid. In both cases, received multicast packets are sent to
600  * every zone for which a group membership entry exists. On IPv6 we need to
601  * check that the target zone still has an address on the receiving physical
602  * interface; it could have been removed since the application issued the
603  * IPV6_JOIN_GROUP.
604  */
605 
606 /*
607  * Squeue Fanout flags:
608  *	0: No fanout.
609  *	1: Fanout across all squeues
610  */
611 boolean_t	ip_squeue_fanout = 0;
612 
613 /*
614  * Maximum dups allowed per packet.
615  */
616 uint_t ip_max_frag_dups = 10;
617 
618 #define	IS_SIMPLE_IPH(ipha)						\
619 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
620 
621 /* RFC1122 Conformance */
622 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
623 
624 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
625 
626 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
627 
628 static int	ip_open(queue_t *q, dev_t *devp, int flag, int sflag,
629 		    cred_t *credp, boolean_t isv6);
630 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t,
631 		    ipha_t **);
632 
633 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t,
634 		    ip_stack_t *);
635 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
636 		    uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
637 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
638 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
639 		    mblk_t *, int, ip_stack_t *);
640 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
641 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
642 		    ill_t *, zoneid_t);
643 static void	icmp_options_update(ipha_t *);
644 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t,
645 		    ip_stack_t *);
646 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
647 		    zoneid_t zoneid, ip_stack_t *);
648 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_stack_t *);
649 static void	icmp_redirect(ill_t *, mblk_t *);
650 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t,
651 		    ip_stack_t *);
652 
653 static void	ip_arp_news(queue_t *, mblk_t *);
654 static boolean_t ip_bind_insert_ire(mblk_t *, ire_t *, iulp_t *,
655 		    ip_stack_t *);
656 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
657 char		*ip_dot_addr(ipaddr_t, char *);
658 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
659 int		ip_close(queue_t *, int);
660 static char	*ip_dot_saddr(uchar_t *, char *);
661 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
662 		    boolean_t, boolean_t, ill_t *, zoneid_t);
663 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
664 		    boolean_t, boolean_t, zoneid_t);
665 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
666 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
667 static void	ip_lrput(queue_t *, mblk_t *);
668 ipaddr_t	ip_net_mask(ipaddr_t);
669 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, conn_t *, zoneid_t,
670 		    ip_stack_t *);
671 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
672 		    conn_t *, uint32_t, zoneid_t, ip_opt_info_t *);
673 char		*ip_nv_lookup(nv_t *, int);
674 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
675 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
676 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
677 static boolean_t	ip_param_register(IDP *ndp, ipparam_t *, size_t,
678     ipndp_t *, size_t);
679 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
680 void	ip_rput(queue_t *, mblk_t *);
681 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
682 		    void *dummy_arg);
683 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
684 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *,
685     ip_stack_t *);
686 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
687 			    ire_t *, ip_stack_t *);
688 static boolean_t	ip_rput_multimblk_ipoptions(queue_t *, ill_t *,
689 			    mblk_t *, ipha_t **, ipaddr_t *, ip_stack_t *);
690 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *,
691     ip_stack_t *);
692 static boolean_t ip_rput_fragment(queue_t *, mblk_t **, ipha_t *, uint32_t *,
693 		    uint16_t *);
694 int		ip_snmp_get(queue_t *, mblk_t *, int);
695 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
696 		    mib2_ipIfStatsEntry_t *, ip_stack_t *);
697 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
698 		    ip_stack_t *);
699 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *);
700 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
701 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
702 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
703 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
704 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
705 		    ip_stack_t *ipst);
706 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
707 		    ip_stack_t *ipst);
708 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
709 		    ip_stack_t *ipst);
710 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
711 		    ip_stack_t *ipst);
712 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
713 		    ip_stack_t *ipst);
714 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
715 		    ip_stack_t *ipst);
716 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
717 		    ip_stack_t *ipst);
718 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
719 		    ip_stack_t *ipst);
720 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *,
721 		    ip_stack_t *ipst);
722 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *,
723 		    ip_stack_t *ipst);
724 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
725 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
726 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
727 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
728 static boolean_t	ip_source_routed(ipha_t *, ip_stack_t *);
729 static boolean_t	ip_source_route_included(ipha_t *);
730 static void	ip_trash_ire_reclaim_stack(ip_stack_t *);
731 
732 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
733 		    zoneid_t, ip_stack_t *);
734 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int, ip_stack_t *);
735 static void	ip_wput_local_options(ipha_t *, ip_stack_t *);
736 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
737 		    zoneid_t, ip_stack_t *);
738 
739 static void	conn_drain_init(ip_stack_t *);
740 static void	conn_drain_fini(ip_stack_t *);
741 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
742 
743 static void	conn_walk_drain(ip_stack_t *);
744 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
745     zoneid_t);
746 
747 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
748 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
749 static void	ip_stack_fini(netstackid_t stackid, void *arg);
750 
751 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
752     zoneid_t);
753 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
754     void *dummy_arg);
755 
756 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
757 
758 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
759     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
760     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
761 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
762 
763 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
764 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
765     caddr_t, cred_t *);
766 extern int	ip_squeue_bind_set(queue_t *q, mblk_t *mp, char *value,
767     caddr_t cp, cred_t *cr);
768 extern int	ip_squeue_profile_set(queue_t *, mblk_t *, char *, caddr_t,
769     cred_t *);
770 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
771     caddr_t cp, cred_t *cr);
772 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
773     cred_t *);
774 static int	ipmp_hook_emulation_set(queue_t *, mblk_t *, char *, caddr_t,
775     cred_t *);
776 static squeue_func_t ip_squeue_switch(int);
777 
778 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
779 static void	ip_kstat_fini(netstackid_t, kstat_t *);
780 static int	ip_kstat_update(kstat_t *kp, int rw);
781 static void	*icmp_kstat_init(netstackid_t);
782 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
783 static int	icmp_kstat_update(kstat_t *kp, int rw);
784 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
785 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
786 
787 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
788 
789 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
790     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
791 
792 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
793     ipha_t *, ill_t *, boolean_t);
794 
795 static void ipobs_init(ip_stack_t *);
796 static void ipobs_fini(ip_stack_t *);
797 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
798 
799 /* How long, in seconds, we allow frags to hang around. */
800 #define	IP_FRAG_TIMEOUT	15
801 
802 /*
803  * Threshold which determines whether MDT should be used when
804  * generating IP fragments; payload size must be greater than
805  * this threshold for MDT to take place.
806  */
807 #define	IP_WPUT_FRAG_MDT_MIN	32768
808 
809 /* Setable in /etc/system only */
810 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
811 
812 static long ip_rput_pullups;
813 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
814 
815 vmem_t *ip_minor_arena_sa; /* for minor nos. from INET_MIN_DEV+2 thru 2^^18-1 */
816 vmem_t *ip_minor_arena_la; /* for minor nos. from 2^^18 thru 2^^32-1 */
817 
818 int	ip_debug;
819 
820 #ifdef DEBUG
821 uint32_t ipsechw_debug = 0;
822 #endif
823 
824 /*
825  * Multirouting/CGTP stuff
826  */
827 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
828 
829 /*
830  * XXX following really should only be in a header. Would need more
831  * header and .c clean up first.
832  */
833 extern optdb_obj_t	ip_opt_obj;
834 
835 ulong_t ip_squeue_enter_unbound = 0;
836 
837 /*
838  * Named Dispatch Parameter Table.
839  * All of these are alterable, within the min/max values given, at run time.
840  */
841 static ipparam_t	lcl_param_arr[] = {
842 	/* min	max	value	name */
843 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
844 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
845 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
846 	{  0,	1,	0,	"ip_respond_to_timestamp"},
847 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
848 	{  0,	1,	1,	"ip_send_redirects"},
849 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
850 	{  0,	10,	0,	"ip_mrtdebug"},
851 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
852 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
853 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
854 	{  1,	255,	255,	"ip_def_ttl" },
855 	{  0,	1,	0,	"ip_forward_src_routed"},
856 	{  0,	256,	32,	"ip_wroff_extra" },
857 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
858 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
859 	{  0,	1,	1,	"ip_path_mtu_discovery" },
860 	{  0,	240,	30,	"ip_ignore_delete_time" },
861 	{  0,	1,	0,	"ip_ignore_redirect" },
862 	{  0,	1,	1,	"ip_output_queue" },
863 	{  1,	254,	1,	"ip_broadcast_ttl" },
864 	{  0,	99999,	100,	"ip_icmp_err_interval" },
865 	{  1,	99999,	10,	"ip_icmp_err_burst" },
866 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
867 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
868 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
869 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
870 	{  0,	1,	1,	"icmp_accept_clear_messages" },
871 	{  0,	1,	1,	"igmp_accept_clear_messages" },
872 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
873 				"ip_ndp_delay_first_probe_time"},
874 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
875 				"ip_ndp_max_unicast_solicit"},
876 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
877 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
878 	{  0,	1,	0,	"ip6_forward_src_routed"},
879 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
880 	{  0,	1,	1,	"ip6_send_redirects"},
881 	{  0,	1,	0,	"ip6_ignore_redirect" },
882 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
883 
884 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
885 
886 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
887 
888 	{  0,	1,	1,	"pim_accept_clear_messages" },
889 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
890 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
891 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
892 	{  0,	15,	0,	"ip_policy_mask" },
893 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
894 	{  0,	255,	1,	"ip_multirt_ttl" },
895 	{  0,	1,	1,	"ip_multidata_outbound" },
896 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
897 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
898 	{  0,	1000,	1,	"ip_max_temp_defend" },
899 	{  0,	1000,	3,	"ip_max_defend" },
900 	{  0,	999999,	30,	"ip_defend_interval" },
901 	{  0,	3600000, 300000, "ip_dup_recovery" },
902 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
903 	{  0,	1,	1,	"ip_lso_outbound" },
904 	{  IGMP_V1_ROUTER, IGMP_V3_ROUTER, IGMP_V3_ROUTER, "igmp_max_version" },
905 	{  MLD_V1_ROUTER, MLD_V2_ROUTER, MLD_V2_ROUTER, "mld_max_version" },
906 	{ 68,	65535,	576,	"ip_pmtu_min" },
907 #ifdef DEBUG
908 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
909 #else
910 	{  0,	0,	0,	"" },
911 #endif
912 };
913 
914 /*
915  * Extended NDP table
916  * The addresses for the first two are filled in to be ips_ip_g_forward
917  * and ips_ipv6_forward at init time.
918  */
919 static ipndp_t	lcl_ndp_arr[] = {
920 	/* getf			setf		data			name */
921 #define	IPNDP_IP_FORWARDING_OFFSET	0
922 	{  ip_param_generic_get,	ip_forward_set,	NULL,
923 	    "ip_forwarding" },
924 #define	IPNDP_IP6_FORWARDING_OFFSET	1
925 	{  ip_param_generic_get,	ip_forward_set,	NULL,
926 	    "ip6_forwarding" },
927 	{  ip_ill_report,	NULL,		NULL,
928 	    "ip_ill_status" },
929 	{  ip_ipif_report,	NULL,		NULL,
930 	    "ip_ipif_status" },
931 	{  ip_conn_report,	NULL,		NULL,
932 	    "ip_conn_status" },
933 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
934 	    "ip_rput_pullups" },
935 	{  ip_srcid_report,	NULL,		NULL,
936 	    "ip_srcid_status" },
937 	{ ip_param_generic_get, ip_squeue_profile_set,
938 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
939 	{ ip_param_generic_get, ip_squeue_bind_set,
940 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
941 	{ ip_param_generic_get, ip_input_proc_set,
942 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
943 	{ ip_param_generic_get, ip_int_set,
944 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
945 #define	IPNDP_CGTP_FILTER_OFFSET	11
946 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
947 	    "ip_cgtp_filter" },
948 	{ ip_param_generic_get, ip_int_set,
949 	    (caddr_t)&ip_soft_rings_cnt, "ip_soft_rings_cnt" },
950 #define	IPNDP_IPMP_HOOK_OFFSET	13
951 	{  ip_param_generic_get, ipmp_hook_emulation_set, NULL,
952 	    "ipmp_hook_emulation" },
953 	{  ip_param_generic_get, ip_int_set, (caddr_t)&ip_debug,
954 	    "ip_debug" },
955 };
956 
957 /*
958  * Table of IP ioctls encoding the various properties of the ioctl and
959  * indexed based on the last byte of the ioctl command. Occasionally there
960  * is a clash, and there is more than 1 ioctl with the same last byte.
961  * In such a case 1 ioctl is encoded in the ndx table and the remaining
962  * ioctls are encoded in the misc table. An entry in the ndx table is
963  * retrieved by indexing on the last byte of the ioctl command and comparing
964  * the ioctl command with the value in the ndx table. In the event of a
965  * mismatch the misc table is then searched sequentially for the desired
966  * ioctl command.
967  *
968  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
969  */
970 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
971 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
972 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
973 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
974 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
975 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
976 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
977 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
978 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
979 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
980 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
981 
982 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
983 			MISC_CMD, ip_siocaddrt, NULL },
984 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
985 			MISC_CMD, ip_siocdelrt, NULL },
986 
987 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
988 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
989 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
990 			IF_CMD, ip_sioctl_get_addr, NULL },
991 
992 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
993 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
994 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
995 			IPI_GET_CMD | IPI_REPL,
996 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
997 
998 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
999 			IPI_PRIV | IPI_WR | IPI_REPL,
1000 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1001 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
1002 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
1003 			IF_CMD, ip_sioctl_get_flags, NULL },
1004 
1005 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1006 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1007 
1008 	/* copyin size cannot be coded for SIOCGIFCONF */
1009 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
1010 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1011 
1012 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1013 			IF_CMD, ip_sioctl_mtu, NULL },
1014 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1015 			IF_CMD, ip_sioctl_get_mtu, NULL },
1016 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1017 			IPI_GET_CMD | IPI_REPL,
1018 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
1019 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1020 			IF_CMD, ip_sioctl_brdaddr, NULL },
1021 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1022 			IPI_GET_CMD | IPI_REPL,
1023 			IF_CMD, ip_sioctl_get_netmask, NULL },
1024 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1025 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1026 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1027 			IPI_GET_CMD | IPI_REPL,
1028 			IF_CMD, ip_sioctl_get_metric, NULL },
1029 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1030 			IF_CMD, ip_sioctl_metric, NULL },
1031 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1032 
1033 	/* See 166-168 below for extended SIOC*XARP ioctls */
1034 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1035 			ARP_CMD, ip_sioctl_arp, NULL },
1036 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1037 			ARP_CMD, ip_sioctl_arp, NULL },
1038 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1039 			ARP_CMD, ip_sioctl_arp, NULL },
1040 
1041 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1042 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1043 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1044 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1045 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1046 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1047 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1048 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1049 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1050 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1051 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1052 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1053 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1054 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1055 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1056 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1057 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1058 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1059 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1060 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1061 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1062 
1063 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1064 			MISC_CMD, if_unitsel, if_unitsel_restart },
1065 
1066 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1067 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1068 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1069 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1070 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1071 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1072 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1073 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1074 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1075 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1076 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1077 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1078 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1079 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1080 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1081 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1082 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1083 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1084 
1085 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1086 			IPI_PRIV | IPI_WR | IPI_MODOK,
1087 			IF_CMD, ip_sioctl_sifname, NULL },
1088 
1089 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1090 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1091 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1092 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1093 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1094 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1095 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1096 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1097 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1098 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1099 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1100 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1101 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1102 
1103 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1104 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1105 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1106 			IF_CMD, ip_sioctl_get_muxid, NULL },
1107 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1108 			IPI_PRIV | IPI_WR | IPI_REPL,
1109 			IF_CMD, ip_sioctl_muxid, NULL },
1110 
1111 	/* Both if and lif variants share same func */
1112 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1113 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1114 	/* Both if and lif variants share same func */
1115 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1116 			IPI_PRIV | IPI_WR | IPI_REPL,
1117 			IF_CMD, ip_sioctl_slifindex, NULL },
1118 
1119 	/* copyin size cannot be coded for SIOCGIFCONF */
1120 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
1121 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1122 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1123 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1124 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1125 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1126 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1127 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1128 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1129 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1130 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1131 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1132 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1133 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1134 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1135 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1136 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1137 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1138 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1139 
1140 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1141 			IPI_PRIV | IPI_WR | IPI_REPL,
1142 			LIF_CMD, ip_sioctl_removeif,
1143 			ip_sioctl_removeif_restart },
1144 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1145 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1146 			LIF_CMD, ip_sioctl_addif, NULL },
1147 #define	SIOCLIFADDR_NDX 112
1148 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1149 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1150 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1151 			IPI_GET_CMD | IPI_REPL,
1152 			LIF_CMD, ip_sioctl_get_addr, NULL },
1153 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1154 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1155 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1156 			IPI_GET_CMD | IPI_REPL,
1157 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1158 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1159 			IPI_PRIV | IPI_WR | IPI_REPL,
1160 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1161 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1162 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1163 			LIF_CMD, ip_sioctl_get_flags, NULL },
1164 
1165 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1166 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1167 
1168 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1169 			ip_sioctl_get_lifconf, NULL },
1170 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1171 			LIF_CMD, ip_sioctl_mtu, NULL },
1172 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1173 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1174 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1175 			IPI_GET_CMD | IPI_REPL,
1176 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1177 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1178 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1179 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1180 			IPI_GET_CMD | IPI_REPL,
1181 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1182 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1183 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1184 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1185 			IPI_GET_CMD | IPI_REPL,
1186 			LIF_CMD, ip_sioctl_get_metric, NULL },
1187 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1188 			LIF_CMD, ip_sioctl_metric, NULL },
1189 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1190 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1191 			LIF_CMD, ip_sioctl_slifname,
1192 			ip_sioctl_slifname_restart },
1193 
1194 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1195 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1196 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1197 			IPI_GET_CMD | IPI_REPL,
1198 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1199 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1200 			IPI_PRIV | IPI_WR | IPI_REPL,
1201 			LIF_CMD, ip_sioctl_muxid, NULL },
1202 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1203 			IPI_GET_CMD | IPI_REPL,
1204 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1205 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1206 			IPI_PRIV | IPI_WR | IPI_REPL,
1207 			LIF_CMD, ip_sioctl_slifindex, 0 },
1208 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1209 			LIF_CMD, ip_sioctl_token, NULL },
1210 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1211 			IPI_GET_CMD | IPI_REPL,
1212 			LIF_CMD, ip_sioctl_get_token, NULL },
1213 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1214 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1215 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1216 			IPI_GET_CMD | IPI_REPL,
1217 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1218 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1219 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1220 
1221 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1222 			IPI_GET_CMD | IPI_REPL,
1223 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1224 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1225 			LIF_CMD, ip_siocdelndp_v6, NULL },
1226 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1227 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1228 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1229 			LIF_CMD, ip_siocsetndp_v6, NULL },
1230 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1231 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1232 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1233 			MISC_CMD, ip_sioctl_tonlink, NULL },
1234 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1235 			MISC_CMD, ip_sioctl_tmysite, NULL },
1236 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1237 		    TUN_CMD, ip_sioctl_tunparam, NULL },
1238 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1239 		    IPI_PRIV | IPI_WR,
1240 		    TUN_CMD, ip_sioctl_tunparam, NULL },
1241 
1242 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1243 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1244 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1245 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1246 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1247 
1248 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1249 			IPI_PRIV | IPI_WR | IPI_REPL,
1250 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1251 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1252 			IPI_PRIV | IPI_WR | IPI_REPL,
1253 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1254 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1255 			IPI_PRIV | IPI_WR | IPI_REPL,
1256 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1257 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1258 			IPI_GET_CMD | IPI_REPL,
1259 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1260 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1261 			IPI_GET_CMD | IPI_REPL,
1262 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1263 
1264 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1265 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1266 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1267 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1268 
1269 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1270 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1271 
1272 	/* These are handled in ip_sioctl_copyin_setup itself */
1273 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1274 			MISC_CMD, NULL, NULL },
1275 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1276 			MISC_CMD, NULL, NULL },
1277 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1278 
1279 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1280 			ip_sioctl_get_lifconf, NULL },
1281 
1282 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1283 			XARP_CMD, ip_sioctl_arp, NULL },
1284 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1285 			XARP_CMD, ip_sioctl_arp, NULL },
1286 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1287 			XARP_CMD, ip_sioctl_arp, NULL },
1288 
1289 	/* SIOCPOPSOCKFS is not handled by IP */
1290 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1291 
1292 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1293 			IPI_GET_CMD | IPI_REPL,
1294 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1295 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1296 			IPI_PRIV | IPI_WR | IPI_REPL,
1297 			LIF_CMD, ip_sioctl_slifzone,
1298 			ip_sioctl_slifzone_restart },
1299 	/* 172-174 are SCTP ioctls and not handled by IP */
1300 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1301 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1302 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1303 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1304 			IPI_GET_CMD, LIF_CMD,
1305 			ip_sioctl_get_lifusesrc, 0 },
1306 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1307 			IPI_PRIV | IPI_WR,
1308 			LIF_CMD, ip_sioctl_slifusesrc,
1309 			NULL },
1310 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1311 			ip_sioctl_get_lifsrcof, NULL },
1312 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1313 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1314 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1315 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1316 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1317 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1318 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1319 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1320 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1321 			ip_sioctl_set_ipmpfailback, NULL },
1322 	/* SIOCSENABLESDP is handled by SDP */
1323 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1324 };
1325 
1326 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1327 
1328 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1329 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1330 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1331 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1332 		TUN_CMD, ip_sioctl_tunparam, NULL },
1333 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1334 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1335 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1336 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1337 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1338 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1339 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1340 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1341 		MISC_CMD, mrt_ioctl},
1342 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1343 		MISC_CMD, mrt_ioctl},
1344 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1345 		MISC_CMD, mrt_ioctl}
1346 };
1347 
1348 int ip_misc_ioctl_count =
1349     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1350 
1351 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1352 					/* Settable in /etc/system */
1353 /* Defined in ip_ire.c */
1354 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1355 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1356 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1357 
1358 static nv_t	ire_nv_arr[] = {
1359 	{ IRE_BROADCAST, "BROADCAST" },
1360 	{ IRE_LOCAL, "LOCAL" },
1361 	{ IRE_LOOPBACK, "LOOPBACK" },
1362 	{ IRE_CACHE, "CACHE" },
1363 	{ IRE_DEFAULT, "DEFAULT" },
1364 	{ IRE_PREFIX, "PREFIX" },
1365 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1366 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1367 	{ IRE_HOST, "HOST" },
1368 	{ 0 }
1369 };
1370 
1371 nv_t	*ire_nv_tbl = ire_nv_arr;
1372 
1373 /* Simple ICMP IP Header Template */
1374 static ipha_t icmp_ipha = {
1375 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1376 };
1377 
1378 struct module_info ip_mod_info = {
1379 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1380 };
1381 
1382 /*
1383  * Duplicate static symbols within a module confuses mdb; so we avoid the
1384  * problem by making the symbols here distinct from those in udp.c.
1385  */
1386 
1387 /*
1388  * Entry points for IP as a device and as a module.
1389  * FIXME: down the road we might want a separate module and driver qinit.
1390  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1391  */
1392 static struct qinit iprinitv4 = {
1393 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1394 	&ip_mod_info
1395 };
1396 
1397 struct qinit iprinitv6 = {
1398 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1399 	&ip_mod_info
1400 };
1401 
1402 static struct qinit ipwinitv4 = {
1403 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1404 	&ip_mod_info
1405 };
1406 
1407 struct qinit ipwinitv6 = {
1408 	(pfi_t)ip_wput_v6, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1409 	&ip_mod_info
1410 };
1411 
1412 static struct qinit iplrinit = {
1413 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1414 	&ip_mod_info
1415 };
1416 
1417 static struct qinit iplwinit = {
1418 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1419 	&ip_mod_info
1420 };
1421 
1422 /* For AF_INET aka /dev/ip */
1423 struct streamtab ipinfov4 = {
1424 	&iprinitv4, &ipwinitv4, &iplrinit, &iplwinit
1425 };
1426 
1427 /* For AF_INET6 aka /dev/ip6 */
1428 struct streamtab ipinfov6 = {
1429 	&iprinitv6, &ipwinitv6, &iplrinit, &iplwinit
1430 };
1431 
1432 #ifdef	DEBUG
1433 static boolean_t skip_sctp_cksum = B_FALSE;
1434 #endif
1435 
1436 /*
1437  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1438  * ip_rput_v6(), ip_output(), etc.  If the message
1439  * block already has a M_CTL at the front of it, then simply set the zoneid
1440  * appropriately.
1441  */
1442 mblk_t *
1443 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1444 {
1445 	mblk_t		*first_mp;
1446 	ipsec_out_t	*io;
1447 
1448 	ASSERT(zoneid != ALL_ZONES);
1449 	if (mp->b_datap->db_type == M_CTL) {
1450 		io = (ipsec_out_t *)mp->b_rptr;
1451 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1452 		io->ipsec_out_zoneid = zoneid;
1453 		return (mp);
1454 	}
1455 
1456 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1457 	if (first_mp == NULL)
1458 		return (NULL);
1459 	io = (ipsec_out_t *)first_mp->b_rptr;
1460 	/* This is not a secure packet */
1461 	io->ipsec_out_secure = B_FALSE;
1462 	io->ipsec_out_zoneid = zoneid;
1463 	first_mp->b_cont = mp;
1464 	return (first_mp);
1465 }
1466 
1467 /*
1468  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1469  */
1470 mblk_t *
1471 ip_copymsg(mblk_t *mp)
1472 {
1473 	mblk_t *nmp;
1474 	ipsec_info_t *in;
1475 
1476 	if (mp->b_datap->db_type != M_CTL)
1477 		return (copymsg(mp));
1478 
1479 	in = (ipsec_info_t *)mp->b_rptr;
1480 
1481 	/*
1482 	 * Note that M_CTL is also used for delivering ICMP error messages
1483 	 * upstream to transport layers.
1484 	 */
1485 	if (in->ipsec_info_type != IPSEC_OUT &&
1486 	    in->ipsec_info_type != IPSEC_IN)
1487 		return (copymsg(mp));
1488 
1489 	nmp = copymsg(mp->b_cont);
1490 
1491 	if (in->ipsec_info_type == IPSEC_OUT) {
1492 		return (ipsec_out_tag(mp, nmp,
1493 		    ((ipsec_out_t *)in)->ipsec_out_ns));
1494 	} else {
1495 		return (ipsec_in_tag(mp, nmp,
1496 		    ((ipsec_in_t *)in)->ipsec_in_ns));
1497 	}
1498 }
1499 
1500 /* Generate an ICMP fragmentation needed message. */
1501 static void
1502 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1503     ip_stack_t *ipst)
1504 {
1505 	icmph_t	icmph;
1506 	mblk_t *first_mp;
1507 	boolean_t mctl_present;
1508 
1509 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1510 
1511 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1512 		if (mctl_present)
1513 			freeb(first_mp);
1514 		return;
1515 	}
1516 
1517 	bzero(&icmph, sizeof (icmph_t));
1518 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1519 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1520 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1521 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1522 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1523 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1524 	    ipst);
1525 }
1526 
1527 /*
1528  * icmp_inbound deals with ICMP messages in the following ways.
1529  *
1530  * 1) It needs to send a reply back and possibly delivering it
1531  *    to the "interested" upper clients.
1532  * 2) It needs to send it to the upper clients only.
1533  * 3) It needs to change some values in IP only.
1534  * 4) It needs to change some values in IP and upper layers e.g TCP.
1535  *
1536  * We need to accomodate icmp messages coming in clear until we get
1537  * everything secure from the wire. If icmp_accept_clear_messages
1538  * is zero we check with the global policy and act accordingly. If
1539  * it is non-zero, we accept the message without any checks. But
1540  * *this does not mean* that this will be delivered to the upper
1541  * clients. By accepting we might send replies back, change our MTU
1542  * value etc. but delivery to the ULP/clients depends on their policy
1543  * dispositions.
1544  *
1545  * We handle the above 4 cases in the context of IPsec in the
1546  * following way :
1547  *
1548  * 1) Send the reply back in the same way as the request came in.
1549  *    If it came in encrypted, it goes out encrypted. If it came in
1550  *    clear, it goes out in clear. Thus, this will prevent chosen
1551  *    plain text attack.
1552  * 2) The client may or may not expect things to come in secure.
1553  *    If it comes in secure, the policy constraints are checked
1554  *    before delivering it to the upper layers. If it comes in
1555  *    clear, ipsec_inbound_accept_clear will decide whether to
1556  *    accept this in clear or not. In both the cases, if the returned
1557  *    message (IP header + 8 bytes) that caused the icmp message has
1558  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1559  *    sending up. If there are only 8 bytes of returned message, then
1560  *    upper client will not be notified.
1561  * 3) Check with global policy to see whether it matches the constaints.
1562  *    But this will be done only if icmp_accept_messages_in_clear is
1563  *    zero.
1564  * 4) If we need to change both in IP and ULP, then the decision taken
1565  *    while affecting the values in IP and while delivering up to TCP
1566  *    should be the same.
1567  *
1568  * 	There are two cases.
1569  *
1570  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1571  *	   failed), we will not deliver it to the ULP, even though they
1572  *	   are *willing* to accept in *clear*. This is fine as our global
1573  *	   disposition to icmp messages asks us reject the datagram.
1574  *
1575  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1576  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1577  *	   to deliver it to ULP (policy failed), it can lead to
1578  *	   consistency problems. The cases known at this time are
1579  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1580  *	   values :
1581  *
1582  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1583  *	     and Upper layer rejects. Then the communication will
1584  *	     come to a stop. This is solved by making similar decisions
1585  *	     at both levels. Currently, when we are unable to deliver
1586  *	     to the Upper Layer (due to policy failures) while IP has
1587  *	     adjusted ire_max_frag, the next outbound datagram would
1588  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1589  *	     will be with the right level of protection. Thus the right
1590  *	     value will be communicated even if we are not able to
1591  *	     communicate when we get from the wire initially. But this
1592  *	     assumes there would be at least one outbound datagram after
1593  *	     IP has adjusted its ire_max_frag value. To make things
1594  *	     simpler, we accept in clear after the validation of
1595  *	     AH/ESP headers.
1596  *
1597  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1598  *	     upper layer depending on the level of protection the upper
1599  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1600  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1601  *	     should be accepted in clear when the Upper layer expects secure.
1602  *	     Thus the communication may get aborted by some bad ICMP
1603  *	     packets.
1604  *
1605  * IPQoS Notes:
1606  * The only instance when a packet is sent for processing is when there
1607  * isn't an ICMP client and if we are interested in it.
1608  * If there is a client, IPPF processing will take place in the
1609  * ip_fanout_proto routine.
1610  *
1611  * Zones notes:
1612  * The packet is only processed in the context of the specified zone: typically
1613  * only this zone will reply to an echo request, and only interested clients in
1614  * this zone will receive a copy of the packet. This means that the caller must
1615  * call icmp_inbound() for each relevant zone.
1616  */
1617 static void
1618 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1619     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1620     ill_t *recv_ill, zoneid_t zoneid)
1621 {
1622 	icmph_t	*icmph;
1623 	ipha_t	*ipha;
1624 	int	iph_hdr_length;
1625 	int	hdr_length;
1626 	boolean_t	interested;
1627 	uint32_t	ts;
1628 	uchar_t	*wptr;
1629 	ipif_t	*ipif;
1630 	mblk_t *first_mp;
1631 	ipsec_in_t *ii;
1632 	ire_t *src_ire;
1633 	boolean_t onlink;
1634 	timestruc_t now;
1635 	uint32_t ill_index;
1636 	ip_stack_t *ipst;
1637 
1638 	ASSERT(ill != NULL);
1639 	ipst = ill->ill_ipst;
1640 
1641 	first_mp = mp;
1642 	if (mctl_present) {
1643 		mp = first_mp->b_cont;
1644 		ASSERT(mp != NULL);
1645 	}
1646 
1647 	ipha = (ipha_t *)mp->b_rptr;
1648 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1649 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1650 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1651 		if (first_mp == NULL)
1652 			return;
1653 	}
1654 
1655 	/*
1656 	 * On a labeled system, we have to check whether the zone itself is
1657 	 * permitted to receive raw traffic.
1658 	 */
1659 	if (is_system_labeled()) {
1660 		if (zoneid == ALL_ZONES)
1661 			zoneid = tsol_packet_to_zoneid(mp);
1662 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1663 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1664 			    zoneid));
1665 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1666 			freemsg(first_mp);
1667 			return;
1668 		}
1669 	}
1670 
1671 	/*
1672 	 * We have accepted the ICMP message. It means that we will
1673 	 * respond to the packet if needed. It may not be delivered
1674 	 * to the upper client depending on the policy constraints
1675 	 * and the disposition in ipsec_inbound_accept_clear.
1676 	 */
1677 
1678 	ASSERT(ill != NULL);
1679 
1680 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1681 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1682 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1683 		/* Last chance to get real. */
1684 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1685 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1686 			freemsg(first_mp);
1687 			return;
1688 		}
1689 		/* Refresh iph following the pullup. */
1690 		ipha = (ipha_t *)mp->b_rptr;
1691 	}
1692 	/* ICMP header checksum, including checksum field, should be zero. */
1693 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1694 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1695 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1696 		freemsg(first_mp);
1697 		return;
1698 	}
1699 	/* The IP header will always be a multiple of four bytes */
1700 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1701 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1702 	    icmph->icmph_code));
1703 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1704 	/* We will set "interested" to "true" if we want a copy */
1705 	interested = B_FALSE;
1706 	switch (icmph->icmph_type) {
1707 	case ICMP_ECHO_REPLY:
1708 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1709 		break;
1710 	case ICMP_DEST_UNREACHABLE:
1711 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1712 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1713 		interested = B_TRUE;	/* Pass up to transport */
1714 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1715 		break;
1716 	case ICMP_SOURCE_QUENCH:
1717 		interested = B_TRUE;	/* Pass up to transport */
1718 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1719 		break;
1720 	case ICMP_REDIRECT:
1721 		if (!ipst->ips_ip_ignore_redirect)
1722 			interested = B_TRUE;
1723 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1724 		break;
1725 	case ICMP_ECHO_REQUEST:
1726 		/*
1727 		 * Whether to respond to echo requests that come in as IP
1728 		 * broadcasts or as IP multicast is subject to debate
1729 		 * (what isn't?).  We aim to please, you pick it.
1730 		 * Default is do it.
1731 		 */
1732 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1733 			/* unicast: always respond */
1734 			interested = B_TRUE;
1735 		} else if (CLASSD(ipha->ipha_dst)) {
1736 			/* multicast: respond based on tunable */
1737 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1738 		} else if (broadcast) {
1739 			/* broadcast: respond based on tunable */
1740 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1741 		}
1742 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1743 		break;
1744 	case ICMP_ROUTER_ADVERTISEMENT:
1745 	case ICMP_ROUTER_SOLICITATION:
1746 		break;
1747 	case ICMP_TIME_EXCEEDED:
1748 		interested = B_TRUE;	/* Pass up to transport */
1749 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1750 		break;
1751 	case ICMP_PARAM_PROBLEM:
1752 		interested = B_TRUE;	/* Pass up to transport */
1753 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1754 		break;
1755 	case ICMP_TIME_STAMP_REQUEST:
1756 		/* Response to Time Stamp Requests is local policy. */
1757 		if (ipst->ips_ip_g_resp_to_timestamp &&
1758 		    /* So is whether to respond if it was an IP broadcast. */
1759 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1760 			int tstamp_len = 3 * sizeof (uint32_t);
1761 
1762 			if (wptr +  tstamp_len > mp->b_wptr) {
1763 				if (!pullupmsg(mp, wptr + tstamp_len -
1764 				    mp->b_rptr)) {
1765 					BUMP_MIB(ill->ill_ip_mib,
1766 					    ipIfStatsInDiscards);
1767 					freemsg(first_mp);
1768 					return;
1769 				}
1770 				/* Refresh ipha following the pullup. */
1771 				ipha = (ipha_t *)mp->b_rptr;
1772 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1773 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1774 			}
1775 			interested = B_TRUE;
1776 		}
1777 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1778 		break;
1779 	case ICMP_TIME_STAMP_REPLY:
1780 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1781 		break;
1782 	case ICMP_INFO_REQUEST:
1783 		/* Per RFC 1122 3.2.2.7, ignore this. */
1784 	case ICMP_INFO_REPLY:
1785 		break;
1786 	case ICMP_ADDRESS_MASK_REQUEST:
1787 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1788 		    !broadcast) &&
1789 		    /* TODO m_pullup of complete header? */
1790 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN) {
1791 			interested = B_TRUE;
1792 		}
1793 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1794 		break;
1795 	case ICMP_ADDRESS_MASK_REPLY:
1796 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1797 		break;
1798 	default:
1799 		interested = B_TRUE;	/* Pass up to transport */
1800 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1801 		break;
1802 	}
1803 	/* See if there is an ICMP client. */
1804 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1805 		/* If there is an ICMP client and we want one too, copy it. */
1806 		mblk_t *first_mp1;
1807 
1808 		if (!interested) {
1809 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1810 			    ip_policy, recv_ill, zoneid);
1811 			return;
1812 		}
1813 		first_mp1 = ip_copymsg(first_mp);
1814 		if (first_mp1 != NULL) {
1815 			ip_fanout_proto(q, first_mp1, ill, ipha,
1816 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1817 		}
1818 	} else if (!interested) {
1819 		freemsg(first_mp);
1820 		return;
1821 	} else {
1822 		/*
1823 		 * Initiate policy processing for this packet if ip_policy
1824 		 * is true.
1825 		 */
1826 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1827 			ill_index = ill->ill_phyint->phyint_ifindex;
1828 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1829 			if (mp == NULL) {
1830 				if (mctl_present) {
1831 					freeb(first_mp);
1832 				}
1833 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1834 				return;
1835 			}
1836 		}
1837 	}
1838 	/* We want to do something with it. */
1839 	/* Check db_ref to make sure we can modify the packet. */
1840 	if (mp->b_datap->db_ref > 1) {
1841 		mblk_t	*first_mp1;
1842 
1843 		first_mp1 = ip_copymsg(first_mp);
1844 		freemsg(first_mp);
1845 		if (!first_mp1) {
1846 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1847 			return;
1848 		}
1849 		first_mp = first_mp1;
1850 		if (mctl_present) {
1851 			mp = first_mp->b_cont;
1852 			ASSERT(mp != NULL);
1853 		} else {
1854 			mp = first_mp;
1855 		}
1856 		ipha = (ipha_t *)mp->b_rptr;
1857 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1858 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1859 	}
1860 	switch (icmph->icmph_type) {
1861 	case ICMP_ADDRESS_MASK_REQUEST:
1862 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1863 		if (ipif == NULL) {
1864 			freemsg(first_mp);
1865 			return;
1866 		}
1867 		/*
1868 		 * outging interface must be IPv4
1869 		 */
1870 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1871 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1872 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1873 		ipif_refrele(ipif);
1874 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1875 		break;
1876 	case ICMP_ECHO_REQUEST:
1877 		icmph->icmph_type = ICMP_ECHO_REPLY;
1878 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1879 		break;
1880 	case ICMP_TIME_STAMP_REQUEST: {
1881 		uint32_t *tsp;
1882 
1883 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1884 		tsp = (uint32_t *)wptr;
1885 		tsp++;		/* Skip past 'originate time' */
1886 		/* Compute # of milliseconds since midnight */
1887 		gethrestime(&now);
1888 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1889 		    now.tv_nsec / (NANOSEC / MILLISEC);
1890 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1891 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1892 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1893 		break;
1894 	}
1895 	default:
1896 		ipha = (ipha_t *)&icmph[1];
1897 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1898 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1899 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1900 				freemsg(first_mp);
1901 				return;
1902 			}
1903 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1904 			ipha = (ipha_t *)&icmph[1];
1905 		}
1906 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1907 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1908 			freemsg(first_mp);
1909 			return;
1910 		}
1911 		hdr_length = IPH_HDR_LENGTH(ipha);
1912 		if (hdr_length < sizeof (ipha_t)) {
1913 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1914 			freemsg(first_mp);
1915 			return;
1916 		}
1917 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1918 			if (!pullupmsg(mp,
1919 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1920 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1921 				freemsg(first_mp);
1922 				return;
1923 			}
1924 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1925 			ipha = (ipha_t *)&icmph[1];
1926 		}
1927 		switch (icmph->icmph_type) {
1928 		case ICMP_REDIRECT:
1929 			/*
1930 			 * As there is no upper client to deliver, we don't
1931 			 * need the first_mp any more.
1932 			 */
1933 			if (mctl_present) {
1934 				freeb(first_mp);
1935 			}
1936 			icmp_redirect(ill, mp);
1937 			return;
1938 		case ICMP_DEST_UNREACHABLE:
1939 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1940 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1941 				    zoneid, mp, iph_hdr_length, ipst)) {
1942 					freemsg(first_mp);
1943 					return;
1944 				}
1945 				/*
1946 				 * icmp_inbound_too_big() may alter mp.
1947 				 * Resynch ipha and icmph accordingly.
1948 				 */
1949 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1950 				ipha = (ipha_t *)&icmph[1];
1951 			}
1952 			/* FALLTHRU */
1953 		default :
1954 			/*
1955 			 * IPQoS notes: Since we have already done IPQoS
1956 			 * processing we don't want to do it again in
1957 			 * the fanout routines called by
1958 			 * icmp_inbound_error_fanout, hence the last
1959 			 * argument, ip_policy, is B_FALSE.
1960 			 */
1961 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1962 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1963 			    B_FALSE, recv_ill, zoneid);
1964 		}
1965 		return;
1966 	}
1967 	/* Send out an ICMP packet */
1968 	icmph->icmph_checksum = 0;
1969 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1970 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1971 		ipif_t	*ipif_chosen;
1972 		/*
1973 		 * Make it look like it was directed to us, so we don't look
1974 		 * like a fool with a broadcast or multicast source address.
1975 		 */
1976 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1977 		/*
1978 		 * Make sure that we haven't grabbed an interface that's DOWN.
1979 		 */
1980 		if (ipif != NULL) {
1981 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
1982 			    ipha->ipha_src, zoneid);
1983 			if (ipif_chosen != NULL) {
1984 				ipif_refrele(ipif);
1985 				ipif = ipif_chosen;
1986 			}
1987 		}
1988 		if (ipif == NULL) {
1989 			ip0dbg(("icmp_inbound: "
1990 			    "No source for broadcast/multicast:\n"
1991 			    "\tsrc 0x%x dst 0x%x ill %p "
1992 			    "ipif_lcl_addr 0x%x\n",
1993 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
1994 			    (void *)ill,
1995 			    ill->ill_ipif->ipif_lcl_addr));
1996 			freemsg(first_mp);
1997 			return;
1998 		}
1999 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
2000 		ipha->ipha_dst = ipif->ipif_src_addr;
2001 		ipif_refrele(ipif);
2002 	}
2003 	/* Reset time to live. */
2004 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
2005 	{
2006 		/* Swap source and destination addresses */
2007 		ipaddr_t tmp;
2008 
2009 		tmp = ipha->ipha_src;
2010 		ipha->ipha_src = ipha->ipha_dst;
2011 		ipha->ipha_dst = tmp;
2012 	}
2013 	ipha->ipha_ident = 0;
2014 	if (!IS_SIMPLE_IPH(ipha))
2015 		icmp_options_update(ipha);
2016 
2017 	/*
2018 	 * ICMP echo replies should go out on the same interface
2019 	 * the request came on as probes used by in.mpathd for detecting
2020 	 * NIC failures are ECHO packets. We turn-off load spreading
2021 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
2022 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
2023 	 * function. This is in turn handled by ip_wput and ip_newroute
2024 	 * to make sure that the packet goes out on the interface it came
2025 	 * in on. If we don't turnoff load spreading, the packets might get
2026 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
2027 	 * to go out and in.mpathd would wrongly detect a failure or
2028 	 * mis-detect a NIC failure for link failure. As load spreading
2029 	 * can happen only if ill_group is not NULL, we do only for
2030 	 * that case and this does not affect the normal case.
2031 	 *
2032 	 * We turn off load spreading only on echo packets that came from
2033 	 * on-link hosts. If the interface route has been deleted, this will
2034 	 * not be enforced as we can't do much. For off-link hosts, as the
2035 	 * default routes in IPv4 does not typically have an ire_ipif
2036 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2037 	 * Moreover, expecting a default route through this interface may
2038 	 * not be correct. We use ipha_dst because of the swap above.
2039 	 */
2040 	onlink = B_FALSE;
2041 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2042 		/*
2043 		 * First, we need to make sure that it is not one of our
2044 		 * local addresses. If we set onlink when it is one of
2045 		 * our local addresses, we will end up creating IRE_CACHES
2046 		 * for one of our local addresses. Then, we will never
2047 		 * accept packets for them afterwards.
2048 		 */
2049 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2050 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2051 		if (src_ire == NULL) {
2052 			ipif = ipif_get_next_ipif(NULL, ill);
2053 			if (ipif == NULL) {
2054 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2055 				freemsg(mp);
2056 				return;
2057 			}
2058 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2059 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2060 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE, ipst);
2061 			ipif_refrele(ipif);
2062 			if (src_ire != NULL) {
2063 				onlink = B_TRUE;
2064 				ire_refrele(src_ire);
2065 			}
2066 		} else {
2067 			ire_refrele(src_ire);
2068 		}
2069 	}
2070 	if (!mctl_present) {
2071 		/*
2072 		 * This packet should go out the same way as it
2073 		 * came in i.e in clear. To make sure that global
2074 		 * policy will not be applied to this in ip_wput_ire,
2075 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2076 		 */
2077 		ASSERT(first_mp == mp);
2078 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2079 		if (first_mp == NULL) {
2080 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2081 			freemsg(mp);
2082 			return;
2083 		}
2084 		ii = (ipsec_in_t *)first_mp->b_rptr;
2085 
2086 		/* This is not a secure packet */
2087 		ii->ipsec_in_secure = B_FALSE;
2088 		if (onlink) {
2089 			ii->ipsec_in_attach_if = B_TRUE;
2090 			ii->ipsec_in_ill_index =
2091 			    ill->ill_phyint->phyint_ifindex;
2092 			ii->ipsec_in_rill_index =
2093 			    recv_ill->ill_phyint->phyint_ifindex;
2094 		}
2095 		first_mp->b_cont = mp;
2096 	} else if (onlink) {
2097 		ii = (ipsec_in_t *)first_mp->b_rptr;
2098 		ii->ipsec_in_attach_if = B_TRUE;
2099 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2100 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2101 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2102 	} else {
2103 		ii = (ipsec_in_t *)first_mp->b_rptr;
2104 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2105 	}
2106 	ii->ipsec_in_zoneid = zoneid;
2107 	ASSERT(zoneid != ALL_ZONES);
2108 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2109 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2110 		return;
2111 	}
2112 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2113 	put(WR(q), first_mp);
2114 }
2115 
2116 static ipaddr_t
2117 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2118 {
2119 	conn_t *connp;
2120 	connf_t *connfp;
2121 	ipaddr_t nexthop_addr = INADDR_ANY;
2122 	int hdr_length = IPH_HDR_LENGTH(ipha);
2123 	uint16_t *up;
2124 	uint32_t ports;
2125 	ip_stack_t *ipst = ill->ill_ipst;
2126 
2127 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2128 	switch (ipha->ipha_protocol) {
2129 		case IPPROTO_TCP:
2130 		{
2131 			tcph_t *tcph;
2132 
2133 			/* do a reverse lookup */
2134 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2135 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2136 			    TCPS_LISTEN, ipst);
2137 			break;
2138 		}
2139 		case IPPROTO_UDP:
2140 		{
2141 			uint32_t dstport, srcport;
2142 
2143 			((uint16_t *)&ports)[0] = up[1];
2144 			((uint16_t *)&ports)[1] = up[0];
2145 
2146 			/* Extract ports in net byte order */
2147 			dstport = htons(ntohl(ports) & 0xFFFF);
2148 			srcport = htons(ntohl(ports) >> 16);
2149 
2150 			connfp = &ipst->ips_ipcl_udp_fanout[
2151 			    IPCL_UDP_HASH(dstport, ipst)];
2152 			mutex_enter(&connfp->connf_lock);
2153 			connp = connfp->connf_head;
2154 
2155 			/* do a reverse lookup */
2156 			while ((connp != NULL) &&
2157 			    (!IPCL_UDP_MATCH(connp, dstport,
2158 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2159 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2160 				connp = connp->conn_next;
2161 			}
2162 			if (connp != NULL)
2163 				CONN_INC_REF(connp);
2164 			mutex_exit(&connfp->connf_lock);
2165 			break;
2166 		}
2167 		case IPPROTO_SCTP:
2168 		{
2169 			in6_addr_t map_src, map_dst;
2170 
2171 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2172 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2173 			((uint16_t *)&ports)[0] = up[1];
2174 			((uint16_t *)&ports)[1] = up[0];
2175 
2176 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2177 			    zoneid, ipst->ips_netstack->netstack_sctp);
2178 			if (connp == NULL) {
2179 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2180 				    zoneid, ports, ipha, ipst);
2181 			} else {
2182 				CONN_INC_REF(connp);
2183 				SCTP_REFRELE(CONN2SCTP(connp));
2184 			}
2185 			break;
2186 		}
2187 		default:
2188 		{
2189 			ipha_t ripha;
2190 
2191 			ripha.ipha_src = ipha->ipha_dst;
2192 			ripha.ipha_dst = ipha->ipha_src;
2193 			ripha.ipha_protocol = ipha->ipha_protocol;
2194 
2195 			connfp = &ipst->ips_ipcl_proto_fanout[
2196 			    ipha->ipha_protocol];
2197 			mutex_enter(&connfp->connf_lock);
2198 			connp = connfp->connf_head;
2199 			for (connp = connfp->connf_head; connp != NULL;
2200 			    connp = connp->conn_next) {
2201 				if (IPCL_PROTO_MATCH(connp,
2202 				    ipha->ipha_protocol, &ripha, ill,
2203 				    0, zoneid)) {
2204 					CONN_INC_REF(connp);
2205 					break;
2206 				}
2207 			}
2208 			mutex_exit(&connfp->connf_lock);
2209 		}
2210 	}
2211 	if (connp != NULL) {
2212 		if (connp->conn_nexthop_set)
2213 			nexthop_addr = connp->conn_nexthop_v4;
2214 		CONN_DEC_REF(connp);
2215 	}
2216 	return (nexthop_addr);
2217 }
2218 
2219 /* Table from RFC 1191 */
2220 static int icmp_frag_size_table[] =
2221 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2222 
2223 /*
2224  * Process received ICMP Packet too big.
2225  * After updating any IRE it does the fanout to any matching transport streams.
2226  * Assumes the message has been pulled up till the IP header that caused
2227  * the error.
2228  *
2229  * Returns B_FALSE on failure and B_TRUE on success.
2230  */
2231 static boolean_t
2232 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2233     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2234     ip_stack_t *ipst)
2235 {
2236 	ire_t	*ire, *first_ire;
2237 	int	mtu, orig_mtu;
2238 	int	hdr_length;
2239 	ipaddr_t nexthop_addr;
2240 	boolean_t disable_pmtud;
2241 
2242 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2243 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2244 	ASSERT(ill != NULL);
2245 
2246 	hdr_length = IPH_HDR_LENGTH(ipha);
2247 
2248 	/* Drop if the original packet contained a source route */
2249 	if (ip_source_route_included(ipha)) {
2250 		return (B_FALSE);
2251 	}
2252 	/*
2253 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2254 	 * header.
2255 	 */
2256 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2257 	    mp->b_wptr) {
2258 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2259 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2260 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2261 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2262 			return (B_FALSE);
2263 		}
2264 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2265 		ipha = (ipha_t *)&icmph[1];
2266 	}
2267 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2268 	if (nexthop_addr != INADDR_ANY) {
2269 		/* nexthop set */
2270 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2271 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2272 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2273 	} else {
2274 		/* nexthop not set */
2275 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2276 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2277 	}
2278 
2279 	if (!first_ire) {
2280 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2281 		    ntohl(ipha->ipha_dst)));
2282 		return (B_FALSE);
2283 	}
2284 
2285 	/* Check for MTU discovery advice as described in RFC 1191 */
2286 	mtu = ntohs(icmph->icmph_du_mtu);
2287 	orig_mtu = mtu;
2288 	disable_pmtud = B_FALSE;
2289 
2290 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2291 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2292 	    ire = ire->ire_next) {
2293 		/*
2294 		 * Look for the connection to which this ICMP message is
2295 		 * directed. If it has the IP_NEXTHOP option set, then the
2296 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2297 		 * option. Else the search is limited to regular IREs.
2298 		 */
2299 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2300 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2301 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2302 		    (nexthop_addr != INADDR_ANY)))
2303 			continue;
2304 
2305 		mutex_enter(&ire->ire_lock);
2306 		if (icmph->icmph_du_zero != 0 || mtu < ipst->ips_ip_pmtu_min) {
2307 			uint32_t length;
2308 			int	i;
2309 
2310 			/*
2311 			 * Use the table from RFC 1191 to figure out
2312 			 * the next "plateau" based on the length in
2313 			 * the original IP packet.
2314 			 */
2315 			length = ntohs(ipha->ipha_length);
2316 			DTRACE_PROBE2(ip4__pmtu__guess, ire_t *, ire,
2317 			    uint32_t, length);
2318 			if (ire->ire_max_frag <= length &&
2319 			    ire->ire_max_frag >= length - hdr_length) {
2320 				/*
2321 				 * Handle broken BSD 4.2 systems that
2322 				 * return the wrong iph_length in ICMP
2323 				 * errors.
2324 				 */
2325 				length -= hdr_length;
2326 			}
2327 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2328 				if (length > icmp_frag_size_table[i])
2329 					break;
2330 			}
2331 			if (i == A_CNT(icmp_frag_size_table)) {
2332 				/* Smaller than 68! */
2333 				disable_pmtud = B_TRUE;
2334 				mtu = ipst->ips_ip_pmtu_min;
2335 			} else {
2336 				mtu = icmp_frag_size_table[i];
2337 				if (mtu < ipst->ips_ip_pmtu_min) {
2338 					mtu = ipst->ips_ip_pmtu_min;
2339 					disable_pmtud = B_TRUE;
2340 				}
2341 			}
2342 			/* Fool the ULP into believing our guessed PMTU. */
2343 			icmph->icmph_du_zero = 0;
2344 			icmph->icmph_du_mtu = htons(mtu);
2345 		}
2346 		if (disable_pmtud)
2347 			ire->ire_frag_flag = 0;
2348 		/* Reduce the IRE max frag value as advised. */
2349 		ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2350 		mutex_exit(&ire->ire_lock);
2351 		DTRACE_PROBE4(ip4__pmtu__change, icmph_t *, icmph, ire_t *,
2352 		    ire, int, orig_mtu, int, mtu);
2353 	}
2354 	rw_exit(&first_ire->ire_bucket->irb_lock);
2355 	ire_refrele(first_ire);
2356 	return (B_TRUE);
2357 }
2358 
2359 /*
2360  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2361  * calls this function.
2362  */
2363 static mblk_t *
2364 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2365 {
2366 	ipha_t *ipha;
2367 	icmph_t *icmph;
2368 	ipha_t *in_ipha;
2369 	int length;
2370 
2371 	ASSERT(mp->b_datap->db_type == M_DATA);
2372 
2373 	/*
2374 	 * For Self-encapsulated packets, we added an extra IP header
2375 	 * without the options. Inner IP header is the one from which
2376 	 * the outer IP header was formed. Thus, we need to remove the
2377 	 * outer IP header. To do this, we pullup the whole message
2378 	 * and overlay whatever follows the outer IP header over the
2379 	 * outer IP header.
2380 	 */
2381 
2382 	if (!pullupmsg(mp, -1))
2383 		return (NULL);
2384 
2385 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2386 	ipha = (ipha_t *)&icmph[1];
2387 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2388 
2389 	/*
2390 	 * The length that we want to overlay is following the inner
2391 	 * IP header. Subtracting the IP header + icmp header + outer
2392 	 * IP header's length should give us the length that we want to
2393 	 * overlay.
2394 	 */
2395 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2396 	    hdr_length;
2397 	/*
2398 	 * Overlay whatever follows the inner header over the
2399 	 * outer header.
2400 	 */
2401 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2402 
2403 	/* Set the wptr to account for the outer header */
2404 	mp->b_wptr -= hdr_length;
2405 	return (mp);
2406 }
2407 
2408 /*
2409  * Try to pass the ICMP message upstream in case the ULP cares.
2410  *
2411  * If the packet that caused the ICMP error is secure, we send
2412  * it to AH/ESP to make sure that the attached packet has a
2413  * valid association. ipha in the code below points to the
2414  * IP header of the packet that caused the error.
2415  *
2416  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2417  * in the context of IPsec. Normally we tell the upper layer
2418  * whenever we send the ire (including ip_bind), the IPsec header
2419  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2420  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2421  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2422  * same thing. As TCP has the IPsec options size that needs to be
2423  * adjusted, we just pass the MTU unchanged.
2424  *
2425  * IFN could have been generated locally or by some router.
2426  *
2427  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2428  *	    This happens because IP adjusted its value of MTU on an
2429  *	    earlier IFN message and could not tell the upper layer,
2430  *	    the new adjusted value of MTU e.g. Packet was encrypted
2431  *	    or there was not enough information to fanout to upper
2432  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2433  *	    generates the IFN, where IPsec processing has *not* been
2434  *	    done.
2435  *
2436  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2437  *	    could have generated this. This happens because ire_max_frag
2438  *	    value in IP was set to a new value, while the IPsec processing
2439  *	    was being done and after we made the fragmentation check in
2440  *	    ip_wput_ire. Thus on return from IPsec processing,
2441  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2442  *	    and generates the IFN. As IPsec processing is over, we fanout
2443  *	    to AH/ESP to remove the header.
2444  *
2445  *	    In both these cases, ipsec_in_loopback will be set indicating
2446  *	    that IFN was generated locally.
2447  *
2448  * ROUTER : IFN could be secure or non-secure.
2449  *
2450  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2451  *	      packet in error has AH/ESP headers to validate the AH/ESP
2452  *	      headers. AH/ESP will verify whether there is a valid SA or
2453  *	      not and send it back. We will fanout again if we have more
2454  *	      data in the packet.
2455  *
2456  *	      If the packet in error does not have AH/ESP, we handle it
2457  *	      like any other case.
2458  *
2459  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2460  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2461  *	      for validation. AH/ESP will verify whether there is a
2462  *	      valid SA or not and send it back. We will fanout again if
2463  *	      we have more data in the packet.
2464  *
2465  *	      If the packet in error does not have AH/ESP, we handle it
2466  *	      like any other case.
2467  */
2468 static void
2469 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2470     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2471     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2472     zoneid_t zoneid)
2473 {
2474 	uint16_t *up;	/* Pointer to ports in ULP header */
2475 	uint32_t ports;	/* reversed ports for fanout */
2476 	ipha_t ripha;	/* With reversed addresses */
2477 	mblk_t *first_mp;
2478 	ipsec_in_t *ii;
2479 	tcph_t	*tcph;
2480 	conn_t	*connp;
2481 	ip_stack_t *ipst;
2482 
2483 	ASSERT(ill != NULL);
2484 
2485 	ASSERT(recv_ill != NULL);
2486 	ipst = recv_ill->ill_ipst;
2487 
2488 	first_mp = mp;
2489 	if (mctl_present) {
2490 		mp = first_mp->b_cont;
2491 		ASSERT(mp != NULL);
2492 
2493 		ii = (ipsec_in_t *)first_mp->b_rptr;
2494 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2495 	} else {
2496 		ii = NULL;
2497 	}
2498 
2499 	switch (ipha->ipha_protocol) {
2500 	case IPPROTO_UDP:
2501 		/*
2502 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2503 		 * transport header.
2504 		 */
2505 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2506 		    mp->b_wptr) {
2507 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2508 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2509 				goto discard_pkt;
2510 			}
2511 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2512 			ipha = (ipha_t *)&icmph[1];
2513 		}
2514 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2515 
2516 		/*
2517 		 * Attempt to find a client stream based on port.
2518 		 * Note that we do a reverse lookup since the header is
2519 		 * in the form we sent it out.
2520 		 * The ripha header is only used for the IP_UDP_MATCH and we
2521 		 * only set the src and dst addresses and protocol.
2522 		 */
2523 		ripha.ipha_src = ipha->ipha_dst;
2524 		ripha.ipha_dst = ipha->ipha_src;
2525 		ripha.ipha_protocol = ipha->ipha_protocol;
2526 		((uint16_t *)&ports)[0] = up[1];
2527 		((uint16_t *)&ports)[1] = up[0];
2528 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2529 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2530 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2531 		    icmph->icmph_type, icmph->icmph_code));
2532 
2533 		/* Have to change db_type after any pullupmsg */
2534 		DB_TYPE(mp) = M_CTL;
2535 
2536 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2537 		    mctl_present, ip_policy, recv_ill, zoneid);
2538 		return;
2539 
2540 	case IPPROTO_TCP:
2541 		/*
2542 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2543 		 * transport header.
2544 		 */
2545 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2546 		    mp->b_wptr) {
2547 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2548 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2549 				goto discard_pkt;
2550 			}
2551 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2552 			ipha = (ipha_t *)&icmph[1];
2553 		}
2554 		/*
2555 		 * Find a TCP client stream for this packet.
2556 		 * Note that we do a reverse lookup since the header is
2557 		 * in the form we sent it out.
2558 		 */
2559 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2560 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2561 		    ipst);
2562 		if (connp == NULL)
2563 			goto discard_pkt;
2564 
2565 		/* Have to change db_type after any pullupmsg */
2566 		DB_TYPE(mp) = M_CTL;
2567 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2568 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2569 		return;
2570 
2571 	case IPPROTO_SCTP:
2572 		/*
2573 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2574 		 * transport header.
2575 		 */
2576 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2577 		    mp->b_wptr) {
2578 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2579 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2580 				goto discard_pkt;
2581 			}
2582 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2583 			ipha = (ipha_t *)&icmph[1];
2584 		}
2585 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2586 		/*
2587 		 * Find a SCTP client stream for this packet.
2588 		 * Note that we do a reverse lookup since the header is
2589 		 * in the form we sent it out.
2590 		 * The ripha header is only used for the matching and we
2591 		 * only set the src and dst addresses, protocol, and version.
2592 		 */
2593 		ripha.ipha_src = ipha->ipha_dst;
2594 		ripha.ipha_dst = ipha->ipha_src;
2595 		ripha.ipha_protocol = ipha->ipha_protocol;
2596 		ripha.ipha_version_and_hdr_length =
2597 		    ipha->ipha_version_and_hdr_length;
2598 		((uint16_t *)&ports)[0] = up[1];
2599 		((uint16_t *)&ports)[1] = up[0];
2600 
2601 		/* Have to change db_type after any pullupmsg */
2602 		DB_TYPE(mp) = M_CTL;
2603 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2604 		    mctl_present, ip_policy, zoneid);
2605 		return;
2606 
2607 	case IPPROTO_ESP:
2608 	case IPPROTO_AH: {
2609 		int ipsec_rc;
2610 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2611 
2612 		/*
2613 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2614 		 * We will re-use the IPSEC_IN if it is already present as
2615 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2616 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2617 		 * one and attach it in the front.
2618 		 */
2619 		if (ii != NULL) {
2620 			/*
2621 			 * ip_fanout_proto_again converts the ICMP errors
2622 			 * that come back from AH/ESP to M_DATA so that
2623 			 * if it is non-AH/ESP and we do a pullupmsg in
2624 			 * this function, it would work. Convert it back
2625 			 * to M_CTL before we send up as this is a ICMP
2626 			 * error. This could have been generated locally or
2627 			 * by some router. Validate the inner IPsec
2628 			 * headers.
2629 			 *
2630 			 * NOTE : ill_index is used by ip_fanout_proto_again
2631 			 * to locate the ill.
2632 			 */
2633 			ASSERT(ill != NULL);
2634 			ii->ipsec_in_ill_index =
2635 			    ill->ill_phyint->phyint_ifindex;
2636 			ii->ipsec_in_rill_index =
2637 			    recv_ill->ill_phyint->phyint_ifindex;
2638 			DB_TYPE(first_mp->b_cont) = M_CTL;
2639 		} else {
2640 			/*
2641 			 * IPSEC_IN is not present. We attach a ipsec_in
2642 			 * message and send up to IPsec for validating
2643 			 * and removing the IPsec headers. Clear
2644 			 * ipsec_in_secure so that when we return
2645 			 * from IPsec, we don't mistakenly think that this
2646 			 * is a secure packet came from the network.
2647 			 *
2648 			 * NOTE : ill_index is used by ip_fanout_proto_again
2649 			 * to locate the ill.
2650 			 */
2651 			ASSERT(first_mp == mp);
2652 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2653 			if (first_mp == NULL) {
2654 				freemsg(mp);
2655 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2656 				return;
2657 			}
2658 			ii = (ipsec_in_t *)first_mp->b_rptr;
2659 
2660 			/* This is not a secure packet */
2661 			ii->ipsec_in_secure = B_FALSE;
2662 			first_mp->b_cont = mp;
2663 			DB_TYPE(mp) = M_CTL;
2664 			ASSERT(ill != NULL);
2665 			ii->ipsec_in_ill_index =
2666 			    ill->ill_phyint->phyint_ifindex;
2667 			ii->ipsec_in_rill_index =
2668 			    recv_ill->ill_phyint->phyint_ifindex;
2669 		}
2670 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2671 
2672 		if (!ipsec_loaded(ipss)) {
2673 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2674 			return;
2675 		}
2676 
2677 		if (ipha->ipha_protocol == IPPROTO_ESP)
2678 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2679 		else
2680 			ipsec_rc = ipsecah_icmp_error(first_mp);
2681 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2682 			return;
2683 
2684 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2685 		return;
2686 	}
2687 	default:
2688 		/*
2689 		 * The ripha header is only used for the lookup and we
2690 		 * only set the src and dst addresses and protocol.
2691 		 */
2692 		ripha.ipha_src = ipha->ipha_dst;
2693 		ripha.ipha_dst = ipha->ipha_src;
2694 		ripha.ipha_protocol = ipha->ipha_protocol;
2695 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2696 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2697 		    ntohl(ipha->ipha_dst),
2698 		    icmph->icmph_type, icmph->icmph_code));
2699 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2700 			ipha_t *in_ipha;
2701 
2702 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2703 			    mp->b_wptr) {
2704 				if (!pullupmsg(mp, (uchar_t *)ipha +
2705 				    hdr_length + sizeof (ipha_t) -
2706 				    mp->b_rptr)) {
2707 					goto discard_pkt;
2708 				}
2709 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2710 				ipha = (ipha_t *)&icmph[1];
2711 			}
2712 			/*
2713 			 * Caller has verified that length has to be
2714 			 * at least the size of IP header.
2715 			 */
2716 			ASSERT(hdr_length >= sizeof (ipha_t));
2717 			/*
2718 			 * Check the sanity of the inner IP header like
2719 			 * we did for the outer header.
2720 			 */
2721 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2722 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2723 				goto discard_pkt;
2724 			}
2725 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2726 				goto discard_pkt;
2727 			}
2728 			/* Check for Self-encapsulated tunnels */
2729 			if (in_ipha->ipha_src == ipha->ipha_src &&
2730 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2731 
2732 				mp = icmp_inbound_self_encap_error(mp,
2733 				    iph_hdr_length, hdr_length);
2734 				if (mp == NULL)
2735 					goto discard_pkt;
2736 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2737 				ipha = (ipha_t *)&icmph[1];
2738 				hdr_length = IPH_HDR_LENGTH(ipha);
2739 				/*
2740 				 * The packet in error is self-encapsualted.
2741 				 * And we are finding it further encapsulated
2742 				 * which we could not have possibly generated.
2743 				 */
2744 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2745 					goto discard_pkt;
2746 				}
2747 				icmp_inbound_error_fanout(q, ill, first_mp,
2748 				    icmph, ipha, iph_hdr_length, hdr_length,
2749 				    mctl_present, ip_policy, recv_ill, zoneid);
2750 				return;
2751 			}
2752 		}
2753 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2754 		    ipha->ipha_protocol == IPPROTO_IPV6) &&
2755 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2756 		    ii != NULL &&
2757 		    ii->ipsec_in_loopback &&
2758 		    ii->ipsec_in_secure) {
2759 			/*
2760 			 * For IP tunnels that get a looped-back
2761 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2762 			 * reported new MTU to take into account the IPsec
2763 			 * headers protecting this configured tunnel.
2764 			 *
2765 			 * This allows the tunnel module (tun.c) to blindly
2766 			 * accept the MTU reported in an ICMP "too big"
2767 			 * message.
2768 			 *
2769 			 * Non-looped back ICMP messages will just be
2770 			 * handled by the security protocols (if needed),
2771 			 * and the first subsequent packet will hit this
2772 			 * path.
2773 			 */
2774 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2775 			    ipsec_in_extra_length(first_mp));
2776 		}
2777 		/* Have to change db_type after any pullupmsg */
2778 		DB_TYPE(mp) = M_CTL;
2779 
2780 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2781 		    ip_policy, recv_ill, zoneid);
2782 		return;
2783 	}
2784 	/* NOTREACHED */
2785 discard_pkt:
2786 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2787 drop_pkt:;
2788 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2789 	freemsg(first_mp);
2790 }
2791 
2792 /*
2793  * Common IP options parser.
2794  *
2795  * Setup routine: fill in *optp with options-parsing state, then
2796  * tail-call ipoptp_next to return the first option.
2797  */
2798 uint8_t
2799 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2800 {
2801 	uint32_t totallen; /* total length of all options */
2802 
2803 	totallen = ipha->ipha_version_and_hdr_length -
2804 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2805 	totallen <<= 2;
2806 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2807 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2808 	optp->ipoptp_flags = 0;
2809 	return (ipoptp_next(optp));
2810 }
2811 
2812 /*
2813  * Common IP options parser: extract next option.
2814  */
2815 uint8_t
2816 ipoptp_next(ipoptp_t *optp)
2817 {
2818 	uint8_t *end = optp->ipoptp_end;
2819 	uint8_t *cur = optp->ipoptp_next;
2820 	uint8_t opt, len, pointer;
2821 
2822 	/*
2823 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2824 	 * has been corrupted.
2825 	 */
2826 	ASSERT(cur <= end);
2827 
2828 	if (cur == end)
2829 		return (IPOPT_EOL);
2830 
2831 	opt = cur[IPOPT_OPTVAL];
2832 
2833 	/*
2834 	 * Skip any NOP options.
2835 	 */
2836 	while (opt == IPOPT_NOP) {
2837 		cur++;
2838 		if (cur == end)
2839 			return (IPOPT_EOL);
2840 		opt = cur[IPOPT_OPTVAL];
2841 	}
2842 
2843 	if (opt == IPOPT_EOL)
2844 		return (IPOPT_EOL);
2845 
2846 	/*
2847 	 * Option requiring a length.
2848 	 */
2849 	if ((cur + 1) >= end) {
2850 		optp->ipoptp_flags |= IPOPTP_ERROR;
2851 		return (IPOPT_EOL);
2852 	}
2853 	len = cur[IPOPT_OLEN];
2854 	if (len < 2) {
2855 		optp->ipoptp_flags |= IPOPTP_ERROR;
2856 		return (IPOPT_EOL);
2857 	}
2858 	optp->ipoptp_cur = cur;
2859 	optp->ipoptp_len = len;
2860 	optp->ipoptp_next = cur + len;
2861 	if (cur + len > end) {
2862 		optp->ipoptp_flags |= IPOPTP_ERROR;
2863 		return (IPOPT_EOL);
2864 	}
2865 
2866 	/*
2867 	 * For the options which require a pointer field, make sure
2868 	 * its there, and make sure it points to either something
2869 	 * inside this option, or the end of the option.
2870 	 */
2871 	switch (opt) {
2872 	case IPOPT_RR:
2873 	case IPOPT_TS:
2874 	case IPOPT_LSRR:
2875 	case IPOPT_SSRR:
2876 		if (len <= IPOPT_OFFSET) {
2877 			optp->ipoptp_flags |= IPOPTP_ERROR;
2878 			return (opt);
2879 		}
2880 		pointer = cur[IPOPT_OFFSET];
2881 		if (pointer - 1 > len) {
2882 			optp->ipoptp_flags |= IPOPTP_ERROR;
2883 			return (opt);
2884 		}
2885 		break;
2886 	}
2887 
2888 	/*
2889 	 * Sanity check the pointer field based on the type of the
2890 	 * option.
2891 	 */
2892 	switch (opt) {
2893 	case IPOPT_RR:
2894 	case IPOPT_SSRR:
2895 	case IPOPT_LSRR:
2896 		if (pointer < IPOPT_MINOFF_SR)
2897 			optp->ipoptp_flags |= IPOPTP_ERROR;
2898 		break;
2899 	case IPOPT_TS:
2900 		if (pointer < IPOPT_MINOFF_IT)
2901 			optp->ipoptp_flags |= IPOPTP_ERROR;
2902 		/*
2903 		 * Note that the Internet Timestamp option also
2904 		 * contains two four bit fields (the Overflow field,
2905 		 * and the Flag field), which follow the pointer
2906 		 * field.  We don't need to check that these fields
2907 		 * fall within the length of the option because this
2908 		 * was implicitely done above.  We've checked that the
2909 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2910 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2911 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2912 		 */
2913 		ASSERT(len > IPOPT_POS_OV_FLG);
2914 		break;
2915 	}
2916 
2917 	return (opt);
2918 }
2919 
2920 /*
2921  * Use the outgoing IP header to create an IP_OPTIONS option the way
2922  * it was passed down from the application.
2923  */
2924 int
2925 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2926 {
2927 	ipoptp_t	opts;
2928 	const uchar_t	*opt;
2929 	uint8_t		optval;
2930 	uint8_t		optlen;
2931 	uint32_t	len = 0;
2932 	uchar_t	*buf1 = buf;
2933 
2934 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2935 	len += IP_ADDR_LEN;
2936 	bzero(buf1, IP_ADDR_LEN);
2937 
2938 	/*
2939 	 * OK to cast away const here, as we don't store through the returned
2940 	 * opts.ipoptp_cur pointer.
2941 	 */
2942 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2943 	    optval != IPOPT_EOL;
2944 	    optval = ipoptp_next(&opts)) {
2945 		int	off;
2946 
2947 		opt = opts.ipoptp_cur;
2948 		optlen = opts.ipoptp_len;
2949 		switch (optval) {
2950 		case IPOPT_SSRR:
2951 		case IPOPT_LSRR:
2952 
2953 			/*
2954 			 * Insert ipha_dst as the first entry in the source
2955 			 * route and move down the entries on step.
2956 			 * The last entry gets placed at buf1.
2957 			 */
2958 			buf[IPOPT_OPTVAL] = optval;
2959 			buf[IPOPT_OLEN] = optlen;
2960 			buf[IPOPT_OFFSET] = optlen;
2961 
2962 			off = optlen - IP_ADDR_LEN;
2963 			if (off < 0) {
2964 				/* No entries in source route */
2965 				break;
2966 			}
2967 			/* Last entry in source route */
2968 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2969 			off -= IP_ADDR_LEN;
2970 
2971 			while (off > 0) {
2972 				bcopy(opt + off,
2973 				    buf + off + IP_ADDR_LEN,
2974 				    IP_ADDR_LEN);
2975 				off -= IP_ADDR_LEN;
2976 			}
2977 			/* ipha_dst into first slot */
2978 			bcopy(&ipha->ipha_dst,
2979 			    buf + off + IP_ADDR_LEN,
2980 			    IP_ADDR_LEN);
2981 			buf += optlen;
2982 			len += optlen;
2983 			break;
2984 
2985 		case IPOPT_COMSEC:
2986 		case IPOPT_SECURITY:
2987 			/* if passing up a label is not ok, then remove */
2988 			if (is_system_labeled())
2989 				break;
2990 			/* FALLTHROUGH */
2991 		default:
2992 			bcopy(opt, buf, optlen);
2993 			buf += optlen;
2994 			len += optlen;
2995 			break;
2996 		}
2997 	}
2998 done:
2999 	/* Pad the resulting options */
3000 	while (len & 0x3) {
3001 		*buf++ = IPOPT_EOL;
3002 		len++;
3003 	}
3004 	return (len);
3005 }
3006 
3007 /*
3008  * Update any record route or timestamp options to include this host.
3009  * Reverse any source route option.
3010  * This routine assumes that the options are well formed i.e. that they
3011  * have already been checked.
3012  */
3013 static void
3014 icmp_options_update(ipha_t *ipha)
3015 {
3016 	ipoptp_t	opts;
3017 	uchar_t		*opt;
3018 	uint8_t		optval;
3019 	ipaddr_t	src;		/* Our local address */
3020 	ipaddr_t	dst;
3021 
3022 	ip2dbg(("icmp_options_update\n"));
3023 	src = ipha->ipha_src;
3024 	dst = ipha->ipha_dst;
3025 
3026 	for (optval = ipoptp_first(&opts, ipha);
3027 	    optval != IPOPT_EOL;
3028 	    optval = ipoptp_next(&opts)) {
3029 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
3030 		opt = opts.ipoptp_cur;
3031 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
3032 		    optval, opts.ipoptp_len));
3033 		switch (optval) {
3034 			int off1, off2;
3035 		case IPOPT_SSRR:
3036 		case IPOPT_LSRR:
3037 			/*
3038 			 * Reverse the source route.  The first entry
3039 			 * should be the next to last one in the current
3040 			 * source route (the last entry is our address).
3041 			 * The last entry should be the final destination.
3042 			 */
3043 			off1 = IPOPT_MINOFF_SR - 1;
3044 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3045 			if (off2 < 0) {
3046 				/* No entries in source route */
3047 				ip1dbg((
3048 				    "icmp_options_update: bad src route\n"));
3049 				break;
3050 			}
3051 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3052 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3053 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3054 			off2 -= IP_ADDR_LEN;
3055 
3056 			while (off1 < off2) {
3057 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3058 				bcopy((char *)opt + off2, (char *)opt + off1,
3059 				    IP_ADDR_LEN);
3060 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3061 				off1 += IP_ADDR_LEN;
3062 				off2 -= IP_ADDR_LEN;
3063 			}
3064 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3065 			break;
3066 		}
3067 	}
3068 }
3069 
3070 /*
3071  * Process received ICMP Redirect messages.
3072  */
3073 static void
3074 icmp_redirect(ill_t *ill, mblk_t *mp)
3075 {
3076 	ipha_t	*ipha;
3077 	int	iph_hdr_length;
3078 	icmph_t	*icmph;
3079 	ipha_t	*ipha_err;
3080 	ire_t	*ire;
3081 	ire_t	*prev_ire;
3082 	ire_t	*save_ire;
3083 	ipaddr_t  src, dst, gateway;
3084 	iulp_t	ulp_info = { 0 };
3085 	int	error;
3086 	ip_stack_t *ipst;
3087 
3088 	ASSERT(ill != NULL);
3089 	ipst = ill->ill_ipst;
3090 
3091 	ipha = (ipha_t *)mp->b_rptr;
3092 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3093 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3094 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3095 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3096 		freemsg(mp);
3097 		return;
3098 	}
3099 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3100 	ipha_err = (ipha_t *)&icmph[1];
3101 	src = ipha->ipha_src;
3102 	dst = ipha_err->ipha_dst;
3103 	gateway = icmph->icmph_rd_gateway;
3104 	/* Make sure the new gateway is reachable somehow. */
3105 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3106 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3107 	/*
3108 	 * Make sure we had a route for the dest in question and that
3109 	 * that route was pointing to the old gateway (the source of the
3110 	 * redirect packet.)
3111 	 */
3112 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3113 	    NULL, MATCH_IRE_GW, ipst);
3114 	/*
3115 	 * Check that
3116 	 *	the redirect was not from ourselves
3117 	 *	the new gateway and the old gateway are directly reachable
3118 	 */
3119 	if (!prev_ire ||
3120 	    !ire ||
3121 	    ire->ire_type == IRE_LOCAL) {
3122 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3123 		freemsg(mp);
3124 		if (ire != NULL)
3125 			ire_refrele(ire);
3126 		if (prev_ire != NULL)
3127 			ire_refrele(prev_ire);
3128 		return;
3129 	}
3130 
3131 	/*
3132 	 * Should we use the old ULP info to create the new gateway?  From
3133 	 * a user's perspective, we should inherit the info so that it
3134 	 * is a "smooth" transition.  If we do not do that, then new
3135 	 * connections going thru the new gateway will have no route metrics,
3136 	 * which is counter-intuitive to user.  From a network point of
3137 	 * view, this may or may not make sense even though the new gateway
3138 	 * is still directly connected to us so the route metrics should not
3139 	 * change much.
3140 	 *
3141 	 * But if the old ire_uinfo is not initialized, we do another
3142 	 * recursive lookup on the dest using the new gateway.  There may
3143 	 * be a route to that.  If so, use it to initialize the redirect
3144 	 * route.
3145 	 */
3146 	if (prev_ire->ire_uinfo.iulp_set) {
3147 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3148 	} else {
3149 		ire_t *tmp_ire;
3150 		ire_t *sire;
3151 
3152 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3153 		    ALL_ZONES, 0, NULL,
3154 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3155 		    ipst);
3156 		if (sire != NULL) {
3157 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3158 			/*
3159 			 * If sire != NULL, ire_ftable_lookup() should not
3160 			 * return a NULL value.
3161 			 */
3162 			ASSERT(tmp_ire != NULL);
3163 			ire_refrele(tmp_ire);
3164 			ire_refrele(sire);
3165 		} else if (tmp_ire != NULL) {
3166 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3167 			    sizeof (iulp_t));
3168 			ire_refrele(tmp_ire);
3169 		}
3170 	}
3171 	if (prev_ire->ire_type == IRE_CACHE)
3172 		ire_delete(prev_ire);
3173 	ire_refrele(prev_ire);
3174 	/*
3175 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3176 	 * require TOS routing
3177 	 */
3178 	switch (icmph->icmph_code) {
3179 	case 0:
3180 	case 1:
3181 		/* TODO: TOS specificity for cases 2 and 3 */
3182 	case 2:
3183 	case 3:
3184 		break;
3185 	default:
3186 		freemsg(mp);
3187 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3188 		ire_refrele(ire);
3189 		return;
3190 	}
3191 	/*
3192 	 * Create a Route Association.  This will allow us to remember that
3193 	 * someone we believe told us to use the particular gateway.
3194 	 */
3195 	save_ire = ire;
3196 	ire = ire_create(
3197 	    (uchar_t *)&dst,			/* dest addr */
3198 	    (uchar_t *)&ip_g_all_ones,		/* mask */
3199 	    (uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3200 	    (uchar_t *)&gateway,		/* gateway addr */
3201 	    &save_ire->ire_max_frag,		/* max frag */
3202 	    NULL,				/* no src nce */
3203 	    NULL,				/* no rfq */
3204 	    NULL,				/* no stq */
3205 	    IRE_HOST,
3206 	    NULL,				/* ipif */
3207 	    0,					/* cmask */
3208 	    0,					/* phandle */
3209 	    0,					/* ihandle */
3210 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3211 	    &ulp_info,
3212 	    NULL,				/* tsol_gc_t */
3213 	    NULL,				/* gcgrp */
3214 	    ipst);
3215 
3216 	if (ire == NULL) {
3217 		freemsg(mp);
3218 		ire_refrele(save_ire);
3219 		return;
3220 	}
3221 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3222 	ire_refrele(save_ire);
3223 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3224 
3225 	if (error == 0) {
3226 		ire_refrele(ire);		/* Held in ire_add_v4 */
3227 		/* tell routing sockets that we received a redirect */
3228 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3229 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3230 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3231 	}
3232 
3233 	/*
3234 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3235 	 * This together with the added IRE has the effect of
3236 	 * modifying an existing redirect.
3237 	 */
3238 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3239 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3240 	if (prev_ire != NULL) {
3241 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3242 			ire_delete(prev_ire);
3243 		ire_refrele(prev_ire);
3244 	}
3245 
3246 	freemsg(mp);
3247 }
3248 
3249 /*
3250  * Generate an ICMP parameter problem message.
3251  */
3252 static void
3253 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3254 	ip_stack_t *ipst)
3255 {
3256 	icmph_t	icmph;
3257 	boolean_t mctl_present;
3258 	mblk_t *first_mp;
3259 
3260 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3261 
3262 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3263 		if (mctl_present)
3264 			freeb(first_mp);
3265 		return;
3266 	}
3267 
3268 	bzero(&icmph, sizeof (icmph_t));
3269 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3270 	icmph.icmph_pp_ptr = ptr;
3271 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3272 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3273 	    ipst);
3274 }
3275 
3276 /*
3277  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3278  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3279  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3280  * an icmp error packet can be sent.
3281  * Assigns an appropriate source address to the packet. If ipha_dst is
3282  * one of our addresses use it for source. Otherwise pick a source based
3283  * on a route lookup back to ipha_src.
3284  * Note that ipha_src must be set here since the
3285  * packet is likely to arrive on an ill queue in ip_wput() which will
3286  * not set a source address.
3287  */
3288 static void
3289 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3290     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3291 {
3292 	ipaddr_t dst;
3293 	icmph_t	*icmph;
3294 	ipha_t	*ipha;
3295 	uint_t	len_needed;
3296 	size_t	msg_len;
3297 	mblk_t	*mp1;
3298 	ipaddr_t src;
3299 	ire_t	*ire;
3300 	mblk_t *ipsec_mp;
3301 	ipsec_out_t	*io = NULL;
3302 
3303 	if (mctl_present) {
3304 		/*
3305 		 * If it is :
3306 		 *
3307 		 * 1) a IPSEC_OUT, then this is caused by outbound
3308 		 *    datagram originating on this host. IPsec processing
3309 		 *    may or may not have been done. Refer to comments above
3310 		 *    icmp_inbound_error_fanout for details.
3311 		 *
3312 		 * 2) a IPSEC_IN if we are generating a icmp_message
3313 		 *    for an incoming datagram destined for us i.e called
3314 		 *    from ip_fanout_send_icmp.
3315 		 */
3316 		ipsec_info_t *in;
3317 		ipsec_mp = mp;
3318 		mp = ipsec_mp->b_cont;
3319 
3320 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3321 		ipha = (ipha_t *)mp->b_rptr;
3322 
3323 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3324 		    in->ipsec_info_type == IPSEC_IN);
3325 
3326 		if (in->ipsec_info_type == IPSEC_IN) {
3327 			/*
3328 			 * Convert the IPSEC_IN to IPSEC_OUT.
3329 			 */
3330 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3331 				BUMP_MIB(&ipst->ips_ip_mib,
3332 				    ipIfStatsOutDiscards);
3333 				return;
3334 			}
3335 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3336 		} else {
3337 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3338 			io = (ipsec_out_t *)in;
3339 			/*
3340 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3341 			 * ire lookup.
3342 			 */
3343 			io->ipsec_out_proc_begin = B_FALSE;
3344 		}
3345 		ASSERT(zoneid == io->ipsec_out_zoneid);
3346 		ASSERT(zoneid != ALL_ZONES);
3347 	} else {
3348 		/*
3349 		 * This is in clear. The icmp message we are building
3350 		 * here should go out in clear.
3351 		 *
3352 		 * Pardon the convolution of it all, but it's easier to
3353 		 * allocate a "use cleartext" IPSEC_IN message and convert
3354 		 * it than it is to allocate a new one.
3355 		 */
3356 		ipsec_in_t *ii;
3357 		ASSERT(DB_TYPE(mp) == M_DATA);
3358 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3359 		if (ipsec_mp == NULL) {
3360 			freemsg(mp);
3361 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3362 			return;
3363 		}
3364 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3365 
3366 		/* This is not a secure packet */
3367 		ii->ipsec_in_secure = B_FALSE;
3368 		/*
3369 		 * For trusted extensions using a shared IP address we can
3370 		 * send using any zoneid.
3371 		 */
3372 		if (zoneid == ALL_ZONES)
3373 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3374 		else
3375 			ii->ipsec_in_zoneid = zoneid;
3376 		ipsec_mp->b_cont = mp;
3377 		ipha = (ipha_t *)mp->b_rptr;
3378 		/*
3379 		 * Convert the IPSEC_IN to IPSEC_OUT.
3380 		 */
3381 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3382 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3383 			return;
3384 		}
3385 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3386 	}
3387 
3388 	/* Remember our eventual destination */
3389 	dst = ipha->ipha_src;
3390 
3391 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3392 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3393 	if (ire != NULL &&
3394 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3395 		src = ipha->ipha_dst;
3396 	} else {
3397 		if (ire != NULL)
3398 			ire_refrele(ire);
3399 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3400 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3401 		    ipst);
3402 		if (ire == NULL) {
3403 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3404 			freemsg(ipsec_mp);
3405 			return;
3406 		}
3407 		src = ire->ire_src_addr;
3408 	}
3409 
3410 	if (ire != NULL)
3411 		ire_refrele(ire);
3412 
3413 	/*
3414 	 * Check if we can send back more then 8 bytes in addition to
3415 	 * the IP header.  We try to send 64 bytes of data and the internal
3416 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3417 	 */
3418 	len_needed = IPH_HDR_LENGTH(ipha);
3419 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3420 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3421 
3422 		if (!pullupmsg(mp, -1)) {
3423 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3424 			freemsg(ipsec_mp);
3425 			return;
3426 		}
3427 		ipha = (ipha_t *)mp->b_rptr;
3428 
3429 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3430 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3431 			    len_needed));
3432 		} else {
3433 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3434 
3435 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3436 			len_needed += ip_hdr_length_v6(mp, ip6h);
3437 		}
3438 	}
3439 	len_needed += ipst->ips_ip_icmp_return;
3440 	msg_len = msgdsize(mp);
3441 	if (msg_len > len_needed) {
3442 		(void) adjmsg(mp, len_needed - msg_len);
3443 		msg_len = len_needed;
3444 	}
3445 	mp1 = allocb_tmpl(sizeof (icmp_ipha) + len, mp);
3446 	if (mp1 == NULL) {
3447 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3448 		freemsg(ipsec_mp);
3449 		return;
3450 	}
3451 	mp1->b_cont = mp;
3452 	mp = mp1;
3453 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3454 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3455 	    io->ipsec_out_type == IPSEC_OUT);
3456 	ipsec_mp->b_cont = mp;
3457 
3458 	/*
3459 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3460 	 * node generates be accepted in peace by all on-host destinations.
3461 	 * If we do NOT assume that all on-host destinations trust
3462 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3463 	 * (Look for ipsec_out_icmp_loopback).
3464 	 */
3465 	io->ipsec_out_icmp_loopback = B_TRUE;
3466 
3467 	ipha = (ipha_t *)mp->b_rptr;
3468 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3469 	*ipha = icmp_ipha;
3470 	ipha->ipha_src = src;
3471 	ipha->ipha_dst = dst;
3472 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3473 	msg_len += sizeof (icmp_ipha) + len;
3474 	if (msg_len > IP_MAXPACKET) {
3475 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3476 		msg_len = IP_MAXPACKET;
3477 	}
3478 	ipha->ipha_length = htons((uint16_t)msg_len);
3479 	icmph = (icmph_t *)&ipha[1];
3480 	bcopy(stuff, icmph, len);
3481 	icmph->icmph_checksum = 0;
3482 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3483 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3484 	put(q, ipsec_mp);
3485 }
3486 
3487 /*
3488  * Determine if an ICMP error packet can be sent given the rate limit.
3489  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3490  * in milliseconds) and a burst size. Burst size number of packets can
3491  * be sent arbitrarely closely spaced.
3492  * The state is tracked using two variables to implement an approximate
3493  * token bucket filter:
3494  *	icmp_pkt_err_last - lbolt value when the last burst started
3495  *	icmp_pkt_err_sent - number of packets sent in current burst
3496  */
3497 boolean_t
3498 icmp_err_rate_limit(ip_stack_t *ipst)
3499 {
3500 	clock_t now = TICK_TO_MSEC(lbolt);
3501 	uint_t refilled; /* Number of packets refilled in tbf since last */
3502 	/* Guard against changes by loading into local variable */
3503 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3504 
3505 	if (err_interval == 0)
3506 		return (B_FALSE);
3507 
3508 	if (ipst->ips_icmp_pkt_err_last > now) {
3509 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3510 		ipst->ips_icmp_pkt_err_last = 0;
3511 		ipst->ips_icmp_pkt_err_sent = 0;
3512 	}
3513 	/*
3514 	 * If we are in a burst update the token bucket filter.
3515 	 * Update the "last" time to be close to "now" but make sure
3516 	 * we don't loose precision.
3517 	 */
3518 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3519 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3520 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3521 			ipst->ips_icmp_pkt_err_sent = 0;
3522 		} else {
3523 			ipst->ips_icmp_pkt_err_sent -= refilled;
3524 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3525 		}
3526 	}
3527 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3528 		/* Start of new burst */
3529 		ipst->ips_icmp_pkt_err_last = now;
3530 	}
3531 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3532 		ipst->ips_icmp_pkt_err_sent++;
3533 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3534 		    ipst->ips_icmp_pkt_err_sent));
3535 		return (B_FALSE);
3536 	}
3537 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3538 	return (B_TRUE);
3539 }
3540 
3541 /*
3542  * Check if it is ok to send an IPv4 ICMP error packet in
3543  * response to the IPv4 packet in mp.
3544  * Free the message and return null if no
3545  * ICMP error packet should be sent.
3546  */
3547 static mblk_t *
3548 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3549 {
3550 	icmph_t	*icmph;
3551 	ipha_t	*ipha;
3552 	uint_t	len_needed;
3553 	ire_t	*src_ire;
3554 	ire_t	*dst_ire;
3555 
3556 	if (!mp)
3557 		return (NULL);
3558 	ipha = (ipha_t *)mp->b_rptr;
3559 	if (ip_csum_hdr(ipha)) {
3560 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3561 		freemsg(mp);
3562 		return (NULL);
3563 	}
3564 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3565 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3566 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3567 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3568 	if (src_ire != NULL || dst_ire != NULL ||
3569 	    CLASSD(ipha->ipha_dst) ||
3570 	    CLASSD(ipha->ipha_src) ||
3571 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3572 		/* Note: only errors to the fragment with offset 0 */
3573 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3574 		freemsg(mp);
3575 		if (src_ire != NULL)
3576 			ire_refrele(src_ire);
3577 		if (dst_ire != NULL)
3578 			ire_refrele(dst_ire);
3579 		return (NULL);
3580 	}
3581 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3582 		/*
3583 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3584 		 * errors in response to any ICMP errors.
3585 		 */
3586 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3587 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3588 			if (!pullupmsg(mp, len_needed)) {
3589 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3590 				freemsg(mp);
3591 				return (NULL);
3592 			}
3593 			ipha = (ipha_t *)mp->b_rptr;
3594 		}
3595 		icmph = (icmph_t *)
3596 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3597 		switch (icmph->icmph_type) {
3598 		case ICMP_DEST_UNREACHABLE:
3599 		case ICMP_SOURCE_QUENCH:
3600 		case ICMP_TIME_EXCEEDED:
3601 		case ICMP_PARAM_PROBLEM:
3602 		case ICMP_REDIRECT:
3603 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3604 			freemsg(mp);
3605 			return (NULL);
3606 		default:
3607 			break;
3608 		}
3609 	}
3610 	/*
3611 	 * If this is a labeled system, then check to see if we're allowed to
3612 	 * send a response to this particular sender.  If not, then just drop.
3613 	 */
3614 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3615 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3616 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3617 		freemsg(mp);
3618 		return (NULL);
3619 	}
3620 	if (icmp_err_rate_limit(ipst)) {
3621 		/*
3622 		 * Only send ICMP error packets every so often.
3623 		 * This should be done on a per port/source basis,
3624 		 * but for now this will suffice.
3625 		 */
3626 		freemsg(mp);
3627 		return (NULL);
3628 	}
3629 	return (mp);
3630 }
3631 
3632 /*
3633  * Generate an ICMP redirect message.
3634  */
3635 static void
3636 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3637 {
3638 	icmph_t	icmph;
3639 
3640 	/*
3641 	 * We are called from ip_rput where we could
3642 	 * not have attached an IPSEC_IN.
3643 	 */
3644 	ASSERT(mp->b_datap->db_type == M_DATA);
3645 
3646 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3647 		return;
3648 	}
3649 
3650 	bzero(&icmph, sizeof (icmph_t));
3651 	icmph.icmph_type = ICMP_REDIRECT;
3652 	icmph.icmph_code = 1;
3653 	icmph.icmph_rd_gateway = gateway;
3654 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3655 	/* Redirects sent by router, and router is global zone */
3656 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3657 }
3658 
3659 /*
3660  * Generate an ICMP time exceeded message.
3661  */
3662 void
3663 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3664     ip_stack_t *ipst)
3665 {
3666 	icmph_t	icmph;
3667 	boolean_t mctl_present;
3668 	mblk_t *first_mp;
3669 
3670 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3671 
3672 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3673 		if (mctl_present)
3674 			freeb(first_mp);
3675 		return;
3676 	}
3677 
3678 	bzero(&icmph, sizeof (icmph_t));
3679 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3680 	icmph.icmph_code = code;
3681 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3682 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3683 	    ipst);
3684 }
3685 
3686 /*
3687  * Generate an ICMP unreachable message.
3688  */
3689 void
3690 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3691     ip_stack_t *ipst)
3692 {
3693 	icmph_t	icmph;
3694 	mblk_t *first_mp;
3695 	boolean_t mctl_present;
3696 
3697 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3698 
3699 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3700 		if (mctl_present)
3701 			freeb(first_mp);
3702 		return;
3703 	}
3704 
3705 	bzero(&icmph, sizeof (icmph_t));
3706 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3707 	icmph.icmph_code = code;
3708 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3709 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3710 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3711 	    zoneid, ipst);
3712 }
3713 
3714 /*
3715  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3716  * duplicate.  As long as someone else holds the address, the interface will
3717  * stay down.  When that conflict goes away, the interface is brought back up.
3718  * This is done so that accidental shutdowns of addresses aren't made
3719  * permanent.  Your server will recover from a failure.
3720  *
3721  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3722  * user space process (dhcpagent).
3723  *
3724  * Recovery completes if ARP reports that the address is now ours (via
3725  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3726  *
3727  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3728  */
3729 static void
3730 ipif_dup_recovery(void *arg)
3731 {
3732 	ipif_t *ipif = arg;
3733 	ill_t *ill = ipif->ipif_ill;
3734 	mblk_t *arp_add_mp;
3735 	mblk_t *arp_del_mp;
3736 	area_t *area;
3737 	ip_stack_t *ipst = ill->ill_ipst;
3738 
3739 	ipif->ipif_recovery_id = 0;
3740 
3741 	/*
3742 	 * No lock needed for moving or condemned check, as this is just an
3743 	 * optimization.
3744 	 */
3745 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3746 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3747 	    (ipif->ipif_state_flags & (IPIF_MOVING | IPIF_CONDEMNED))) {
3748 		/* No reason to try to bring this address back. */
3749 		return;
3750 	}
3751 
3752 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3753 		goto alloc_fail;
3754 
3755 	if (ipif->ipif_arp_del_mp == NULL) {
3756 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3757 			goto alloc_fail;
3758 		ipif->ipif_arp_del_mp = arp_del_mp;
3759 	}
3760 
3761 	/* Setting the 'unverified' flag restarts DAD */
3762 	area = (area_t *)arp_add_mp->b_rptr;
3763 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3764 	    ACE_F_UNVERIFIED;
3765 	putnext(ill->ill_rq, arp_add_mp);
3766 	return;
3767 
3768 alloc_fail:
3769 	/*
3770 	 * On allocation failure, just restart the timer.  Note that the ipif
3771 	 * is down here, so no other thread could be trying to start a recovery
3772 	 * timer.  The ill_lock protects the condemned flag and the recovery
3773 	 * timer ID.
3774 	 */
3775 	freemsg(arp_add_mp);
3776 	mutex_enter(&ill->ill_lock);
3777 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3778 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3779 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3780 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3781 	}
3782 	mutex_exit(&ill->ill_lock);
3783 }
3784 
3785 /*
3786  * This is for exclusive changes due to ARP.  Either tear down an interface due
3787  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3788  */
3789 /* ARGSUSED */
3790 static void
3791 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3792 {
3793 	ill_t	*ill = rq->q_ptr;
3794 	arh_t *arh;
3795 	ipaddr_t src;
3796 	ipif_t	*ipif;
3797 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3798 	char hbuf[MAC_STR_LEN];
3799 	char sbuf[INET_ADDRSTRLEN];
3800 	const char *failtype;
3801 	boolean_t bring_up;
3802 	ip_stack_t *ipst = ill->ill_ipst;
3803 
3804 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3805 	case AR_CN_READY:
3806 		failtype = NULL;
3807 		bring_up = B_TRUE;
3808 		break;
3809 	case AR_CN_FAILED:
3810 		failtype = "in use";
3811 		bring_up = B_FALSE;
3812 		break;
3813 	default:
3814 		failtype = "claimed";
3815 		bring_up = B_FALSE;
3816 		break;
3817 	}
3818 
3819 	arh = (arh_t *)mp->b_cont->b_rptr;
3820 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3821 
3822 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3823 	    sizeof (hbuf));
3824 	(void) ip_dot_addr(src, sbuf);
3825 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3826 
3827 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3828 		    ipif->ipif_lcl_addr != src) {
3829 			continue;
3830 		}
3831 
3832 		/*
3833 		 * If we failed on a recovery probe, then restart the timer to
3834 		 * try again later.
3835 		 */
3836 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3837 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3838 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3839 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3840 		    ipst->ips_ip_dup_recovery > 0 &&
3841 		    ipif->ipif_recovery_id == 0) {
3842 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3843 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3844 			continue;
3845 		}
3846 
3847 		/*
3848 		 * If what we're trying to do has already been done, then do
3849 		 * nothing.
3850 		 */
3851 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3852 			continue;
3853 
3854 		ipif_get_name(ipif, ibuf, sizeof (ibuf));
3855 
3856 		if (failtype == NULL) {
3857 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3858 			    ibuf);
3859 		} else {
3860 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3861 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3862 		}
3863 
3864 		if (bring_up) {
3865 			ASSERT(ill->ill_dl_up);
3866 			/*
3867 			 * Free up the ARP delete message so we can allocate
3868 			 * a fresh one through the normal path.
3869 			 */
3870 			freemsg(ipif->ipif_arp_del_mp);
3871 			ipif->ipif_arp_del_mp = NULL;
3872 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3873 			    EINPROGRESS) {
3874 				ipif->ipif_addr_ready = 1;
3875 				(void) ipif_up_done(ipif);
3876 			}
3877 			continue;
3878 		}
3879 
3880 		mutex_enter(&ill->ill_lock);
3881 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3882 		ipif->ipif_flags |= IPIF_DUPLICATE;
3883 		ill->ill_ipif_dup_count++;
3884 		mutex_exit(&ill->ill_lock);
3885 		/*
3886 		 * Already exclusive on the ill; no need to handle deferred
3887 		 * processing here.
3888 		 */
3889 		(void) ipif_down(ipif, NULL, NULL);
3890 		ipif_down_tail(ipif);
3891 		mutex_enter(&ill->ill_lock);
3892 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3893 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3894 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3895 		    ipst->ips_ip_dup_recovery > 0) {
3896 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3897 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3898 		}
3899 		mutex_exit(&ill->ill_lock);
3900 	}
3901 	freemsg(mp);
3902 }
3903 
3904 /* ARGSUSED */
3905 static void
3906 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3907 {
3908 	ill_t	*ill = rq->q_ptr;
3909 	arh_t *arh;
3910 	ipaddr_t src;
3911 	ipif_t	*ipif;
3912 
3913 	arh = (arh_t *)mp->b_cont->b_rptr;
3914 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3915 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3916 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3917 			(void) ipif_resolver_up(ipif, Res_act_defend);
3918 	}
3919 	freemsg(mp);
3920 }
3921 
3922 /*
3923  * News from ARP.  ARP sends notification of interesting events down
3924  * to its clients using M_CTL messages with the interesting ARP packet
3925  * attached via b_cont.
3926  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3927  * queue as opposed to ARP sending the message to all the clients, i.e. all
3928  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3929  * table if a cache IRE is found to delete all the entries for the address in
3930  * the packet.
3931  */
3932 static void
3933 ip_arp_news(queue_t *q, mblk_t *mp)
3934 {
3935 	arcn_t		*arcn;
3936 	arh_t		*arh;
3937 	ire_t		*ire = NULL;
3938 	char		hbuf[MAC_STR_LEN];
3939 	char		sbuf[INET_ADDRSTRLEN];
3940 	ipaddr_t	src;
3941 	in6_addr_t	v6src;
3942 	boolean_t	isv6 = B_FALSE;
3943 	ipif_t		*ipif;
3944 	ill_t		*ill;
3945 	ip_stack_t	*ipst;
3946 
3947 	if (CONN_Q(q)) {
3948 		conn_t *connp = Q_TO_CONN(q);
3949 
3950 		ipst = connp->conn_netstack->netstack_ip;
3951 	} else {
3952 		ill_t *ill = (ill_t *)q->q_ptr;
3953 
3954 		ipst = ill->ill_ipst;
3955 	}
3956 
3957 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3958 		if (q->q_next) {
3959 			putnext(q, mp);
3960 		} else
3961 			freemsg(mp);
3962 		return;
3963 	}
3964 	arh = (arh_t *)mp->b_cont->b_rptr;
3965 	/* Is it one we are interested in? */
3966 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3967 		isv6 = B_TRUE;
3968 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3969 		    IPV6_ADDR_LEN);
3970 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3971 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3972 		    IP_ADDR_LEN);
3973 	} else {
3974 		freemsg(mp);
3975 		return;
3976 	}
3977 
3978 	ill = q->q_ptr;
3979 
3980 	arcn = (arcn_t *)mp->b_rptr;
3981 	switch (arcn->arcn_code) {
3982 	case AR_CN_BOGON:
3983 		/*
3984 		 * Someone is sending ARP packets with a source protocol
3985 		 * address that we have published and for which we believe our
3986 		 * entry is authoritative and (when ill_arp_extend is set)
3987 		 * verified to be unique on the network.
3988 		 *
3989 		 * The ARP module internally handles the cases where the sender
3990 		 * is just probing (for DAD) and where the hardware address of
3991 		 * a non-authoritative entry has changed.  Thus, these are the
3992 		 * real conflicts, and we have to do resolution.
3993 		 *
3994 		 * We back away quickly from the address if it's from DHCP or
3995 		 * otherwise temporary and hasn't been used recently (or at
3996 		 * all).  We'd like to include "deprecated" addresses here as
3997 		 * well (as there's no real reason to defend something we're
3998 		 * discarding), but IPMP "reuses" this flag to mean something
3999 		 * other than the standard meaning.
4000 		 *
4001 		 * If the ARP module above is not extended (meaning that it
4002 		 * doesn't know how to defend the address), then we just log
4003 		 * the problem as we always did and continue on.  It's not
4004 		 * right, but there's little else we can do, and those old ATM
4005 		 * users are going away anyway.
4006 		 */
4007 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
4008 		    hbuf, sizeof (hbuf));
4009 		(void) ip_dot_addr(src, sbuf);
4010 		if (isv6) {
4011 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
4012 			    ipst);
4013 		} else {
4014 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
4015 		}
4016 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
4017 			uint32_t now;
4018 			uint32_t maxage;
4019 			clock_t lused;
4020 			uint_t maxdefense;
4021 			uint_t defs;
4022 
4023 			/*
4024 			 * First, figure out if this address hasn't been used
4025 			 * in a while.  If it hasn't, then it's a better
4026 			 * candidate for abandoning.
4027 			 */
4028 			ipif = ire->ire_ipif;
4029 			ASSERT(ipif != NULL);
4030 			now = gethrestime_sec();
4031 			maxage = now - ire->ire_create_time;
4032 			if (maxage > ipst->ips_ip_max_temp_idle)
4033 				maxage = ipst->ips_ip_max_temp_idle;
4034 			lused = drv_hztousec(ddi_get_lbolt() -
4035 			    ire->ire_last_used_time) / MICROSEC + 1;
4036 			if (lused >= maxage && (ipif->ipif_flags &
4037 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4038 				maxdefense = ipst->ips_ip_max_temp_defend;
4039 			else
4040 				maxdefense = ipst->ips_ip_max_defend;
4041 
4042 			/*
4043 			 * Now figure out how many times we've defended
4044 			 * ourselves.  Ignore defenses that happened long in
4045 			 * the past.
4046 			 */
4047 			mutex_enter(&ire->ire_lock);
4048 			if ((defs = ire->ire_defense_count) > 0 &&
4049 			    now - ire->ire_defense_time >
4050 			    ipst->ips_ip_defend_interval) {
4051 				ire->ire_defense_count = defs = 0;
4052 			}
4053 			ire->ire_defense_count++;
4054 			ire->ire_defense_time = now;
4055 			mutex_exit(&ire->ire_lock);
4056 			ill_refhold(ill);
4057 			ire_refrele(ire);
4058 
4059 			/*
4060 			 * If we've defended ourselves too many times already,
4061 			 * then give up and tear down the interface(s) using
4062 			 * this address.  Otherwise, defend by sending out a
4063 			 * gratuitous ARP.
4064 			 */
4065 			if (defs >= maxdefense && ill->ill_arp_extend) {
4066 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4067 				    B_FALSE);
4068 			} else {
4069 				cmn_err(CE_WARN,
4070 				    "node %s is using our IP address %s on %s",
4071 				    hbuf, sbuf, ill->ill_name);
4072 				/*
4073 				 * If this is an old (ATM) ARP module, then
4074 				 * don't try to defend the address.  Remain
4075 				 * compatible with the old behavior.  Defend
4076 				 * only with new ARP.
4077 				 */
4078 				if (ill->ill_arp_extend) {
4079 					qwriter_ip(ill, q, mp, ip_arp_defend,
4080 					    NEW_OP, B_FALSE);
4081 				} else {
4082 					ill_refrele(ill);
4083 				}
4084 			}
4085 			return;
4086 		}
4087 		cmn_err(CE_WARN,
4088 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4089 		    hbuf, sbuf, ill->ill_name);
4090 		if (ire != NULL)
4091 			ire_refrele(ire);
4092 		break;
4093 	case AR_CN_ANNOUNCE:
4094 		if (isv6) {
4095 			/*
4096 			 * For XRESOLV interfaces.
4097 			 * Delete the IRE cache entry and NCE for this
4098 			 * v6 address
4099 			 */
4100 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4101 			/*
4102 			 * If v6src is a non-zero, it's a router address
4103 			 * as below. Do the same sort of thing to clean
4104 			 * out off-net IRE_CACHE entries that go through
4105 			 * the router.
4106 			 */
4107 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4108 				ire_walk_v6(ire_delete_cache_gw_v6,
4109 				    (char *)&v6src, ALL_ZONES, ipst);
4110 			}
4111 		} else {
4112 			nce_hw_map_t hwm;
4113 
4114 			/*
4115 			 * ARP gives us a copy of any packet where it thinks
4116 			 * the address has changed, so that we can update our
4117 			 * caches.  We're responsible for caching known answers
4118 			 * in the current design.  We check whether the
4119 			 * hardware address really has changed in all of our
4120 			 * entries that have cached this mapping, and if so, we
4121 			 * blow them away.  This way we will immediately pick
4122 			 * up the rare case of a host changing hardware
4123 			 * address.
4124 			 */
4125 			if (src == 0)
4126 				break;
4127 			hwm.hwm_addr = src;
4128 			hwm.hwm_hwlen = arh->arh_hlen;
4129 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4130 			NDP_HW_CHANGE_INCR(ipst->ips_ndp4);
4131 			ndp_walk_common(ipst->ips_ndp4, NULL,
4132 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4133 			NDP_HW_CHANGE_DECR(ipst->ips_ndp4);
4134 		}
4135 		break;
4136 	case AR_CN_READY:
4137 		/* No external v6 resolver has a contract to use this */
4138 		if (isv6)
4139 			break;
4140 		/* If the link is down, we'll retry this later */
4141 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4142 			break;
4143 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4144 		    NULL, NULL, ipst);
4145 		if (ipif != NULL) {
4146 			/*
4147 			 * If this is a duplicate recovery, then we now need to
4148 			 * go exclusive to bring this thing back up.
4149 			 */
4150 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4151 			    IPIF_DUPLICATE) {
4152 				ipif_refrele(ipif);
4153 				ill_refhold(ill);
4154 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4155 				    B_FALSE);
4156 				return;
4157 			}
4158 			/*
4159 			 * If this is the first notice that this address is
4160 			 * ready, then let the user know now.
4161 			 */
4162 			if ((ipif->ipif_flags & IPIF_UP) &&
4163 			    !ipif->ipif_addr_ready) {
4164 				ipif_mask_reply(ipif);
4165 				ipif_up_notify(ipif);
4166 			}
4167 			ipif->ipif_addr_ready = 1;
4168 			ipif_refrele(ipif);
4169 		}
4170 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp), ipst);
4171 		if (ire != NULL) {
4172 			ire->ire_defense_count = 0;
4173 			ire_refrele(ire);
4174 		}
4175 		break;
4176 	case AR_CN_FAILED:
4177 		/* No external v6 resolver has a contract to use this */
4178 		if (isv6)
4179 			break;
4180 		ill_refhold(ill);
4181 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, B_FALSE);
4182 		return;
4183 	}
4184 	freemsg(mp);
4185 }
4186 
4187 /*
4188  * Create a mblk suitable for carrying the interface index and/or source link
4189  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4190  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4191  * application.
4192  */
4193 mblk_t *
4194 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4195     ip_stack_t *ipst)
4196 {
4197 	mblk_t		*mp;
4198 	ip_pktinfo_t	*pinfo;
4199 	ipha_t *ipha;
4200 	struct ether_header *pether;
4201 
4202 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4203 	if (mp == NULL) {
4204 		ip1dbg(("ip_add_info: allocation failure.\n"));
4205 		return (data_mp);
4206 	}
4207 
4208 	ipha	= (ipha_t *)data_mp->b_rptr;
4209 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4210 	bzero(pinfo, sizeof (ip_pktinfo_t));
4211 	pinfo->ip_pkt_flags = (uchar_t)flags;
4212 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4213 
4214 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4215 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4216 	if (flags & IPF_RECVADDR) {
4217 		ipif_t	*ipif;
4218 		ire_t	*ire;
4219 
4220 		/*
4221 		 * Only valid for V4
4222 		 */
4223 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4224 		    (IPV4_VERSION << 4));
4225 
4226 		ipif = ipif_get_next_ipif(NULL, ill);
4227 		if (ipif != NULL) {
4228 			/*
4229 			 * Since a decision has already been made to deliver the
4230 			 * packet, there is no need to test for SECATTR and
4231 			 * ZONEONLY.
4232 			 * When a multicast packet is transmitted
4233 			 * a cache entry is created for the multicast address.
4234 			 * When delivering a copy of the packet or when new
4235 			 * packets are received we do not want to match on the
4236 			 * cached entry so explicitly match on
4237 			 * IRE_LOCAL and IRE_LOOPBACK
4238 			 */
4239 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4240 			    IRE_LOCAL | IRE_LOOPBACK,
4241 			    ipif, zoneid, NULL,
4242 			    MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP, ipst);
4243 			if (ire == NULL) {
4244 				/*
4245 				 * packet must have come on a different
4246 				 * interface.
4247 				 * Since a decision has already been made to
4248 				 * deliver the packet, there is no need to test
4249 				 * for SECATTR and ZONEONLY.
4250 				 * Only match on local and broadcast ire's.
4251 				 * See detailed comment above.
4252 				 */
4253 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4254 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4255 				    NULL, MATCH_IRE_TYPE, ipst);
4256 			}
4257 
4258 			if (ire == NULL) {
4259 				/*
4260 				 * This is either a multicast packet or
4261 				 * the address has been removed since
4262 				 * the packet was received.
4263 				 * Return INADDR_ANY so that normal source
4264 				 * selection occurs for the response.
4265 				 */
4266 
4267 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4268 			} else {
4269 				pinfo->ip_pkt_match_addr.s_addr =
4270 				    ire->ire_src_addr;
4271 				ire_refrele(ire);
4272 			}
4273 			ipif_refrele(ipif);
4274 		} else {
4275 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4276 		}
4277 	}
4278 
4279 	pether = (struct ether_header *)((char *)ipha
4280 	    - sizeof (struct ether_header));
4281 	/*
4282 	 * Make sure the interface is an ethernet type, since this option
4283 	 * is currently supported only on this type of interface. Also make
4284 	 * sure we are pointing correctly above db_base.
4285 	 */
4286 
4287 	if ((flags & IPF_RECVSLLA) &&
4288 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4289 	    (ill->ill_type == IFT_ETHER) &&
4290 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4291 
4292 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4293 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4294 		    (uchar_t *)pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4295 	} else {
4296 		/*
4297 		 * Clear the bit. Indicate to upper layer that IP is not
4298 		 * sending this ancillary info.
4299 		 */
4300 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4301 	}
4302 
4303 	mp->b_datap->db_type = M_CTL;
4304 	mp->b_wptr += sizeof (ip_pktinfo_t);
4305 	mp->b_cont = data_mp;
4306 
4307 	return (mp);
4308 }
4309 
4310 /*
4311  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4312  * part of the bind request.
4313  */
4314 
4315 boolean_t
4316 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4317 {
4318 	ipsec_in_t *ii;
4319 
4320 	ASSERT(policy_mp != NULL);
4321 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4322 
4323 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4324 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4325 
4326 	connp->conn_policy = ii->ipsec_in_policy;
4327 	ii->ipsec_in_policy = NULL;
4328 
4329 	if (ii->ipsec_in_action != NULL) {
4330 		if (connp->conn_latch == NULL) {
4331 			connp->conn_latch = iplatch_create();
4332 			if (connp->conn_latch == NULL)
4333 				return (B_FALSE);
4334 		}
4335 		ipsec_latch_inbound(connp->conn_latch, ii);
4336 	}
4337 	return (B_TRUE);
4338 }
4339 
4340 /*
4341  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4342  * and to arrange for power-fanout assist.  The ULP is identified by
4343  * adding a single byte at the end of the original bind message.
4344  * A ULP other than UDP or TCP that wishes to be recognized passes
4345  * down a bind with a zero length address.
4346  *
4347  * The binding works as follows:
4348  * - A zero byte address means just bind to the protocol.
4349  * - A four byte address is treated as a request to validate
4350  *   that the address is a valid local address, appropriate for
4351  *   an application to bind to. This does not affect any fanout
4352  *   information in IP.
4353  * - A sizeof sin_t byte address is used to bind to only the local address
4354  *   and port.
4355  * - A sizeof ipa_conn_t byte address contains complete fanout information
4356  *   consisting of local and remote addresses and ports.  In
4357  *   this case, the addresses are both validated as appropriate
4358  *   for this operation, and, if so, the information is retained
4359  *   for use in the inbound fanout.
4360  *
4361  * The ULP (except in the zero-length bind) can append an
4362  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4363  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4364  * a copy of the source or destination IRE (source for local bind;
4365  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4366  * policy information contained should be copied on to the conn.
4367  *
4368  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4369  */
4370 mblk_t *
4371 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4372 {
4373 	ssize_t		len;
4374 	struct T_bind_req	*tbr;
4375 	sin_t		*sin;
4376 	ipa_conn_t	*ac;
4377 	uchar_t		*ucp;
4378 	mblk_t		*mp1;
4379 	boolean_t	ire_requested;
4380 	boolean_t	ipsec_policy_set = B_FALSE;
4381 	int		error = 0;
4382 	int		protocol;
4383 	ipa_conn_x_t	*acx;
4384 
4385 	ASSERT(!connp->conn_af_isv6);
4386 	connp->conn_pkt_isv6 = B_FALSE;
4387 
4388 	len = MBLKL(mp);
4389 	if (len < (sizeof (*tbr) + 1)) {
4390 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4391 		    "ip_bind: bogus msg, len %ld", len);
4392 		/* XXX: Need to return something better */
4393 		goto bad_addr;
4394 	}
4395 	/* Back up and extract the protocol identifier. */
4396 	mp->b_wptr--;
4397 	protocol = *mp->b_wptr & 0xFF;
4398 	tbr = (struct T_bind_req *)mp->b_rptr;
4399 	/* Reset the message type in preparation for shipping it back. */
4400 	DB_TYPE(mp) = M_PCPROTO;
4401 
4402 	connp->conn_ulp = (uint8_t)protocol;
4403 
4404 	/*
4405 	 * Check for a zero length address.  This is from a protocol that
4406 	 * wants to register to receive all packets of its type.
4407 	 */
4408 	if (tbr->ADDR_length == 0) {
4409 		/*
4410 		 * These protocols are now intercepted in ip_bind_v6().
4411 		 * Reject protocol-level binds here for now.
4412 		 *
4413 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4414 		 * so that the protocol type cannot be SCTP.
4415 		 */
4416 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4417 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4418 			goto bad_addr;
4419 		}
4420 
4421 		/*
4422 		 *
4423 		 * The udp module never sends down a zero-length address,
4424 		 * and allowing this on a labeled system will break MLP
4425 		 * functionality.
4426 		 */
4427 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4428 			goto bad_addr;
4429 
4430 		if (connp->conn_mac_exempt)
4431 			goto bad_addr;
4432 
4433 		/* No hash here really.  The table is big enough. */
4434 		connp->conn_srcv6 = ipv6_all_zeros;
4435 
4436 		ipcl_proto_insert(connp, protocol);
4437 
4438 		tbr->PRIM_type = T_BIND_ACK;
4439 		return (mp);
4440 	}
4441 
4442 	/* Extract the address pointer from the message. */
4443 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4444 	    tbr->ADDR_length);
4445 	if (ucp == NULL) {
4446 		ip1dbg(("ip_bind: no address\n"));
4447 		goto bad_addr;
4448 	}
4449 	if (!OK_32PTR(ucp)) {
4450 		ip1dbg(("ip_bind: unaligned address\n"));
4451 		goto bad_addr;
4452 	}
4453 	/*
4454 	 * Check for trailing mps.
4455 	 */
4456 
4457 	mp1 = mp->b_cont;
4458 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4459 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4460 
4461 	switch (tbr->ADDR_length) {
4462 	default:
4463 		ip1dbg(("ip_bind: bad address length %d\n",
4464 		    (int)tbr->ADDR_length));
4465 		goto bad_addr;
4466 
4467 	case IP_ADDR_LEN:
4468 		/* Verification of local address only */
4469 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4470 		    ire_requested, ipsec_policy_set, B_FALSE);
4471 		break;
4472 
4473 	case sizeof (sin_t):
4474 		sin = (sin_t *)ucp;
4475 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4476 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4477 		break;
4478 
4479 	case sizeof (ipa_conn_t):
4480 		ac = (ipa_conn_t *)ucp;
4481 		/* For raw socket, the local port is not set. */
4482 		if (ac->ac_lport == 0)
4483 			ac->ac_lport = connp->conn_lport;
4484 		/* Always verify destination reachability. */
4485 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4486 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4487 		    ipsec_policy_set, B_TRUE, B_TRUE);
4488 		break;
4489 
4490 	case sizeof (ipa_conn_x_t):
4491 		acx = (ipa_conn_x_t *)ucp;
4492 		/*
4493 		 * Whether or not to verify destination reachability depends
4494 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4495 		 */
4496 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4497 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4498 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4499 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4500 		break;
4501 	}
4502 	if (error == EINPROGRESS)
4503 		return (NULL);
4504 	else if (error != 0)
4505 		goto bad_addr;
4506 	/*
4507 	 * Pass the IPsec headers size in ire_ipsec_overhead.
4508 	 * We can't do this in ip_bind_insert_ire because the policy
4509 	 * may not have been inherited at that point in time and hence
4510 	 * conn_out_enforce_policy may not be set.
4511 	 */
4512 	mp1 = mp->b_cont;
4513 	if (ire_requested && connp->conn_out_enforce_policy &&
4514 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4515 		ire_t *ire = (ire_t *)mp1->b_rptr;
4516 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4517 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4518 	}
4519 
4520 	/* Send it home. */
4521 	mp->b_datap->db_type = M_PCPROTO;
4522 	tbr->PRIM_type = T_BIND_ACK;
4523 	return (mp);
4524 
4525 bad_addr:
4526 	/*
4527 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4528 	 * a unix errno.
4529 	 */
4530 	if (error > 0)
4531 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4532 	else
4533 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4534 	return (mp);
4535 }
4536 
4537 /*
4538  * Here address is verified to be a valid local address.
4539  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4540  * address is also considered a valid local address.
4541  * In the case of a broadcast/multicast address, however, the
4542  * upper protocol is expected to reset the src address
4543  * to 0 if it sees a IRE_BROADCAST type returned so that
4544  * no packets are emitted with broadcast/multicast address as
4545  * source address (that violates hosts requirements RFC1122)
4546  * The addresses valid for bind are:
4547  *	(1) - INADDR_ANY (0)
4548  *	(2) - IP address of an UP interface
4549  *	(3) - IP address of a DOWN interface
4550  *	(4) - valid local IP broadcast addresses. In this case
4551  *	the conn will only receive packets destined to
4552  *	the specified broadcast address.
4553  *	(5) - a multicast address. In this case
4554  *	the conn will only receive packets destined to
4555  *	the specified multicast address. Note: the
4556  *	application still has to issue an
4557  *	IP_ADD_MEMBERSHIP socket option.
4558  *
4559  * On error, return -1 for TBADADDR otherwise pass the
4560  * errno with TSYSERR reply.
4561  *
4562  * In all the above cases, the bound address must be valid in the current zone.
4563  * When the address is loopback, multicast or broadcast, there might be many
4564  * matching IREs so bind has to look up based on the zone.
4565  *
4566  * Note: lport is in network byte order.
4567  */
4568 int
4569 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4570     boolean_t ire_requested, boolean_t ipsec_policy_set,
4571     boolean_t fanout_insert)
4572 {
4573 	int		error = 0;
4574 	ire_t		*src_ire;
4575 	mblk_t		*policy_mp;
4576 	ipif_t		*ipif;
4577 	zoneid_t	zoneid;
4578 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4579 
4580 	if (ipsec_policy_set) {
4581 		policy_mp = mp->b_cont;
4582 	}
4583 
4584 	/*
4585 	 * If it was previously connected, conn_fully_bound would have
4586 	 * been set.
4587 	 */
4588 	connp->conn_fully_bound = B_FALSE;
4589 
4590 	src_ire = NULL;
4591 	ipif = NULL;
4592 
4593 	zoneid = IPCL_ZONEID(connp);
4594 
4595 	if (src_addr) {
4596 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4597 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4598 		/*
4599 		 * If an address other than 0.0.0.0 is requested,
4600 		 * we verify that it is a valid address for bind
4601 		 * Note: Following code is in if-else-if form for
4602 		 * readability compared to a condition check.
4603 		 */
4604 		/* LINTED - statement has no consequent */
4605 		if (IRE_IS_LOCAL(src_ire)) {
4606 			/*
4607 			 * (2) Bind to address of local UP interface
4608 			 */
4609 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4610 			/*
4611 			 * (4) Bind to broadcast address
4612 			 * Note: permitted only from transports that
4613 			 * request IRE
4614 			 */
4615 			if (!ire_requested)
4616 				error = EADDRNOTAVAIL;
4617 		} else {
4618 			/*
4619 			 * (3) Bind to address of local DOWN interface
4620 			 * (ipif_lookup_addr() looks up all interfaces
4621 			 * but we do not get here for UP interfaces
4622 			 * - case (2) above)
4623 			 * We put the protocol byte back into the mblk
4624 			 * since we may come back via ip_wput_nondata()
4625 			 * later with this mblk if ipif_lookup_addr chooses
4626 			 * to defer processing.
4627 			 */
4628 			*mp->b_wptr++ = (char)connp->conn_ulp;
4629 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4630 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4631 			    &error, ipst)) != NULL) {
4632 				ipif_refrele(ipif);
4633 			} else if (error == EINPROGRESS) {
4634 				if (src_ire != NULL)
4635 					ire_refrele(src_ire);
4636 				return (EINPROGRESS);
4637 			} else if (CLASSD(src_addr)) {
4638 				error = 0;
4639 				if (src_ire != NULL)
4640 					ire_refrele(src_ire);
4641 				/*
4642 				 * (5) bind to multicast address.
4643 				 * Fake out the IRE returned to upper
4644 				 * layer to be a broadcast IRE.
4645 				 */
4646 				src_ire = ire_ctable_lookup(
4647 				    INADDR_BROADCAST, INADDR_ANY,
4648 				    IRE_BROADCAST, NULL, zoneid, NULL,
4649 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4650 				    ipst);
4651 				if (src_ire == NULL || !ire_requested)
4652 					error = EADDRNOTAVAIL;
4653 			} else {
4654 				/*
4655 				 * Not a valid address for bind
4656 				 */
4657 				error = EADDRNOTAVAIL;
4658 			}
4659 			/*
4660 			 * Just to keep it consistent with the processing in
4661 			 * ip_bind_v4()
4662 			 */
4663 			mp->b_wptr--;
4664 		}
4665 		if (error) {
4666 			/* Red Alert!  Attempting to be a bogon! */
4667 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4668 			    ntohl(src_addr)));
4669 			goto bad_addr;
4670 		}
4671 	}
4672 
4673 	/*
4674 	 * Allow setting new policies. For example, disconnects come
4675 	 * down as ipa_t bind. As we would have set conn_policy_cached
4676 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4677 	 * can change after the disconnect.
4678 	 */
4679 	connp->conn_policy_cached = B_FALSE;
4680 
4681 	/*
4682 	 * If not fanout_insert this was just an address verification
4683 	 */
4684 	if (fanout_insert) {
4685 		/*
4686 		 * The addresses have been verified. Time to insert in
4687 		 * the correct fanout list.
4688 		 */
4689 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4690 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4691 		connp->conn_lport = lport;
4692 		connp->conn_fport = 0;
4693 		/*
4694 		 * Do we need to add a check to reject Multicast packets
4695 		 */
4696 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4697 	}
4698 
4699 	if (error == 0) {
4700 		if (ire_requested) {
4701 			if (!ip_bind_insert_ire(mp, src_ire, NULL, ipst)) {
4702 				error = -1;
4703 				/* Falls through to bad_addr */
4704 			}
4705 		} else if (ipsec_policy_set) {
4706 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4707 				error = -1;
4708 				/* Falls through to bad_addr */
4709 			}
4710 		}
4711 	}
4712 bad_addr:
4713 	if (error != 0) {
4714 		if (connp->conn_anon_port) {
4715 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4716 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4717 			    B_FALSE);
4718 		}
4719 		connp->conn_mlp_type = mlptSingle;
4720 	}
4721 	if (src_ire != NULL)
4722 		IRE_REFRELE(src_ire);
4723 	if (ipsec_policy_set) {
4724 		ASSERT(policy_mp == mp->b_cont);
4725 		ASSERT(policy_mp != NULL);
4726 		freeb(policy_mp);
4727 		/*
4728 		 * As of now assume that nothing else accompanies
4729 		 * IPSEC_POLICY_SET.
4730 		 */
4731 		mp->b_cont = NULL;
4732 	}
4733 	return (error);
4734 }
4735 
4736 /*
4737  * Verify that both the source and destination addresses
4738  * are valid.  If verify_dst is false, then the destination address may be
4739  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4740  * destination reachability, while tunnels do not.
4741  * Note that we allow connect to broadcast and multicast
4742  * addresses when ire_requested is set. Thus the ULP
4743  * has to check for IRE_BROADCAST and multicast.
4744  *
4745  * Returns zero if ok.
4746  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4747  * (for use with TSYSERR reply).
4748  *
4749  * Note: lport and fport are in network byte order.
4750  */
4751 int
4752 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4753     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4754     boolean_t ire_requested, boolean_t ipsec_policy_set,
4755     boolean_t fanout_insert, boolean_t verify_dst)
4756 {
4757 	ire_t		*src_ire;
4758 	ire_t		*dst_ire;
4759 	int		error = 0;
4760 	int 		protocol;
4761 	mblk_t		*policy_mp;
4762 	ire_t		*sire = NULL;
4763 	ire_t		*md_dst_ire = NULL;
4764 	ire_t		*lso_dst_ire = NULL;
4765 	ill_t		*ill = NULL;
4766 	zoneid_t	zoneid;
4767 	ipaddr_t	src_addr = *src_addrp;
4768 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4769 
4770 	src_ire = dst_ire = NULL;
4771 	protocol = *mp->b_wptr & 0xFF;
4772 
4773 	/*
4774 	 * If we never got a disconnect before, clear it now.
4775 	 */
4776 	connp->conn_fully_bound = B_FALSE;
4777 
4778 	if (ipsec_policy_set) {
4779 		policy_mp = mp->b_cont;
4780 	}
4781 
4782 	zoneid = IPCL_ZONEID(connp);
4783 
4784 	if (CLASSD(dst_addr)) {
4785 		/* Pick up an IRE_BROADCAST */
4786 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4787 		    NULL, zoneid, MBLK_GETLABEL(mp),
4788 		    (MATCH_IRE_RECURSIVE |
4789 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4790 		    MATCH_IRE_SECATTR), ipst);
4791 	} else {
4792 		/*
4793 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4794 		 * and onlink ipif is not found set ENETUNREACH error.
4795 		 */
4796 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4797 			ipif_t *ipif;
4798 
4799 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4800 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4801 			if (ipif == NULL) {
4802 				error = ENETUNREACH;
4803 				goto bad_addr;
4804 			}
4805 			ipif_refrele(ipif);
4806 		}
4807 
4808 		if (connp->conn_nexthop_set) {
4809 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4810 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4811 			    MATCH_IRE_SECATTR, ipst);
4812 		} else {
4813 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4814 			    &sire, zoneid, MBLK_GETLABEL(mp),
4815 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4816 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4817 			    MATCH_IRE_SECATTR), ipst);
4818 		}
4819 	}
4820 	/*
4821 	 * dst_ire can't be a broadcast when not ire_requested.
4822 	 * We also prevent ire's with src address INADDR_ANY to
4823 	 * be used, which are created temporarily for
4824 	 * sending out packets from endpoints that have
4825 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4826 	 * reachable.  If verify_dst is false, the destination needn't be
4827 	 * reachable.
4828 	 *
4829 	 * If we match on a reject or black hole, then we've got a
4830 	 * local failure.  May as well fail out the connect() attempt,
4831 	 * since it's never going to succeed.
4832 	 */
4833 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4834 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4835 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4836 		/*
4837 		 * If we're verifying destination reachability, we always want
4838 		 * to complain here.
4839 		 *
4840 		 * If we're not verifying destination reachability but the
4841 		 * destination has a route, we still want to fail on the
4842 		 * temporary address and broadcast address tests.
4843 		 */
4844 		if (verify_dst || (dst_ire != NULL)) {
4845 			if (ip_debug > 2) {
4846 				pr_addr_dbg("ip_bind_connected: bad connected "
4847 				    "dst %s\n", AF_INET, &dst_addr);
4848 			}
4849 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4850 				error = ENETUNREACH;
4851 			else
4852 				error = EHOSTUNREACH;
4853 			goto bad_addr;
4854 		}
4855 	}
4856 
4857 	/*
4858 	 * We now know that routing will allow us to reach the destination.
4859 	 * Check whether Trusted Solaris policy allows communication with this
4860 	 * host, and pretend that the destination is unreachable if not.
4861 	 *
4862 	 * This is never a problem for TCP, since that transport is known to
4863 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4864 	 * handling.  If the remote is unreachable, it will be detected at that
4865 	 * point, so there's no reason to check it here.
4866 	 *
4867 	 * Note that for sendto (and other datagram-oriented friends), this
4868 	 * check is done as part of the data path label computation instead.
4869 	 * The check here is just to make non-TCP connect() report the right
4870 	 * error.
4871 	 */
4872 	if (dst_ire != NULL && is_system_labeled() &&
4873 	    !IPCL_IS_TCP(connp) &&
4874 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4875 	    connp->conn_mac_exempt, ipst) != 0) {
4876 		error = EHOSTUNREACH;
4877 		if (ip_debug > 2) {
4878 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4879 			    AF_INET, &dst_addr);
4880 		}
4881 		goto bad_addr;
4882 	}
4883 
4884 	/*
4885 	 * If the app does a connect(), it means that it will most likely
4886 	 * send more than 1 packet to the destination.  It makes sense
4887 	 * to clear the temporary flag.
4888 	 */
4889 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4890 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4891 		irb_t *irb = dst_ire->ire_bucket;
4892 
4893 		rw_enter(&irb->irb_lock, RW_WRITER);
4894 		/*
4895 		 * We need to recheck for IRE_MARK_TEMPORARY after acquiring
4896 		 * the lock to guarantee irb_tmp_ire_cnt.
4897 		 */
4898 		if (dst_ire->ire_marks & IRE_MARK_TEMPORARY) {
4899 			dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4900 			irb->irb_tmp_ire_cnt--;
4901 		}
4902 		rw_exit(&irb->irb_lock);
4903 	}
4904 
4905 	/*
4906 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4907 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4908 	 * eligibility tests for passive connects are handled separately
4909 	 * through tcp_adapt_ire().  We do this before the source address
4910 	 * selection, because dst_ire may change after a call to
4911 	 * ipif_select_source().  This is a best-effort check, as the
4912 	 * packet for this connection may not actually go through
4913 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4914 	 * calling ip_newroute().  This is why we further check on the
4915 	 * IRE during LSO/Multidata packet transmission in
4916 	 * tcp_lsosend()/tcp_multisend().
4917 	 */
4918 	if (!ipsec_policy_set && dst_ire != NULL &&
4919 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4920 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4921 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4922 			lso_dst_ire = dst_ire;
4923 			IRE_REFHOLD(lso_dst_ire);
4924 		} else if (ipst->ips_ip_multidata_outbound &&
4925 		    ILL_MDT_CAPABLE(ill)) {
4926 			md_dst_ire = dst_ire;
4927 			IRE_REFHOLD(md_dst_ire);
4928 		}
4929 	}
4930 
4931 	if (dst_ire != NULL &&
4932 	    dst_ire->ire_type == IRE_LOCAL &&
4933 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4934 		/*
4935 		 * If the IRE belongs to a different zone, look for a matching
4936 		 * route in the forwarding table and use the source address from
4937 		 * that route.
4938 		 */
4939 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4940 		    zoneid, 0, NULL,
4941 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4942 		    MATCH_IRE_RJ_BHOLE, ipst);
4943 		if (src_ire == NULL) {
4944 			error = EHOSTUNREACH;
4945 			goto bad_addr;
4946 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4947 			if (!(src_ire->ire_type & IRE_HOST))
4948 				error = ENETUNREACH;
4949 			else
4950 				error = EHOSTUNREACH;
4951 			goto bad_addr;
4952 		}
4953 		if (src_addr == INADDR_ANY)
4954 			src_addr = src_ire->ire_src_addr;
4955 		ire_refrele(src_ire);
4956 		src_ire = NULL;
4957 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4958 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4959 			src_addr = sire->ire_src_addr;
4960 			ire_refrele(dst_ire);
4961 			dst_ire = sire;
4962 			sire = NULL;
4963 		} else {
4964 			/*
4965 			 * Pick a source address so that a proper inbound
4966 			 * load spreading would happen.
4967 			 */
4968 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4969 			ipif_t *src_ipif = NULL;
4970 			ire_t *ipif_ire;
4971 
4972 			/*
4973 			 * Supply a local source address such that inbound
4974 			 * load spreading happens.
4975 			 *
4976 			 * Determine the best source address on this ill for
4977 			 * the destination.
4978 			 *
4979 			 * 1) For broadcast, we should return a broadcast ire
4980 			 *    found above so that upper layers know that the
4981 			 *    destination address is a broadcast address.
4982 			 *
4983 			 * 2) If this is part of a group, select a better
4984 			 *    source address so that better inbound load
4985 			 *    balancing happens. Do the same if the ipif
4986 			 *    is DEPRECATED.
4987 			 *
4988 			 * 3) If the outgoing interface is part of a usesrc
4989 			 *    group, then try selecting a source address from
4990 			 *    the usesrc ILL.
4991 			 */
4992 			if ((dst_ire->ire_zoneid != zoneid &&
4993 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4994 			    (!(dst_ire->ire_flags & RTF_SETSRC)) &&
4995 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4996 			    ((dst_ill->ill_group != NULL) ||
4997 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4998 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4999 				/*
5000 				 * If the destination is reachable via a
5001 				 * given gateway, the selected source address
5002 				 * should be in the same subnet as the gateway.
5003 				 * Otherwise, the destination is not reachable.
5004 				 *
5005 				 * If there are no interfaces on the same subnet
5006 				 * as the destination, ipif_select_source gives
5007 				 * first non-deprecated interface which might be
5008 				 * on a different subnet than the gateway.
5009 				 * This is not desirable. Hence pass the dst_ire
5010 				 * source address to ipif_select_source.
5011 				 * It is sure that the destination is reachable
5012 				 * with the dst_ire source address subnet.
5013 				 * So passing dst_ire source address to
5014 				 * ipif_select_source will make sure that the
5015 				 * selected source will be on the same subnet
5016 				 * as dst_ire source address.
5017 				 */
5018 				ipaddr_t saddr =
5019 				    dst_ire->ire_ipif->ipif_src_addr;
5020 				src_ipif = ipif_select_source(dst_ill,
5021 				    saddr, zoneid);
5022 				if (src_ipif != NULL) {
5023 					if (IS_VNI(src_ipif->ipif_ill)) {
5024 						/*
5025 						 * For VNI there is no
5026 						 * interface route
5027 						 */
5028 						src_addr =
5029 						    src_ipif->ipif_src_addr;
5030 					} else {
5031 						ipif_ire =
5032 						    ipif_to_ire(src_ipif);
5033 						if (ipif_ire != NULL) {
5034 							IRE_REFRELE(dst_ire);
5035 							dst_ire = ipif_ire;
5036 						}
5037 						src_addr =
5038 						    dst_ire->ire_src_addr;
5039 					}
5040 					ipif_refrele(src_ipif);
5041 				} else {
5042 					src_addr = dst_ire->ire_src_addr;
5043 				}
5044 			} else {
5045 				src_addr = dst_ire->ire_src_addr;
5046 			}
5047 		}
5048 	}
5049 
5050 	/*
5051 	 * We do ire_route_lookup() here (and not
5052 	 * interface lookup as we assert that
5053 	 * src_addr should only come from an
5054 	 * UP interface for hard binding.
5055 	 */
5056 	ASSERT(src_ire == NULL);
5057 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5058 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5059 	/* src_ire must be a local|loopback */
5060 	if (!IRE_IS_LOCAL(src_ire)) {
5061 		if (ip_debug > 2) {
5062 			pr_addr_dbg("ip_bind_connected: bad connected "
5063 			    "src %s\n", AF_INET, &src_addr);
5064 		}
5065 		error = EADDRNOTAVAIL;
5066 		goto bad_addr;
5067 	}
5068 
5069 	/*
5070 	 * If the source address is a loopback address, the
5071 	 * destination had best be local or multicast.
5072 	 * The transports that can't handle multicast will reject
5073 	 * those addresses.
5074 	 */
5075 	if (src_ire->ire_type == IRE_LOOPBACK &&
5076 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5077 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5078 		error = -1;
5079 		goto bad_addr;
5080 	}
5081 
5082 	/*
5083 	 * Allow setting new policies. For example, disconnects come
5084 	 * down as ipa_t bind. As we would have set conn_policy_cached
5085 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5086 	 * can change after the disconnect.
5087 	 */
5088 	connp->conn_policy_cached = B_FALSE;
5089 
5090 	/*
5091 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5092 	 * can handle their passed-in conn's.
5093 	 */
5094 
5095 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5096 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5097 	connp->conn_lport = lport;
5098 	connp->conn_fport = fport;
5099 	*src_addrp = src_addr;
5100 
5101 	ASSERT(!(ipsec_policy_set && ire_requested));
5102 	if (ire_requested) {
5103 		iulp_t *ulp_info = NULL;
5104 
5105 		/*
5106 		 * Note that sire will not be NULL if this is an off-link
5107 		 * connection and there is not cache for that dest yet.
5108 		 *
5109 		 * XXX Because of an existing bug, if there are multiple
5110 		 * default routes, the IRE returned now may not be the actual
5111 		 * default route used (default routes are chosen in a
5112 		 * round robin fashion).  So if the metrics for different
5113 		 * default routes are different, we may return the wrong
5114 		 * metrics.  This will not be a problem if the existing
5115 		 * bug is fixed.
5116 		 */
5117 		if (sire != NULL) {
5118 			ulp_info = &(sire->ire_uinfo);
5119 		}
5120 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info, ipst)) {
5121 			error = -1;
5122 			goto bad_addr;
5123 		}
5124 	} else if (ipsec_policy_set) {
5125 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5126 			error = -1;
5127 			goto bad_addr;
5128 		}
5129 	}
5130 
5131 	/*
5132 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5133 	 * we'll cache that.  If we don't, we'll inherit global policy.
5134 	 *
5135 	 * We can't insert until the conn reflects the policy. Note that
5136 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5137 	 * connections where we don't have a policy. This is to prevent
5138 	 * global policy lookups in the inbound path.
5139 	 *
5140 	 * If we insert before we set conn_policy_cached,
5141 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5142 	 * because global policy cound be non-empty. We normally call
5143 	 * ipsec_check_policy() for conn_policy_cached connections only if
5144 	 * ipc_in_enforce_policy is set. But in this case,
5145 	 * conn_policy_cached can get set anytime since we made the
5146 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5147 	 * called, which will make the above assumption false.  Thus, we
5148 	 * need to insert after we set conn_policy_cached.
5149 	 */
5150 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5151 		goto bad_addr;
5152 
5153 	if (fanout_insert) {
5154 		/*
5155 		 * The addresses have been verified. Time to insert in
5156 		 * the correct fanout list.
5157 		 */
5158 		error = ipcl_conn_insert(connp, protocol, src_addr,
5159 		    dst_addr, connp->conn_ports);
5160 	}
5161 
5162 	if (error == 0) {
5163 		connp->conn_fully_bound = B_TRUE;
5164 		/*
5165 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5166 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5167 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5168 		 * ip_xxinfo_return(), which performs further checks
5169 		 * against them and upon success, returns the LSO/MDT info
5170 		 * mblk which we will attach to the bind acknowledgment.
5171 		 */
5172 		if (lso_dst_ire != NULL) {
5173 			mblk_t *lsoinfo_mp;
5174 
5175 			ASSERT(ill->ill_lso_capab != NULL);
5176 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5177 			    ill->ill_name, ill->ill_lso_capab)) != NULL)
5178 				linkb(mp, lsoinfo_mp);
5179 		} else if (md_dst_ire != NULL) {
5180 			mblk_t *mdinfo_mp;
5181 
5182 			ASSERT(ill->ill_mdt_capab != NULL);
5183 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5184 			    ill->ill_name, ill->ill_mdt_capab)) != NULL)
5185 				linkb(mp, mdinfo_mp);
5186 		}
5187 	}
5188 bad_addr:
5189 	if (ipsec_policy_set) {
5190 		ASSERT(policy_mp == mp->b_cont);
5191 		ASSERT(policy_mp != NULL);
5192 		freeb(policy_mp);
5193 		/*
5194 		 * As of now assume that nothing else accompanies
5195 		 * IPSEC_POLICY_SET.
5196 		 */
5197 		mp->b_cont = NULL;
5198 	}
5199 	if (src_ire != NULL)
5200 		IRE_REFRELE(src_ire);
5201 	if (dst_ire != NULL)
5202 		IRE_REFRELE(dst_ire);
5203 	if (sire != NULL)
5204 		IRE_REFRELE(sire);
5205 	if (md_dst_ire != NULL)
5206 		IRE_REFRELE(md_dst_ire);
5207 	if (lso_dst_ire != NULL)
5208 		IRE_REFRELE(lso_dst_ire);
5209 	return (error);
5210 }
5211 
5212 /*
5213  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5214  * Prefers dst_ire over src_ire.
5215  */
5216 static boolean_t
5217 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5218 {
5219 	mblk_t	*mp1;
5220 	ire_t *ret_ire = NULL;
5221 
5222 	mp1 = mp->b_cont;
5223 	ASSERT(mp1 != NULL);
5224 
5225 	if (ire != NULL) {
5226 		/*
5227 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5228 		 * appended mblk. Its <upper protocol>'s
5229 		 * job to make sure there is room.
5230 		 */
5231 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5232 			return (0);
5233 
5234 		mp1->b_datap->db_type = IRE_DB_TYPE;
5235 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5236 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5237 		ret_ire = (ire_t *)mp1->b_rptr;
5238 		/*
5239 		 * Pass the latest setting of the ip_path_mtu_discovery and
5240 		 * copy the ulp info if any.
5241 		 */
5242 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5243 		    IPH_DF : 0;
5244 		if (ulp_info != NULL) {
5245 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5246 			    sizeof (iulp_t));
5247 		}
5248 		ret_ire->ire_mp = mp1;
5249 	} else {
5250 		/*
5251 		 * No IRE was found. Remove IRE mblk.
5252 		 */
5253 		mp->b_cont = mp1->b_cont;
5254 		freeb(mp1);
5255 	}
5256 
5257 	return (1);
5258 }
5259 
5260 /*
5261  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5262  * the final piece where we don't.  Return a pointer to the first mblk in the
5263  * result, and update the pointer to the next mblk to chew on.  If anything
5264  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5265  * NULL pointer.
5266  */
5267 mblk_t *
5268 ip_carve_mp(mblk_t **mpp, ssize_t len)
5269 {
5270 	mblk_t	*mp0;
5271 	mblk_t	*mp1;
5272 	mblk_t	*mp2;
5273 
5274 	if (!len || !mpp || !(mp0 = *mpp))
5275 		return (NULL);
5276 	/* If we aren't going to consume the first mblk, we need a dup. */
5277 	if (mp0->b_wptr - mp0->b_rptr > len) {
5278 		mp1 = dupb(mp0);
5279 		if (mp1) {
5280 			/* Partition the data between the two mblks. */
5281 			mp1->b_wptr = mp1->b_rptr + len;
5282 			mp0->b_rptr = mp1->b_wptr;
5283 			/*
5284 			 * after adjustments if mblk not consumed is now
5285 			 * unaligned, try to align it. If this fails free
5286 			 * all messages and let upper layer recover.
5287 			 */
5288 			if (!OK_32PTR(mp0->b_rptr)) {
5289 				if (!pullupmsg(mp0, -1)) {
5290 					freemsg(mp0);
5291 					freemsg(mp1);
5292 					*mpp = NULL;
5293 					return (NULL);
5294 				}
5295 			}
5296 		}
5297 		return (mp1);
5298 	}
5299 	/* Eat through as many mblks as we need to get len bytes. */
5300 	len -= mp0->b_wptr - mp0->b_rptr;
5301 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5302 		if (mp2->b_wptr - mp2->b_rptr > len) {
5303 			/*
5304 			 * We won't consume the entire last mblk.  Like
5305 			 * above, dup and partition it.
5306 			 */
5307 			mp1->b_cont = dupb(mp2);
5308 			mp1 = mp1->b_cont;
5309 			if (!mp1) {
5310 				/*
5311 				 * Trouble.  Rather than go to a lot of
5312 				 * trouble to clean up, we free the messages.
5313 				 * This won't be any worse than losing it on
5314 				 * the wire.
5315 				 */
5316 				freemsg(mp0);
5317 				freemsg(mp2);
5318 				*mpp = NULL;
5319 				return (NULL);
5320 			}
5321 			mp1->b_wptr = mp1->b_rptr + len;
5322 			mp2->b_rptr = mp1->b_wptr;
5323 			/*
5324 			 * after adjustments if mblk not consumed is now
5325 			 * unaligned, try to align it. If this fails free
5326 			 * all messages and let upper layer recover.
5327 			 */
5328 			if (!OK_32PTR(mp2->b_rptr)) {
5329 				if (!pullupmsg(mp2, -1)) {
5330 					freemsg(mp0);
5331 					freemsg(mp2);
5332 					*mpp = NULL;
5333 					return (NULL);
5334 				}
5335 			}
5336 			*mpp = mp2;
5337 			return (mp0);
5338 		}
5339 		/* Decrement len by the amount we just got. */
5340 		len -= mp2->b_wptr - mp2->b_rptr;
5341 	}
5342 	/*
5343 	 * len should be reduced to zero now.  If not our caller has
5344 	 * screwed up.
5345 	 */
5346 	if (len) {
5347 		/* Shouldn't happen! */
5348 		freemsg(mp0);
5349 		*mpp = NULL;
5350 		return (NULL);
5351 	}
5352 	/*
5353 	 * We consumed up to exactly the end of an mblk.  Detach the part
5354 	 * we are returning from the rest of the chain.
5355 	 */
5356 	mp1->b_cont = NULL;
5357 	*mpp = mp2;
5358 	return (mp0);
5359 }
5360 
5361 /* The ill stream is being unplumbed. Called from ip_close */
5362 int
5363 ip_modclose(ill_t *ill)
5364 {
5365 	boolean_t success;
5366 	ipsq_t	*ipsq;
5367 	ipif_t	*ipif;
5368 	queue_t	*q = ill->ill_rq;
5369 	ip_stack_t	*ipst = ill->ill_ipst;
5370 	clock_t timeout;
5371 
5372 	/*
5373 	 * Wait for the ACKs of all deferred control messages to be processed.
5374 	 * In particular, we wait for a potential capability reset initiated
5375 	 * in ip_sioctl_plink() to complete before proceeding.
5376 	 *
5377 	 * Note: we wait for at most ip_modclose_ackwait_ms (by default 3000 ms)
5378 	 * in case the driver never replies.
5379 	 */
5380 	timeout = lbolt + MSEC_TO_TICK(ip_modclose_ackwait_ms);
5381 	mutex_enter(&ill->ill_lock);
5382 	while (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
5383 		if (cv_timedwait(&ill->ill_cv, &ill->ill_lock, timeout) < 0) {
5384 			/* Timeout */
5385 			break;
5386 		}
5387 	}
5388 	mutex_exit(&ill->ill_lock);
5389 
5390 	/*
5391 	 * Forcibly enter the ipsq after some delay. This is to take
5392 	 * care of the case when some ioctl does not complete because
5393 	 * we sent a control message to the driver and it did not
5394 	 * send us a reply. We want to be able to at least unplumb
5395 	 * and replumb rather than force the user to reboot the system.
5396 	 */
5397 	success = ipsq_enter(ill, B_FALSE);
5398 
5399 	/*
5400 	 * Open/close/push/pop is guaranteed to be single threaded
5401 	 * per stream by STREAMS. FS guarantees that all references
5402 	 * from top are gone before close is called. So there can't
5403 	 * be another close thread that has set CONDEMNED on this ill.
5404 	 * and cause ipsq_enter to return failure.
5405 	 */
5406 	ASSERT(success);
5407 	ipsq = ill->ill_phyint->phyint_ipsq;
5408 
5409 	/*
5410 	 * Mark it condemned. No new reference will be made to this ill.
5411 	 * Lookup functions will return an error. Threads that try to
5412 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5413 	 * that the refcnt will drop down to zero.
5414 	 */
5415 	mutex_enter(&ill->ill_lock);
5416 	ill->ill_state_flags |= ILL_CONDEMNED;
5417 	for (ipif = ill->ill_ipif; ipif != NULL;
5418 	    ipif = ipif->ipif_next) {
5419 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5420 	}
5421 	/*
5422 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5423 	 * returns  error if ILL_CONDEMNED is set
5424 	 */
5425 	cv_broadcast(&ill->ill_cv);
5426 	mutex_exit(&ill->ill_lock);
5427 
5428 	/*
5429 	 * Send all the deferred DLPI messages downstream which came in
5430 	 * during the small window right before ipsq_enter(). We do this
5431 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5432 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5433 	 */
5434 	ill_dlpi_send_deferred(ill);
5435 
5436 	/*
5437 	 * Shut down fragmentation reassembly.
5438 	 * ill_frag_timer won't start a timer again.
5439 	 * Now cancel any existing timer
5440 	 */
5441 	(void) untimeout(ill->ill_frag_timer_id);
5442 	(void) ill_frag_timeout(ill, 0);
5443 
5444 	/*
5445 	 * If MOVE was in progress, clear the
5446 	 * move_in_progress fields also.
5447 	 */
5448 	if (ill->ill_move_in_progress) {
5449 		ILL_CLEAR_MOVE(ill);
5450 	}
5451 
5452 	/*
5453 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5454 	 * this ill. Then wait for the refcnts to drop to zero.
5455 	 * ill_is_freeable checks whether the ill is really quiescent.
5456 	 * Then make sure that threads that are waiting to enter the
5457 	 * ipsq have seen the error returned by ipsq_enter and have
5458 	 * gone away. Then we call ill_delete_tail which does the
5459 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5460 	 */
5461 	ill_delete(ill);
5462 	mutex_enter(&ill->ill_lock);
5463 	while (!ill_is_freeable(ill))
5464 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5465 	while (ill->ill_waiters)
5466 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5467 
5468 	mutex_exit(&ill->ill_lock);
5469 
5470 	/*
5471 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5472 	 * it held until the end of the function since the cleanup
5473 	 * below needs to be able to use the ip_stack_t.
5474 	 */
5475 	netstack_hold(ipst->ips_netstack);
5476 
5477 	/* qprocsoff is called in ill_delete_tail */
5478 	ill_delete_tail(ill);
5479 	ASSERT(ill->ill_ipst == NULL);
5480 
5481 	/*
5482 	 * Walk through all upper (conn) streams and qenable
5483 	 * those that have queued data.
5484 	 * close synchronization needs this to
5485 	 * be done to ensure that all upper layers blocked
5486 	 * due to flow control to the closing device
5487 	 * get unblocked.
5488 	 */
5489 	ip1dbg(("ip_wsrv: walking\n"));
5490 	conn_walk_drain(ipst);
5491 
5492 	mutex_enter(&ipst->ips_ip_mi_lock);
5493 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5494 	mutex_exit(&ipst->ips_ip_mi_lock);
5495 
5496 	/*
5497 	 * credp could be null if the open didn't succeed and ip_modopen
5498 	 * itself calls ip_close.
5499 	 */
5500 	if (ill->ill_credp != NULL)
5501 		crfree(ill->ill_credp);
5502 
5503 	/*
5504 	 * Now we are done with the module close pieces that
5505 	 * need the netstack_t.
5506 	 */
5507 	netstack_rele(ipst->ips_netstack);
5508 
5509 	mi_close_free((IDP)ill);
5510 	q->q_ptr = WR(q)->q_ptr = NULL;
5511 
5512 	ipsq_exit(ipsq);
5513 
5514 	return (0);
5515 }
5516 
5517 /*
5518  * This is called as part of close() for IP, UDP, ICMP, and RTS
5519  * in order to quiesce the conn.
5520  */
5521 void
5522 ip_quiesce_conn(conn_t *connp)
5523 {
5524 	boolean_t	drain_cleanup_reqd = B_FALSE;
5525 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5526 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5527 	ip_stack_t	*ipst;
5528 
5529 	ASSERT(!IPCL_IS_TCP(connp));
5530 	ipst = connp->conn_netstack->netstack_ip;
5531 
5532 	/*
5533 	 * Mark the conn as closing, and this conn must not be
5534 	 * inserted in future into any list. Eg. conn_drain_insert(),
5535 	 * won't insert this conn into the conn_drain_list.
5536 	 * Similarly ill_pending_mp_add() will not add any mp to
5537 	 * the pending mp list, after this conn has started closing.
5538 	 *
5539 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5540 	 * cannot get set henceforth.
5541 	 */
5542 	mutex_enter(&connp->conn_lock);
5543 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5544 	connp->conn_state_flags |= CONN_CLOSING;
5545 	if (connp->conn_idl != NULL)
5546 		drain_cleanup_reqd = B_TRUE;
5547 	if (connp->conn_oper_pending_ill != NULL)
5548 		conn_ioctl_cleanup_reqd = B_TRUE;
5549 	if (connp->conn_dhcpinit_ill != NULL) {
5550 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
5551 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
5552 		connp->conn_dhcpinit_ill = NULL;
5553 	}
5554 	if (connp->conn_ilg_inuse != 0)
5555 		ilg_cleanup_reqd = B_TRUE;
5556 	mutex_exit(&connp->conn_lock);
5557 
5558 	if (conn_ioctl_cleanup_reqd)
5559 		conn_ioctl_cleanup(connp);
5560 
5561 	if (is_system_labeled() && connp->conn_anon_port) {
5562 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5563 		    connp->conn_mlp_type, connp->conn_ulp,
5564 		    ntohs(connp->conn_lport), B_FALSE);
5565 		connp->conn_anon_port = 0;
5566 	}
5567 	connp->conn_mlp_type = mlptSingle;
5568 
5569 	/*
5570 	 * Remove this conn from any fanout list it is on.
5571 	 * and then wait for any threads currently operating
5572 	 * on this endpoint to finish
5573 	 */
5574 	ipcl_hash_remove(connp);
5575 
5576 	/*
5577 	 * Remove this conn from the drain list, and do
5578 	 * any other cleanup that may be required.
5579 	 * (Only non-tcp streams may have a non-null conn_idl.
5580 	 * TCP streams are never flow controlled, and
5581 	 * conn_idl will be null)
5582 	 */
5583 	if (drain_cleanup_reqd)
5584 		conn_drain_tail(connp, B_TRUE);
5585 
5586 	if (connp == ipst->ips_ip_g_mrouter)
5587 		(void) ip_mrouter_done(NULL, ipst);
5588 
5589 	if (ilg_cleanup_reqd)
5590 		ilg_delete_all(connp);
5591 
5592 	conn_delete_ire(connp, NULL);
5593 
5594 	/*
5595 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5596 	 * callers from write side can't be there now because close
5597 	 * is in progress. The only other caller is ipcl_walk
5598 	 * which checks for the condemned flag.
5599 	 */
5600 	mutex_enter(&connp->conn_lock);
5601 	connp->conn_state_flags |= CONN_CONDEMNED;
5602 	while (connp->conn_ref != 1)
5603 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5604 	connp->conn_state_flags |= CONN_QUIESCED;
5605 	mutex_exit(&connp->conn_lock);
5606 }
5607 
5608 /* ARGSUSED */
5609 int
5610 ip_close(queue_t *q, int flags)
5611 {
5612 	conn_t		*connp;
5613 
5614 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5615 
5616 	/*
5617 	 * Call the appropriate delete routine depending on whether this is
5618 	 * a module or device.
5619 	 */
5620 	if (WR(q)->q_next != NULL) {
5621 		/* This is a module close */
5622 		return (ip_modclose((ill_t *)q->q_ptr));
5623 	}
5624 
5625 	connp = q->q_ptr;
5626 	ip_quiesce_conn(connp);
5627 
5628 	qprocsoff(q);
5629 
5630 	/*
5631 	 * Now we are truly single threaded on this stream, and can
5632 	 * delete the things hanging off the connp, and finally the connp.
5633 	 * We removed this connp from the fanout list, it cannot be
5634 	 * accessed thru the fanouts, and we already waited for the
5635 	 * conn_ref to drop to 0. We are already in close, so
5636 	 * there cannot be any other thread from the top. qprocsoff
5637 	 * has completed, and service has completed or won't run in
5638 	 * future.
5639 	 */
5640 	ASSERT(connp->conn_ref == 1);
5641 
5642 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
5643 
5644 	connp->conn_ref--;
5645 	ipcl_conn_destroy(connp);
5646 
5647 	q->q_ptr = WR(q)->q_ptr = NULL;
5648 	return (0);
5649 }
5650 
5651 /*
5652  * Wapper around putnext() so that ip_rts_request can merely use
5653  * conn_recv.
5654  */
5655 /*ARGSUSED2*/
5656 static void
5657 ip_conn_input(void *arg1, mblk_t *mp, void *arg2)
5658 {
5659 	conn_t *connp = (conn_t *)arg1;
5660 
5661 	putnext(connp->conn_rq, mp);
5662 }
5663 
5664 /* Return the IP checksum for the IP header at "iph". */
5665 uint16_t
5666 ip_csum_hdr(ipha_t *ipha)
5667 {
5668 	uint16_t	*uph;
5669 	uint32_t	sum;
5670 	int		opt_len;
5671 
5672 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5673 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5674 	uph = (uint16_t *)ipha;
5675 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5676 	    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5677 	if (opt_len > 0) {
5678 		do {
5679 			sum += uph[10];
5680 			sum += uph[11];
5681 			uph += 2;
5682 		} while (--opt_len);
5683 	}
5684 	sum = (sum & 0xFFFF) + (sum >> 16);
5685 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5686 	if (sum == 0xffff)
5687 		sum = 0;
5688 	return ((uint16_t)sum);
5689 }
5690 
5691 /*
5692  * Called when the module is about to be unloaded
5693  */
5694 void
5695 ip_ddi_destroy(void)
5696 {
5697 	tnet_fini();
5698 
5699 	icmp_ddi_destroy();
5700 	rts_ddi_destroy();
5701 	udp_ddi_destroy();
5702 	sctp_ddi_g_destroy();
5703 	tcp_ddi_g_destroy();
5704 	ipsec_policy_g_destroy();
5705 	ipcl_g_destroy();
5706 	ip_net_g_destroy();
5707 	ip_ire_g_fini();
5708 	inet_minor_destroy(ip_minor_arena_sa);
5709 #if defined(_LP64)
5710 	inet_minor_destroy(ip_minor_arena_la);
5711 #endif
5712 
5713 #ifdef DEBUG
5714 	list_destroy(&ip_thread_list);
5715 	rw_destroy(&ip_thread_rwlock);
5716 	tsd_destroy(&ip_thread_data);
5717 #endif
5718 
5719 	netstack_unregister(NS_IP);
5720 }
5721 
5722 /*
5723  * First step in cleanup.
5724  */
5725 /* ARGSUSED */
5726 static void
5727 ip_stack_shutdown(netstackid_t stackid, void *arg)
5728 {
5729 	ip_stack_t *ipst = (ip_stack_t *)arg;
5730 
5731 #ifdef NS_DEBUG
5732 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5733 #endif
5734 
5735 	/* Get rid of loopback interfaces and their IREs */
5736 	ip_loopback_cleanup(ipst);
5737 
5738 	/*
5739 	 * The *_hook_shutdown()s start the process of notifying any
5740 	 * consumers that things are going away.... nothing is destroyed.
5741 	 */
5742 	ipv4_hook_shutdown(ipst);
5743 	ipv6_hook_shutdown(ipst);
5744 }
5745 
5746 /*
5747  * Free the IP stack instance.
5748  */
5749 static void
5750 ip_stack_fini(netstackid_t stackid, void *arg)
5751 {
5752 	ip_stack_t *ipst = (ip_stack_t *)arg;
5753 	int ret;
5754 
5755 	/*
5756 	 * At this point, all of the notifications that the events and
5757 	 * protocols are going away have been run, meaning that we can
5758 	 * now set about starting to clean things up.
5759 	 */
5760 	ipv4_hook_destroy(ipst);
5761 	ipv6_hook_destroy(ipst);
5762 	ip_net_destroy(ipst);
5763 
5764 #ifdef NS_DEBUG
5765 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5766 #endif
5767 	rw_destroy(&ipst->ips_srcid_lock);
5768 
5769 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5770 	ipst->ips_ip_mibkp = NULL;
5771 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5772 	ipst->ips_icmp_mibkp = NULL;
5773 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5774 	ipst->ips_ip_kstat = NULL;
5775 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5776 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5777 	ipst->ips_ip6_kstat = NULL;
5778 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5779 
5780 	nd_free(&ipst->ips_ip_g_nd);
5781 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5782 	ipst->ips_param_arr = NULL;
5783 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5784 	ipst->ips_ndp_arr = NULL;
5785 
5786 	ip_mrouter_stack_destroy(ipst);
5787 
5788 	mutex_destroy(&ipst->ips_ip_mi_lock);
5789 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5790 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5791 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5792 
5793 	ret = untimeout(ipst->ips_igmp_timeout_id);
5794 	if (ret == -1) {
5795 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5796 	} else {
5797 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5798 		ipst->ips_igmp_timeout_id = 0;
5799 	}
5800 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5801 	if (ret == -1) {
5802 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5803 	} else {
5804 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5805 		ipst->ips_igmp_slowtimeout_id = 0;
5806 	}
5807 	ret = untimeout(ipst->ips_mld_timeout_id);
5808 	if (ret == -1) {
5809 		ASSERT(ipst->ips_mld_timeout_id == 0);
5810 	} else {
5811 		ASSERT(ipst->ips_mld_timeout_id != 0);
5812 		ipst->ips_mld_timeout_id = 0;
5813 	}
5814 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5815 	if (ret == -1) {
5816 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5817 	} else {
5818 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5819 		ipst->ips_mld_slowtimeout_id = 0;
5820 	}
5821 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5822 	if (ret == -1) {
5823 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5824 	} else {
5825 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5826 		ipst->ips_ip_ire_expire_id = 0;
5827 	}
5828 
5829 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5830 	mutex_destroy(&ipst->ips_mld_timer_lock);
5831 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5832 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5833 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5834 	rw_destroy(&ipst->ips_ill_g_lock);
5835 
5836 	ipobs_fini(ipst);
5837 	ip_ire_fini(ipst);
5838 	ip6_asp_free(ipst);
5839 	conn_drain_fini(ipst);
5840 	ipcl_destroy(ipst);
5841 
5842 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5843 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5844 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5845 	ipst->ips_ndp4 = NULL;
5846 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5847 	ipst->ips_ndp6 = NULL;
5848 
5849 	if (ipst->ips_loopback_ksp != NULL) {
5850 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5851 		ipst->ips_loopback_ksp = NULL;
5852 	}
5853 
5854 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5855 	ipst->ips_phyint_g_list = NULL;
5856 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5857 	ipst->ips_ill_g_heads = NULL;
5858 
5859 	kmem_free(ipst, sizeof (*ipst));
5860 }
5861 
5862 /*
5863  * This function is called from the TSD destructor, and is used to debug
5864  * reference count issues in IP. See block comment in <inet/ip_if.h> for
5865  * details.
5866  */
5867 static void
5868 ip_thread_exit(void *phash)
5869 {
5870 	th_hash_t *thh = phash;
5871 
5872 	rw_enter(&ip_thread_rwlock, RW_WRITER);
5873 	list_remove(&ip_thread_list, thh);
5874 	rw_exit(&ip_thread_rwlock);
5875 	mod_hash_destroy_hash(thh->thh_hash);
5876 	kmem_free(thh, sizeof (*thh));
5877 }
5878 
5879 /*
5880  * Called when the IP kernel module is loaded into the kernel
5881  */
5882 void
5883 ip_ddi_init(void)
5884 {
5885 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5886 
5887 	/*
5888 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5889 	 * initial devices: ip, ip6, tcp, tcp6.
5890 	 */
5891 	/*
5892 	 * If this is a 64-bit kernel, then create two separate arenas -
5893 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
5894 	 * other for socket apps in the range 2^^18 through 2^^32-1.
5895 	 */
5896 	ip_minor_arena_la = NULL;
5897 	ip_minor_arena_sa = NULL;
5898 #if defined(_LP64)
5899 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5900 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
5901 		cmn_err(CE_PANIC,
5902 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5903 	}
5904 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
5905 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
5906 		cmn_err(CE_PANIC,
5907 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
5908 	}
5909 #else
5910 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5911 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
5912 		cmn_err(CE_PANIC,
5913 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5914 	}
5915 #endif
5916 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5917 
5918 	ipcl_g_init();
5919 	ip_ire_g_init();
5920 	ip_net_g_init();
5921 
5922 #ifdef DEBUG
5923 	tsd_create(&ip_thread_data, ip_thread_exit);
5924 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
5925 	list_create(&ip_thread_list, sizeof (th_hash_t),
5926 	    offsetof(th_hash_t, thh_link));
5927 #endif
5928 
5929 	/*
5930 	 * We want to be informed each time a stack is created or
5931 	 * destroyed in the kernel, so we can maintain the
5932 	 * set of udp_stack_t's.
5933 	 */
5934 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5935 	    ip_stack_fini);
5936 
5937 	ipsec_policy_g_init();
5938 	tcp_ddi_g_init();
5939 	sctp_ddi_g_init();
5940 
5941 	tnet_init();
5942 
5943 	udp_ddi_init();
5944 	rts_ddi_init();
5945 	icmp_ddi_init();
5946 }
5947 
5948 /*
5949  * Initialize the IP stack instance.
5950  */
5951 static void *
5952 ip_stack_init(netstackid_t stackid, netstack_t *ns)
5953 {
5954 	ip_stack_t	*ipst;
5955 	ipparam_t	*pa;
5956 	ipndp_t		*na;
5957 
5958 #ifdef NS_DEBUG
5959 	printf("ip_stack_init(stack %d)\n", stackid);
5960 #endif
5961 
5962 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
5963 	ipst->ips_netstack = ns;
5964 
5965 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
5966 	    KM_SLEEP);
5967 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
5968 	    KM_SLEEP);
5969 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5970 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5971 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5972 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5973 
5974 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5975 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5976 	ipst->ips_igmp_deferred_next = INFINITY;
5977 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5978 	ipst->ips_mld_deferred_next = INFINITY;
5979 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5980 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5981 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5982 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5983 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
5984 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5985 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5986 
5987 	ipcl_init(ipst);
5988 	ip_ire_init(ipst);
5989 	ip6_asp_init(ipst);
5990 	ipif_init(ipst);
5991 	conn_drain_init(ipst);
5992 	ip_mrouter_stack_init(ipst);
5993 
5994 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
5995 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
5996 
5997 	ipst->ips_ip_multirt_log_interval = 1000;
5998 
5999 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
6000 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
6001 	ipst->ips_ill_index = 1;
6002 
6003 	ipst->ips_saved_ip_g_forward = -1;
6004 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
6005 
6006 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
6007 	ipst->ips_param_arr = pa;
6008 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
6009 
6010 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
6011 	ipst->ips_ndp_arr = na;
6012 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
6013 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
6014 	    (caddr_t)&ipst->ips_ip_g_forward;
6015 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
6016 	    (caddr_t)&ipst->ips_ipv6_forward;
6017 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
6018 	    "ip_cgtp_filter") == 0);
6019 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
6020 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
6021 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_name,
6022 	    "ipmp_hook_emulation") == 0);
6023 	ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_data =
6024 	    (caddr_t)&ipst->ips_ipmp_hook_emulation;
6025 
6026 	(void) ip_param_register(&ipst->ips_ip_g_nd,
6027 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
6028 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
6029 
6030 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
6031 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
6032 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
6033 	ipst->ips_ip6_kstat =
6034 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6035 
6036 	ipst->ips_ipmp_enable_failback = B_TRUE;
6037 
6038 	ipst->ips_ip_src_id = 1;
6039 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6040 
6041 	ipobs_init(ipst);
6042 	ip_net_init(ipst, ns);
6043 	ipv4_hook_init(ipst);
6044 	ipv6_hook_init(ipst);
6045 
6046 	return (ipst);
6047 }
6048 
6049 /*
6050  * Allocate and initialize a DLPI template of the specified length.  (May be
6051  * called as writer.)
6052  */
6053 mblk_t *
6054 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6055 {
6056 	mblk_t	*mp;
6057 
6058 	mp = allocb(len, BPRI_MED);
6059 	if (!mp)
6060 		return (NULL);
6061 
6062 	/*
6063 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6064 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6065 	 * that other DLPI are M_PROTO.
6066 	 */
6067 	if (prim == DL_INFO_REQ) {
6068 		mp->b_datap->db_type = M_PCPROTO;
6069 	} else {
6070 		mp->b_datap->db_type = M_PROTO;
6071 	}
6072 
6073 	mp->b_wptr = mp->b_rptr + len;
6074 	bzero(mp->b_rptr, len);
6075 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6076 	return (mp);
6077 }
6078 
6079 /*
6080  * Debug formatting routine.  Returns a character string representation of the
6081  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6082  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6083  *
6084  * Once the ndd table-printing interfaces are removed, this can be changed to
6085  * standard dotted-decimal form.
6086  */
6087 char *
6088 ip_dot_addr(ipaddr_t addr, char *buf)
6089 {
6090 	uint8_t *ap = (uint8_t *)&addr;
6091 
6092 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6093 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6094 	return (buf);
6095 }
6096 
6097 /*
6098  * Write the given MAC address as a printable string in the usual colon-
6099  * separated format.
6100  */
6101 const char *
6102 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6103 {
6104 	char *bp;
6105 
6106 	if (alen == 0 || buflen < 4)
6107 		return ("?");
6108 	bp = buf;
6109 	for (;;) {
6110 		/*
6111 		 * If there are more MAC address bytes available, but we won't
6112 		 * have any room to print them, then add "..." to the string
6113 		 * instead.  See below for the 'magic number' explanation.
6114 		 */
6115 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6116 			(void) strcpy(bp, "...");
6117 			break;
6118 		}
6119 		(void) sprintf(bp, "%02x", *addr++);
6120 		bp += 2;
6121 		if (--alen == 0)
6122 			break;
6123 		*bp++ = ':';
6124 		buflen -= 3;
6125 		/*
6126 		 * At this point, based on the first 'if' statement above,
6127 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6128 		 * buflen >= 4.  The first case leaves room for the final "xx"
6129 		 * number and trailing NUL byte.  The second leaves room for at
6130 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6131 		 * that statement.
6132 		 */
6133 	}
6134 	return (buf);
6135 }
6136 
6137 /*
6138  * Send an ICMP error after patching up the packet appropriately.  Returns
6139  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6140  */
6141 static boolean_t
6142 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6143     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6144     zoneid_t zoneid, ip_stack_t *ipst)
6145 {
6146 	ipha_t *ipha;
6147 	mblk_t *first_mp;
6148 	boolean_t secure;
6149 	unsigned char db_type;
6150 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6151 
6152 	first_mp = mp;
6153 	if (mctl_present) {
6154 		mp = mp->b_cont;
6155 		secure = ipsec_in_is_secure(first_mp);
6156 		ASSERT(mp != NULL);
6157 	} else {
6158 		/*
6159 		 * If this is an ICMP error being reported - which goes
6160 		 * up as M_CTLs, we need to convert them to M_DATA till
6161 		 * we finish checking with global policy because
6162 		 * ipsec_check_global_policy() assumes M_DATA as clear
6163 		 * and M_CTL as secure.
6164 		 */
6165 		db_type = DB_TYPE(mp);
6166 		DB_TYPE(mp) = M_DATA;
6167 		secure = B_FALSE;
6168 	}
6169 	/*
6170 	 * We are generating an icmp error for some inbound packet.
6171 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6172 	 * Before we generate an error, check with global policy
6173 	 * to see whether this is allowed to enter the system. As
6174 	 * there is no "conn", we are checking with global policy.
6175 	 */
6176 	ipha = (ipha_t *)mp->b_rptr;
6177 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6178 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6179 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6180 		if (first_mp == NULL)
6181 			return (B_FALSE);
6182 	}
6183 
6184 	if (!mctl_present)
6185 		DB_TYPE(mp) = db_type;
6186 
6187 	if (flags & IP_FF_SEND_ICMP) {
6188 		if (flags & IP_FF_HDR_COMPLETE) {
6189 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6190 				freemsg(first_mp);
6191 				return (B_TRUE);
6192 			}
6193 		}
6194 		if (flags & IP_FF_CKSUM) {
6195 			/*
6196 			 * Have to correct checksum since
6197 			 * the packet might have been
6198 			 * fragmented and the reassembly code in ip_rput
6199 			 * does not restore the IP checksum.
6200 			 */
6201 			ipha->ipha_hdr_checksum = 0;
6202 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6203 		}
6204 		switch (icmp_type) {
6205 		case ICMP_DEST_UNREACHABLE:
6206 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6207 			    ipst);
6208 			break;
6209 		default:
6210 			freemsg(first_mp);
6211 			break;
6212 		}
6213 	} else {
6214 		freemsg(first_mp);
6215 		return (B_FALSE);
6216 	}
6217 
6218 	return (B_TRUE);
6219 }
6220 
6221 /*
6222  * Used to send an ICMP error message when a packet is received for
6223  * a protocol that is not supported. The mblk passed as argument
6224  * is consumed by this function.
6225  */
6226 void
6227 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6228     ip_stack_t *ipst)
6229 {
6230 	mblk_t *mp;
6231 	ipha_t *ipha;
6232 	ill_t *ill;
6233 	ipsec_in_t *ii;
6234 
6235 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6236 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6237 
6238 	mp = ipsec_mp->b_cont;
6239 	ipsec_mp->b_cont = NULL;
6240 	ipha = (ipha_t *)mp->b_rptr;
6241 	/* Get ill from index in ipsec_in_t. */
6242 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6243 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6244 	    ipst);
6245 	if (ill != NULL) {
6246 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6247 			if (ip_fanout_send_icmp(q, mp, flags,
6248 			    ICMP_DEST_UNREACHABLE,
6249 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6250 				BUMP_MIB(ill->ill_ip_mib,
6251 				    ipIfStatsInUnknownProtos);
6252 			}
6253 		} else {
6254 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6255 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6256 			    0, B_FALSE, zoneid, ipst)) {
6257 				BUMP_MIB(ill->ill_ip_mib,
6258 				    ipIfStatsInUnknownProtos);
6259 			}
6260 		}
6261 		ill_refrele(ill);
6262 	} else { /* re-link for the freemsg() below. */
6263 		ipsec_mp->b_cont = mp;
6264 	}
6265 
6266 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6267 	freemsg(ipsec_mp);
6268 }
6269 
6270 /*
6271  * See if the inbound datagram has had IPsec processing applied to it.
6272  */
6273 boolean_t
6274 ipsec_in_is_secure(mblk_t *ipsec_mp)
6275 {
6276 	ipsec_in_t *ii;
6277 
6278 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6279 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6280 
6281 	if (ii->ipsec_in_loopback) {
6282 		return (ii->ipsec_in_secure);
6283 	} else {
6284 		return (ii->ipsec_in_ah_sa != NULL ||
6285 		    ii->ipsec_in_esp_sa != NULL ||
6286 		    ii->ipsec_in_decaps);
6287 	}
6288 }
6289 
6290 /*
6291  * Handle protocols with which IP is less intimate.  There
6292  * can be more than one stream bound to a particular
6293  * protocol.  When this is the case, normally each one gets a copy
6294  * of any incoming packets.
6295  *
6296  * IPsec NOTE :
6297  *
6298  * Don't allow a secure packet going up a non-secure connection.
6299  * We don't allow this because
6300  *
6301  * 1) Reply might go out in clear which will be dropped at
6302  *    the sending side.
6303  * 2) If the reply goes out in clear it will give the
6304  *    adversary enough information for getting the key in
6305  *    most of the cases.
6306  *
6307  * Moreover getting a secure packet when we expect clear
6308  * implies that SA's were added without checking for
6309  * policy on both ends. This should not happen once ISAKMP
6310  * is used to negotiate SAs as SAs will be added only after
6311  * verifying the policy.
6312  *
6313  * NOTE : If the packet was tunneled and not multicast we only send
6314  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6315  * back to delivering packets to AF_INET6 raw sockets.
6316  *
6317  * IPQoS Notes:
6318  * Once we have determined the client, invoke IPPF processing.
6319  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6320  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6321  * ip_policy will be false.
6322  *
6323  * Zones notes:
6324  * Currently only applications in the global zone can create raw sockets for
6325  * protocols other than ICMP. So unlike the broadcast / multicast case of
6326  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6327  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6328  */
6329 static void
6330 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6331     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6332     zoneid_t zoneid)
6333 {
6334 	queue_t	*rq;
6335 	mblk_t	*mp1, *first_mp1;
6336 	uint_t	protocol = ipha->ipha_protocol;
6337 	ipaddr_t dst;
6338 	boolean_t one_only;
6339 	mblk_t *first_mp = mp;
6340 	boolean_t secure;
6341 	uint32_t ill_index;
6342 	conn_t	*connp, *first_connp, *next_connp;
6343 	connf_t	*connfp;
6344 	boolean_t shared_addr;
6345 	mib2_ipIfStatsEntry_t *mibptr;
6346 	ip_stack_t *ipst = recv_ill->ill_ipst;
6347 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6348 
6349 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6350 	if (mctl_present) {
6351 		mp = first_mp->b_cont;
6352 		secure = ipsec_in_is_secure(first_mp);
6353 		ASSERT(mp != NULL);
6354 	} else {
6355 		secure = B_FALSE;
6356 	}
6357 	dst = ipha->ipha_dst;
6358 	/*
6359 	 * If the packet was tunneled and not multicast we only send to it
6360 	 * the first match.
6361 	 */
6362 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6363 	    !CLASSD(dst));
6364 
6365 	shared_addr = (zoneid == ALL_ZONES);
6366 	if (shared_addr) {
6367 		/*
6368 		 * We don't allow multilevel ports for raw IP, so no need to
6369 		 * check for that here.
6370 		 */
6371 		zoneid = tsol_packet_to_zoneid(mp);
6372 	}
6373 
6374 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6375 	mutex_enter(&connfp->connf_lock);
6376 	connp = connfp->connf_head;
6377 	for (connp = connfp->connf_head; connp != NULL;
6378 	    connp = connp->conn_next) {
6379 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6380 		    zoneid) &&
6381 		    (!is_system_labeled() ||
6382 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6383 		    connp))) {
6384 			break;
6385 		}
6386 	}
6387 
6388 	if (connp == NULL || connp->conn_upq == NULL) {
6389 		/*
6390 		 * No one bound to these addresses.  Is
6391 		 * there a client that wants all
6392 		 * unclaimed datagrams?
6393 		 */
6394 		mutex_exit(&connfp->connf_lock);
6395 		/*
6396 		 * Check for IPPROTO_ENCAP...
6397 		 */
6398 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6399 			/*
6400 			 * If an IPsec mblk is here on a multicast
6401 			 * tunnel (using ip_mroute stuff), check policy here,
6402 			 * THEN ship off to ip_mroute_decap().
6403 			 *
6404 			 * BTW,  If I match a configured IP-in-IP
6405 			 * tunnel, this path will not be reached, and
6406 			 * ip_mroute_decap will never be called.
6407 			 */
6408 			first_mp = ipsec_check_global_policy(first_mp, connp,
6409 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6410 			if (first_mp != NULL) {
6411 				if (mctl_present)
6412 					freeb(first_mp);
6413 				ip_mroute_decap(q, mp, ill);
6414 			} /* Else we already freed everything! */
6415 		} else {
6416 			/*
6417 			 * Otherwise send an ICMP protocol unreachable.
6418 			 */
6419 			if (ip_fanout_send_icmp(q, first_mp, flags,
6420 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6421 			    mctl_present, zoneid, ipst)) {
6422 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6423 			}
6424 		}
6425 		return;
6426 	}
6427 	CONN_INC_REF(connp);
6428 	first_connp = connp;
6429 
6430 	/*
6431 	 * Only send message to one tunnel driver by immediately
6432 	 * terminating the loop.
6433 	 */
6434 	connp = one_only ? NULL : connp->conn_next;
6435 
6436 	for (;;) {
6437 		while (connp != NULL) {
6438 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6439 			    flags, zoneid) &&
6440 			    (!is_system_labeled() ||
6441 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6442 			    shared_addr, connp)))
6443 				break;
6444 			connp = connp->conn_next;
6445 		}
6446 
6447 		/*
6448 		 * Copy the packet.
6449 		 */
6450 		if (connp == NULL || connp->conn_upq == NULL ||
6451 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6452 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6453 			/*
6454 			 * No more interested clients or memory
6455 			 * allocation failed
6456 			 */
6457 			connp = first_connp;
6458 			break;
6459 		}
6460 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6461 		CONN_INC_REF(connp);
6462 		mutex_exit(&connfp->connf_lock);
6463 		rq = connp->conn_rq;
6464 		if (!canputnext(rq)) {
6465 			if (flags & IP_FF_RAWIP) {
6466 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6467 			} else {
6468 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6469 			}
6470 
6471 			freemsg(first_mp1);
6472 		} else {
6473 			/*
6474 			 * Don't enforce here if we're an actual tunnel -
6475 			 * let "tun" do it instead.
6476 			 */
6477 			if (!IPCL_IS_IPTUN(connp) &&
6478 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6479 			    secure)) {
6480 				first_mp1 = ipsec_check_inbound_policy
6481 				    (first_mp1, connp, ipha, NULL,
6482 				    mctl_present);
6483 			}
6484 			if (first_mp1 != NULL) {
6485 				int in_flags = 0;
6486 				/*
6487 				 * ip_fanout_proto also gets called from
6488 				 * icmp_inbound_error_fanout, in which case
6489 				 * the msg type is M_CTL.  Don't add info
6490 				 * in this case for the time being. In future
6491 				 * when there is a need for knowing the
6492 				 * inbound iface index for ICMP error msgs,
6493 				 * then this can be changed.
6494 				 */
6495 				if (connp->conn_recvif)
6496 					in_flags = IPF_RECVIF;
6497 				/*
6498 				 * The ULP may support IP_RECVPKTINFO for both
6499 				 * IP v4 and v6 so pass the appropriate argument
6500 				 * based on conn IP version.
6501 				 */
6502 				if (connp->conn_ip_recvpktinfo) {
6503 					if (connp->conn_af_isv6) {
6504 						/*
6505 						 * V6 only needs index
6506 						 */
6507 						in_flags |= IPF_RECVIF;
6508 					} else {
6509 						/*
6510 						 * V4 needs index +
6511 						 * matching address.
6512 						 */
6513 						in_flags |= IPF_RECVADDR;
6514 					}
6515 				}
6516 				if ((in_flags != 0) &&
6517 				    (mp->b_datap->db_type != M_CTL)) {
6518 					/*
6519 					 * the actual data will be
6520 					 * contained in b_cont upon
6521 					 * successful return of the
6522 					 * following call else
6523 					 * original mblk is returned
6524 					 */
6525 					ASSERT(recv_ill != NULL);
6526 					mp1 = ip_add_info(mp1, recv_ill,
6527 					    in_flags, IPCL_ZONEID(connp), ipst);
6528 				}
6529 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6530 				if (mctl_present)
6531 					freeb(first_mp1);
6532 				(connp->conn_recv)(connp, mp1, NULL);
6533 			}
6534 		}
6535 		mutex_enter(&connfp->connf_lock);
6536 		/* Follow the next pointer before releasing the conn. */
6537 		next_connp = connp->conn_next;
6538 		CONN_DEC_REF(connp);
6539 		connp = next_connp;
6540 	}
6541 
6542 	/* Last one.  Send it upstream. */
6543 	mutex_exit(&connfp->connf_lock);
6544 
6545 	/*
6546 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6547 	 * will be set to false.
6548 	 */
6549 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6550 		ill_index = ill->ill_phyint->phyint_ifindex;
6551 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6552 		if (mp == NULL) {
6553 			CONN_DEC_REF(connp);
6554 			if (mctl_present) {
6555 				freeb(first_mp);
6556 			}
6557 			return;
6558 		}
6559 	}
6560 
6561 	rq = connp->conn_rq;
6562 	if (!canputnext(rq)) {
6563 		if (flags & IP_FF_RAWIP) {
6564 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6565 		} else {
6566 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6567 		}
6568 
6569 		freemsg(first_mp);
6570 	} else {
6571 		if (IPCL_IS_IPTUN(connp)) {
6572 			/*
6573 			 * Tunneled packet.  We enforce policy in the tunnel
6574 			 * module itself.
6575 			 *
6576 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6577 			 * a policy check.
6578 			 * FIXME to use conn_recv for tun later.
6579 			 */
6580 			putnext(rq, first_mp);
6581 			CONN_DEC_REF(connp);
6582 			return;
6583 		}
6584 
6585 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6586 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6587 			    ipha, NULL, mctl_present);
6588 		}
6589 
6590 		if (first_mp != NULL) {
6591 			int in_flags = 0;
6592 
6593 			/*
6594 			 * ip_fanout_proto also gets called
6595 			 * from icmp_inbound_error_fanout, in
6596 			 * which case the msg type is M_CTL.
6597 			 * Don't add info in this case for time
6598 			 * being. In future when there is a
6599 			 * need for knowing the inbound iface
6600 			 * index for ICMP error msgs, then this
6601 			 * can be changed
6602 			 */
6603 			if (connp->conn_recvif)
6604 				in_flags = IPF_RECVIF;
6605 			if (connp->conn_ip_recvpktinfo) {
6606 				if (connp->conn_af_isv6) {
6607 					/*
6608 					 * V6 only needs index
6609 					 */
6610 					in_flags |= IPF_RECVIF;
6611 				} else {
6612 					/*
6613 					 * V4 needs index +
6614 					 * matching address.
6615 					 */
6616 					in_flags |= IPF_RECVADDR;
6617 				}
6618 			}
6619 			if ((in_flags != 0) &&
6620 			    (mp->b_datap->db_type != M_CTL)) {
6621 
6622 				/*
6623 				 * the actual data will be contained in
6624 				 * b_cont upon successful return
6625 				 * of the following call else original
6626 				 * mblk is returned
6627 				 */
6628 				ASSERT(recv_ill != NULL);
6629 				mp = ip_add_info(mp, recv_ill,
6630 				    in_flags, IPCL_ZONEID(connp), ipst);
6631 			}
6632 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6633 			(connp->conn_recv)(connp, mp, NULL);
6634 			if (mctl_present)
6635 				freeb(first_mp);
6636 		}
6637 	}
6638 	CONN_DEC_REF(connp);
6639 }
6640 
6641 /*
6642  * Fanout for TCP packets
6643  * The caller puts <fport, lport> in the ports parameter.
6644  *
6645  * IPQoS Notes
6646  * Before sending it to the client, invoke IPPF processing.
6647  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6648  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6649  * ip_policy is false.
6650  */
6651 static void
6652 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6653     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6654 {
6655 	mblk_t  *first_mp;
6656 	boolean_t secure;
6657 	uint32_t ill_index;
6658 	int	ip_hdr_len;
6659 	tcph_t	*tcph;
6660 	boolean_t syn_present = B_FALSE;
6661 	conn_t	*connp;
6662 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6663 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6664 
6665 	ASSERT(recv_ill != NULL);
6666 
6667 	first_mp = mp;
6668 	if (mctl_present) {
6669 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6670 		mp = first_mp->b_cont;
6671 		secure = ipsec_in_is_secure(first_mp);
6672 		ASSERT(mp != NULL);
6673 	} else {
6674 		secure = B_FALSE;
6675 	}
6676 
6677 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6678 
6679 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6680 	    zoneid, ipst)) == NULL) {
6681 		/*
6682 		 * No connected connection or listener. Send a
6683 		 * TH_RST via tcp_xmit_listeners_reset.
6684 		 */
6685 
6686 		/* Initiate IPPf processing, if needed. */
6687 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6688 			uint32_t ill_index;
6689 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6690 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6691 			if (first_mp == NULL)
6692 				return;
6693 		}
6694 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6695 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6696 		    zoneid));
6697 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6698 		    ipst->ips_netstack->netstack_tcp, NULL);
6699 		return;
6700 	}
6701 
6702 	/*
6703 	 * Allocate the SYN for the TCP connection here itself
6704 	 */
6705 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6706 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6707 		if (IPCL_IS_TCP(connp)) {
6708 			squeue_t *sqp;
6709 
6710 			/*
6711 			 * For fused tcp loopback, assign the eager's
6712 			 * squeue to be that of the active connect's.
6713 			 * Note that we don't check for IP_FF_LOOPBACK
6714 			 * here since this routine gets called only
6715 			 * for loopback (unlike the IPv6 counterpart).
6716 			 */
6717 			ASSERT(Q_TO_CONN(q) != NULL);
6718 			if (do_tcp_fusion &&
6719 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6720 			    !secure &&
6721 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6722 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6723 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6724 				sqp = Q_TO_CONN(q)->conn_sqp;
6725 			} else {
6726 				sqp = IP_SQUEUE_GET(lbolt);
6727 			}
6728 
6729 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6730 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6731 			syn_present = B_TRUE;
6732 		}
6733 	}
6734 
6735 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6736 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6737 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6738 		if ((flags & TH_RST) || (flags & TH_URG)) {
6739 			CONN_DEC_REF(connp);
6740 			freemsg(first_mp);
6741 			return;
6742 		}
6743 		if (flags & TH_ACK) {
6744 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6745 			    ipst->ips_netstack->netstack_tcp, connp);
6746 			CONN_DEC_REF(connp);
6747 			return;
6748 		}
6749 
6750 		CONN_DEC_REF(connp);
6751 		freemsg(first_mp);
6752 		return;
6753 	}
6754 
6755 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6756 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6757 		    NULL, mctl_present);
6758 		if (first_mp == NULL) {
6759 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6760 			CONN_DEC_REF(connp);
6761 			return;
6762 		}
6763 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6764 			ASSERT(syn_present);
6765 			if (mctl_present) {
6766 				ASSERT(first_mp != mp);
6767 				first_mp->b_datap->db_struioflag |=
6768 				    STRUIO_POLICY;
6769 			} else {
6770 				ASSERT(first_mp == mp);
6771 				mp->b_datap->db_struioflag &=
6772 				    ~STRUIO_EAGER;
6773 				mp->b_datap->db_struioflag |=
6774 				    STRUIO_POLICY;
6775 			}
6776 		} else {
6777 			/*
6778 			 * Discard first_mp early since we're dealing with a
6779 			 * fully-connected conn_t and tcp doesn't do policy in
6780 			 * this case.
6781 			 */
6782 			if (mctl_present) {
6783 				freeb(first_mp);
6784 				mctl_present = B_FALSE;
6785 			}
6786 			first_mp = mp;
6787 		}
6788 	}
6789 
6790 	/*
6791 	 * Initiate policy processing here if needed. If we get here from
6792 	 * icmp_inbound_error_fanout, ip_policy is false.
6793 	 */
6794 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6795 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6796 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6797 		if (mp == NULL) {
6798 			CONN_DEC_REF(connp);
6799 			if (mctl_present)
6800 				freeb(first_mp);
6801 			return;
6802 		} else if (mctl_present) {
6803 			ASSERT(first_mp != mp);
6804 			first_mp->b_cont = mp;
6805 		} else {
6806 			first_mp = mp;
6807 		}
6808 	}
6809 
6810 
6811 
6812 	/* Handle socket options. */
6813 	if (!syn_present &&
6814 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6815 		/* Add header */
6816 		ASSERT(recv_ill != NULL);
6817 		/*
6818 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6819 		 * IPF_RECVIF.
6820 		 */
6821 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6822 		    ipst);
6823 		if (mp == NULL) {
6824 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6825 			CONN_DEC_REF(connp);
6826 			if (mctl_present)
6827 				freeb(first_mp);
6828 			return;
6829 		} else if (mctl_present) {
6830 			/*
6831 			 * ip_add_info might return a new mp.
6832 			 */
6833 			ASSERT(first_mp != mp);
6834 			first_mp->b_cont = mp;
6835 		} else {
6836 			first_mp = mp;
6837 		}
6838 	}
6839 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6840 	if (IPCL_IS_TCP(connp)) {
6841 		/* do not drain, certain use cases can blow the stack */
6842 		squeue_enter_nodrain(connp->conn_sqp, first_mp,
6843 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6844 	} else {
6845 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
6846 		(connp->conn_recv)(connp, first_mp, NULL);
6847 		CONN_DEC_REF(connp);
6848 	}
6849 }
6850 
6851 /*
6852  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
6853  * pass it along to ESP if the SPI is non-zero.  Returns TRUE if the mblk
6854  * is not consumed.
6855  *
6856  * One of four things can happen, all of which affect the passed-in mblk:
6857  *
6858  * 1.) ICMP messages that go through here just get returned TRUE.
6859  *
6860  * 2.) The packet is stock UDP and gets its zero-SPI stripped.  Return TRUE.
6861  *
6862  * 3.) The packet is ESP-in-UDP, gets transformed into an equivalent
6863  *     ESP packet, and is passed along to ESP for consumption.  Return FALSE.
6864  *
6865  * 4.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
6866  */
6867 static boolean_t
6868 zero_spi_check(queue_t *q, mblk_t *mp, ire_t *ire, ill_t *recv_ill,
6869     ipsec_stack_t *ipss)
6870 {
6871 	int shift, plen, iph_len;
6872 	ipha_t *ipha;
6873 	udpha_t *udpha;
6874 	uint32_t *spi;
6875 	uint32_t esp_ports;
6876 	uint8_t *orptr;
6877 	boolean_t free_ire;
6878 
6879 	if (DB_TYPE(mp) == M_CTL) {
6880 		/*
6881 		 * ICMP message with UDP inside.  Don't bother stripping, just
6882 		 * send it up.
6883 		 *
6884 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
6885 		 * to ignore errors set by ICMP anyway ('cause they might be
6886 		 * forged), but that's the app's decision, not ours.
6887 		 */
6888 
6889 		/* Bunch of reality checks for DEBUG kernels... */
6890 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
6891 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
6892 
6893 		return (B_TRUE);
6894 	}
6895 
6896 	ipha = (ipha_t *)mp->b_rptr;
6897 	iph_len = IPH_HDR_LENGTH(ipha);
6898 	plen = ntohs(ipha->ipha_length);
6899 
6900 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
6901 		/*
6902 		 * Most likely a keepalive for the benefit of an intervening
6903 		 * NAT.  These aren't for us, per se, so drop it.
6904 		 *
6905 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
6906 		 * byte packets (keepalives are 1-byte), but we'll drop them
6907 		 * also.
6908 		 */
6909 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6910 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
6911 		return (B_FALSE);
6912 	}
6913 
6914 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
6915 		/* might as well pull it all up - it might be ESP. */
6916 		if (!pullupmsg(mp, -1)) {
6917 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6918 			    DROPPER(ipss, ipds_esp_nomem),
6919 			    &ipss->ipsec_dropper);
6920 			return (B_FALSE);
6921 		}
6922 
6923 		ipha = (ipha_t *)mp->b_rptr;
6924 	}
6925 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
6926 	if (*spi == 0) {
6927 		/* UDP packet - remove 0-spi. */
6928 		shift = sizeof (uint32_t);
6929 	} else {
6930 		/* ESP-in-UDP packet - reduce to ESP. */
6931 		ipha->ipha_protocol = IPPROTO_ESP;
6932 		shift = sizeof (udpha_t);
6933 	}
6934 
6935 	/* Fix IP header */
6936 	ipha->ipha_length = htons(plen - shift);
6937 	ipha->ipha_hdr_checksum = 0;
6938 
6939 	orptr = mp->b_rptr;
6940 	mp->b_rptr += shift;
6941 
6942 	udpha = (udpha_t *)(orptr + iph_len);
6943 	if (*spi == 0) {
6944 		ASSERT((uint8_t *)ipha == orptr);
6945 		udpha->uha_length = htons(plen - shift - iph_len);
6946 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
6947 		esp_ports = 0;
6948 	} else {
6949 		esp_ports = *((uint32_t *)udpha);
6950 		ASSERT(esp_ports != 0);
6951 	}
6952 	ovbcopy(orptr, orptr + shift, iph_len);
6953 	if (esp_ports != 0) /* Punt up for ESP processing. */ {
6954 		ipha = (ipha_t *)(orptr + shift);
6955 
6956 		free_ire = (ire == NULL);
6957 		if (free_ire) {
6958 			/* Re-acquire ire. */
6959 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
6960 			    ipss->ipsec_netstack->netstack_ip);
6961 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
6962 				if (ire != NULL)
6963 					ire_refrele(ire);
6964 				/*
6965 				 * Do a regular freemsg(), as this is an IP
6966 				 * error (no local route) not an IPsec one.
6967 				 */
6968 				freemsg(mp);
6969 			}
6970 		}
6971 
6972 		ip_proto_input(q, mp, ipha, ire, recv_ill, esp_ports);
6973 		if (free_ire)
6974 			ire_refrele(ire);
6975 	}
6976 
6977 	return (esp_ports == 0);
6978 }
6979 
6980 /*
6981  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6982  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6983  * Caller is responsible for dropping references to the conn, and freeing
6984  * first_mp.
6985  *
6986  * IPQoS Notes
6987  * Before sending it to the client, invoke IPPF processing. Policy processing
6988  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6989  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6990  * ip_wput_local, ip_policy is false.
6991  */
6992 static void
6993 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
6994     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
6995     boolean_t ip_policy)
6996 {
6997 	boolean_t	mctl_present = (first_mp != NULL);
6998 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
6999 	uint32_t	ill_index;
7000 	ip_stack_t	*ipst = recv_ill->ill_ipst;
7001 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
7002 
7003 	ASSERT(ill != NULL);
7004 
7005 	if (mctl_present)
7006 		first_mp->b_cont = mp;
7007 	else
7008 		first_mp = mp;
7009 
7010 	if (CONN_UDP_FLOWCTLD(connp)) {
7011 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
7012 		freemsg(first_mp);
7013 		return;
7014 	}
7015 
7016 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
7017 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
7018 		    NULL, mctl_present);
7019 		if (first_mp == NULL) {
7020 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7021 			return;	/* Freed by ipsec_check_inbound_policy(). */
7022 		}
7023 	}
7024 	if (mctl_present)
7025 		freeb(first_mp);
7026 
7027 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
7028 	if (connp->conn_udp->udp_nat_t_endpoint) {
7029 		if (mctl_present) {
7030 			/* mctl_present *shouldn't* happen. */
7031 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
7032 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
7033 			    &ipss->ipsec_dropper);
7034 			return;
7035 		}
7036 
7037 		if (!zero_spi_check(ill->ill_rq, mp, NULL, recv_ill, ipss))
7038 			return;
7039 	}
7040 
7041 	/* Handle options. */
7042 	if (connp->conn_recvif)
7043 		in_flags = IPF_RECVIF;
7044 	/*
7045 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7046 	 * passed to ip_add_info is based on IP version of connp.
7047 	 */
7048 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7049 		if (connp->conn_af_isv6) {
7050 			/*
7051 			 * V6 only needs index
7052 			 */
7053 			in_flags |= IPF_RECVIF;
7054 		} else {
7055 			/*
7056 			 * V4 needs index + matching address.
7057 			 */
7058 			in_flags |= IPF_RECVADDR;
7059 		}
7060 	}
7061 
7062 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7063 		in_flags |= IPF_RECVSLLA;
7064 
7065 	/*
7066 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7067 	 * freed if the packet is dropped. The caller will do so.
7068 	 */
7069 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7070 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7071 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7072 		if (mp == NULL) {
7073 			return;
7074 		}
7075 	}
7076 	if ((in_flags != 0) &&
7077 	    (mp->b_datap->db_type != M_CTL)) {
7078 		/*
7079 		 * The actual data will be contained in b_cont
7080 		 * upon successful return of the following call
7081 		 * else original mblk is returned
7082 		 */
7083 		ASSERT(recv_ill != NULL);
7084 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7085 		    ipst);
7086 	}
7087 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7088 	/* Send it upstream */
7089 	(connp->conn_recv)(connp, mp, NULL);
7090 }
7091 
7092 /*
7093  * Fanout for UDP packets.
7094  * The caller puts <fport, lport> in the ports parameter.
7095  *
7096  * If SO_REUSEADDR is set all multicast and broadcast packets
7097  * will be delivered to all streams bound to the same port.
7098  *
7099  * Zones notes:
7100  * Multicast and broadcast packets will be distributed to streams in all zones.
7101  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7102  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7103  * packets. To maintain this behavior with multiple zones, the conns are grouped
7104  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7105  * each zone. If unset, all the following conns in the same zone are skipped.
7106  */
7107 static void
7108 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7109     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7110     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7111 {
7112 	uint32_t	dstport, srcport;
7113 	ipaddr_t	dst;
7114 	mblk_t		*first_mp;
7115 	boolean_t	secure;
7116 	in6_addr_t	v6src;
7117 	conn_t		*connp;
7118 	connf_t		*connfp;
7119 	conn_t		*first_connp;
7120 	conn_t		*next_connp;
7121 	mblk_t		*mp1, *first_mp1;
7122 	ipaddr_t	src;
7123 	zoneid_t	last_zoneid;
7124 	boolean_t	reuseaddr;
7125 	boolean_t	shared_addr;
7126 	boolean_t	unlabeled;
7127 	ip_stack_t	*ipst;
7128 
7129 	ASSERT(recv_ill != NULL);
7130 	ipst = recv_ill->ill_ipst;
7131 
7132 	first_mp = mp;
7133 	if (mctl_present) {
7134 		mp = first_mp->b_cont;
7135 		first_mp->b_cont = NULL;
7136 		secure = ipsec_in_is_secure(first_mp);
7137 		ASSERT(mp != NULL);
7138 	} else {
7139 		first_mp = NULL;
7140 		secure = B_FALSE;
7141 	}
7142 
7143 	/* Extract ports in net byte order */
7144 	dstport = htons(ntohl(ports) & 0xFFFF);
7145 	srcport = htons(ntohl(ports) >> 16);
7146 	dst = ipha->ipha_dst;
7147 	src = ipha->ipha_src;
7148 
7149 	unlabeled = B_FALSE;
7150 	if (is_system_labeled())
7151 		/* Cred cannot be null on IPv4 */
7152 		unlabeled = (crgetlabel(DB_CRED(mp))->tsl_flags &
7153 		    TSLF_UNLABELED) != 0;
7154 	shared_addr = (zoneid == ALL_ZONES);
7155 	if (shared_addr) {
7156 		/*
7157 		 * No need to handle exclusive-stack zones since ALL_ZONES
7158 		 * only applies to the shared stack.
7159 		 */
7160 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7161 		/*
7162 		 * If no shared MLP is found, tsol_mlp_findzone returns
7163 		 * ALL_ZONES.  In that case, we assume it's SLP, and
7164 		 * search for the zone based on the packet label.
7165 		 *
7166 		 * If there is such a zone, we prefer to find a
7167 		 * connection in it.  Otherwise, we look for a
7168 		 * MAC-exempt connection in any zone whose label
7169 		 * dominates the default label on the packet.
7170 		 */
7171 		if (zoneid == ALL_ZONES)
7172 			zoneid = tsol_packet_to_zoneid(mp);
7173 		else
7174 			unlabeled = B_FALSE;
7175 	}
7176 
7177 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7178 	mutex_enter(&connfp->connf_lock);
7179 	connp = connfp->connf_head;
7180 	if (!broadcast && !CLASSD(dst)) {
7181 		/*
7182 		 * Not broadcast or multicast. Send to the one (first)
7183 		 * client we find. No need to check conn_wantpacket()
7184 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7185 		 * IPv4 unicast packets.
7186 		 */
7187 		while ((connp != NULL) &&
7188 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7189 		    (!IPCL_ZONE_MATCH(connp, zoneid) &&
7190 		    !(unlabeled && connp->conn_mac_exempt)))) {
7191 			/*
7192 			 * We keep searching since the conn did not match,
7193 			 * or its zone did not match and it is not either
7194 			 * an allzones conn or a mac exempt conn (if the
7195 			 * sender is unlabeled.)
7196 			 */
7197 			connp = connp->conn_next;
7198 		}
7199 
7200 		if (connp == NULL || connp->conn_upq == NULL)
7201 			goto notfound;
7202 
7203 		if (is_system_labeled() &&
7204 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7205 		    connp))
7206 			goto notfound;
7207 
7208 		CONN_INC_REF(connp);
7209 		mutex_exit(&connfp->connf_lock);
7210 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7211 		    flags, recv_ill, ip_policy);
7212 		IP_STAT(ipst, ip_udp_fannorm);
7213 		CONN_DEC_REF(connp);
7214 		return;
7215 	}
7216 
7217 	/*
7218 	 * Broadcast and multicast case
7219 	 *
7220 	 * Need to check conn_wantpacket().
7221 	 * If SO_REUSEADDR has been set on the first we send the
7222 	 * packet to all clients that have joined the group and
7223 	 * match the port.
7224 	 */
7225 
7226 	while (connp != NULL) {
7227 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7228 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7229 		    (!is_system_labeled() ||
7230 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7231 		    connp)))
7232 			break;
7233 		connp = connp->conn_next;
7234 	}
7235 
7236 	if (connp == NULL || connp->conn_upq == NULL)
7237 		goto notfound;
7238 
7239 	first_connp = connp;
7240 	/*
7241 	 * When SO_REUSEADDR is not set, send the packet only to the first
7242 	 * matching connection in its zone by keeping track of the zoneid.
7243 	 */
7244 	reuseaddr = first_connp->conn_reuseaddr;
7245 	last_zoneid = first_connp->conn_zoneid;
7246 
7247 	CONN_INC_REF(connp);
7248 	connp = connp->conn_next;
7249 	for (;;) {
7250 		while (connp != NULL) {
7251 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7252 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7253 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7254 			    (!is_system_labeled() ||
7255 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7256 			    shared_addr, connp)))
7257 				break;
7258 			connp = connp->conn_next;
7259 		}
7260 		/*
7261 		 * Just copy the data part alone. The mctl part is
7262 		 * needed just for verifying policy and it is never
7263 		 * sent up.
7264 		 */
7265 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7266 		    ((mp1 = copymsg(mp)) == NULL))) {
7267 			/*
7268 			 * No more interested clients or memory
7269 			 * allocation failed
7270 			 */
7271 			connp = first_connp;
7272 			break;
7273 		}
7274 		if (connp->conn_zoneid != last_zoneid) {
7275 			/*
7276 			 * Update the zoneid so that the packet isn't sent to
7277 			 * any more conns in the same zone unless SO_REUSEADDR
7278 			 * is set.
7279 			 */
7280 			reuseaddr = connp->conn_reuseaddr;
7281 			last_zoneid = connp->conn_zoneid;
7282 		}
7283 		if (first_mp != NULL) {
7284 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7285 			    ipsec_info_type == IPSEC_IN);
7286 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7287 			    ipst->ips_netstack);
7288 			if (first_mp1 == NULL) {
7289 				freemsg(mp1);
7290 				connp = first_connp;
7291 				break;
7292 			}
7293 		} else {
7294 			first_mp1 = NULL;
7295 		}
7296 		CONN_INC_REF(connp);
7297 		mutex_exit(&connfp->connf_lock);
7298 		/*
7299 		 * IPQoS notes: We don't send the packet for policy
7300 		 * processing here, will do it for the last one (below).
7301 		 * i.e. we do it per-packet now, but if we do policy
7302 		 * processing per-conn, then we would need to do it
7303 		 * here too.
7304 		 */
7305 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7306 		    ipha, flags, recv_ill, B_FALSE);
7307 		mutex_enter(&connfp->connf_lock);
7308 		/* Follow the next pointer before releasing the conn. */
7309 		next_connp = connp->conn_next;
7310 		IP_STAT(ipst, ip_udp_fanmb);
7311 		CONN_DEC_REF(connp);
7312 		connp = next_connp;
7313 	}
7314 
7315 	/* Last one.  Send it upstream. */
7316 	mutex_exit(&connfp->connf_lock);
7317 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7318 	    recv_ill, ip_policy);
7319 	IP_STAT(ipst, ip_udp_fanmb);
7320 	CONN_DEC_REF(connp);
7321 	return;
7322 
7323 notfound:
7324 
7325 	mutex_exit(&connfp->connf_lock);
7326 	IP_STAT(ipst, ip_udp_fanothers);
7327 	/*
7328 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7329 	 * have already been matched above, since they live in the IPv4
7330 	 * fanout tables. This implies we only need to
7331 	 * check for IPv6 in6addr_any endpoints here.
7332 	 * Thus we compare using ipv6_all_zeros instead of the destination
7333 	 * address, except for the multicast group membership lookup which
7334 	 * uses the IPv4 destination.
7335 	 */
7336 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7337 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7338 	mutex_enter(&connfp->connf_lock);
7339 	connp = connfp->connf_head;
7340 	if (!broadcast && !CLASSD(dst)) {
7341 		while (connp != NULL) {
7342 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7343 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7344 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7345 			    !connp->conn_ipv6_v6only)
7346 				break;
7347 			connp = connp->conn_next;
7348 		}
7349 
7350 		if (connp != NULL && is_system_labeled() &&
7351 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7352 		    connp))
7353 			connp = NULL;
7354 
7355 		if (connp == NULL || connp->conn_upq == NULL) {
7356 			/*
7357 			 * No one bound to this port.  Is
7358 			 * there a client that wants all
7359 			 * unclaimed datagrams?
7360 			 */
7361 			mutex_exit(&connfp->connf_lock);
7362 
7363 			if (mctl_present)
7364 				first_mp->b_cont = mp;
7365 			else
7366 				first_mp = mp;
7367 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7368 			    connf_head != NULL) {
7369 				ip_fanout_proto(q, first_mp, ill, ipha,
7370 				    flags | IP_FF_RAWIP, mctl_present,
7371 				    ip_policy, recv_ill, zoneid);
7372 			} else {
7373 				if (ip_fanout_send_icmp(q, first_mp, flags,
7374 				    ICMP_DEST_UNREACHABLE,
7375 				    ICMP_PORT_UNREACHABLE,
7376 				    mctl_present, zoneid, ipst)) {
7377 					BUMP_MIB(ill->ill_ip_mib,
7378 					    udpIfStatsNoPorts);
7379 				}
7380 			}
7381 			return;
7382 		}
7383 
7384 		CONN_INC_REF(connp);
7385 		mutex_exit(&connfp->connf_lock);
7386 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7387 		    flags, recv_ill, ip_policy);
7388 		CONN_DEC_REF(connp);
7389 		return;
7390 	}
7391 	/*
7392 	 * IPv4 multicast packet being delivered to an AF_INET6
7393 	 * in6addr_any endpoint.
7394 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7395 	 * and not conn_wantpacket_v6() since any multicast membership is
7396 	 * for an IPv4-mapped multicast address.
7397 	 * The packet is sent to all clients in all zones that have joined the
7398 	 * group and match the port.
7399 	 */
7400 	while (connp != NULL) {
7401 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7402 		    srcport, v6src) &&
7403 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7404 		    (!is_system_labeled() ||
7405 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7406 		    connp)))
7407 			break;
7408 		connp = connp->conn_next;
7409 	}
7410 
7411 	if (connp == NULL || connp->conn_upq == NULL) {
7412 		/*
7413 		 * No one bound to this port.  Is
7414 		 * there a client that wants all
7415 		 * unclaimed datagrams?
7416 		 */
7417 		mutex_exit(&connfp->connf_lock);
7418 
7419 		if (mctl_present)
7420 			first_mp->b_cont = mp;
7421 		else
7422 			first_mp = mp;
7423 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7424 		    NULL) {
7425 			ip_fanout_proto(q, first_mp, ill, ipha,
7426 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7427 			    recv_ill, zoneid);
7428 		} else {
7429 			/*
7430 			 * We used to attempt to send an icmp error here, but
7431 			 * since this is known to be a multicast packet
7432 			 * and we don't send icmp errors in response to
7433 			 * multicast, just drop the packet and give up sooner.
7434 			 */
7435 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7436 			freemsg(first_mp);
7437 		}
7438 		return;
7439 	}
7440 
7441 	first_connp = connp;
7442 
7443 	CONN_INC_REF(connp);
7444 	connp = connp->conn_next;
7445 	for (;;) {
7446 		while (connp != NULL) {
7447 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7448 			    ipv6_all_zeros, srcport, v6src) &&
7449 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7450 			    (!is_system_labeled() ||
7451 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7452 			    shared_addr, connp)))
7453 				break;
7454 			connp = connp->conn_next;
7455 		}
7456 		/*
7457 		 * Just copy the data part alone. The mctl part is
7458 		 * needed just for verifying policy and it is never
7459 		 * sent up.
7460 		 */
7461 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7462 		    ((mp1 = copymsg(mp)) == NULL))) {
7463 			/*
7464 			 * No more intested clients or memory
7465 			 * allocation failed
7466 			 */
7467 			connp = first_connp;
7468 			break;
7469 		}
7470 		if (first_mp != NULL) {
7471 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7472 			    ipsec_info_type == IPSEC_IN);
7473 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7474 			    ipst->ips_netstack);
7475 			if (first_mp1 == NULL) {
7476 				freemsg(mp1);
7477 				connp = first_connp;
7478 				break;
7479 			}
7480 		} else {
7481 			first_mp1 = NULL;
7482 		}
7483 		CONN_INC_REF(connp);
7484 		mutex_exit(&connfp->connf_lock);
7485 		/*
7486 		 * IPQoS notes: We don't send the packet for policy
7487 		 * processing here, will do it for the last one (below).
7488 		 * i.e. we do it per-packet now, but if we do policy
7489 		 * processing per-conn, then we would need to do it
7490 		 * here too.
7491 		 */
7492 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7493 		    ipha, flags, recv_ill, B_FALSE);
7494 		mutex_enter(&connfp->connf_lock);
7495 		/* Follow the next pointer before releasing the conn. */
7496 		next_connp = connp->conn_next;
7497 		CONN_DEC_REF(connp);
7498 		connp = next_connp;
7499 	}
7500 
7501 	/* Last one.  Send it upstream. */
7502 	mutex_exit(&connfp->connf_lock);
7503 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7504 	    recv_ill, ip_policy);
7505 	CONN_DEC_REF(connp);
7506 }
7507 
7508 /*
7509  * Complete the ip_wput header so that it
7510  * is possible to generate ICMP
7511  * errors.
7512  */
7513 int
7514 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7515 {
7516 	ire_t *ire;
7517 
7518 	if (ipha->ipha_src == INADDR_ANY) {
7519 		ire = ire_lookup_local(zoneid, ipst);
7520 		if (ire == NULL) {
7521 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7522 			return (1);
7523 		}
7524 		ipha->ipha_src = ire->ire_addr;
7525 		ire_refrele(ire);
7526 	}
7527 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7528 	ipha->ipha_hdr_checksum = 0;
7529 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7530 	return (0);
7531 }
7532 
7533 /*
7534  * Nobody should be sending
7535  * packets up this stream
7536  */
7537 static void
7538 ip_lrput(queue_t *q, mblk_t *mp)
7539 {
7540 	mblk_t *mp1;
7541 
7542 	switch (mp->b_datap->db_type) {
7543 	case M_FLUSH:
7544 		/* Turn around */
7545 		if (*mp->b_rptr & FLUSHW) {
7546 			*mp->b_rptr &= ~FLUSHR;
7547 			qreply(q, mp);
7548 			return;
7549 		}
7550 		break;
7551 	}
7552 	/* Could receive messages that passed through ar_rput */
7553 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7554 		mp1->b_prev = mp1->b_next = NULL;
7555 	freemsg(mp);
7556 }
7557 
7558 /* Nobody should be sending packets down this stream */
7559 /* ARGSUSED */
7560 void
7561 ip_lwput(queue_t *q, mblk_t *mp)
7562 {
7563 	freemsg(mp);
7564 }
7565 
7566 /*
7567  * Move the first hop in any source route to ipha_dst and remove that part of
7568  * the source route.  Called by other protocols.  Errors in option formatting
7569  * are ignored - will be handled by ip_wput_options Return the final
7570  * destination (either ipha_dst or the last entry in a source route.)
7571  */
7572 ipaddr_t
7573 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7574 {
7575 	ipoptp_t	opts;
7576 	uchar_t		*opt;
7577 	uint8_t		optval;
7578 	uint8_t		optlen;
7579 	ipaddr_t	dst;
7580 	int		i;
7581 	ire_t		*ire;
7582 	ip_stack_t	*ipst = ns->netstack_ip;
7583 
7584 	ip2dbg(("ip_massage_options\n"));
7585 	dst = ipha->ipha_dst;
7586 	for (optval = ipoptp_first(&opts, ipha);
7587 	    optval != IPOPT_EOL;
7588 	    optval = ipoptp_next(&opts)) {
7589 		opt = opts.ipoptp_cur;
7590 		switch (optval) {
7591 			uint8_t off;
7592 		case IPOPT_SSRR:
7593 		case IPOPT_LSRR:
7594 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7595 				ip1dbg(("ip_massage_options: bad src route\n"));
7596 				break;
7597 			}
7598 			optlen = opts.ipoptp_len;
7599 			off = opt[IPOPT_OFFSET];
7600 			off--;
7601 		redo_srr:
7602 			if (optlen < IP_ADDR_LEN ||
7603 			    off > optlen - IP_ADDR_LEN) {
7604 				/* End of source route */
7605 				ip1dbg(("ip_massage_options: end of SR\n"));
7606 				break;
7607 			}
7608 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7609 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7610 			    ntohl(dst)));
7611 			/*
7612 			 * Check if our address is present more than
7613 			 * once as consecutive hops in source route.
7614 			 * XXX verify per-interface ip_forwarding
7615 			 * for source route?
7616 			 */
7617 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7618 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7619 			if (ire != NULL) {
7620 				ire_refrele(ire);
7621 				off += IP_ADDR_LEN;
7622 				goto redo_srr;
7623 			}
7624 			if (dst == htonl(INADDR_LOOPBACK)) {
7625 				ip1dbg(("ip_massage_options: loopback addr in "
7626 				    "source route!\n"));
7627 				break;
7628 			}
7629 			/*
7630 			 * Update ipha_dst to be the first hop and remove the
7631 			 * first hop from the source route (by overwriting
7632 			 * part of the option with NOP options).
7633 			 */
7634 			ipha->ipha_dst = dst;
7635 			/* Put the last entry in dst */
7636 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7637 			    3;
7638 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7639 
7640 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7641 			    ntohl(dst)));
7642 			/* Move down and overwrite */
7643 			opt[IP_ADDR_LEN] = opt[0];
7644 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7645 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7646 			for (i = 0; i < IP_ADDR_LEN; i++)
7647 				opt[i] = IPOPT_NOP;
7648 			break;
7649 		}
7650 	}
7651 	return (dst);
7652 }
7653 
7654 /*
7655  * Return the network mask
7656  * associated with the specified address.
7657  */
7658 ipaddr_t
7659 ip_net_mask(ipaddr_t addr)
7660 {
7661 	uchar_t	*up = (uchar_t *)&addr;
7662 	ipaddr_t mask = 0;
7663 	uchar_t	*maskp = (uchar_t *)&mask;
7664 
7665 #if defined(__i386) || defined(__amd64)
7666 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7667 #endif
7668 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7669 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7670 #endif
7671 	if (CLASSD(addr)) {
7672 		maskp[0] = 0xF0;
7673 		return (mask);
7674 	}
7675 
7676 	/* We assume Class E default netmask to be 32 */
7677 	if (CLASSE(addr))
7678 		return (0xffffffffU);
7679 
7680 	if (addr == 0)
7681 		return (0);
7682 	maskp[0] = 0xFF;
7683 	if ((up[0] & 0x80) == 0)
7684 		return (mask);
7685 
7686 	maskp[1] = 0xFF;
7687 	if ((up[0] & 0xC0) == 0x80)
7688 		return (mask);
7689 
7690 	maskp[2] = 0xFF;
7691 	if ((up[0] & 0xE0) == 0xC0)
7692 		return (mask);
7693 
7694 	/* Otherwise return no mask */
7695 	return ((ipaddr_t)0);
7696 }
7697 
7698 /*
7699  * Select an ill for the packet by considering load spreading across
7700  * a different ill in the group if dst_ill is part of some group.
7701  */
7702 ill_t *
7703 ip_newroute_get_dst_ill(ill_t *dst_ill)
7704 {
7705 	ill_t *ill;
7706 
7707 	/*
7708 	 * We schedule irrespective of whether the source address is
7709 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7710 	 */
7711 	ill = illgrp_scheduler(dst_ill);
7712 	if (ill == NULL)
7713 		return (NULL);
7714 
7715 	/*
7716 	 * For groups with names ip_sioctl_groupname ensures that all
7717 	 * ills are of same type. For groups without names, ifgrp_insert
7718 	 * ensures this.
7719 	 */
7720 	ASSERT(dst_ill->ill_type == ill->ill_type);
7721 
7722 	return (ill);
7723 }
7724 
7725 /*
7726  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7727  */
7728 ill_t *
7729 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6,
7730     ip_stack_t *ipst)
7731 {
7732 	ill_t *ret_ill;
7733 
7734 	ASSERT(ifindex != 0);
7735 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7736 	    ipst);
7737 	if (ret_ill == NULL ||
7738 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7739 		if (isv6) {
7740 			if (ill != NULL) {
7741 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7742 			} else {
7743 				BUMP_MIB(&ipst->ips_ip6_mib,
7744 				    ipIfStatsOutDiscards);
7745 			}
7746 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7747 			    "bad ifindex %d.\n", ifindex));
7748 		} else {
7749 			if (ill != NULL) {
7750 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7751 			} else {
7752 				BUMP_MIB(&ipst->ips_ip_mib,
7753 				    ipIfStatsOutDiscards);
7754 			}
7755 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7756 			    "bad ifindex %d.\n", ifindex));
7757 		}
7758 		if (ret_ill != NULL)
7759 			ill_refrele(ret_ill);
7760 		freemsg(first_mp);
7761 		return (NULL);
7762 	}
7763 
7764 	return (ret_ill);
7765 }
7766 
7767 /*
7768  * IPv4 -
7769  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7770  * out a packet to a destination address for which we do not have specific
7771  * (or sufficient) routing information.
7772  *
7773  * NOTE : These are the scopes of some of the variables that point at IRE,
7774  *	  which needs to be followed while making any future modifications
7775  *	  to avoid memory leaks.
7776  *
7777  *	- ire and sire are the entries looked up initially by
7778  *	  ire_ftable_lookup.
7779  *	- ipif_ire is used to hold the interface ire associated with
7780  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7781  *	  it before branching out to error paths.
7782  *	- save_ire is initialized before ire_create, so that ire returned
7783  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7784  *	  before breaking out of the switch.
7785  *
7786  *	Thus on failures, we have to REFRELE only ire and sire, if they
7787  *	are not NULL.
7788  */
7789 void
7790 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7791     zoneid_t zoneid, ip_stack_t *ipst)
7792 {
7793 	areq_t	*areq;
7794 	ipaddr_t gw = 0;
7795 	ire_t	*ire = NULL;
7796 	mblk_t	*res_mp;
7797 	ipaddr_t *addrp;
7798 	ipaddr_t nexthop_addr;
7799 	ipif_t  *src_ipif = NULL;
7800 	ill_t	*dst_ill = NULL;
7801 	ipha_t  *ipha;
7802 	ire_t	*sire = NULL;
7803 	mblk_t	*first_mp;
7804 	ire_t	*save_ire;
7805 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7806 	ushort_t ire_marks = 0;
7807 	boolean_t mctl_present;
7808 	ipsec_out_t *io;
7809 	mblk_t	*saved_mp;
7810 	ire_t	*first_sire = NULL;
7811 	mblk_t	*copy_mp = NULL;
7812 	mblk_t	*xmit_mp = NULL;
7813 	ipaddr_t save_dst;
7814 	uint32_t multirt_flags =
7815 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7816 	boolean_t multirt_is_resolvable;
7817 	boolean_t multirt_resolve_next;
7818 	boolean_t unspec_src;
7819 	boolean_t do_attach_ill = B_FALSE;
7820 	boolean_t ip_nexthop = B_FALSE;
7821 	tsol_ire_gw_secattr_t *attrp = NULL;
7822 	tsol_gcgrp_t *gcgrp = NULL;
7823 	tsol_gcgrp_addr_t ga;
7824 
7825 	if (ip_debug > 2) {
7826 		/* ip1dbg */
7827 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7828 	}
7829 
7830 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7831 	if (mctl_present) {
7832 		io = (ipsec_out_t *)first_mp->b_rptr;
7833 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7834 		ASSERT(zoneid == io->ipsec_out_zoneid);
7835 		ASSERT(zoneid != ALL_ZONES);
7836 	}
7837 
7838 	ipha = (ipha_t *)mp->b_rptr;
7839 
7840 	/* All multicast lookups come through ip_newroute_ipif() */
7841 	if (CLASSD(dst)) {
7842 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7843 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7844 		freemsg(first_mp);
7845 		return;
7846 	}
7847 
7848 	if (mctl_present && io->ipsec_out_attach_if) {
7849 		/* ip_grab_attach_ill returns a held ill */
7850 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7851 		    io->ipsec_out_ill_index, B_FALSE, ipst);
7852 
7853 		/* Failure case frees things for us. */
7854 		if (attach_ill == NULL)
7855 			return;
7856 
7857 		/*
7858 		 * Check if we need an ire that will not be
7859 		 * looked up by anybody else i.e. HIDDEN.
7860 		 */
7861 		if (ill_is_probeonly(attach_ill))
7862 			ire_marks = IRE_MARK_HIDDEN;
7863 	}
7864 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7865 		ip_nexthop = B_TRUE;
7866 		nexthop_addr = io->ipsec_out_nexthop_addr;
7867 	}
7868 	/*
7869 	 * If this IRE is created for forwarding or it is not for
7870 	 * traffic for congestion controlled protocols, mark it as temporary.
7871 	 */
7872 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7873 		ire_marks |= IRE_MARK_TEMPORARY;
7874 
7875 	/*
7876 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7877 	 * chain until it gets the most specific information available.
7878 	 * For example, we know that there is no IRE_CACHE for this dest,
7879 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7880 	 * ire_ftable_lookup will look up the gateway, etc.
7881 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7882 	 * to the destination, of equal netmask length in the forward table,
7883 	 * will be recursively explored. If no information is available
7884 	 * for the final gateway of that route, we force the returned ire
7885 	 * to be equal to sire using MATCH_IRE_PARENT.
7886 	 * At least, in this case we have a starting point (in the buckets)
7887 	 * to look for other routes to the destination in the forward table.
7888 	 * This is actually used only for multirouting, where a list
7889 	 * of routes has to be processed in sequence.
7890 	 *
7891 	 * In the process of coming up with the most specific information,
7892 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7893 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7894 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7895 	 * Two caveats when handling incomplete ire's in ip_newroute:
7896 	 * - we should be careful when accessing its ire_nce (specifically
7897 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7898 	 * - not all legacy code path callers are prepared to handle
7899 	 *   incomplete ire's, so we should not create/add incomplete
7900 	 *   ire_cache entries here. (See discussion about temporary solution
7901 	 *   further below).
7902 	 *
7903 	 * In order to minimize packet dropping, and to preserve existing
7904 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7905 	 * gateway, and instead use the IF_RESOLVER ire to send out
7906 	 * another request to ARP (this is achieved by passing the
7907 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7908 	 * arp response comes back in ip_wput_nondata, we will create
7909 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7910 	 *
7911 	 * Note that this is a temporary solution; the correct solution is
7912 	 * to create an incomplete  per-dst ire_cache entry, and send the
7913 	 * packet out when the gw's nce is resolved. In order to achieve this,
7914 	 * all packet processing must have been completed prior to calling
7915 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7916 	 * to be modified to accomodate this solution.
7917 	 */
7918 	if (ip_nexthop) {
7919 		/*
7920 		 * The first time we come here, we look for an IRE_INTERFACE
7921 		 * entry for the specified nexthop, set the dst to be the
7922 		 * nexthop address and create an IRE_CACHE entry for the
7923 		 * nexthop. The next time around, we are able to find an
7924 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7925 		 * nexthop address and create an IRE_CACHE entry for the
7926 		 * destination address via the specified nexthop.
7927 		 */
7928 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7929 		    MBLK_GETLABEL(mp), ipst);
7930 		if (ire != NULL) {
7931 			gw = nexthop_addr;
7932 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7933 		} else {
7934 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7935 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7936 			    MBLK_GETLABEL(mp),
7937 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
7938 			    ipst);
7939 			if (ire != NULL) {
7940 				dst = nexthop_addr;
7941 			}
7942 		}
7943 	} else if (attach_ill == NULL) {
7944 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7945 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
7946 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7947 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7948 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
7949 		    ipst);
7950 	} else {
7951 		/*
7952 		 * attach_ill is set only for communicating with
7953 		 * on-link hosts. So, don't look for DEFAULT.
7954 		 */
7955 		ipif_t	*attach_ipif;
7956 
7957 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
7958 		if (attach_ipif == NULL) {
7959 			ill_refrele(attach_ill);
7960 			goto icmp_err_ret;
7961 		}
7962 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
7963 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
7964 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
7965 		    MATCH_IRE_SECATTR, ipst);
7966 		ipif_refrele(attach_ipif);
7967 	}
7968 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7969 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7970 
7971 	/*
7972 	 * This loop is run only once in most cases.
7973 	 * We loop to resolve further routes only when the destination
7974 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7975 	 */
7976 	do {
7977 		/* Clear the previous iteration's values */
7978 		if (src_ipif != NULL) {
7979 			ipif_refrele(src_ipif);
7980 			src_ipif = NULL;
7981 		}
7982 		if (dst_ill != NULL) {
7983 			ill_refrele(dst_ill);
7984 			dst_ill = NULL;
7985 		}
7986 
7987 		multirt_resolve_next = B_FALSE;
7988 		/*
7989 		 * We check if packets have to be multirouted.
7990 		 * In this case, given the current <ire, sire> couple,
7991 		 * we look for the next suitable <ire, sire>.
7992 		 * This check is done in ire_multirt_lookup(),
7993 		 * which applies various criteria to find the next route
7994 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7995 		 * unchanged if it detects it has not been tried yet.
7996 		 */
7997 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7998 			ip3dbg(("ip_newroute: starting next_resolution "
7999 			    "with first_mp %p, tag %d\n",
8000 			    (void *)first_mp,
8001 			    MULTIRT_DEBUG_TAGGED(first_mp)));
8002 
8003 			ASSERT(sire != NULL);
8004 			multirt_is_resolvable =
8005 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
8006 			    MBLK_GETLABEL(mp), ipst);
8007 
8008 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
8009 			    "ire %p, sire %p\n",
8010 			    multirt_is_resolvable,
8011 			    (void *)ire, (void *)sire));
8012 
8013 			if (!multirt_is_resolvable) {
8014 				/*
8015 				 * No more multirt route to resolve; give up
8016 				 * (all routes resolved or no more
8017 				 * resolvable routes).
8018 				 */
8019 				if (ire != NULL) {
8020 					ire_refrele(ire);
8021 					ire = NULL;
8022 				}
8023 			} else {
8024 				ASSERT(sire != NULL);
8025 				ASSERT(ire != NULL);
8026 				/*
8027 				 * We simply use first_sire as a flag that
8028 				 * indicates if a resolvable multirt route
8029 				 * has already been found.
8030 				 * If it is not the case, we may have to send
8031 				 * an ICMP error to report that the
8032 				 * destination is unreachable.
8033 				 * We do not IRE_REFHOLD first_sire.
8034 				 */
8035 				if (first_sire == NULL) {
8036 					first_sire = sire;
8037 				}
8038 			}
8039 		}
8040 		if (ire == NULL) {
8041 			if (ip_debug > 3) {
8042 				/* ip2dbg */
8043 				pr_addr_dbg("ip_newroute: "
8044 				    "can't resolve %s\n", AF_INET, &dst);
8045 			}
8046 			ip3dbg(("ip_newroute: "
8047 			    "ire %p, sire %p, first_sire %p\n",
8048 			    (void *)ire, (void *)sire, (void *)first_sire));
8049 
8050 			if (sire != NULL) {
8051 				ire_refrele(sire);
8052 				sire = NULL;
8053 			}
8054 
8055 			if (first_sire != NULL) {
8056 				/*
8057 				 * At least one multirt route has been found
8058 				 * in the same call to ip_newroute();
8059 				 * there is no need to report an ICMP error.
8060 				 * first_sire was not IRE_REFHOLDed.
8061 				 */
8062 				MULTIRT_DEBUG_UNTAG(first_mp);
8063 				freemsg(first_mp);
8064 				return;
8065 			}
8066 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8067 			    RTA_DST, ipst);
8068 			if (attach_ill != NULL)
8069 				ill_refrele(attach_ill);
8070 			goto icmp_err_ret;
8071 		}
8072 
8073 		/*
8074 		 * Verify that the returned IRE does not have either
8075 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8076 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8077 		 */
8078 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8079 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8080 			if (attach_ill != NULL)
8081 				ill_refrele(attach_ill);
8082 			goto icmp_err_ret;
8083 		}
8084 		/*
8085 		 * Increment the ire_ob_pkt_count field for ire if it is an
8086 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8087 		 * increment the same for the parent IRE, sire, if it is some
8088 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8089 		 */
8090 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8091 			UPDATE_OB_PKT_COUNT(ire);
8092 			ire->ire_last_used_time = lbolt;
8093 		}
8094 
8095 		if (sire != NULL) {
8096 			gw = sire->ire_gateway_addr;
8097 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8098 			    IRE_INTERFACE)) == 0);
8099 			UPDATE_OB_PKT_COUNT(sire);
8100 			sire->ire_last_used_time = lbolt;
8101 		}
8102 		/*
8103 		 * We have a route to reach the destination.
8104 		 *
8105 		 * 1) If the interface is part of ill group, try to get a new
8106 		 *    ill taking load spreading into account.
8107 		 *
8108 		 * 2) After selecting the ill, get a source address that
8109 		 *    might create good inbound load spreading.
8110 		 *    ipif_select_source does this for us.
8111 		 *
8112 		 * If the application specified the ill (ifindex), we still
8113 		 * load spread. Only if the packets needs to go out
8114 		 * specifically on a given ill e.g. binding to
8115 		 * IPIF_NOFAILOVER address, then we don't try to use a
8116 		 * different ill for load spreading.
8117 		 */
8118 		if (attach_ill == NULL) {
8119 			/*
8120 			 * Don't perform outbound load spreading in the
8121 			 * case of an RTF_MULTIRT route, as we actually
8122 			 * typically want to replicate outgoing packets
8123 			 * through particular interfaces.
8124 			 */
8125 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8126 				dst_ill = ire->ire_ipif->ipif_ill;
8127 				/* for uniformity */
8128 				ill_refhold(dst_ill);
8129 			} else {
8130 				/*
8131 				 * If we are here trying to create an IRE_CACHE
8132 				 * for an offlink destination and have the
8133 				 * IRE_CACHE for the next hop and the latter is
8134 				 * using virtual IP source address selection i.e
8135 				 * it's ire->ire_ipif is pointing to a virtual
8136 				 * network interface (vni) then
8137 				 * ip_newroute_get_dst_ll() will return the vni
8138 				 * interface as the dst_ill. Since the vni is
8139 				 * virtual i.e not associated with any physical
8140 				 * interface, it cannot be the dst_ill, hence
8141 				 * in such a case call ip_newroute_get_dst_ll()
8142 				 * with the stq_ill instead of the ire_ipif ILL.
8143 				 * The function returns a refheld ill.
8144 				 */
8145 				if ((ire->ire_type == IRE_CACHE) &&
8146 				    IS_VNI(ire->ire_ipif->ipif_ill))
8147 					dst_ill = ip_newroute_get_dst_ill(
8148 					    ire->ire_stq->q_ptr);
8149 				else
8150 					dst_ill = ip_newroute_get_dst_ill(
8151 					    ire->ire_ipif->ipif_ill);
8152 			}
8153 			if (dst_ill == NULL) {
8154 				if (ip_debug > 2) {
8155 					pr_addr_dbg("ip_newroute: "
8156 					    "no dst ill for dst"
8157 					    " %s\n", AF_INET, &dst);
8158 				}
8159 				goto icmp_err_ret;
8160 			}
8161 		} else {
8162 			dst_ill = ire->ire_ipif->ipif_ill;
8163 			/* for uniformity */
8164 			ill_refhold(dst_ill);
8165 			/*
8166 			 * We should have found a route matching ill as we
8167 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
8168 			 * Rather than asserting, when there is a mismatch,
8169 			 * we just drop the packet.
8170 			 */
8171 			if (dst_ill != attach_ill) {
8172 				ip0dbg(("ip_newroute: Packet dropped as "
8173 				    "IPIF_NOFAILOVER ill is %s, "
8174 				    "ire->ire_ipif->ipif_ill is %s\n",
8175 				    attach_ill->ill_name,
8176 				    dst_ill->ill_name));
8177 				ill_refrele(attach_ill);
8178 				goto icmp_err_ret;
8179 			}
8180 		}
8181 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
8182 		if (attach_ill != NULL) {
8183 			ill_refrele(attach_ill);
8184 			attach_ill = NULL;
8185 			do_attach_ill = B_TRUE;
8186 		}
8187 		ASSERT(dst_ill != NULL);
8188 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8189 
8190 		/*
8191 		 * Pick the best source address from dst_ill.
8192 		 *
8193 		 * 1) If it is part of a multipathing group, we would
8194 		 *    like to spread the inbound packets across different
8195 		 *    interfaces. ipif_select_source picks a random source
8196 		 *    across the different ills in the group.
8197 		 *
8198 		 * 2) If it is not part of a multipathing group, we try
8199 		 *    to pick the source address from the destination
8200 		 *    route. Clustering assumes that when we have multiple
8201 		 *    prefixes hosted on an interface, the prefix of the
8202 		 *    source address matches the prefix of the destination
8203 		 *    route. We do this only if the address is not
8204 		 *    DEPRECATED.
8205 		 *
8206 		 * 3) If the conn is in a different zone than the ire, we
8207 		 *    need to pick a source address from the right zone.
8208 		 *
8209 		 * NOTE : If we hit case (1) above, the prefix of the source
8210 		 *	  address picked may not match the prefix of the
8211 		 *	  destination routes prefix as ipif_select_source
8212 		 *	  does not look at "dst" while picking a source
8213 		 *	  address.
8214 		 *	  If we want the same behavior as (2), we will need
8215 		 *	  to change the behavior of ipif_select_source.
8216 		 */
8217 		ASSERT(src_ipif == NULL);
8218 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8219 			/*
8220 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8221 			 * Check that the ipif matching the requested source
8222 			 * address still exists.
8223 			 */
8224 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8225 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8226 		}
8227 
8228 		unspec_src = (connp != NULL && connp->conn_unspec_src);
8229 
8230 		if (src_ipif == NULL &&
8231 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
8232 			ire_marks |= IRE_MARK_USESRC_CHECK;
8233 			if ((dst_ill->ill_group != NULL) ||
8234 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8235 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8236 			    ire->ire_zoneid != ALL_ZONES) ||
8237 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8238 				/*
8239 				 * If the destination is reachable via a
8240 				 * given gateway, the selected source address
8241 				 * should be in the same subnet as the gateway.
8242 				 * Otherwise, the destination is not reachable.
8243 				 *
8244 				 * If there are no interfaces on the same subnet
8245 				 * as the destination, ipif_select_source gives
8246 				 * first non-deprecated interface which might be
8247 				 * on a different subnet than the gateway.
8248 				 * This is not desirable. Hence pass the dst_ire
8249 				 * source address to ipif_select_source.
8250 				 * It is sure that the destination is reachable
8251 				 * with the dst_ire source address subnet.
8252 				 * So passing dst_ire source address to
8253 				 * ipif_select_source will make sure that the
8254 				 * selected source will be on the same subnet
8255 				 * as dst_ire source address.
8256 				 */
8257 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8258 				src_ipif = ipif_select_source(dst_ill, saddr,
8259 				    zoneid);
8260 				if (src_ipif == NULL) {
8261 					if (ip_debug > 2) {
8262 						pr_addr_dbg("ip_newroute: "
8263 						    "no src for dst %s ",
8264 						    AF_INET, &dst);
8265 						printf("through interface %s\n",
8266 						    dst_ill->ill_name);
8267 					}
8268 					goto icmp_err_ret;
8269 				}
8270 			} else {
8271 				src_ipif = ire->ire_ipif;
8272 				ASSERT(src_ipif != NULL);
8273 				/* hold src_ipif for uniformity */
8274 				ipif_refhold(src_ipif);
8275 			}
8276 		}
8277 
8278 		/*
8279 		 * Assign a source address while we have the conn.
8280 		 * We can't have ip_wput_ire pick a source address when the
8281 		 * packet returns from arp since we need to look at
8282 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8283 		 * going through arp.
8284 		 *
8285 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8286 		 *	  it uses ip6i to store this information.
8287 		 */
8288 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
8289 			ipha->ipha_src = src_ipif->ipif_src_addr;
8290 
8291 		if (ip_debug > 3) {
8292 			/* ip2dbg */
8293 			pr_addr_dbg("ip_newroute: first hop %s\n",
8294 			    AF_INET, &gw);
8295 		}
8296 		ip2dbg(("\tire type %s (%d)\n",
8297 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8298 
8299 		/*
8300 		 * The TTL of multirouted packets is bounded by the
8301 		 * ip_multirt_ttl ndd variable.
8302 		 */
8303 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8304 			/* Force TTL of multirouted packets */
8305 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8306 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8307 				ip2dbg(("ip_newroute: forcing multirt TTL "
8308 				    "to %d (was %d), dst 0x%08x\n",
8309 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8310 				    ntohl(sire->ire_addr)));
8311 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8312 			}
8313 		}
8314 		/*
8315 		 * At this point in ip_newroute(), ire is either the
8316 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8317 		 * destination or an IRE_INTERFACE type that should be used
8318 		 * to resolve an on-subnet destination or an on-subnet
8319 		 * next-hop gateway.
8320 		 *
8321 		 * In the IRE_CACHE case, we have the following :
8322 		 *
8323 		 * 1) src_ipif - used for getting a source address.
8324 		 *
8325 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8326 		 *    means packets using this IRE_CACHE will go out on
8327 		 *    dst_ill.
8328 		 *
8329 		 * 3) The IRE sire will point to the prefix that is the
8330 		 *    longest  matching route for the destination. These
8331 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8332 		 *
8333 		 *    The newly created IRE_CACHE entry for the off-subnet
8334 		 *    destination is tied to both the prefix route and the
8335 		 *    interface route used to resolve the next-hop gateway
8336 		 *    via the ire_phandle and ire_ihandle fields,
8337 		 *    respectively.
8338 		 *
8339 		 * In the IRE_INTERFACE case, we have the following :
8340 		 *
8341 		 * 1) src_ipif - used for getting a source address.
8342 		 *
8343 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8344 		 *    means packets using the IRE_CACHE that we will build
8345 		 *    here will go out on dst_ill.
8346 		 *
8347 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8348 		 *    to be created will only be tied to the IRE_INTERFACE
8349 		 *    that was derived from the ire_ihandle field.
8350 		 *
8351 		 *    If sire is non-NULL, it means the destination is
8352 		 *    off-link and we will first create the IRE_CACHE for the
8353 		 *    gateway. Next time through ip_newroute, we will create
8354 		 *    the IRE_CACHE for the final destination as described
8355 		 *    above.
8356 		 *
8357 		 * In both cases, after the current resolution has been
8358 		 * completed (or possibly initialised, in the IRE_INTERFACE
8359 		 * case), the loop may be re-entered to attempt the resolution
8360 		 * of another RTF_MULTIRT route.
8361 		 *
8362 		 * When an IRE_CACHE entry for the off-subnet destination is
8363 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8364 		 * for further processing in emission loops.
8365 		 */
8366 		save_ire = ire;
8367 		switch (ire->ire_type) {
8368 		case IRE_CACHE: {
8369 			ire_t	*ipif_ire;
8370 
8371 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8372 			if (gw == 0)
8373 				gw = ire->ire_gateway_addr;
8374 			/*
8375 			 * We need 3 ire's to create a new cache ire for an
8376 			 * off-link destination from the cache ire of the
8377 			 * gateway.
8378 			 *
8379 			 *	1. The prefix ire 'sire' (Note that this does
8380 			 *	   not apply to the conn_nexthop_set case)
8381 			 *	2. The cache ire of the gateway 'ire'
8382 			 *	3. The interface ire 'ipif_ire'
8383 			 *
8384 			 * We have (1) and (2). We lookup (3) below.
8385 			 *
8386 			 * If there is no interface route to the gateway,
8387 			 * it is a race condition, where we found the cache
8388 			 * but the interface route has been deleted.
8389 			 */
8390 			if (ip_nexthop) {
8391 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8392 			} else {
8393 				ipif_ire =
8394 				    ire_ihandle_lookup_offlink(ire, sire);
8395 			}
8396 			if (ipif_ire == NULL) {
8397 				ip1dbg(("ip_newroute: "
8398 				    "ire_ihandle_lookup_offlink failed\n"));
8399 				goto icmp_err_ret;
8400 			}
8401 
8402 			/*
8403 			 * Check cached gateway IRE for any security
8404 			 * attributes; if found, associate the gateway
8405 			 * credentials group to the destination IRE.
8406 			 */
8407 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8408 				mutex_enter(&attrp->igsa_lock);
8409 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8410 					GCGRP_REFHOLD(gcgrp);
8411 				mutex_exit(&attrp->igsa_lock);
8412 			}
8413 
8414 			/*
8415 			 * XXX For the source of the resolver mp,
8416 			 * we are using the same DL_UNITDATA_REQ
8417 			 * (from save_ire->ire_nce->nce_res_mp)
8418 			 * though the save_ire is not pointing at the same ill.
8419 			 * This is incorrect. We need to send it up to the
8420 			 * resolver to get the right res_mp. For ethernets
8421 			 * this may be okay (ill_type == DL_ETHER).
8422 			 */
8423 
8424 			ire = ire_create(
8425 			    (uchar_t *)&dst,		/* dest address */
8426 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8427 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8428 			    (uchar_t *)&gw,		/* gateway address */
8429 			    &save_ire->ire_max_frag,
8430 			    save_ire->ire_nce,		/* src nce */
8431 			    dst_ill->ill_rq,		/* recv-from queue */
8432 			    dst_ill->ill_wq,		/* send-to queue */
8433 			    IRE_CACHE,			/* IRE type */
8434 			    src_ipif,
8435 			    (sire != NULL) ?
8436 			    sire->ire_mask : 0, 	/* Parent mask */
8437 			    (sire != NULL) ?
8438 			    sire->ire_phandle : 0,	/* Parent handle */
8439 			    ipif_ire->ire_ihandle,	/* Interface handle */
8440 			    (sire != NULL) ? (sire->ire_flags &
8441 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8442 			    (sire != NULL) ?
8443 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8444 			    NULL,
8445 			    gcgrp,
8446 			    ipst);
8447 
8448 			if (ire == NULL) {
8449 				if (gcgrp != NULL) {
8450 					GCGRP_REFRELE(gcgrp);
8451 					gcgrp = NULL;
8452 				}
8453 				ire_refrele(ipif_ire);
8454 				ire_refrele(save_ire);
8455 				break;
8456 			}
8457 
8458 			/* reference now held by IRE */
8459 			gcgrp = NULL;
8460 
8461 			ire->ire_marks |= ire_marks;
8462 
8463 			/*
8464 			 * Prevent sire and ipif_ire from getting deleted.
8465 			 * The newly created ire is tied to both of them via
8466 			 * the phandle and ihandle respectively.
8467 			 */
8468 			if (sire != NULL) {
8469 				IRB_REFHOLD(sire->ire_bucket);
8470 				/* Has it been removed already ? */
8471 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8472 					IRB_REFRELE(sire->ire_bucket);
8473 					ire_refrele(ipif_ire);
8474 					ire_refrele(save_ire);
8475 					break;
8476 				}
8477 			}
8478 
8479 			IRB_REFHOLD(ipif_ire->ire_bucket);
8480 			/* Has it been removed already ? */
8481 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8482 				IRB_REFRELE(ipif_ire->ire_bucket);
8483 				if (sire != NULL)
8484 					IRB_REFRELE(sire->ire_bucket);
8485 				ire_refrele(ipif_ire);
8486 				ire_refrele(save_ire);
8487 				break;
8488 			}
8489 
8490 			xmit_mp = first_mp;
8491 			/*
8492 			 * In the case of multirouting, a copy
8493 			 * of the packet is done before its sending.
8494 			 * The copy is used to attempt another
8495 			 * route resolution, in a next loop.
8496 			 */
8497 			if (ire->ire_flags & RTF_MULTIRT) {
8498 				copy_mp = copymsg(first_mp);
8499 				if (copy_mp != NULL) {
8500 					xmit_mp = copy_mp;
8501 					MULTIRT_DEBUG_TAG(first_mp);
8502 				}
8503 			}
8504 			ire_add_then_send(q, ire, xmit_mp);
8505 			ire_refrele(save_ire);
8506 
8507 			/* Assert that sire is not deleted yet. */
8508 			if (sire != NULL) {
8509 				ASSERT(sire->ire_ptpn != NULL);
8510 				IRB_REFRELE(sire->ire_bucket);
8511 			}
8512 
8513 			/* Assert that ipif_ire is not deleted yet. */
8514 			ASSERT(ipif_ire->ire_ptpn != NULL);
8515 			IRB_REFRELE(ipif_ire->ire_bucket);
8516 			ire_refrele(ipif_ire);
8517 
8518 			/*
8519 			 * If copy_mp is not NULL, multirouting was
8520 			 * requested. We loop to initiate a next
8521 			 * route resolution attempt, starting from sire.
8522 			 */
8523 			if (copy_mp != NULL) {
8524 				/*
8525 				 * Search for the next unresolved
8526 				 * multirt route.
8527 				 */
8528 				copy_mp = NULL;
8529 				ipif_ire = NULL;
8530 				ire = NULL;
8531 				multirt_resolve_next = B_TRUE;
8532 				continue;
8533 			}
8534 			if (sire != NULL)
8535 				ire_refrele(sire);
8536 			ipif_refrele(src_ipif);
8537 			ill_refrele(dst_ill);
8538 			return;
8539 		}
8540 		case IRE_IF_NORESOLVER: {
8541 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8542 			    dst_ill->ill_resolver_mp == NULL) {
8543 				ip1dbg(("ip_newroute: dst_ill %p "
8544 				    "for IRE_IF_NORESOLVER ire %p has "
8545 				    "no ill_resolver_mp\n",
8546 				    (void *)dst_ill, (void *)ire));
8547 				break;
8548 			}
8549 
8550 			/*
8551 			 * TSol note: We are creating the ire cache for the
8552 			 * destination 'dst'. If 'dst' is offlink, going
8553 			 * through the first hop 'gw', the security attributes
8554 			 * of 'dst' must be set to point to the gateway
8555 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8556 			 * is possible that 'dst' is a potential gateway that is
8557 			 * referenced by some route that has some security
8558 			 * attributes. Thus in the former case, we need to do a
8559 			 * gcgrp_lookup of 'gw' while in the latter case we
8560 			 * need to do gcgrp_lookup of 'dst' itself.
8561 			 */
8562 			ga.ga_af = AF_INET;
8563 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8564 			    &ga.ga_addr);
8565 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8566 
8567 			ire = ire_create(
8568 			    (uchar_t *)&dst,		/* dest address */
8569 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8570 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8571 			    (uchar_t *)&gw,		/* gateway address */
8572 			    &save_ire->ire_max_frag,
8573 			    NULL,			/* no src nce */
8574 			    dst_ill->ill_rq,		/* recv-from queue */
8575 			    dst_ill->ill_wq,		/* send-to queue */
8576 			    IRE_CACHE,
8577 			    src_ipif,
8578 			    save_ire->ire_mask,		/* Parent mask */
8579 			    (sire != NULL) ?		/* Parent handle */
8580 			    sire->ire_phandle : 0,
8581 			    save_ire->ire_ihandle,	/* Interface handle */
8582 			    (sire != NULL) ? sire->ire_flags &
8583 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8584 			    &(save_ire->ire_uinfo),
8585 			    NULL,
8586 			    gcgrp,
8587 			    ipst);
8588 
8589 			if (ire == NULL) {
8590 				if (gcgrp != NULL) {
8591 					GCGRP_REFRELE(gcgrp);
8592 					gcgrp = NULL;
8593 				}
8594 				ire_refrele(save_ire);
8595 				break;
8596 			}
8597 
8598 			/* reference now held by IRE */
8599 			gcgrp = NULL;
8600 
8601 			ire->ire_marks |= ire_marks;
8602 
8603 			/* Prevent save_ire from getting deleted */
8604 			IRB_REFHOLD(save_ire->ire_bucket);
8605 			/* Has it been removed already ? */
8606 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8607 				IRB_REFRELE(save_ire->ire_bucket);
8608 				ire_refrele(save_ire);
8609 				break;
8610 			}
8611 
8612 			/*
8613 			 * In the case of multirouting, a copy
8614 			 * of the packet is made before it is sent.
8615 			 * The copy is used in the next
8616 			 * loop to attempt another resolution.
8617 			 */
8618 			xmit_mp = first_mp;
8619 			if ((sire != NULL) &&
8620 			    (sire->ire_flags & RTF_MULTIRT)) {
8621 				copy_mp = copymsg(first_mp);
8622 				if (copy_mp != NULL) {
8623 					xmit_mp = copy_mp;
8624 					MULTIRT_DEBUG_TAG(first_mp);
8625 				}
8626 			}
8627 			ire_add_then_send(q, ire, xmit_mp);
8628 
8629 			/* Assert that it is not deleted yet. */
8630 			ASSERT(save_ire->ire_ptpn != NULL);
8631 			IRB_REFRELE(save_ire->ire_bucket);
8632 			ire_refrele(save_ire);
8633 
8634 			if (copy_mp != NULL) {
8635 				/*
8636 				 * If we found a (no)resolver, we ignore any
8637 				 * trailing top priority IRE_CACHE in further
8638 				 * loops. This ensures that we do not omit any
8639 				 * (no)resolver.
8640 				 * This IRE_CACHE, if any, will be processed
8641 				 * by another thread entering ip_newroute().
8642 				 * IRE_CACHE entries, if any, will be processed
8643 				 * by another thread entering ip_newroute(),
8644 				 * (upon resolver response, for instance).
8645 				 * This aims to force parallel multirt
8646 				 * resolutions as soon as a packet must be sent.
8647 				 * In the best case, after the tx of only one
8648 				 * packet, all reachable routes are resolved.
8649 				 * Otherwise, the resolution of all RTF_MULTIRT
8650 				 * routes would require several emissions.
8651 				 */
8652 				multirt_flags &= ~MULTIRT_CACHEGW;
8653 
8654 				/*
8655 				 * Search for the next unresolved multirt
8656 				 * route.
8657 				 */
8658 				copy_mp = NULL;
8659 				save_ire = NULL;
8660 				ire = NULL;
8661 				multirt_resolve_next = B_TRUE;
8662 				continue;
8663 			}
8664 
8665 			/*
8666 			 * Don't need sire anymore
8667 			 */
8668 			if (sire != NULL)
8669 				ire_refrele(sire);
8670 
8671 			ipif_refrele(src_ipif);
8672 			ill_refrele(dst_ill);
8673 			return;
8674 		}
8675 		case IRE_IF_RESOLVER:
8676 			/*
8677 			 * We can't build an IRE_CACHE yet, but at least we
8678 			 * found a resolver that can help.
8679 			 */
8680 			res_mp = dst_ill->ill_resolver_mp;
8681 			if (!OK_RESOLVER_MP(res_mp))
8682 				break;
8683 
8684 			/*
8685 			 * To be at this point in the code with a non-zero gw
8686 			 * means that dst is reachable through a gateway that
8687 			 * we have never resolved.  By changing dst to the gw
8688 			 * addr we resolve the gateway first.
8689 			 * When ire_add_then_send() tries to put the IP dg
8690 			 * to dst, it will reenter ip_newroute() at which
8691 			 * time we will find the IRE_CACHE for the gw and
8692 			 * create another IRE_CACHE in case IRE_CACHE above.
8693 			 */
8694 			if (gw != INADDR_ANY) {
8695 				/*
8696 				 * The source ipif that was determined above was
8697 				 * relative to the destination address, not the
8698 				 * gateway's. If src_ipif was not taken out of
8699 				 * the IRE_IF_RESOLVER entry, we'll need to call
8700 				 * ipif_select_source() again.
8701 				 */
8702 				if (src_ipif != ire->ire_ipif) {
8703 					ipif_refrele(src_ipif);
8704 					src_ipif = ipif_select_source(dst_ill,
8705 					    gw, zoneid);
8706 					if (src_ipif == NULL) {
8707 						if (ip_debug > 2) {
8708 							pr_addr_dbg(
8709 							    "ip_newroute: no "
8710 							    "src for gw %s ",
8711 							    AF_INET, &gw);
8712 							printf("through "
8713 							    "interface %s\n",
8714 							    dst_ill->ill_name);
8715 						}
8716 						goto icmp_err_ret;
8717 					}
8718 				}
8719 				save_dst = dst;
8720 				dst = gw;
8721 				gw = INADDR_ANY;
8722 			}
8723 
8724 			/*
8725 			 * We obtain a partial IRE_CACHE which we will pass
8726 			 * along with the resolver query.  When the response
8727 			 * comes back it will be there ready for us to add.
8728 			 * The ire_max_frag is atomically set under the
8729 			 * irebucket lock in ire_add_v[46].
8730 			 */
8731 
8732 			ire = ire_create_mp(
8733 			    (uchar_t *)&dst,		/* dest address */
8734 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8735 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8736 			    (uchar_t *)&gw,		/* gateway address */
8737 			    NULL,			/* ire_max_frag */
8738 			    NULL,			/* no src nce */
8739 			    dst_ill->ill_rq,		/* recv-from queue */
8740 			    dst_ill->ill_wq,		/* send-to queue */
8741 			    IRE_CACHE,
8742 			    src_ipif,			/* Interface ipif */
8743 			    save_ire->ire_mask,		/* Parent mask */
8744 			    0,
8745 			    save_ire->ire_ihandle,	/* Interface handle */
8746 			    0,				/* flags if any */
8747 			    &(save_ire->ire_uinfo),
8748 			    NULL,
8749 			    NULL,
8750 			    ipst);
8751 
8752 			if (ire == NULL) {
8753 				ire_refrele(save_ire);
8754 				break;
8755 			}
8756 
8757 			if ((sire != NULL) &&
8758 			    (sire->ire_flags & RTF_MULTIRT)) {
8759 				copy_mp = copymsg(first_mp);
8760 				if (copy_mp != NULL)
8761 					MULTIRT_DEBUG_TAG(copy_mp);
8762 			}
8763 
8764 			ire->ire_marks |= ire_marks;
8765 
8766 			/*
8767 			 * Construct message chain for the resolver
8768 			 * of the form:
8769 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8770 			 * Packet could contain a IPSEC_OUT mp.
8771 			 *
8772 			 * NOTE : ire will be added later when the response
8773 			 * comes back from ARP. If the response does not
8774 			 * come back, ARP frees the packet. For this reason,
8775 			 * we can't REFHOLD the bucket of save_ire to prevent
8776 			 * deletions. We may not be able to REFRELE the bucket
8777 			 * if the response never comes back. Thus, before
8778 			 * adding the ire, ire_add_v4 will make sure that the
8779 			 * interface route does not get deleted. This is the
8780 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8781 			 * where we can always prevent deletions because of
8782 			 * the synchronous nature of adding IRES i.e
8783 			 * ire_add_then_send is called after creating the IRE.
8784 			 */
8785 			ASSERT(ire->ire_mp != NULL);
8786 			ire->ire_mp->b_cont = first_mp;
8787 			/* Have saved_mp handy, for cleanup if canput fails */
8788 			saved_mp = mp;
8789 			mp = copyb(res_mp);
8790 			if (mp == NULL) {
8791 				/* Prepare for cleanup */
8792 				mp = saved_mp; /* pkt */
8793 				ire_delete(ire); /* ire_mp */
8794 				ire = NULL;
8795 				ire_refrele(save_ire);
8796 				if (copy_mp != NULL) {
8797 					MULTIRT_DEBUG_UNTAG(copy_mp);
8798 					freemsg(copy_mp);
8799 					copy_mp = NULL;
8800 				}
8801 				break;
8802 			}
8803 			linkb(mp, ire->ire_mp);
8804 
8805 			/*
8806 			 * Fill in the source and dest addrs for the resolver.
8807 			 * NOTE: this depends on memory layouts imposed by
8808 			 * ill_init().
8809 			 */
8810 			areq = (areq_t *)mp->b_rptr;
8811 			addrp = (ipaddr_t *)((char *)areq +
8812 			    areq->areq_sender_addr_offset);
8813 			if (do_attach_ill) {
8814 				/*
8815 				 * This is bind to no failover case.
8816 				 * arp packet also must go out on attach_ill.
8817 				 */
8818 				ASSERT(ipha->ipha_src != NULL);
8819 				*addrp = ipha->ipha_src;
8820 			} else {
8821 				*addrp = save_ire->ire_src_addr;
8822 			}
8823 
8824 			ire_refrele(save_ire);
8825 			addrp = (ipaddr_t *)((char *)areq +
8826 			    areq->areq_target_addr_offset);
8827 			*addrp = dst;
8828 			/* Up to the resolver. */
8829 			if (canputnext(dst_ill->ill_rq) &&
8830 			    !(dst_ill->ill_arp_closing)) {
8831 				putnext(dst_ill->ill_rq, mp);
8832 				ire = NULL;
8833 				if (copy_mp != NULL) {
8834 					/*
8835 					 * If we found a resolver, we ignore
8836 					 * any trailing top priority IRE_CACHE
8837 					 * in the further loops. This ensures
8838 					 * that we do not omit any resolver.
8839 					 * IRE_CACHE entries, if any, will be
8840 					 * processed next time we enter
8841 					 * ip_newroute().
8842 					 */
8843 					multirt_flags &= ~MULTIRT_CACHEGW;
8844 					/*
8845 					 * Search for the next unresolved
8846 					 * multirt route.
8847 					 */
8848 					first_mp = copy_mp;
8849 					copy_mp = NULL;
8850 					/* Prepare the next resolution loop. */
8851 					mp = first_mp;
8852 					EXTRACT_PKT_MP(mp, first_mp,
8853 					    mctl_present);
8854 					if (mctl_present)
8855 						io = (ipsec_out_t *)
8856 						    first_mp->b_rptr;
8857 					ipha = (ipha_t *)mp->b_rptr;
8858 
8859 					ASSERT(sire != NULL);
8860 
8861 					dst = save_dst;
8862 					multirt_resolve_next = B_TRUE;
8863 					continue;
8864 				}
8865 
8866 				if (sire != NULL)
8867 					ire_refrele(sire);
8868 
8869 				/*
8870 				 * The response will come back in ip_wput
8871 				 * with db_type IRE_DB_TYPE.
8872 				 */
8873 				ipif_refrele(src_ipif);
8874 				ill_refrele(dst_ill);
8875 				return;
8876 			} else {
8877 				/* Prepare for cleanup */
8878 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8879 				    mp);
8880 				mp->b_cont = NULL;
8881 				freeb(mp); /* areq */
8882 				/*
8883 				 * this is an ire that is not added to the
8884 				 * cache. ire_freemblk will handle the release
8885 				 * of any resources associated with the ire.
8886 				 */
8887 				ire_delete(ire); /* ire_mp */
8888 				mp = saved_mp; /* pkt */
8889 				ire = NULL;
8890 				if (copy_mp != NULL) {
8891 					MULTIRT_DEBUG_UNTAG(copy_mp);
8892 					freemsg(copy_mp);
8893 					copy_mp = NULL;
8894 				}
8895 				break;
8896 			}
8897 		default:
8898 			break;
8899 		}
8900 	} while (multirt_resolve_next);
8901 
8902 	ip1dbg(("ip_newroute: dropped\n"));
8903 	/* Did this packet originate externally? */
8904 	if (mp->b_prev) {
8905 		mp->b_next = NULL;
8906 		mp->b_prev = NULL;
8907 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8908 	} else {
8909 		if (dst_ill != NULL) {
8910 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8911 		} else {
8912 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8913 		}
8914 	}
8915 	ASSERT(copy_mp == NULL);
8916 	MULTIRT_DEBUG_UNTAG(first_mp);
8917 	freemsg(first_mp);
8918 	if (ire != NULL)
8919 		ire_refrele(ire);
8920 	if (sire != NULL)
8921 		ire_refrele(sire);
8922 	if (src_ipif != NULL)
8923 		ipif_refrele(src_ipif);
8924 	if (dst_ill != NULL)
8925 		ill_refrele(dst_ill);
8926 	return;
8927 
8928 icmp_err_ret:
8929 	ip1dbg(("ip_newroute: no route\n"));
8930 	if (src_ipif != NULL)
8931 		ipif_refrele(src_ipif);
8932 	if (dst_ill != NULL)
8933 		ill_refrele(dst_ill);
8934 	if (sire != NULL)
8935 		ire_refrele(sire);
8936 	/* Did this packet originate externally? */
8937 	if (mp->b_prev) {
8938 		mp->b_next = NULL;
8939 		mp->b_prev = NULL;
8940 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8941 		q = WR(q);
8942 	} else {
8943 		/*
8944 		 * There is no outgoing ill, so just increment the
8945 		 * system MIB.
8946 		 */
8947 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
8948 		/*
8949 		 * Since ip_wput() isn't close to finished, we fill
8950 		 * in enough of the header for credible error reporting.
8951 		 */
8952 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
8953 			/* Failed */
8954 			MULTIRT_DEBUG_UNTAG(first_mp);
8955 			freemsg(first_mp);
8956 			if (ire != NULL)
8957 				ire_refrele(ire);
8958 			return;
8959 		}
8960 	}
8961 
8962 	/*
8963 	 * At this point we will have ire only if RTF_BLACKHOLE
8964 	 * or RTF_REJECT flags are set on the IRE. It will not
8965 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8966 	 */
8967 	if (ire != NULL) {
8968 		if (ire->ire_flags & RTF_BLACKHOLE) {
8969 			ire_refrele(ire);
8970 			MULTIRT_DEBUG_UNTAG(first_mp);
8971 			freemsg(first_mp);
8972 			return;
8973 		}
8974 		ire_refrele(ire);
8975 	}
8976 	if (ip_source_routed(ipha, ipst)) {
8977 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8978 		    zoneid, ipst);
8979 		return;
8980 	}
8981 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
8982 }
8983 
8984 ip_opt_info_t zero_info;
8985 
8986 /*
8987  * IPv4 -
8988  * ip_newroute_ipif is called by ip_wput_multicast and
8989  * ip_rput_forward_multicast whenever we need to send
8990  * out a packet to a destination address for which we do not have specific
8991  * routing information. It is used when the packet will be sent out
8992  * on a specific interface. It is also called by ip_wput() when IP_BOUND_IF
8993  * socket option is set or icmp error message wants to go out on a particular
8994  * interface for a unicast packet.
8995  *
8996  * In most cases, the destination address is resolved thanks to the ipif
8997  * intrinsic resolver. However, there are some cases where the call to
8998  * ip_newroute_ipif must take into account the potential presence of
8999  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
9000  * that uses the interface. This is specified through flags,
9001  * which can be a combination of:
9002  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
9003  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
9004  *   and flags. Additionally, the packet source address has to be set to
9005  *   the specified address. The caller is thus expected to set this flag
9006  *   if the packet has no specific source address yet.
9007  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
9008  *   flag, the resulting ire will inherit the flag. All unresolved routes
9009  *   to the destination must be explored in the same call to
9010  *   ip_newroute_ipif().
9011  */
9012 static void
9013 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
9014     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
9015 {
9016 	areq_t	*areq;
9017 	ire_t	*ire = NULL;
9018 	mblk_t	*res_mp;
9019 	ipaddr_t *addrp;
9020 	mblk_t *first_mp;
9021 	ire_t	*save_ire = NULL;
9022 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
9023 	ipif_t	*src_ipif = NULL;
9024 	ushort_t ire_marks = 0;
9025 	ill_t	*dst_ill = NULL;
9026 	boolean_t mctl_present;
9027 	ipsec_out_t *io;
9028 	ipha_t *ipha;
9029 	int	ihandle = 0;
9030 	mblk_t	*saved_mp;
9031 	ire_t   *fire = NULL;
9032 	mblk_t  *copy_mp = NULL;
9033 	boolean_t multirt_resolve_next;
9034 	boolean_t unspec_src;
9035 	ipaddr_t ipha_dst;
9036 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
9037 
9038 	/*
9039 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9040 	 * here for uniformity
9041 	 */
9042 	ipif_refhold(ipif);
9043 
9044 	/*
9045 	 * This loop is run only once in most cases.
9046 	 * We loop to resolve further routes only when the destination
9047 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9048 	 */
9049 	do {
9050 		if (dst_ill != NULL) {
9051 			ill_refrele(dst_ill);
9052 			dst_ill = NULL;
9053 		}
9054 		if (src_ipif != NULL) {
9055 			ipif_refrele(src_ipif);
9056 			src_ipif = NULL;
9057 		}
9058 		multirt_resolve_next = B_FALSE;
9059 
9060 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9061 		    ipif->ipif_ill->ill_name));
9062 
9063 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
9064 		if (mctl_present)
9065 			io = (ipsec_out_t *)first_mp->b_rptr;
9066 
9067 		ipha = (ipha_t *)mp->b_rptr;
9068 
9069 		/*
9070 		 * Save the packet destination address, we may need it after
9071 		 * the packet has been consumed.
9072 		 */
9073 		ipha_dst = ipha->ipha_dst;
9074 
9075 		/*
9076 		 * If the interface is a pt-pt interface we look for an
9077 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9078 		 * local_address and the pt-pt destination address. Otherwise
9079 		 * we just match the local address.
9080 		 * NOTE: dst could be different than ipha->ipha_dst in case
9081 		 * of sending igmp multicast packets over a point-to-point
9082 		 * connection.
9083 		 * Thus we must be careful enough to check ipha_dst to be a
9084 		 * multicast address, otherwise it will take xmit_if path for
9085 		 * multicast packets resulting into kernel stack overflow by
9086 		 * repeated calls to ip_newroute_ipif from ire_send().
9087 		 */
9088 		if (CLASSD(ipha_dst) &&
9089 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9090 			goto err_ret;
9091 		}
9092 
9093 		/*
9094 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9095 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9096 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9097 		 * propagate its flags to the new ire.
9098 		 */
9099 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9100 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9101 			ip2dbg(("ip_newroute_ipif: "
9102 			    "ipif_lookup_multi_ire("
9103 			    "ipif %p, dst %08x) = fire %p\n",
9104 			    (void *)ipif, ntohl(dst), (void *)fire));
9105 		}
9106 
9107 		if (mctl_present && io->ipsec_out_attach_if) {
9108 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
9109 			    io->ipsec_out_ill_index, B_FALSE, ipst);
9110 
9111 			/* Failure case frees things for us. */
9112 			if (attach_ill == NULL) {
9113 				ipif_refrele(ipif);
9114 				if (fire != NULL)
9115 					ire_refrele(fire);
9116 				return;
9117 			}
9118 
9119 			/*
9120 			 * Check if we need an ire that will not be
9121 			 * looked up by anybody else i.e. HIDDEN.
9122 			 */
9123 			if (ill_is_probeonly(attach_ill)) {
9124 				ire_marks = IRE_MARK_HIDDEN;
9125 			}
9126 			/*
9127 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
9128 			 * case.
9129 			 */
9130 			dst_ill = ipif->ipif_ill;
9131 			/* attach_ill has been refheld by ip_grab_attach_ill */
9132 			ASSERT(dst_ill == attach_ill);
9133 		} else {
9134 			/*
9135 			 * If the interface belongs to an interface group,
9136 			 * make sure the next possible interface in the group
9137 			 * is used.  This encourages load spreading among
9138 			 * peers in an interface group.
9139 			 * Note: load spreading is disabled for RTF_MULTIRT
9140 			 * routes.
9141 			 */
9142 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9143 			    (fire->ire_flags & RTF_MULTIRT)) {
9144 				/*
9145 				 * Don't perform outbound load spreading
9146 				 * in the case of an RTF_MULTIRT issued route,
9147 				 * we actually typically want to replicate
9148 				 * outgoing packets through particular
9149 				 * interfaces.
9150 				 */
9151 				dst_ill = ipif->ipif_ill;
9152 				ill_refhold(dst_ill);
9153 			} else {
9154 				dst_ill = ip_newroute_get_dst_ill(
9155 				    ipif->ipif_ill);
9156 			}
9157 			if (dst_ill == NULL) {
9158 				if (ip_debug > 2) {
9159 					pr_addr_dbg("ip_newroute_ipif: "
9160 					    "no dst ill for dst %s\n",
9161 					    AF_INET, &dst);
9162 				}
9163 				goto err_ret;
9164 			}
9165 		}
9166 
9167 		/*
9168 		 * Pick a source address preferring non-deprecated ones.
9169 		 * Unlike ip_newroute, we don't do any source address
9170 		 * selection here since for multicast it really does not help
9171 		 * in inbound load spreading as in the unicast case.
9172 		 */
9173 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9174 		    (fire->ire_flags & RTF_SETSRC)) {
9175 			/*
9176 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9177 			 * on that interface. This ire has RTF_SETSRC flag, so
9178 			 * the source address of the packet must be changed.
9179 			 * Check that the ipif matching the requested source
9180 			 * address still exists.
9181 			 */
9182 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9183 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9184 		}
9185 
9186 		unspec_src = (connp != NULL && connp->conn_unspec_src);
9187 
9188 		if (((!ipif->ipif_isv6 && ipif->ipif_lcl_addr == INADDR_ANY) ||
9189 		    (ipif->ipif_flags & (IPIF_DEPRECATED|IPIF_UP)) != IPIF_UP ||
9190 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9191 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9192 		    (src_ipif == NULL) &&
9193 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
9194 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9195 			if (src_ipif == NULL) {
9196 				if (ip_debug > 2) {
9197 					/* ip1dbg */
9198 					pr_addr_dbg("ip_newroute_ipif: "
9199 					    "no src for dst %s",
9200 					    AF_INET, &dst);
9201 				}
9202 				ip1dbg((" through interface %s\n",
9203 				    dst_ill->ill_name));
9204 				goto err_ret;
9205 			}
9206 			ipif_refrele(ipif);
9207 			ipif = src_ipif;
9208 			ipif_refhold(ipif);
9209 		}
9210 		if (src_ipif == NULL) {
9211 			src_ipif = ipif;
9212 			ipif_refhold(src_ipif);
9213 		}
9214 
9215 		/*
9216 		 * Assign a source address while we have the conn.
9217 		 * We can't have ip_wput_ire pick a source address when the
9218 		 * packet returns from arp since conn_unspec_src might be set
9219 		 * and we lose the conn when going through arp.
9220 		 */
9221 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
9222 			ipha->ipha_src = src_ipif->ipif_src_addr;
9223 
9224 		/*
9225 		 * In the case of IP_BOUND_IF and IP_PKTINFO, it is possible
9226 		 * that the outgoing interface does not have an interface ire.
9227 		 */
9228 		if (CLASSD(ipha_dst) && (connp == NULL ||
9229 		    connp->conn_outgoing_ill == NULL) &&
9230 		    infop->ip_opt_ill_index == 0) {
9231 			/* ipif_to_ire returns an held ire */
9232 			ire = ipif_to_ire(ipif);
9233 			if (ire == NULL)
9234 				goto err_ret;
9235 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9236 				goto err_ret;
9237 			/*
9238 			 * ihandle is needed when the ire is added to
9239 			 * cache table.
9240 			 */
9241 			save_ire = ire;
9242 			ihandle = save_ire->ire_ihandle;
9243 
9244 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9245 			    "flags %04x\n",
9246 			    (void *)ire, (void *)ipif, flags));
9247 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9248 			    (fire->ire_flags & RTF_MULTIRT)) {
9249 				/*
9250 				 * As requested by flags, an IRE_OFFSUBNET was
9251 				 * looked up on that interface. This ire has
9252 				 * RTF_MULTIRT flag, so the resolution loop will
9253 				 * be re-entered to resolve additional routes on
9254 				 * other interfaces. For that purpose, a copy of
9255 				 * the packet is performed at this point.
9256 				 */
9257 				fire->ire_last_used_time = lbolt;
9258 				copy_mp = copymsg(first_mp);
9259 				if (copy_mp) {
9260 					MULTIRT_DEBUG_TAG(copy_mp);
9261 				}
9262 			}
9263 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9264 			    (fire->ire_flags & RTF_SETSRC)) {
9265 				/*
9266 				 * As requested by flags, an IRE_OFFSUBET was
9267 				 * looked up on that interface. This ire has
9268 				 * RTF_SETSRC flag, so the source address of the
9269 				 * packet must be changed.
9270 				 */
9271 				ipha->ipha_src = fire->ire_src_addr;
9272 			}
9273 		} else {
9274 			ASSERT((connp == NULL) ||
9275 			    (connp->conn_outgoing_ill != NULL) ||
9276 			    (connp->conn_dontroute) ||
9277 			    infop->ip_opt_ill_index != 0);
9278 			/*
9279 			 * The only ways we can come here are:
9280 			 * 1) IP_BOUND_IF socket option is set
9281 			 * 2) SO_DONTROUTE socket option is set
9282 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9283 			 * In all cases, the new ire will not be added
9284 			 * into cache table.
9285 			 */
9286 			ire_marks |= IRE_MARK_NOADD;
9287 		}
9288 
9289 		switch (ipif->ipif_net_type) {
9290 		case IRE_IF_NORESOLVER: {
9291 			/* We have what we need to build an IRE_CACHE. */
9292 
9293 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9294 			    (dst_ill->ill_resolver_mp == NULL)) {
9295 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9296 				    "for IRE_IF_NORESOLVER ire %p has "
9297 				    "no ill_resolver_mp\n",
9298 				    (void *)dst_ill, (void *)ire));
9299 				break;
9300 			}
9301 
9302 			/*
9303 			 * The new ire inherits the IRE_OFFSUBNET flags
9304 			 * and source address, if this was requested.
9305 			 */
9306 			ire = ire_create(
9307 			    (uchar_t *)&dst,		/* dest address */
9308 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9309 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9310 			    NULL,			/* gateway address */
9311 			    &ipif->ipif_mtu,
9312 			    NULL,			/* no src nce */
9313 			    dst_ill->ill_rq,		/* recv-from queue */
9314 			    dst_ill->ill_wq,		/* send-to queue */
9315 			    IRE_CACHE,
9316 			    src_ipif,
9317 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9318 			    (fire != NULL) ?		/* Parent handle */
9319 			    fire->ire_phandle : 0,
9320 			    ihandle,			/* Interface handle */
9321 			    (fire != NULL) ?
9322 			    (fire->ire_flags &
9323 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9324 			    (save_ire == NULL ? &ire_uinfo_null :
9325 			    &save_ire->ire_uinfo),
9326 			    NULL,
9327 			    NULL,
9328 			    ipst);
9329 
9330 			if (ire == NULL) {
9331 				if (save_ire != NULL)
9332 					ire_refrele(save_ire);
9333 				break;
9334 			}
9335 
9336 			ire->ire_marks |= ire_marks;
9337 
9338 			/*
9339 			 * If IRE_MARK_NOADD is set then we need to convert
9340 			 * the max_fragp to a useable value now. This is
9341 			 * normally done in ire_add_v[46]. We also need to
9342 			 * associate the ire with an nce (normally would be
9343 			 * done in ip_wput_nondata()).
9344 			 *
9345 			 * Note that IRE_MARK_NOADD packets created here
9346 			 * do not have a non-null ire_mp pointer. The null
9347 			 * value of ire_bucket indicates that they were
9348 			 * never added.
9349 			 */
9350 			if (ire->ire_marks & IRE_MARK_NOADD) {
9351 				uint_t  max_frag;
9352 
9353 				max_frag = *ire->ire_max_fragp;
9354 				ire->ire_max_fragp = NULL;
9355 				ire->ire_max_frag = max_frag;
9356 
9357 				if ((ire->ire_nce = ndp_lookup_v4(
9358 				    ire_to_ill(ire),
9359 				    (ire->ire_gateway_addr != INADDR_ANY ?
9360 				    &ire->ire_gateway_addr : &ire->ire_addr),
9361 				    B_FALSE)) == NULL) {
9362 					if (save_ire != NULL)
9363 						ire_refrele(save_ire);
9364 					break;
9365 				}
9366 				ASSERT(ire->ire_nce->nce_state ==
9367 				    ND_REACHABLE);
9368 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9369 			}
9370 
9371 			/* Prevent save_ire from getting deleted */
9372 			if (save_ire != NULL) {
9373 				IRB_REFHOLD(save_ire->ire_bucket);
9374 				/* Has it been removed already ? */
9375 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9376 					IRB_REFRELE(save_ire->ire_bucket);
9377 					ire_refrele(save_ire);
9378 					break;
9379 				}
9380 			}
9381 
9382 			ire_add_then_send(q, ire, first_mp);
9383 
9384 			/* Assert that save_ire is not deleted yet. */
9385 			if (save_ire != NULL) {
9386 				ASSERT(save_ire->ire_ptpn != NULL);
9387 				IRB_REFRELE(save_ire->ire_bucket);
9388 				ire_refrele(save_ire);
9389 				save_ire = NULL;
9390 			}
9391 			if (fire != NULL) {
9392 				ire_refrele(fire);
9393 				fire = NULL;
9394 			}
9395 
9396 			/*
9397 			 * the resolution loop is re-entered if this
9398 			 * was requested through flags and if we
9399 			 * actually are in a multirouting case.
9400 			 */
9401 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9402 				boolean_t need_resolve =
9403 				    ire_multirt_need_resolve(ipha_dst,
9404 				    MBLK_GETLABEL(copy_mp), ipst);
9405 				if (!need_resolve) {
9406 					MULTIRT_DEBUG_UNTAG(copy_mp);
9407 					freemsg(copy_mp);
9408 					copy_mp = NULL;
9409 				} else {
9410 					/*
9411 					 * ipif_lookup_group() calls
9412 					 * ire_lookup_multi() that uses
9413 					 * ire_ftable_lookup() to find
9414 					 * an IRE_INTERFACE for the group.
9415 					 * In the multirt case,
9416 					 * ire_lookup_multi() then invokes
9417 					 * ire_multirt_lookup() to find
9418 					 * the next resolvable ire.
9419 					 * As a result, we obtain an new
9420 					 * interface, derived from the
9421 					 * next ire.
9422 					 */
9423 					ipif_refrele(ipif);
9424 					ipif = ipif_lookup_group(ipha_dst,
9425 					    zoneid, ipst);
9426 					ip2dbg(("ip_newroute_ipif: "
9427 					    "multirt dst %08x, ipif %p\n",
9428 					    htonl(dst), (void *)ipif));
9429 					if (ipif != NULL) {
9430 						mp = copy_mp;
9431 						copy_mp = NULL;
9432 						multirt_resolve_next = B_TRUE;
9433 						continue;
9434 					} else {
9435 						freemsg(copy_mp);
9436 					}
9437 				}
9438 			}
9439 			if (ipif != NULL)
9440 				ipif_refrele(ipif);
9441 			ill_refrele(dst_ill);
9442 			ipif_refrele(src_ipif);
9443 			return;
9444 		}
9445 		case IRE_IF_RESOLVER:
9446 			/*
9447 			 * We can't build an IRE_CACHE yet, but at least
9448 			 * we found a resolver that can help.
9449 			 */
9450 			res_mp = dst_ill->ill_resolver_mp;
9451 			if (!OK_RESOLVER_MP(res_mp))
9452 				break;
9453 
9454 			/*
9455 			 * We obtain a partial IRE_CACHE which we will pass
9456 			 * along with the resolver query.  When the response
9457 			 * comes back it will be there ready for us to add.
9458 			 * The new ire inherits the IRE_OFFSUBNET flags
9459 			 * and source address, if this was requested.
9460 			 * The ire_max_frag is atomically set under the
9461 			 * irebucket lock in ire_add_v[46]. Only in the
9462 			 * case of IRE_MARK_NOADD, we set it here itself.
9463 			 */
9464 			ire = ire_create_mp(
9465 			    (uchar_t *)&dst,		/* dest address */
9466 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9467 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9468 			    NULL,			/* gateway address */
9469 			    (ire_marks & IRE_MARK_NOADD) ?
9470 			    ipif->ipif_mtu : 0,		/* max_frag */
9471 			    NULL,			/* no src nce */
9472 			    dst_ill->ill_rq,		/* recv-from queue */
9473 			    dst_ill->ill_wq,		/* send-to queue */
9474 			    IRE_CACHE,
9475 			    src_ipif,
9476 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9477 			    (fire != NULL) ?		/* Parent handle */
9478 			    fire->ire_phandle : 0,
9479 			    ihandle,			/* Interface handle */
9480 			    (fire != NULL) ?		/* flags if any */
9481 			    (fire->ire_flags &
9482 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9483 			    (save_ire == NULL ? &ire_uinfo_null :
9484 			    &save_ire->ire_uinfo),
9485 			    NULL,
9486 			    NULL,
9487 			    ipst);
9488 
9489 			if (save_ire != NULL) {
9490 				ire_refrele(save_ire);
9491 				save_ire = NULL;
9492 			}
9493 			if (ire == NULL)
9494 				break;
9495 
9496 			ire->ire_marks |= ire_marks;
9497 			/*
9498 			 * Construct message chain for the resolver of the
9499 			 * form:
9500 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9501 			 *
9502 			 * NOTE : ire will be added later when the response
9503 			 * comes back from ARP. If the response does not
9504 			 * come back, ARP frees the packet. For this reason,
9505 			 * we can't REFHOLD the bucket of save_ire to prevent
9506 			 * deletions. We may not be able to REFRELE the
9507 			 * bucket if the response never comes back.
9508 			 * Thus, before adding the ire, ire_add_v4 will make
9509 			 * sure that the interface route does not get deleted.
9510 			 * This is the only case unlike ip_newroute_v6,
9511 			 * ip_newroute_ipif_v6 where we can always prevent
9512 			 * deletions because ire_add_then_send is called after
9513 			 * creating the IRE.
9514 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9515 			 * does not add this IRE into the IRE CACHE.
9516 			 */
9517 			ASSERT(ire->ire_mp != NULL);
9518 			ire->ire_mp->b_cont = first_mp;
9519 			/* Have saved_mp handy, for cleanup if canput fails */
9520 			saved_mp = mp;
9521 			mp = copyb(res_mp);
9522 			if (mp == NULL) {
9523 				/* Prepare for cleanup */
9524 				mp = saved_mp; /* pkt */
9525 				ire_delete(ire); /* ire_mp */
9526 				ire = NULL;
9527 				if (copy_mp != NULL) {
9528 					MULTIRT_DEBUG_UNTAG(copy_mp);
9529 					freemsg(copy_mp);
9530 					copy_mp = NULL;
9531 				}
9532 				break;
9533 			}
9534 			linkb(mp, ire->ire_mp);
9535 
9536 			/*
9537 			 * Fill in the source and dest addrs for the resolver.
9538 			 * NOTE: this depends on memory layouts imposed by
9539 			 * ill_init().
9540 			 */
9541 			areq = (areq_t *)mp->b_rptr;
9542 			addrp = (ipaddr_t *)((char *)areq +
9543 			    areq->areq_sender_addr_offset);
9544 			*addrp = ire->ire_src_addr;
9545 			addrp = (ipaddr_t *)((char *)areq +
9546 			    areq->areq_target_addr_offset);
9547 			*addrp = dst;
9548 			/* Up to the resolver. */
9549 			if (canputnext(dst_ill->ill_rq) &&
9550 			    !(dst_ill->ill_arp_closing)) {
9551 				putnext(dst_ill->ill_rq, mp);
9552 				/*
9553 				 * The response will come back in ip_wput
9554 				 * with db_type IRE_DB_TYPE.
9555 				 */
9556 			} else {
9557 				mp->b_cont = NULL;
9558 				freeb(mp); /* areq */
9559 				ire_delete(ire); /* ire_mp */
9560 				saved_mp->b_next = NULL;
9561 				saved_mp->b_prev = NULL;
9562 				freemsg(first_mp); /* pkt */
9563 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9564 			}
9565 
9566 			if (fire != NULL) {
9567 				ire_refrele(fire);
9568 				fire = NULL;
9569 			}
9570 
9571 
9572 			/*
9573 			 * The resolution loop is re-entered if this was
9574 			 * requested through flags and we actually are
9575 			 * in a multirouting case.
9576 			 */
9577 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9578 				boolean_t need_resolve =
9579 				    ire_multirt_need_resolve(ipha_dst,
9580 				    MBLK_GETLABEL(copy_mp), ipst);
9581 				if (!need_resolve) {
9582 					MULTIRT_DEBUG_UNTAG(copy_mp);
9583 					freemsg(copy_mp);
9584 					copy_mp = NULL;
9585 				} else {
9586 					/*
9587 					 * ipif_lookup_group() calls
9588 					 * ire_lookup_multi() that uses
9589 					 * ire_ftable_lookup() to find
9590 					 * an IRE_INTERFACE for the group.
9591 					 * In the multirt case,
9592 					 * ire_lookup_multi() then invokes
9593 					 * ire_multirt_lookup() to find
9594 					 * the next resolvable ire.
9595 					 * As a result, we obtain an new
9596 					 * interface, derived from the
9597 					 * next ire.
9598 					 */
9599 					ipif_refrele(ipif);
9600 					ipif = ipif_lookup_group(ipha_dst,
9601 					    zoneid, ipst);
9602 					if (ipif != NULL) {
9603 						mp = copy_mp;
9604 						copy_mp = NULL;
9605 						multirt_resolve_next = B_TRUE;
9606 						continue;
9607 					} else {
9608 						freemsg(copy_mp);
9609 					}
9610 				}
9611 			}
9612 			if (ipif != NULL)
9613 				ipif_refrele(ipif);
9614 			ill_refrele(dst_ill);
9615 			ipif_refrele(src_ipif);
9616 			return;
9617 		default:
9618 			break;
9619 		}
9620 	} while (multirt_resolve_next);
9621 
9622 err_ret:
9623 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9624 	if (fire != NULL)
9625 		ire_refrele(fire);
9626 	ipif_refrele(ipif);
9627 	/* Did this packet originate externally? */
9628 	if (dst_ill != NULL)
9629 		ill_refrele(dst_ill);
9630 	if (src_ipif != NULL)
9631 		ipif_refrele(src_ipif);
9632 	if (mp->b_prev || mp->b_next) {
9633 		mp->b_next = NULL;
9634 		mp->b_prev = NULL;
9635 	} else {
9636 		/*
9637 		 * Since ip_wput() isn't close to finished, we fill
9638 		 * in enough of the header for credible error reporting.
9639 		 */
9640 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9641 			/* Failed */
9642 			freemsg(first_mp);
9643 			if (ire != NULL)
9644 				ire_refrele(ire);
9645 			return;
9646 		}
9647 	}
9648 	/*
9649 	 * At this point we will have ire only if RTF_BLACKHOLE
9650 	 * or RTF_REJECT flags are set on the IRE. It will not
9651 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9652 	 */
9653 	if (ire != NULL) {
9654 		if (ire->ire_flags & RTF_BLACKHOLE) {
9655 			ire_refrele(ire);
9656 			freemsg(first_mp);
9657 			return;
9658 		}
9659 		ire_refrele(ire);
9660 	}
9661 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9662 }
9663 
9664 /* Name/Value Table Lookup Routine */
9665 char *
9666 ip_nv_lookup(nv_t *nv, int value)
9667 {
9668 	if (!nv)
9669 		return (NULL);
9670 	for (; nv->nv_name; nv++) {
9671 		if (nv->nv_value == value)
9672 			return (nv->nv_name);
9673 	}
9674 	return ("unknown");
9675 }
9676 
9677 /*
9678  * This is a module open, i.e. this is a control stream for access
9679  * to a DLPI device.  We allocate an ill_t as the instance data in
9680  * this case.
9681  */
9682 int
9683 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9684 {
9685 	ill_t	*ill;
9686 	int	err;
9687 	zoneid_t zoneid;
9688 	netstack_t *ns;
9689 	ip_stack_t *ipst;
9690 
9691 	/*
9692 	 * Prevent unprivileged processes from pushing IP so that
9693 	 * they can't send raw IP.
9694 	 */
9695 	if (secpolicy_net_rawaccess(credp) != 0)
9696 		return (EPERM);
9697 
9698 	ns = netstack_find_by_cred(credp);
9699 	ASSERT(ns != NULL);
9700 	ipst = ns->netstack_ip;
9701 	ASSERT(ipst != NULL);
9702 
9703 	/*
9704 	 * For exclusive stacks we set the zoneid to zero
9705 	 * to make IP operate as if in the global zone.
9706 	 */
9707 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9708 		zoneid = GLOBAL_ZONEID;
9709 	else
9710 		zoneid = crgetzoneid(credp);
9711 
9712 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9713 	q->q_ptr = WR(q)->q_ptr = ill;
9714 	ill->ill_ipst = ipst;
9715 	ill->ill_zoneid = zoneid;
9716 
9717 	/*
9718 	 * ill_init initializes the ill fields and then sends down
9719 	 * down a DL_INFO_REQ after calling qprocson.
9720 	 */
9721 	err = ill_init(q, ill);
9722 	if (err != 0) {
9723 		mi_free(ill);
9724 		netstack_rele(ipst->ips_netstack);
9725 		q->q_ptr = NULL;
9726 		WR(q)->q_ptr = NULL;
9727 		return (err);
9728 	}
9729 
9730 	/* ill_init initializes the ipsq marking this thread as writer */
9731 	ipsq_exit(ill->ill_phyint->phyint_ipsq);
9732 	/* Wait for the DL_INFO_ACK */
9733 	mutex_enter(&ill->ill_lock);
9734 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9735 		/*
9736 		 * Return value of 0 indicates a pending signal.
9737 		 */
9738 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9739 		if (err == 0) {
9740 			mutex_exit(&ill->ill_lock);
9741 			(void) ip_close(q, 0);
9742 			return (EINTR);
9743 		}
9744 	}
9745 	mutex_exit(&ill->ill_lock);
9746 
9747 	/*
9748 	 * ip_rput_other could have set an error  in ill_error on
9749 	 * receipt of M_ERROR.
9750 	 */
9751 
9752 	err = ill->ill_error;
9753 	if (err != 0) {
9754 		(void) ip_close(q, 0);
9755 		return (err);
9756 	}
9757 
9758 	ill->ill_credp = credp;
9759 	crhold(credp);
9760 
9761 	mutex_enter(&ipst->ips_ip_mi_lock);
9762 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9763 	    credp);
9764 	mutex_exit(&ipst->ips_ip_mi_lock);
9765 	if (err) {
9766 		(void) ip_close(q, 0);
9767 		return (err);
9768 	}
9769 	return (0);
9770 }
9771 
9772 /* For /dev/ip aka AF_INET open */
9773 int
9774 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9775 {
9776 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
9777 }
9778 
9779 /* For /dev/ip6 aka AF_INET6 open */
9780 int
9781 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9782 {
9783 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
9784 }
9785 
9786 /* IP open routine. */
9787 int
9788 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9789     boolean_t isv6)
9790 {
9791 	conn_t 		*connp;
9792 	major_t		maj;
9793 	zoneid_t	zoneid;
9794 	netstack_t	*ns;
9795 	ip_stack_t	*ipst;
9796 
9797 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9798 
9799 	/* Allow reopen. */
9800 	if (q->q_ptr != NULL)
9801 		return (0);
9802 
9803 	if (sflag & MODOPEN) {
9804 		/* This is a module open */
9805 		return (ip_modopen(q, devp, flag, sflag, credp));
9806 	}
9807 
9808 	ns = netstack_find_by_cred(credp);
9809 	ASSERT(ns != NULL);
9810 	ipst = ns->netstack_ip;
9811 	ASSERT(ipst != NULL);
9812 
9813 	/*
9814 	 * For exclusive stacks we set the zoneid to zero
9815 	 * to make IP operate as if in the global zone.
9816 	 */
9817 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9818 		zoneid = GLOBAL_ZONEID;
9819 	else
9820 		zoneid = crgetzoneid(credp);
9821 
9822 	/*
9823 	 * We are opening as a device. This is an IP client stream, and we
9824 	 * allocate an conn_t as the instance data.
9825 	 */
9826 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9827 
9828 	/*
9829 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9830 	 * done by netstack_find_by_cred()
9831 	 */
9832 	netstack_rele(ipst->ips_netstack);
9833 
9834 	connp->conn_zoneid = zoneid;
9835 
9836 	connp->conn_upq = q;
9837 	q->q_ptr = WR(q)->q_ptr = connp;
9838 
9839 	if (flag & SO_SOCKSTR)
9840 		connp->conn_flags |= IPCL_SOCKET;
9841 
9842 	/* Minor tells us which /dev entry was opened */
9843 	if (isv6) {
9844 		connp->conn_flags |= IPCL_ISV6;
9845 		connp->conn_af_isv6 = B_TRUE;
9846 		ip_setpktversion(connp, isv6, B_FALSE, ipst);
9847 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9848 	} else {
9849 		connp->conn_af_isv6 = B_FALSE;
9850 		connp->conn_pkt_isv6 = B_FALSE;
9851 	}
9852 
9853 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9854 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9855 		connp->conn_minor_arena = ip_minor_arena_la;
9856 	} else {
9857 		/*
9858 		 * Either minor numbers in the large arena were exhausted
9859 		 * or a non socket application is doing the open.
9860 		 * Try to allocate from the small arena.
9861 		 */
9862 		if ((connp->conn_dev =
9863 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9864 			/* CONN_DEC_REF takes care of netstack_rele() */
9865 			q->q_ptr = WR(q)->q_ptr = NULL;
9866 			CONN_DEC_REF(connp);
9867 			return (EBUSY);
9868 		}
9869 		connp->conn_minor_arena = ip_minor_arena_sa;
9870 	}
9871 
9872 	maj = getemajor(*devp);
9873 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9874 
9875 	/*
9876 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9877 	 */
9878 	connp->conn_cred = credp;
9879 
9880 	/*
9881 	 * Handle IP_RTS_REQUEST and other ioctls which use conn_recv
9882 	 */
9883 	connp->conn_recv = ip_conn_input;
9884 
9885 	crhold(connp->conn_cred);
9886 
9887 	/*
9888 	 * If the caller has the process-wide flag set, then default to MAC
9889 	 * exempt mode.  This allows read-down to unlabeled hosts.
9890 	 */
9891 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9892 		connp->conn_mac_exempt = B_TRUE;
9893 
9894 	connp->conn_rq = q;
9895 	connp->conn_wq = WR(q);
9896 
9897 	/* Non-zero default values */
9898 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9899 
9900 	/*
9901 	 * Make the conn globally visible to walkers
9902 	 */
9903 	ASSERT(connp->conn_ref == 1);
9904 	mutex_enter(&connp->conn_lock);
9905 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9906 	mutex_exit(&connp->conn_lock);
9907 
9908 	qprocson(q);
9909 
9910 	return (0);
9911 }
9912 
9913 /*
9914  * Change the output format (IPv4 vs. IPv6) for a conn_t.
9915  * Note that there is no race since either ip_output function works - it
9916  * is just an optimization to enter the best ip_output routine directly.
9917  */
9918 void
9919 ip_setpktversion(conn_t *connp, boolean_t isv6, boolean_t bump_mib,
9920     ip_stack_t *ipst)
9921 {
9922 	if (isv6)  {
9923 		if (bump_mib) {
9924 			BUMP_MIB(&ipst->ips_ip6_mib,
9925 			    ipIfStatsOutSwitchIPVersion);
9926 		}
9927 		connp->conn_send = ip_output_v6;
9928 		connp->conn_pkt_isv6 = B_TRUE;
9929 	} else {
9930 		if (bump_mib) {
9931 			BUMP_MIB(&ipst->ips_ip_mib,
9932 			    ipIfStatsOutSwitchIPVersion);
9933 		}
9934 		connp->conn_send = ip_output;
9935 		connp->conn_pkt_isv6 = B_FALSE;
9936 	}
9937 
9938 }
9939 
9940 /*
9941  * See if IPsec needs loading because of the options in mp.
9942  */
9943 static boolean_t
9944 ipsec_opt_present(mblk_t *mp)
9945 {
9946 	uint8_t *optcp, *next_optcp, *opt_endcp;
9947 	struct opthdr *opt;
9948 	struct T_opthdr *topt;
9949 	int opthdr_len;
9950 	t_uscalar_t optname, optlevel;
9951 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9952 	ipsec_req_t *ipsr;
9953 
9954 	/*
9955 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9956 	 * return TRUE.
9957 	 */
9958 
9959 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9960 	opt_endcp = optcp + tor->OPT_length;
9961 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9962 		opthdr_len = sizeof (struct T_opthdr);
9963 	} else {		/* O_OPTMGMT_REQ */
9964 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9965 		opthdr_len = sizeof (struct opthdr);
9966 	}
9967 	for (; optcp < opt_endcp; optcp = next_optcp) {
9968 		if (optcp + opthdr_len > opt_endcp)
9969 			return (B_FALSE);	/* Not enough option header. */
9970 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9971 			topt = (struct T_opthdr *)optcp;
9972 			optlevel = topt->level;
9973 			optname = topt->name;
9974 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9975 		} else {
9976 			opt = (struct opthdr *)optcp;
9977 			optlevel = opt->level;
9978 			optname = opt->name;
9979 			next_optcp = optcp + opthdr_len +
9980 			    _TPI_ALIGN_OPT(opt->len);
9981 		}
9982 		if ((next_optcp < optcp) || /* wraparound pointer space */
9983 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9984 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9985 			return (B_FALSE); /* bad option buffer */
9986 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9987 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9988 			/*
9989 			 * Check to see if it's an all-bypass or all-zeroes
9990 			 * IPsec request.  Don't bother loading IPsec if
9991 			 * the socket doesn't want to use it.  (A good example
9992 			 * is a bypass request.)
9993 			 *
9994 			 * Basically, if any of the non-NEVER bits are set,
9995 			 * load IPsec.
9996 			 */
9997 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9998 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9999 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
10000 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
10001 			    != 0)
10002 				return (B_TRUE);
10003 		}
10004 	}
10005 	return (B_FALSE);
10006 }
10007 
10008 /*
10009  * If conn is is waiting for ipsec to finish loading, kick it.
10010  */
10011 /* ARGSUSED */
10012 static void
10013 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
10014 {
10015 	t_scalar_t	optreq_prim;
10016 	mblk_t		*mp;
10017 	cred_t		*cr;
10018 	int		err = 0;
10019 
10020 	/*
10021 	 * This function is called, after ipsec loading is complete.
10022 	 * Since IP checks exclusively and atomically (i.e it prevents
10023 	 * ipsec load from completing until ip_optcom_req completes)
10024 	 * whether ipsec load is complete, there cannot be a race with IP
10025 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
10026 	 */
10027 	mutex_enter(&connp->conn_lock);
10028 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
10029 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
10030 		mp = connp->conn_ipsec_opt_mp;
10031 		connp->conn_ipsec_opt_mp = NULL;
10032 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
10033 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
10034 		mutex_exit(&connp->conn_lock);
10035 
10036 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
10037 
10038 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
10039 		if (optreq_prim == T_OPTMGMT_REQ) {
10040 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10041 			    &ip_opt_obj, B_FALSE);
10042 		} else {
10043 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10044 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10045 			    &ip_opt_obj, B_FALSE);
10046 		}
10047 		if (err != EINPROGRESS)
10048 			CONN_OPER_PENDING_DONE(connp);
10049 		return;
10050 	}
10051 	mutex_exit(&connp->conn_lock);
10052 }
10053 
10054 /*
10055  * Called from the ipsec_loader thread, outside any perimeter, to tell
10056  * ip qenable any of the queues waiting for the ipsec loader to
10057  * complete.
10058  */
10059 void
10060 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10061 {
10062 	netstack_t *ns = ipss->ipsec_netstack;
10063 
10064 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10065 }
10066 
10067 /*
10068  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10069  * determines the grp on which it has to become exclusive, queues the mp
10070  * and sq draining restarts the optmgmt
10071  */
10072 static boolean_t
10073 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10074 {
10075 	conn_t *connp = Q_TO_CONN(q);
10076 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10077 
10078 	/*
10079 	 * Take IPsec requests and treat them special.
10080 	 */
10081 	if (ipsec_opt_present(mp)) {
10082 		/* First check if IPsec is loaded. */
10083 		mutex_enter(&ipss->ipsec_loader_lock);
10084 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10085 			mutex_exit(&ipss->ipsec_loader_lock);
10086 			return (B_FALSE);
10087 		}
10088 		mutex_enter(&connp->conn_lock);
10089 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10090 
10091 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10092 		connp->conn_ipsec_opt_mp = mp;
10093 		mutex_exit(&connp->conn_lock);
10094 		mutex_exit(&ipss->ipsec_loader_lock);
10095 
10096 		ipsec_loader_loadnow(ipss);
10097 		return (B_TRUE);
10098 	}
10099 	return (B_FALSE);
10100 }
10101 
10102 /*
10103  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10104  * all of them are copied to the conn_t. If the req is "zero", the policy is
10105  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10106  * fields.
10107  * We keep only the latest setting of the policy and thus policy setting
10108  * is not incremental/cumulative.
10109  *
10110  * Requests to set policies with multiple alternative actions will
10111  * go through a different API.
10112  */
10113 int
10114 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10115 {
10116 	uint_t ah_req = 0;
10117 	uint_t esp_req = 0;
10118 	uint_t se_req = 0;
10119 	ipsec_selkey_t sel;
10120 	ipsec_act_t *actp = NULL;
10121 	uint_t nact;
10122 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10123 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10124 	ipsec_policy_root_t *pr;
10125 	ipsec_policy_head_t *ph;
10126 	int fam;
10127 	boolean_t is_pol_reset;
10128 	int error = 0;
10129 	netstack_t	*ns = connp->conn_netstack;
10130 	ip_stack_t	*ipst = ns->netstack_ip;
10131 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10132 
10133 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10134 
10135 	/*
10136 	 * The IP_SEC_OPT option does not allow variable length parameters,
10137 	 * hence a request cannot be NULL.
10138 	 */
10139 	if (req == NULL)
10140 		return (EINVAL);
10141 
10142 	ah_req = req->ipsr_ah_req;
10143 	esp_req = req->ipsr_esp_req;
10144 	se_req = req->ipsr_self_encap_req;
10145 
10146 	/* Don't allow setting self-encap without one or more of AH/ESP. */
10147 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
10148 		return (EINVAL);
10149 
10150 	/*
10151 	 * Are we dealing with a request to reset the policy (i.e.
10152 	 * zero requests).
10153 	 */
10154 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10155 	    (esp_req & REQ_MASK) == 0 &&
10156 	    (se_req & REQ_MASK) == 0);
10157 
10158 	if (!is_pol_reset) {
10159 		/*
10160 		 * If we couldn't load IPsec, fail with "protocol
10161 		 * not supported".
10162 		 * IPsec may not have been loaded for a request with zero
10163 		 * policies, so we don't fail in this case.
10164 		 */
10165 		mutex_enter(&ipss->ipsec_loader_lock);
10166 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10167 			mutex_exit(&ipss->ipsec_loader_lock);
10168 			return (EPROTONOSUPPORT);
10169 		}
10170 		mutex_exit(&ipss->ipsec_loader_lock);
10171 
10172 		/*
10173 		 * Test for valid requests. Invalid algorithms
10174 		 * need to be tested by IPsec code because new
10175 		 * algorithms can be added dynamically.
10176 		 */
10177 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10178 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10179 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10180 			return (EINVAL);
10181 		}
10182 
10183 		/*
10184 		 * Only privileged users can issue these
10185 		 * requests.
10186 		 */
10187 		if (((ah_req & IPSEC_PREF_NEVER) ||
10188 		    (esp_req & IPSEC_PREF_NEVER) ||
10189 		    (se_req & IPSEC_PREF_NEVER)) &&
10190 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10191 			return (EPERM);
10192 		}
10193 
10194 		/*
10195 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10196 		 * are mutually exclusive.
10197 		 */
10198 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10199 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10200 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10201 			/* Both of them are set */
10202 			return (EINVAL);
10203 		}
10204 	}
10205 
10206 	mutex_enter(&connp->conn_lock);
10207 
10208 	/*
10209 	 * If we have already cached policies in ip_bind_connected*(), don't
10210 	 * let them change now. We cache policies for connections
10211 	 * whose src,dst [addr, port] is known.
10212 	 */
10213 	if (connp->conn_policy_cached) {
10214 		mutex_exit(&connp->conn_lock);
10215 		return (EINVAL);
10216 	}
10217 
10218 	/*
10219 	 * We have a zero policies, reset the connection policy if already
10220 	 * set. This will cause the connection to inherit the
10221 	 * global policy, if any.
10222 	 */
10223 	if (is_pol_reset) {
10224 		if (connp->conn_policy != NULL) {
10225 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10226 			connp->conn_policy = NULL;
10227 		}
10228 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10229 		connp->conn_in_enforce_policy = B_FALSE;
10230 		connp->conn_out_enforce_policy = B_FALSE;
10231 		mutex_exit(&connp->conn_lock);
10232 		return (0);
10233 	}
10234 
10235 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10236 	    ipst->ips_netstack);
10237 	if (ph == NULL)
10238 		goto enomem;
10239 
10240 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10241 	if (actp == NULL)
10242 		goto enomem;
10243 
10244 	/*
10245 	 * Always allocate IPv4 policy entries, since they can also
10246 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10247 	 */
10248 	bzero(&sel, sizeof (sel));
10249 	sel.ipsl_valid = IPSL_IPV4;
10250 
10251 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10252 	    ipst->ips_netstack);
10253 	if (pin4 == NULL)
10254 		goto enomem;
10255 
10256 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10257 	    ipst->ips_netstack);
10258 	if (pout4 == NULL)
10259 		goto enomem;
10260 
10261 	if (connp->conn_af_isv6) {
10262 		/*
10263 		 * We're looking at a v6 socket, also allocate the
10264 		 * v6-specific entries...
10265 		 */
10266 		sel.ipsl_valid = IPSL_IPV6;
10267 		pin6 = ipsec_policy_create(&sel, actp, nact,
10268 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10269 		if (pin6 == NULL)
10270 			goto enomem;
10271 
10272 		pout6 = ipsec_policy_create(&sel, actp, nact,
10273 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10274 		if (pout6 == NULL)
10275 			goto enomem;
10276 
10277 		/*
10278 		 * .. and file them away in the right place.
10279 		 */
10280 		fam = IPSEC_AF_V6;
10281 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10282 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10283 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10284 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10285 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10286 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10287 	}
10288 
10289 	ipsec_actvec_free(actp, nact);
10290 
10291 	/*
10292 	 * File the v4 policies.
10293 	 */
10294 	fam = IPSEC_AF_V4;
10295 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10296 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10297 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10298 
10299 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10300 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10301 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10302 
10303 	/*
10304 	 * If the requests need security, set enforce_policy.
10305 	 * If the requests are IPSEC_PREF_NEVER, one should
10306 	 * still set conn_out_enforce_policy so that an ipsec_out
10307 	 * gets attached in ip_wput. This is needed so that
10308 	 * for connections that we don't cache policy in ip_bind,
10309 	 * if global policy matches in ip_wput_attach_policy, we
10310 	 * don't wrongly inherit global policy. Similarly, we need
10311 	 * to set conn_in_enforce_policy also so that we don't verify
10312 	 * policy wrongly.
10313 	 */
10314 	if ((ah_req & REQ_MASK) != 0 ||
10315 	    (esp_req & REQ_MASK) != 0 ||
10316 	    (se_req & REQ_MASK) != 0) {
10317 		connp->conn_in_enforce_policy = B_TRUE;
10318 		connp->conn_out_enforce_policy = B_TRUE;
10319 		connp->conn_flags |= IPCL_CHECK_POLICY;
10320 	}
10321 
10322 	mutex_exit(&connp->conn_lock);
10323 	return (error);
10324 #undef REQ_MASK
10325 
10326 	/*
10327 	 * Common memory-allocation-failure exit path.
10328 	 */
10329 enomem:
10330 	mutex_exit(&connp->conn_lock);
10331 	if (actp != NULL)
10332 		ipsec_actvec_free(actp, nact);
10333 	if (pin4 != NULL)
10334 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10335 	if (pout4 != NULL)
10336 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10337 	if (pin6 != NULL)
10338 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10339 	if (pout6 != NULL)
10340 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10341 	return (ENOMEM);
10342 }
10343 
10344 /*
10345  * Only for options that pass in an IP addr. Currently only V4 options
10346  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10347  * So this function assumes level is IPPROTO_IP
10348  */
10349 int
10350 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10351     mblk_t *first_mp)
10352 {
10353 	ipif_t *ipif = NULL;
10354 	int error;
10355 	ill_t *ill;
10356 	int zoneid;
10357 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10358 
10359 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10360 
10361 	if (addr != INADDR_ANY || checkonly) {
10362 		ASSERT(connp != NULL);
10363 		zoneid = IPCL_ZONEID(connp);
10364 		if (option == IP_NEXTHOP) {
10365 			ipif = ipif_lookup_onlink_addr(addr,
10366 			    connp->conn_zoneid, ipst);
10367 		} else {
10368 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10369 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10370 			    &error, ipst);
10371 		}
10372 		if (ipif == NULL) {
10373 			if (error == EINPROGRESS)
10374 				return (error);
10375 			else if ((option == IP_MULTICAST_IF) ||
10376 			    (option == IP_NEXTHOP))
10377 				return (EHOSTUNREACH);
10378 			else
10379 				return (EINVAL);
10380 		} else if (checkonly) {
10381 			if (option == IP_MULTICAST_IF) {
10382 				ill = ipif->ipif_ill;
10383 				/* not supported by the virtual network iface */
10384 				if (IS_VNI(ill)) {
10385 					ipif_refrele(ipif);
10386 					return (EINVAL);
10387 				}
10388 			}
10389 			ipif_refrele(ipif);
10390 			return (0);
10391 		}
10392 		ill = ipif->ipif_ill;
10393 		mutex_enter(&connp->conn_lock);
10394 		mutex_enter(&ill->ill_lock);
10395 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10396 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10397 			mutex_exit(&ill->ill_lock);
10398 			mutex_exit(&connp->conn_lock);
10399 			ipif_refrele(ipif);
10400 			return (option == IP_MULTICAST_IF ?
10401 			    EHOSTUNREACH : EINVAL);
10402 		}
10403 	} else {
10404 		mutex_enter(&connp->conn_lock);
10405 	}
10406 
10407 	/* None of the options below are supported on the VNI */
10408 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10409 		mutex_exit(&ill->ill_lock);
10410 		mutex_exit(&connp->conn_lock);
10411 		ipif_refrele(ipif);
10412 		return (EINVAL);
10413 	}
10414 
10415 	switch (option) {
10416 	case IP_DONTFAILOVER_IF:
10417 		/*
10418 		 * This option is used by in.mpathd to ensure
10419 		 * that IPMP probe packets only go out on the
10420 		 * test interfaces. in.mpathd sets this option
10421 		 * on the non-failover interfaces.
10422 		 * For backward compatibility, this option
10423 		 * implicitly sets IP_MULTICAST_IF, as used
10424 		 * be done in bind(), so that ip_wput gets
10425 		 * this ipif to send mcast packets.
10426 		 */
10427 		if (ipif != NULL) {
10428 			ASSERT(addr != INADDR_ANY);
10429 			connp->conn_nofailover_ill = ipif->ipif_ill;
10430 			connp->conn_multicast_ipif = ipif;
10431 		} else {
10432 			ASSERT(addr == INADDR_ANY);
10433 			connp->conn_nofailover_ill = NULL;
10434 			connp->conn_multicast_ipif = NULL;
10435 		}
10436 		break;
10437 
10438 	case IP_MULTICAST_IF:
10439 		connp->conn_multicast_ipif = ipif;
10440 		break;
10441 	case IP_NEXTHOP:
10442 		connp->conn_nexthop_v4 = addr;
10443 		connp->conn_nexthop_set = B_TRUE;
10444 		break;
10445 	}
10446 
10447 	if (ipif != NULL) {
10448 		mutex_exit(&ill->ill_lock);
10449 		mutex_exit(&connp->conn_lock);
10450 		ipif_refrele(ipif);
10451 		return (0);
10452 	}
10453 	mutex_exit(&connp->conn_lock);
10454 	/* We succeded in cleared the option */
10455 	return (0);
10456 }
10457 
10458 /*
10459  * For options that pass in an ifindex specifying the ill. V6 options always
10460  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10461  */
10462 int
10463 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10464     int level, int option, mblk_t *first_mp)
10465 {
10466 	ill_t *ill = NULL;
10467 	int error = 0;
10468 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10469 
10470 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10471 	if (ifindex != 0) {
10472 		ASSERT(connp != NULL);
10473 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10474 		    first_mp, ip_restart_optmgmt, &error, ipst);
10475 		if (ill != NULL) {
10476 			if (checkonly) {
10477 				/* not supported by the virtual network iface */
10478 				if (IS_VNI(ill)) {
10479 					ill_refrele(ill);
10480 					return (EINVAL);
10481 				}
10482 				ill_refrele(ill);
10483 				return (0);
10484 			}
10485 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10486 			    0, NULL)) {
10487 				ill_refrele(ill);
10488 				ill = NULL;
10489 				mutex_enter(&connp->conn_lock);
10490 				goto setit;
10491 			}
10492 			mutex_enter(&connp->conn_lock);
10493 			mutex_enter(&ill->ill_lock);
10494 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10495 				mutex_exit(&ill->ill_lock);
10496 				mutex_exit(&connp->conn_lock);
10497 				ill_refrele(ill);
10498 				ill = NULL;
10499 				mutex_enter(&connp->conn_lock);
10500 			}
10501 			goto setit;
10502 		} else if (error == EINPROGRESS) {
10503 			return (error);
10504 		} else {
10505 			error = 0;
10506 		}
10507 	}
10508 	mutex_enter(&connp->conn_lock);
10509 setit:
10510 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10511 
10512 	/*
10513 	 * The options below assume that the ILL (if any) transmits and/or
10514 	 * receives traffic. Neither of which is true for the virtual network
10515 	 * interface, so fail setting these on a VNI.
10516 	 */
10517 	if (IS_VNI(ill)) {
10518 		ASSERT(ill != NULL);
10519 		mutex_exit(&ill->ill_lock);
10520 		mutex_exit(&connp->conn_lock);
10521 		ill_refrele(ill);
10522 		return (EINVAL);
10523 	}
10524 
10525 	if (level == IPPROTO_IP) {
10526 		switch (option) {
10527 		case IP_BOUND_IF:
10528 			connp->conn_incoming_ill = ill;
10529 			connp->conn_outgoing_ill = ill;
10530 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10531 			    0 : ifindex;
10532 			break;
10533 
10534 		case IP_MULTICAST_IF:
10535 			/*
10536 			 * This option is an internal special. The socket
10537 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10538 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10539 			 * specifies an ifindex and we try first on V6 ill's.
10540 			 * If we don't find one, we they try using on v4 ill's
10541 			 * intenally and we come here.
10542 			 */
10543 			if (!checkonly && ill != NULL) {
10544 				ipif_t	*ipif;
10545 				ipif = ill->ill_ipif;
10546 
10547 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10548 					mutex_exit(&ill->ill_lock);
10549 					mutex_exit(&connp->conn_lock);
10550 					ill_refrele(ill);
10551 					ill = NULL;
10552 					mutex_enter(&connp->conn_lock);
10553 				} else {
10554 					connp->conn_multicast_ipif = ipif;
10555 				}
10556 			}
10557 			break;
10558 
10559 		case IP_DHCPINIT_IF:
10560 			if (connp->conn_dhcpinit_ill != NULL) {
10561 				/*
10562 				 * We've locked the conn so conn_cleanup_ill()
10563 				 * cannot clear conn_dhcpinit_ill -- so it's
10564 				 * safe to access the ill.
10565 				 */
10566 				ill_t *oill = connp->conn_dhcpinit_ill;
10567 
10568 				ASSERT(oill->ill_dhcpinit != 0);
10569 				atomic_dec_32(&oill->ill_dhcpinit);
10570 				connp->conn_dhcpinit_ill = NULL;
10571 			}
10572 
10573 			if (ill != NULL) {
10574 				connp->conn_dhcpinit_ill = ill;
10575 				atomic_inc_32(&ill->ill_dhcpinit);
10576 			}
10577 			break;
10578 		}
10579 	} else {
10580 		switch (option) {
10581 		case IPV6_BOUND_IF:
10582 			connp->conn_incoming_ill = ill;
10583 			connp->conn_outgoing_ill = ill;
10584 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10585 			    0 : ifindex;
10586 			break;
10587 
10588 		case IPV6_BOUND_PIF:
10589 			/*
10590 			 * Limit all transmit to this ill.
10591 			 * Unlike IPV6_BOUND_IF, using this option
10592 			 * prevents load spreading and failover from
10593 			 * happening when the interface is part of the
10594 			 * group. That's why we don't need to remember
10595 			 * the ifindex in orig_bound_ifindex as in
10596 			 * IPV6_BOUND_IF.
10597 			 */
10598 			connp->conn_outgoing_pill = ill;
10599 			break;
10600 
10601 		case IPV6_DONTFAILOVER_IF:
10602 			/*
10603 			 * This option is used by in.mpathd to ensure
10604 			 * that IPMP probe packets only go out on the
10605 			 * test interfaces. in.mpathd sets this option
10606 			 * on the non-failover interfaces.
10607 			 */
10608 			connp->conn_nofailover_ill = ill;
10609 			/*
10610 			 * For backward compatibility, this option
10611 			 * implicitly sets ip_multicast_ill as used in
10612 			 * IPV6_MULTICAST_IF so that ip_wput gets
10613 			 * this ill to send mcast packets.
10614 			 */
10615 			connp->conn_multicast_ill = ill;
10616 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10617 			    0 : ifindex;
10618 			break;
10619 
10620 		case IPV6_MULTICAST_IF:
10621 			/*
10622 			 * Set conn_multicast_ill to be the IPv6 ill.
10623 			 * Set conn_multicast_ipif to be an IPv4 ipif
10624 			 * for ifindex to make IPv4 mapped addresses
10625 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10626 			 * Even if no IPv6 ill exists for the ifindex
10627 			 * we need to check for an IPv4 ifindex in order
10628 			 * for this to work with mapped addresses. In that
10629 			 * case only set conn_multicast_ipif.
10630 			 */
10631 			if (!checkonly) {
10632 				if (ifindex == 0) {
10633 					connp->conn_multicast_ill = NULL;
10634 					connp->conn_orig_multicast_ifindex = 0;
10635 					connp->conn_multicast_ipif = NULL;
10636 				} else if (ill != NULL) {
10637 					connp->conn_multicast_ill = ill;
10638 					connp->conn_orig_multicast_ifindex =
10639 					    ifindex;
10640 				}
10641 			}
10642 			break;
10643 		}
10644 	}
10645 
10646 	if (ill != NULL) {
10647 		mutex_exit(&ill->ill_lock);
10648 		mutex_exit(&connp->conn_lock);
10649 		ill_refrele(ill);
10650 		return (0);
10651 	}
10652 	mutex_exit(&connp->conn_lock);
10653 	/*
10654 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10655 	 * locate the ill and could not set the option (ifindex != 0)
10656 	 */
10657 	return (ifindex == 0 ? 0 : EINVAL);
10658 }
10659 
10660 /* This routine sets socket options. */
10661 /* ARGSUSED */
10662 int
10663 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10664     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10665     void *dummy, cred_t *cr, mblk_t *first_mp)
10666 {
10667 	int		*i1 = (int *)invalp;
10668 	conn_t		*connp = Q_TO_CONN(q);
10669 	int		error = 0;
10670 	boolean_t	checkonly;
10671 	ire_t		*ire;
10672 	boolean_t	found;
10673 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10674 
10675 	switch (optset_context) {
10676 
10677 	case SETFN_OPTCOM_CHECKONLY:
10678 		checkonly = B_TRUE;
10679 		/*
10680 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10681 		 * inlen != 0 implies value supplied and
10682 		 * 	we have to "pretend" to set it.
10683 		 * inlen == 0 implies that there is no
10684 		 * 	value part in T_CHECK request and just validation
10685 		 * done elsewhere should be enough, we just return here.
10686 		 */
10687 		if (inlen == 0) {
10688 			*outlenp = 0;
10689 			return (0);
10690 		}
10691 		break;
10692 	case SETFN_OPTCOM_NEGOTIATE:
10693 	case SETFN_UD_NEGOTIATE:
10694 	case SETFN_CONN_NEGOTIATE:
10695 		checkonly = B_FALSE;
10696 		break;
10697 	default:
10698 		/*
10699 		 * We should never get here
10700 		 */
10701 		*outlenp = 0;
10702 		return (EINVAL);
10703 	}
10704 
10705 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10706 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10707 
10708 	/*
10709 	 * For fixed length options, no sanity check
10710 	 * of passed in length is done. It is assumed *_optcom_req()
10711 	 * routines do the right thing.
10712 	 */
10713 
10714 	switch (level) {
10715 	case SOL_SOCKET:
10716 		/*
10717 		 * conn_lock protects the bitfields, and is used to
10718 		 * set the fields atomically.
10719 		 */
10720 		switch (name) {
10721 		case SO_BROADCAST:
10722 			if (!checkonly) {
10723 				/* TODO: use value someplace? */
10724 				mutex_enter(&connp->conn_lock);
10725 				connp->conn_broadcast = *i1 ? 1 : 0;
10726 				mutex_exit(&connp->conn_lock);
10727 			}
10728 			break;	/* goto sizeof (int) option return */
10729 		case SO_USELOOPBACK:
10730 			if (!checkonly) {
10731 				/* TODO: use value someplace? */
10732 				mutex_enter(&connp->conn_lock);
10733 				connp->conn_loopback = *i1 ? 1 : 0;
10734 				mutex_exit(&connp->conn_lock);
10735 			}
10736 			break;	/* goto sizeof (int) option return */
10737 		case SO_DONTROUTE:
10738 			if (!checkonly) {
10739 				mutex_enter(&connp->conn_lock);
10740 				connp->conn_dontroute = *i1 ? 1 : 0;
10741 				mutex_exit(&connp->conn_lock);
10742 			}
10743 			break;	/* goto sizeof (int) option return */
10744 		case SO_REUSEADDR:
10745 			if (!checkonly) {
10746 				mutex_enter(&connp->conn_lock);
10747 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10748 				mutex_exit(&connp->conn_lock);
10749 			}
10750 			break;	/* goto sizeof (int) option return */
10751 		case SO_PROTOTYPE:
10752 			if (!checkonly) {
10753 				mutex_enter(&connp->conn_lock);
10754 				connp->conn_proto = *i1;
10755 				mutex_exit(&connp->conn_lock);
10756 			}
10757 			break;	/* goto sizeof (int) option return */
10758 		case SO_ALLZONES:
10759 			if (!checkonly) {
10760 				mutex_enter(&connp->conn_lock);
10761 				if (IPCL_IS_BOUND(connp)) {
10762 					mutex_exit(&connp->conn_lock);
10763 					return (EINVAL);
10764 				}
10765 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10766 				mutex_exit(&connp->conn_lock);
10767 			}
10768 			break;	/* goto sizeof (int) option return */
10769 		case SO_ANON_MLP:
10770 			if (!checkonly) {
10771 				mutex_enter(&connp->conn_lock);
10772 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10773 				mutex_exit(&connp->conn_lock);
10774 			}
10775 			break;	/* goto sizeof (int) option return */
10776 		case SO_MAC_EXEMPT:
10777 			if (secpolicy_net_mac_aware(cr) != 0 ||
10778 			    IPCL_IS_BOUND(connp))
10779 				return (EACCES);
10780 			if (!checkonly) {
10781 				mutex_enter(&connp->conn_lock);
10782 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10783 				mutex_exit(&connp->conn_lock);
10784 			}
10785 			break;	/* goto sizeof (int) option return */
10786 		default:
10787 			/*
10788 			 * "soft" error (negative)
10789 			 * option not handled at this level
10790 			 * Note: Do not modify *outlenp
10791 			 */
10792 			return (-EINVAL);
10793 		}
10794 		break;
10795 	case IPPROTO_IP:
10796 		switch (name) {
10797 		case IP_NEXTHOP:
10798 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10799 				return (EPERM);
10800 			/* FALLTHRU */
10801 		case IP_MULTICAST_IF:
10802 		case IP_DONTFAILOVER_IF: {
10803 			ipaddr_t addr = *i1;
10804 
10805 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10806 			    first_mp);
10807 			if (error != 0)
10808 				return (error);
10809 			break;	/* goto sizeof (int) option return */
10810 		}
10811 
10812 		case IP_MULTICAST_TTL:
10813 			/* Recorded in transport above IP */
10814 			*outvalp = *invalp;
10815 			*outlenp = sizeof (uchar_t);
10816 			return (0);
10817 		case IP_MULTICAST_LOOP:
10818 			if (!checkonly) {
10819 				mutex_enter(&connp->conn_lock);
10820 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10821 				mutex_exit(&connp->conn_lock);
10822 			}
10823 			*outvalp = *invalp;
10824 			*outlenp = sizeof (uchar_t);
10825 			return (0);
10826 		case IP_ADD_MEMBERSHIP:
10827 		case MCAST_JOIN_GROUP:
10828 		case IP_DROP_MEMBERSHIP:
10829 		case MCAST_LEAVE_GROUP: {
10830 			struct ip_mreq *mreqp;
10831 			struct group_req *greqp;
10832 			ire_t *ire;
10833 			boolean_t done = B_FALSE;
10834 			ipaddr_t group, ifaddr;
10835 			struct sockaddr_in *sin;
10836 			uint32_t *ifindexp;
10837 			boolean_t mcast_opt = B_TRUE;
10838 			mcast_record_t fmode;
10839 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10840 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10841 
10842 			switch (name) {
10843 			case IP_ADD_MEMBERSHIP:
10844 				mcast_opt = B_FALSE;
10845 				/* FALLTHRU */
10846 			case MCAST_JOIN_GROUP:
10847 				fmode = MODE_IS_EXCLUDE;
10848 				optfn = ip_opt_add_group;
10849 				break;
10850 
10851 			case IP_DROP_MEMBERSHIP:
10852 				mcast_opt = B_FALSE;
10853 				/* FALLTHRU */
10854 			case MCAST_LEAVE_GROUP:
10855 				fmode = MODE_IS_INCLUDE;
10856 				optfn = ip_opt_delete_group;
10857 				break;
10858 			}
10859 
10860 			if (mcast_opt) {
10861 				greqp = (struct group_req *)i1;
10862 				sin = (struct sockaddr_in *)&greqp->gr_group;
10863 				if (sin->sin_family != AF_INET) {
10864 					*outlenp = 0;
10865 					return (ENOPROTOOPT);
10866 				}
10867 				group = (ipaddr_t)sin->sin_addr.s_addr;
10868 				ifaddr = INADDR_ANY;
10869 				ifindexp = &greqp->gr_interface;
10870 			} else {
10871 				mreqp = (struct ip_mreq *)i1;
10872 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10873 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10874 				ifindexp = NULL;
10875 			}
10876 
10877 			/*
10878 			 * In the multirouting case, we need to replicate
10879 			 * the request on all interfaces that will take part
10880 			 * in replication.  We do so because multirouting is
10881 			 * reflective, thus we will probably receive multi-
10882 			 * casts on those interfaces.
10883 			 * The ip_multirt_apply_membership() succeeds if the
10884 			 * operation succeeds on at least one interface.
10885 			 */
10886 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10887 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10888 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10889 			if (ire != NULL) {
10890 				if (ire->ire_flags & RTF_MULTIRT) {
10891 					error = ip_multirt_apply_membership(
10892 					    optfn, ire, connp, checkonly, group,
10893 					    fmode, INADDR_ANY, first_mp);
10894 					done = B_TRUE;
10895 				}
10896 				ire_refrele(ire);
10897 			}
10898 			if (!done) {
10899 				error = optfn(connp, checkonly, group, ifaddr,
10900 				    ifindexp, fmode, INADDR_ANY, first_mp);
10901 			}
10902 			if (error) {
10903 				/*
10904 				 * EINPROGRESS is a soft error, needs retry
10905 				 * so don't make *outlenp zero.
10906 				 */
10907 				if (error != EINPROGRESS)
10908 					*outlenp = 0;
10909 				return (error);
10910 			}
10911 			/* OK return - copy input buffer into output buffer */
10912 			if (invalp != outvalp) {
10913 				/* don't trust bcopy for identical src/dst */
10914 				bcopy(invalp, outvalp, inlen);
10915 			}
10916 			*outlenp = inlen;
10917 			return (0);
10918 		}
10919 		case IP_BLOCK_SOURCE:
10920 		case IP_UNBLOCK_SOURCE:
10921 		case IP_ADD_SOURCE_MEMBERSHIP:
10922 		case IP_DROP_SOURCE_MEMBERSHIP:
10923 		case MCAST_BLOCK_SOURCE:
10924 		case MCAST_UNBLOCK_SOURCE:
10925 		case MCAST_JOIN_SOURCE_GROUP:
10926 		case MCAST_LEAVE_SOURCE_GROUP: {
10927 			struct ip_mreq_source *imreqp;
10928 			struct group_source_req *gsreqp;
10929 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10930 			uint32_t ifindex = 0;
10931 			mcast_record_t fmode;
10932 			struct sockaddr_in *sin;
10933 			ire_t *ire;
10934 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10935 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10936 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10937 
10938 			switch (name) {
10939 			case IP_BLOCK_SOURCE:
10940 				mcast_opt = B_FALSE;
10941 				/* FALLTHRU */
10942 			case MCAST_BLOCK_SOURCE:
10943 				fmode = MODE_IS_EXCLUDE;
10944 				optfn = ip_opt_add_group;
10945 				break;
10946 
10947 			case IP_UNBLOCK_SOURCE:
10948 				mcast_opt = B_FALSE;
10949 				/* FALLTHRU */
10950 			case MCAST_UNBLOCK_SOURCE:
10951 				fmode = MODE_IS_EXCLUDE;
10952 				optfn = ip_opt_delete_group;
10953 				break;
10954 
10955 			case IP_ADD_SOURCE_MEMBERSHIP:
10956 				mcast_opt = B_FALSE;
10957 				/* FALLTHRU */
10958 			case MCAST_JOIN_SOURCE_GROUP:
10959 				fmode = MODE_IS_INCLUDE;
10960 				optfn = ip_opt_add_group;
10961 				break;
10962 
10963 			case IP_DROP_SOURCE_MEMBERSHIP:
10964 				mcast_opt = B_FALSE;
10965 				/* FALLTHRU */
10966 			case MCAST_LEAVE_SOURCE_GROUP:
10967 				fmode = MODE_IS_INCLUDE;
10968 				optfn = ip_opt_delete_group;
10969 				break;
10970 			}
10971 
10972 			if (mcast_opt) {
10973 				gsreqp = (struct group_source_req *)i1;
10974 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10975 					*outlenp = 0;
10976 					return (ENOPROTOOPT);
10977 				}
10978 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10979 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10980 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10981 				src = (ipaddr_t)sin->sin_addr.s_addr;
10982 				ifindex = gsreqp->gsr_interface;
10983 			} else {
10984 				imreqp = (struct ip_mreq_source *)i1;
10985 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10986 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10987 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10988 			}
10989 
10990 			/*
10991 			 * In the multirouting case, we need to replicate
10992 			 * the request as noted in the mcast cases above.
10993 			 */
10994 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10995 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10996 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10997 			if (ire != NULL) {
10998 				if (ire->ire_flags & RTF_MULTIRT) {
10999 					error = ip_multirt_apply_membership(
11000 					    optfn, ire, connp, checkonly, grp,
11001 					    fmode, src, first_mp);
11002 					done = B_TRUE;
11003 				}
11004 				ire_refrele(ire);
11005 			}
11006 			if (!done) {
11007 				error = optfn(connp, checkonly, grp, ifaddr,
11008 				    &ifindex, fmode, src, first_mp);
11009 			}
11010 			if (error != 0) {
11011 				/*
11012 				 * EINPROGRESS is a soft error, needs retry
11013 				 * so don't make *outlenp zero.
11014 				 */
11015 				if (error != EINPROGRESS)
11016 					*outlenp = 0;
11017 				return (error);
11018 			}
11019 			/* OK return - copy input buffer into output buffer */
11020 			if (invalp != outvalp) {
11021 				bcopy(invalp, outvalp, inlen);
11022 			}
11023 			*outlenp = inlen;
11024 			return (0);
11025 		}
11026 		case IP_SEC_OPT:
11027 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11028 			if (error != 0) {
11029 				*outlenp = 0;
11030 				return (error);
11031 			}
11032 			break;
11033 		case IP_HDRINCL:
11034 		case IP_OPTIONS:
11035 		case T_IP_OPTIONS:
11036 		case IP_TOS:
11037 		case T_IP_TOS:
11038 		case IP_TTL:
11039 		case IP_RECVDSTADDR:
11040 		case IP_RECVOPTS:
11041 			/* OK return - copy input buffer into output buffer */
11042 			if (invalp != outvalp) {
11043 				/* don't trust bcopy for identical src/dst */
11044 				bcopy(invalp, outvalp, inlen);
11045 			}
11046 			*outlenp = inlen;
11047 			return (0);
11048 		case IP_RECVIF:
11049 			/* Retrieve the inbound interface index */
11050 			if (!checkonly) {
11051 				mutex_enter(&connp->conn_lock);
11052 				connp->conn_recvif = *i1 ? 1 : 0;
11053 				mutex_exit(&connp->conn_lock);
11054 			}
11055 			break;	/* goto sizeof (int) option return */
11056 		case IP_RECVPKTINFO:
11057 			if (!checkonly) {
11058 				mutex_enter(&connp->conn_lock);
11059 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11060 				mutex_exit(&connp->conn_lock);
11061 			}
11062 			break;	/* goto sizeof (int) option return */
11063 		case IP_RECVSLLA:
11064 			/* Retrieve the source link layer address */
11065 			if (!checkonly) {
11066 				mutex_enter(&connp->conn_lock);
11067 				connp->conn_recvslla = *i1 ? 1 : 0;
11068 				mutex_exit(&connp->conn_lock);
11069 			}
11070 			break;	/* goto sizeof (int) option return */
11071 		case MRT_INIT:
11072 		case MRT_DONE:
11073 		case MRT_ADD_VIF:
11074 		case MRT_DEL_VIF:
11075 		case MRT_ADD_MFC:
11076 		case MRT_DEL_MFC:
11077 		case MRT_ASSERT:
11078 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11079 				*outlenp = 0;
11080 				return (error);
11081 			}
11082 			error = ip_mrouter_set((int)name, q, checkonly,
11083 			    (uchar_t *)invalp, inlen, first_mp);
11084 			if (error) {
11085 				*outlenp = 0;
11086 				return (error);
11087 			}
11088 			/* OK return - copy input buffer into output buffer */
11089 			if (invalp != outvalp) {
11090 				/* don't trust bcopy for identical src/dst */
11091 				bcopy(invalp, outvalp, inlen);
11092 			}
11093 			*outlenp = inlen;
11094 			return (0);
11095 		case IP_BOUND_IF:
11096 		case IP_DHCPINIT_IF:
11097 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11098 			    level, name, first_mp);
11099 			if (error != 0)
11100 				return (error);
11101 			break; 		/* goto sizeof (int) option return */
11102 
11103 		case IP_UNSPEC_SRC:
11104 			/* Allow sending with a zero source address */
11105 			if (!checkonly) {
11106 				mutex_enter(&connp->conn_lock);
11107 				connp->conn_unspec_src = *i1 ? 1 : 0;
11108 				mutex_exit(&connp->conn_lock);
11109 			}
11110 			break;	/* goto sizeof (int) option return */
11111 		default:
11112 			/*
11113 			 * "soft" error (negative)
11114 			 * option not handled at this level
11115 			 * Note: Do not modify *outlenp
11116 			 */
11117 			return (-EINVAL);
11118 		}
11119 		break;
11120 	case IPPROTO_IPV6:
11121 		switch (name) {
11122 		case IPV6_BOUND_IF:
11123 		case IPV6_BOUND_PIF:
11124 		case IPV6_DONTFAILOVER_IF:
11125 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11126 			    level, name, first_mp);
11127 			if (error != 0)
11128 				return (error);
11129 			break; 		/* goto sizeof (int) option return */
11130 
11131 		case IPV6_MULTICAST_IF:
11132 			/*
11133 			 * The only possible errors are EINPROGRESS and
11134 			 * EINVAL. EINPROGRESS will be restarted and is not
11135 			 * a hard error. We call this option on both V4 and V6
11136 			 * If both return EINVAL, then this call returns
11137 			 * EINVAL. If at least one of them succeeds we
11138 			 * return success.
11139 			 */
11140 			found = B_FALSE;
11141 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11142 			    level, name, first_mp);
11143 			if (error == EINPROGRESS)
11144 				return (error);
11145 			if (error == 0)
11146 				found = B_TRUE;
11147 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11148 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11149 			if (error == 0)
11150 				found = B_TRUE;
11151 			if (!found)
11152 				return (error);
11153 			break; 		/* goto sizeof (int) option return */
11154 
11155 		case IPV6_MULTICAST_HOPS:
11156 			/* Recorded in transport above IP */
11157 			break;	/* goto sizeof (int) option return */
11158 		case IPV6_MULTICAST_LOOP:
11159 			if (!checkonly) {
11160 				mutex_enter(&connp->conn_lock);
11161 				connp->conn_multicast_loop = *i1;
11162 				mutex_exit(&connp->conn_lock);
11163 			}
11164 			break;	/* goto sizeof (int) option return */
11165 		case IPV6_JOIN_GROUP:
11166 		case MCAST_JOIN_GROUP:
11167 		case IPV6_LEAVE_GROUP:
11168 		case MCAST_LEAVE_GROUP: {
11169 			struct ipv6_mreq *ip_mreqp;
11170 			struct group_req *greqp;
11171 			ire_t *ire;
11172 			boolean_t done = B_FALSE;
11173 			in6_addr_t groupv6;
11174 			uint32_t ifindex;
11175 			boolean_t mcast_opt = B_TRUE;
11176 			mcast_record_t fmode;
11177 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11178 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11179 
11180 			switch (name) {
11181 			case IPV6_JOIN_GROUP:
11182 				mcast_opt = B_FALSE;
11183 				/* FALLTHRU */
11184 			case MCAST_JOIN_GROUP:
11185 				fmode = MODE_IS_EXCLUDE;
11186 				optfn = ip_opt_add_group_v6;
11187 				break;
11188 
11189 			case IPV6_LEAVE_GROUP:
11190 				mcast_opt = B_FALSE;
11191 				/* FALLTHRU */
11192 			case MCAST_LEAVE_GROUP:
11193 				fmode = MODE_IS_INCLUDE;
11194 				optfn = ip_opt_delete_group_v6;
11195 				break;
11196 			}
11197 
11198 			if (mcast_opt) {
11199 				struct sockaddr_in *sin;
11200 				struct sockaddr_in6 *sin6;
11201 				greqp = (struct group_req *)i1;
11202 				if (greqp->gr_group.ss_family == AF_INET) {
11203 					sin = (struct sockaddr_in *)
11204 					    &(greqp->gr_group);
11205 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11206 					    &groupv6);
11207 				} else {
11208 					sin6 = (struct sockaddr_in6 *)
11209 					    &(greqp->gr_group);
11210 					groupv6 = sin6->sin6_addr;
11211 				}
11212 				ifindex = greqp->gr_interface;
11213 			} else {
11214 				ip_mreqp = (struct ipv6_mreq *)i1;
11215 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11216 				ifindex = ip_mreqp->ipv6mr_interface;
11217 			}
11218 			/*
11219 			 * In the multirouting case, we need to replicate
11220 			 * the request on all interfaces that will take part
11221 			 * in replication.  We do so because multirouting is
11222 			 * reflective, thus we will probably receive multi-
11223 			 * casts on those interfaces.
11224 			 * The ip_multirt_apply_membership_v6() succeeds if
11225 			 * the operation succeeds on at least one interface.
11226 			 */
11227 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11228 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11229 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11230 			if (ire != NULL) {
11231 				if (ire->ire_flags & RTF_MULTIRT) {
11232 					error = ip_multirt_apply_membership_v6(
11233 					    optfn, ire, connp, checkonly,
11234 					    &groupv6, fmode, &ipv6_all_zeros,
11235 					    first_mp);
11236 					done = B_TRUE;
11237 				}
11238 				ire_refrele(ire);
11239 			}
11240 			if (!done) {
11241 				error = optfn(connp, checkonly, &groupv6,
11242 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11243 			}
11244 			if (error) {
11245 				/*
11246 				 * EINPROGRESS is a soft error, needs retry
11247 				 * so don't make *outlenp zero.
11248 				 */
11249 				if (error != EINPROGRESS)
11250 					*outlenp = 0;
11251 				return (error);
11252 			}
11253 			/* OK return - copy input buffer into output buffer */
11254 			if (invalp != outvalp) {
11255 				/* don't trust bcopy for identical src/dst */
11256 				bcopy(invalp, outvalp, inlen);
11257 			}
11258 			*outlenp = inlen;
11259 			return (0);
11260 		}
11261 		case MCAST_BLOCK_SOURCE:
11262 		case MCAST_UNBLOCK_SOURCE:
11263 		case MCAST_JOIN_SOURCE_GROUP:
11264 		case MCAST_LEAVE_SOURCE_GROUP: {
11265 			struct group_source_req *gsreqp;
11266 			in6_addr_t v6grp, v6src;
11267 			uint32_t ifindex;
11268 			mcast_record_t fmode;
11269 			ire_t *ire;
11270 			boolean_t done = B_FALSE;
11271 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11272 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11273 
11274 			switch (name) {
11275 			case MCAST_BLOCK_SOURCE:
11276 				fmode = MODE_IS_EXCLUDE;
11277 				optfn = ip_opt_add_group_v6;
11278 				break;
11279 			case MCAST_UNBLOCK_SOURCE:
11280 				fmode = MODE_IS_EXCLUDE;
11281 				optfn = ip_opt_delete_group_v6;
11282 				break;
11283 			case MCAST_JOIN_SOURCE_GROUP:
11284 				fmode = MODE_IS_INCLUDE;
11285 				optfn = ip_opt_add_group_v6;
11286 				break;
11287 			case MCAST_LEAVE_SOURCE_GROUP:
11288 				fmode = MODE_IS_INCLUDE;
11289 				optfn = ip_opt_delete_group_v6;
11290 				break;
11291 			}
11292 
11293 			gsreqp = (struct group_source_req *)i1;
11294 			ifindex = gsreqp->gsr_interface;
11295 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11296 				struct sockaddr_in *s;
11297 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11298 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11299 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11300 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11301 			} else {
11302 				struct sockaddr_in6 *s6;
11303 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11304 				v6grp = s6->sin6_addr;
11305 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11306 				v6src = s6->sin6_addr;
11307 			}
11308 
11309 			/*
11310 			 * In the multirouting case, we need to replicate
11311 			 * the request as noted in the mcast cases above.
11312 			 */
11313 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11314 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11315 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11316 			if (ire != NULL) {
11317 				if (ire->ire_flags & RTF_MULTIRT) {
11318 					error = ip_multirt_apply_membership_v6(
11319 					    optfn, ire, connp, checkonly,
11320 					    &v6grp, fmode, &v6src, first_mp);
11321 					done = B_TRUE;
11322 				}
11323 				ire_refrele(ire);
11324 			}
11325 			if (!done) {
11326 				error = optfn(connp, checkonly, &v6grp,
11327 				    ifindex, fmode, &v6src, first_mp);
11328 			}
11329 			if (error != 0) {
11330 				/*
11331 				 * EINPROGRESS is a soft error, needs retry
11332 				 * so don't make *outlenp zero.
11333 				 */
11334 				if (error != EINPROGRESS)
11335 					*outlenp = 0;
11336 				return (error);
11337 			}
11338 			/* OK return - copy input buffer into output buffer */
11339 			if (invalp != outvalp) {
11340 				bcopy(invalp, outvalp, inlen);
11341 			}
11342 			*outlenp = inlen;
11343 			return (0);
11344 		}
11345 		case IPV6_UNICAST_HOPS:
11346 			/* Recorded in transport above IP */
11347 			break;	/* goto sizeof (int) option return */
11348 		case IPV6_UNSPEC_SRC:
11349 			/* Allow sending with a zero source address */
11350 			if (!checkonly) {
11351 				mutex_enter(&connp->conn_lock);
11352 				connp->conn_unspec_src = *i1 ? 1 : 0;
11353 				mutex_exit(&connp->conn_lock);
11354 			}
11355 			break;	/* goto sizeof (int) option return */
11356 		case IPV6_RECVPKTINFO:
11357 			if (!checkonly) {
11358 				mutex_enter(&connp->conn_lock);
11359 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11360 				mutex_exit(&connp->conn_lock);
11361 			}
11362 			break;	/* goto sizeof (int) option return */
11363 		case IPV6_RECVTCLASS:
11364 			if (!checkonly) {
11365 				if (*i1 < 0 || *i1 > 1) {
11366 					return (EINVAL);
11367 				}
11368 				mutex_enter(&connp->conn_lock);
11369 				connp->conn_ipv6_recvtclass = *i1;
11370 				mutex_exit(&connp->conn_lock);
11371 			}
11372 			break;
11373 		case IPV6_RECVPATHMTU:
11374 			if (!checkonly) {
11375 				if (*i1 < 0 || *i1 > 1) {
11376 					return (EINVAL);
11377 				}
11378 				mutex_enter(&connp->conn_lock);
11379 				connp->conn_ipv6_recvpathmtu = *i1;
11380 				mutex_exit(&connp->conn_lock);
11381 			}
11382 			break;
11383 		case IPV6_RECVHOPLIMIT:
11384 			if (!checkonly) {
11385 				mutex_enter(&connp->conn_lock);
11386 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11387 				mutex_exit(&connp->conn_lock);
11388 			}
11389 			break;	/* goto sizeof (int) option return */
11390 		case IPV6_RECVHOPOPTS:
11391 			if (!checkonly) {
11392 				mutex_enter(&connp->conn_lock);
11393 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11394 				mutex_exit(&connp->conn_lock);
11395 			}
11396 			break;	/* goto sizeof (int) option return */
11397 		case IPV6_RECVDSTOPTS:
11398 			if (!checkonly) {
11399 				mutex_enter(&connp->conn_lock);
11400 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11401 				mutex_exit(&connp->conn_lock);
11402 			}
11403 			break;	/* goto sizeof (int) option return */
11404 		case IPV6_RECVRTHDR:
11405 			if (!checkonly) {
11406 				mutex_enter(&connp->conn_lock);
11407 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11408 				mutex_exit(&connp->conn_lock);
11409 			}
11410 			break;	/* goto sizeof (int) option return */
11411 		case IPV6_RECVRTHDRDSTOPTS:
11412 			if (!checkonly) {
11413 				mutex_enter(&connp->conn_lock);
11414 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11415 				mutex_exit(&connp->conn_lock);
11416 			}
11417 			break;	/* goto sizeof (int) option return */
11418 		case IPV6_PKTINFO:
11419 			if (inlen == 0)
11420 				return (-EINVAL);	/* clearing option */
11421 			error = ip6_set_pktinfo(cr, connp,
11422 			    (struct in6_pktinfo *)invalp, first_mp);
11423 			if (error != 0)
11424 				*outlenp = 0;
11425 			else
11426 				*outlenp = inlen;
11427 			return (error);
11428 		case IPV6_NEXTHOP: {
11429 			struct sockaddr_in6 *sin6;
11430 
11431 			/* Verify that the nexthop is reachable */
11432 			if (inlen == 0)
11433 				return (-EINVAL);	/* clearing option */
11434 
11435 			sin6 = (struct sockaddr_in6 *)invalp;
11436 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11437 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11438 			    NULL, MATCH_IRE_DEFAULT, ipst);
11439 
11440 			if (ire == NULL) {
11441 				*outlenp = 0;
11442 				return (EHOSTUNREACH);
11443 			}
11444 			ire_refrele(ire);
11445 			return (-EINVAL);
11446 		}
11447 		case IPV6_SEC_OPT:
11448 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11449 			if (error != 0) {
11450 				*outlenp = 0;
11451 				return (error);
11452 			}
11453 			break;
11454 		case IPV6_SRC_PREFERENCES: {
11455 			/*
11456 			 * This is implemented strictly in the ip module
11457 			 * (here and in tcp_opt_*() to accomodate tcp
11458 			 * sockets).  Modules above ip pass this option
11459 			 * down here since ip is the only one that needs to
11460 			 * be aware of source address preferences.
11461 			 *
11462 			 * This socket option only affects connected
11463 			 * sockets that haven't already bound to a specific
11464 			 * IPv6 address.  In other words, sockets that
11465 			 * don't call bind() with an address other than the
11466 			 * unspecified address and that call connect().
11467 			 * ip_bind_connected_v6() passes these preferences
11468 			 * to the ipif_select_source_v6() function.
11469 			 */
11470 			if (inlen != sizeof (uint32_t))
11471 				return (EINVAL);
11472 			error = ip6_set_src_preferences(connp,
11473 			    *(uint32_t *)invalp);
11474 			if (error != 0) {
11475 				*outlenp = 0;
11476 				return (error);
11477 			} else {
11478 				*outlenp = sizeof (uint32_t);
11479 			}
11480 			break;
11481 		}
11482 		case IPV6_V6ONLY:
11483 			if (*i1 < 0 || *i1 > 1) {
11484 				return (EINVAL);
11485 			}
11486 			mutex_enter(&connp->conn_lock);
11487 			connp->conn_ipv6_v6only = *i1;
11488 			mutex_exit(&connp->conn_lock);
11489 			break;
11490 		default:
11491 			return (-EINVAL);
11492 		}
11493 		break;
11494 	default:
11495 		/*
11496 		 * "soft" error (negative)
11497 		 * option not handled at this level
11498 		 * Note: Do not modify *outlenp
11499 		 */
11500 		return (-EINVAL);
11501 	}
11502 	/*
11503 	 * Common case of return from an option that is sizeof (int)
11504 	 */
11505 	*(int *)outvalp = *i1;
11506 	*outlenp = sizeof (int);
11507 	return (0);
11508 }
11509 
11510 /*
11511  * This routine gets default values of certain options whose default
11512  * values are maintained by protocol specific code
11513  */
11514 /* ARGSUSED */
11515 int
11516 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11517 {
11518 	int *i1 = (int *)ptr;
11519 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11520 
11521 	switch (level) {
11522 	case IPPROTO_IP:
11523 		switch (name) {
11524 		case IP_MULTICAST_TTL:
11525 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11526 			return (sizeof (uchar_t));
11527 		case IP_MULTICAST_LOOP:
11528 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11529 			return (sizeof (uchar_t));
11530 		default:
11531 			return (-1);
11532 		}
11533 	case IPPROTO_IPV6:
11534 		switch (name) {
11535 		case IPV6_UNICAST_HOPS:
11536 			*i1 = ipst->ips_ipv6_def_hops;
11537 			return (sizeof (int));
11538 		case IPV6_MULTICAST_HOPS:
11539 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11540 			return (sizeof (int));
11541 		case IPV6_MULTICAST_LOOP:
11542 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11543 			return (sizeof (int));
11544 		case IPV6_V6ONLY:
11545 			*i1 = 1;
11546 			return (sizeof (int));
11547 		default:
11548 			return (-1);
11549 		}
11550 	default:
11551 		return (-1);
11552 	}
11553 	/* NOTREACHED */
11554 }
11555 
11556 /*
11557  * Given a destination address and a pointer to where to put the information
11558  * this routine fills in the mtuinfo.
11559  */
11560 int
11561 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11562     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11563 {
11564 	ire_t *ire;
11565 	ip_stack_t	*ipst = ns->netstack_ip;
11566 
11567 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11568 		return (-1);
11569 
11570 	bzero(mtuinfo, sizeof (*mtuinfo));
11571 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11572 	mtuinfo->ip6m_addr.sin6_port = port;
11573 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11574 
11575 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11576 	if (ire != NULL) {
11577 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11578 		ire_refrele(ire);
11579 	} else {
11580 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11581 	}
11582 	return (sizeof (struct ip6_mtuinfo));
11583 }
11584 
11585 /*
11586  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11587  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11588  * isn't.  This doesn't matter as the error checking is done properly for the
11589  * other MRT options coming in through ip_opt_set.
11590  */
11591 int
11592 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11593 {
11594 	conn_t		*connp = Q_TO_CONN(q);
11595 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11596 
11597 	switch (level) {
11598 	case IPPROTO_IP:
11599 		switch (name) {
11600 		case MRT_VERSION:
11601 		case MRT_ASSERT:
11602 			(void) ip_mrouter_get(name, q, ptr);
11603 			return (sizeof (int));
11604 		case IP_SEC_OPT:
11605 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11606 		case IP_NEXTHOP:
11607 			if (connp->conn_nexthop_set) {
11608 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11609 				return (sizeof (ipaddr_t));
11610 			} else
11611 				return (0);
11612 		case IP_RECVPKTINFO:
11613 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11614 			return (sizeof (int));
11615 		default:
11616 			break;
11617 		}
11618 		break;
11619 	case IPPROTO_IPV6:
11620 		switch (name) {
11621 		case IPV6_SEC_OPT:
11622 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11623 		case IPV6_SRC_PREFERENCES: {
11624 			return (ip6_get_src_preferences(connp,
11625 			    (uint32_t *)ptr));
11626 		}
11627 		case IPV6_V6ONLY:
11628 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11629 			return (sizeof (int));
11630 		case IPV6_PATHMTU:
11631 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11632 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11633 		default:
11634 			break;
11635 		}
11636 		break;
11637 	default:
11638 		break;
11639 	}
11640 	return (-1);
11641 }
11642 
11643 /* Named Dispatch routine to get a current value out of our parameter table. */
11644 /* ARGSUSED */
11645 static int
11646 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11647 {
11648 	ipparam_t *ippa = (ipparam_t *)cp;
11649 
11650 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11651 	return (0);
11652 }
11653 
11654 /* ARGSUSED */
11655 static int
11656 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11657 {
11658 
11659 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11660 	return (0);
11661 }
11662 
11663 /*
11664  * Set ip{,6}_forwarding values.  This means walking through all of the
11665  * ill's and toggling their forwarding values.
11666  */
11667 /* ARGSUSED */
11668 static int
11669 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11670 {
11671 	long new_value;
11672 	int *forwarding_value = (int *)cp;
11673 	ill_t *ill;
11674 	boolean_t isv6;
11675 	ill_walk_context_t ctx;
11676 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11677 
11678 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11679 
11680 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11681 	    new_value < 0 || new_value > 1) {
11682 		return (EINVAL);
11683 	}
11684 
11685 	*forwarding_value = new_value;
11686 
11687 	/*
11688 	 * Regardless of the current value of ip_forwarding, set all per-ill
11689 	 * values of ip_forwarding to the value being set.
11690 	 *
11691 	 * Bring all the ill's up to date with the new global value.
11692 	 */
11693 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11694 
11695 	if (isv6)
11696 		ill = ILL_START_WALK_V6(&ctx, ipst);
11697 	else
11698 		ill = ILL_START_WALK_V4(&ctx, ipst);
11699 
11700 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11701 		(void) ill_forward_set(ill, new_value != 0);
11702 
11703 	rw_exit(&ipst->ips_ill_g_lock);
11704 	return (0);
11705 }
11706 
11707 /*
11708  * Walk through the param array specified registering each element with the
11709  * Named Dispatch handler. This is called only during init. So it is ok
11710  * not to acquire any locks
11711  */
11712 static boolean_t
11713 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11714     ipndp_t *ipnd, size_t ipnd_cnt)
11715 {
11716 	for (; ippa_cnt-- > 0; ippa++) {
11717 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11718 			if (!nd_load(ndp, ippa->ip_param_name,
11719 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11720 				nd_free(ndp);
11721 				return (B_FALSE);
11722 			}
11723 		}
11724 	}
11725 
11726 	for (; ipnd_cnt-- > 0; ipnd++) {
11727 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11728 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11729 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11730 			    ipnd->ip_ndp_data)) {
11731 				nd_free(ndp);
11732 				return (B_FALSE);
11733 			}
11734 		}
11735 	}
11736 
11737 	return (B_TRUE);
11738 }
11739 
11740 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11741 /* ARGSUSED */
11742 static int
11743 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11744 {
11745 	long		new_value;
11746 	ipparam_t	*ippa = (ipparam_t *)cp;
11747 
11748 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11749 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11750 		return (EINVAL);
11751 	}
11752 	ippa->ip_param_value = new_value;
11753 	return (0);
11754 }
11755 
11756 /*
11757  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11758  * When an ipf is passed here for the first time, if
11759  * we already have in-order fragments on the queue, we convert from the fast-
11760  * path reassembly scheme to the hard-case scheme.  From then on, additional
11761  * fragments are reassembled here.  We keep track of the start and end offsets
11762  * of each piece, and the number of holes in the chain.  When the hole count
11763  * goes to zero, we are done!
11764  *
11765  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11766  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11767  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11768  * after the call to ip_reassemble().
11769  */
11770 int
11771 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11772     size_t msg_len)
11773 {
11774 	uint_t	end;
11775 	mblk_t	*next_mp;
11776 	mblk_t	*mp1;
11777 	uint_t	offset;
11778 	boolean_t incr_dups = B_TRUE;
11779 	boolean_t offset_zero_seen = B_FALSE;
11780 	boolean_t pkt_boundary_checked = B_FALSE;
11781 
11782 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11783 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11784 
11785 	/* Add in byte count */
11786 	ipf->ipf_count += msg_len;
11787 	if (ipf->ipf_end) {
11788 		/*
11789 		 * We were part way through in-order reassembly, but now there
11790 		 * is a hole.  We walk through messages already queued, and
11791 		 * mark them for hard case reassembly.  We know that up till
11792 		 * now they were in order starting from offset zero.
11793 		 */
11794 		offset = 0;
11795 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11796 			IP_REASS_SET_START(mp1, offset);
11797 			if (offset == 0) {
11798 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11799 				offset = -ipf->ipf_nf_hdr_len;
11800 			}
11801 			offset += mp1->b_wptr - mp1->b_rptr;
11802 			IP_REASS_SET_END(mp1, offset);
11803 		}
11804 		/* One hole at the end. */
11805 		ipf->ipf_hole_cnt = 1;
11806 		/* Brand it as a hard case, forever. */
11807 		ipf->ipf_end = 0;
11808 	}
11809 	/* Walk through all the new pieces. */
11810 	do {
11811 		end = start + (mp->b_wptr - mp->b_rptr);
11812 		/*
11813 		 * If start is 0, decrease 'end' only for the first mblk of
11814 		 * the fragment. Otherwise 'end' can get wrong value in the
11815 		 * second pass of the loop if first mblk is exactly the
11816 		 * size of ipf_nf_hdr_len.
11817 		 */
11818 		if (start == 0 && !offset_zero_seen) {
11819 			/* First segment */
11820 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11821 			end -= ipf->ipf_nf_hdr_len;
11822 			offset_zero_seen = B_TRUE;
11823 		}
11824 		next_mp = mp->b_cont;
11825 		/*
11826 		 * We are checking to see if there is any interesing data
11827 		 * to process.  If there isn't and the mblk isn't the
11828 		 * one which carries the unfragmentable header then we
11829 		 * drop it.  It's possible to have just the unfragmentable
11830 		 * header come through without any data.  That needs to be
11831 		 * saved.
11832 		 *
11833 		 * If the assert at the top of this function holds then the
11834 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11835 		 * is infrequently traveled enough that the test is left in
11836 		 * to protect against future code changes which break that
11837 		 * invariant.
11838 		 */
11839 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11840 			/* Empty.  Blast it. */
11841 			IP_REASS_SET_START(mp, 0);
11842 			IP_REASS_SET_END(mp, 0);
11843 			/*
11844 			 * If the ipf points to the mblk we are about to free,
11845 			 * update ipf to point to the next mblk (or NULL
11846 			 * if none).
11847 			 */
11848 			if (ipf->ipf_mp->b_cont == mp)
11849 				ipf->ipf_mp->b_cont = next_mp;
11850 			freeb(mp);
11851 			continue;
11852 		}
11853 		mp->b_cont = NULL;
11854 		IP_REASS_SET_START(mp, start);
11855 		IP_REASS_SET_END(mp, end);
11856 		if (!ipf->ipf_tail_mp) {
11857 			ipf->ipf_tail_mp = mp;
11858 			ipf->ipf_mp->b_cont = mp;
11859 			if (start == 0 || !more) {
11860 				ipf->ipf_hole_cnt = 1;
11861 				/*
11862 				 * if the first fragment comes in more than one
11863 				 * mblk, this loop will be executed for each
11864 				 * mblk. Need to adjust hole count so exiting
11865 				 * this routine will leave hole count at 1.
11866 				 */
11867 				if (next_mp)
11868 					ipf->ipf_hole_cnt++;
11869 			} else
11870 				ipf->ipf_hole_cnt = 2;
11871 			continue;
11872 		} else if (ipf->ipf_last_frag_seen && !more &&
11873 		    !pkt_boundary_checked) {
11874 			/*
11875 			 * We check datagram boundary only if this fragment
11876 			 * claims to be the last fragment and we have seen a
11877 			 * last fragment in the past too. We do this only
11878 			 * once for a given fragment.
11879 			 *
11880 			 * start cannot be 0 here as fragments with start=0
11881 			 * and MF=0 gets handled as a complete packet. These
11882 			 * fragments should not reach here.
11883 			 */
11884 
11885 			if (start + msgdsize(mp) !=
11886 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11887 				/*
11888 				 * We have two fragments both of which claim
11889 				 * to be the last fragment but gives conflicting
11890 				 * information about the whole datagram size.
11891 				 * Something fishy is going on. Drop the
11892 				 * fragment and free up the reassembly list.
11893 				 */
11894 				return (IP_REASS_FAILED);
11895 			}
11896 
11897 			/*
11898 			 * We shouldn't come to this code block again for this
11899 			 * particular fragment.
11900 			 */
11901 			pkt_boundary_checked = B_TRUE;
11902 		}
11903 
11904 		/* New stuff at or beyond tail? */
11905 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11906 		if (start >= offset) {
11907 			if (ipf->ipf_last_frag_seen) {
11908 				/* current fragment is beyond last fragment */
11909 				return (IP_REASS_FAILED);
11910 			}
11911 			/* Link it on end. */
11912 			ipf->ipf_tail_mp->b_cont = mp;
11913 			ipf->ipf_tail_mp = mp;
11914 			if (more) {
11915 				if (start != offset)
11916 					ipf->ipf_hole_cnt++;
11917 			} else if (start == offset && next_mp == NULL)
11918 					ipf->ipf_hole_cnt--;
11919 			continue;
11920 		}
11921 		mp1 = ipf->ipf_mp->b_cont;
11922 		offset = IP_REASS_START(mp1);
11923 		/* New stuff at the front? */
11924 		if (start < offset) {
11925 			if (start == 0) {
11926 				if (end >= offset) {
11927 					/* Nailed the hole at the begining. */
11928 					ipf->ipf_hole_cnt--;
11929 				}
11930 			} else if (end < offset) {
11931 				/*
11932 				 * A hole, stuff, and a hole where there used
11933 				 * to be just a hole.
11934 				 */
11935 				ipf->ipf_hole_cnt++;
11936 			}
11937 			mp->b_cont = mp1;
11938 			/* Check for overlap. */
11939 			while (end > offset) {
11940 				if (end < IP_REASS_END(mp1)) {
11941 					mp->b_wptr -= end - offset;
11942 					IP_REASS_SET_END(mp, offset);
11943 					BUMP_MIB(ill->ill_ip_mib,
11944 					    ipIfStatsReasmPartDups);
11945 					break;
11946 				}
11947 				/* Did we cover another hole? */
11948 				if ((mp1->b_cont &&
11949 				    IP_REASS_END(mp1) !=
11950 				    IP_REASS_START(mp1->b_cont) &&
11951 				    end >= IP_REASS_START(mp1->b_cont)) ||
11952 				    (!ipf->ipf_last_frag_seen && !more)) {
11953 					ipf->ipf_hole_cnt--;
11954 				}
11955 				/* Clip out mp1. */
11956 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11957 					/*
11958 					 * After clipping out mp1, this guy
11959 					 * is now hanging off the end.
11960 					 */
11961 					ipf->ipf_tail_mp = mp;
11962 				}
11963 				IP_REASS_SET_START(mp1, 0);
11964 				IP_REASS_SET_END(mp1, 0);
11965 				/* Subtract byte count */
11966 				ipf->ipf_count -= mp1->b_datap->db_lim -
11967 				    mp1->b_datap->db_base;
11968 				freeb(mp1);
11969 				BUMP_MIB(ill->ill_ip_mib,
11970 				    ipIfStatsReasmPartDups);
11971 				mp1 = mp->b_cont;
11972 				if (!mp1)
11973 					break;
11974 				offset = IP_REASS_START(mp1);
11975 			}
11976 			ipf->ipf_mp->b_cont = mp;
11977 			continue;
11978 		}
11979 		/*
11980 		 * The new piece starts somewhere between the start of the head
11981 		 * and before the end of the tail.
11982 		 */
11983 		for (; mp1; mp1 = mp1->b_cont) {
11984 			offset = IP_REASS_END(mp1);
11985 			if (start < offset) {
11986 				if (end <= offset) {
11987 					/* Nothing new. */
11988 					IP_REASS_SET_START(mp, 0);
11989 					IP_REASS_SET_END(mp, 0);
11990 					/* Subtract byte count */
11991 					ipf->ipf_count -= mp->b_datap->db_lim -
11992 					    mp->b_datap->db_base;
11993 					if (incr_dups) {
11994 						ipf->ipf_num_dups++;
11995 						incr_dups = B_FALSE;
11996 					}
11997 					freeb(mp);
11998 					BUMP_MIB(ill->ill_ip_mib,
11999 					    ipIfStatsReasmDuplicates);
12000 					break;
12001 				}
12002 				/*
12003 				 * Trim redundant stuff off beginning of new
12004 				 * piece.
12005 				 */
12006 				IP_REASS_SET_START(mp, offset);
12007 				mp->b_rptr += offset - start;
12008 				BUMP_MIB(ill->ill_ip_mib,
12009 				    ipIfStatsReasmPartDups);
12010 				start = offset;
12011 				if (!mp1->b_cont) {
12012 					/*
12013 					 * After trimming, this guy is now
12014 					 * hanging off the end.
12015 					 */
12016 					mp1->b_cont = mp;
12017 					ipf->ipf_tail_mp = mp;
12018 					if (!more) {
12019 						ipf->ipf_hole_cnt--;
12020 					}
12021 					break;
12022 				}
12023 			}
12024 			if (start >= IP_REASS_START(mp1->b_cont))
12025 				continue;
12026 			/* Fill a hole */
12027 			if (start > offset)
12028 				ipf->ipf_hole_cnt++;
12029 			mp->b_cont = mp1->b_cont;
12030 			mp1->b_cont = mp;
12031 			mp1 = mp->b_cont;
12032 			offset = IP_REASS_START(mp1);
12033 			if (end >= offset) {
12034 				ipf->ipf_hole_cnt--;
12035 				/* Check for overlap. */
12036 				while (end > offset) {
12037 					if (end < IP_REASS_END(mp1)) {
12038 						mp->b_wptr -= end - offset;
12039 						IP_REASS_SET_END(mp, offset);
12040 						/*
12041 						 * TODO we might bump
12042 						 * this up twice if there is
12043 						 * overlap at both ends.
12044 						 */
12045 						BUMP_MIB(ill->ill_ip_mib,
12046 						    ipIfStatsReasmPartDups);
12047 						break;
12048 					}
12049 					/* Did we cover another hole? */
12050 					if ((mp1->b_cont &&
12051 					    IP_REASS_END(mp1)
12052 					    != IP_REASS_START(mp1->b_cont) &&
12053 					    end >=
12054 					    IP_REASS_START(mp1->b_cont)) ||
12055 					    (!ipf->ipf_last_frag_seen &&
12056 					    !more)) {
12057 						ipf->ipf_hole_cnt--;
12058 					}
12059 					/* Clip out mp1. */
12060 					if ((mp->b_cont = mp1->b_cont) ==
12061 					    NULL) {
12062 						/*
12063 						 * After clipping out mp1,
12064 						 * this guy is now hanging
12065 						 * off the end.
12066 						 */
12067 						ipf->ipf_tail_mp = mp;
12068 					}
12069 					IP_REASS_SET_START(mp1, 0);
12070 					IP_REASS_SET_END(mp1, 0);
12071 					/* Subtract byte count */
12072 					ipf->ipf_count -=
12073 					    mp1->b_datap->db_lim -
12074 					    mp1->b_datap->db_base;
12075 					freeb(mp1);
12076 					BUMP_MIB(ill->ill_ip_mib,
12077 					    ipIfStatsReasmPartDups);
12078 					mp1 = mp->b_cont;
12079 					if (!mp1)
12080 						break;
12081 					offset = IP_REASS_START(mp1);
12082 				}
12083 			}
12084 			break;
12085 		}
12086 	} while (start = end, mp = next_mp);
12087 
12088 	/* Fragment just processed could be the last one. Remember this fact */
12089 	if (!more)
12090 		ipf->ipf_last_frag_seen = B_TRUE;
12091 
12092 	/* Still got holes? */
12093 	if (ipf->ipf_hole_cnt)
12094 		return (IP_REASS_PARTIAL);
12095 	/* Clean up overloaded fields to avoid upstream disasters. */
12096 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12097 		IP_REASS_SET_START(mp1, 0);
12098 		IP_REASS_SET_END(mp1, 0);
12099 	}
12100 	return (IP_REASS_COMPLETE);
12101 }
12102 
12103 /*
12104  * ipsec processing for the fast path, used for input UDP Packets
12105  * Returns true if ready for passup to UDP.
12106  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
12107  * was an ESP-in-UDP packet, etc.).
12108  */
12109 static boolean_t
12110 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12111     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
12112 {
12113 	uint32_t	ill_index;
12114 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12115 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12116 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12117 	udp_t		*udp = connp->conn_udp;
12118 
12119 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12120 	/* The ill_index of the incoming ILL */
12121 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12122 
12123 	/* pass packet up to the transport */
12124 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12125 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12126 		    NULL, mctl_present);
12127 		if (*first_mpp == NULL) {
12128 			return (B_FALSE);
12129 		}
12130 	}
12131 
12132 	/* Initiate IPPF processing for fastpath UDP */
12133 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12134 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12135 		if (*mpp == NULL) {
12136 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12137 			    "deferred/dropped during IPPF processing\n"));
12138 			return (B_FALSE);
12139 		}
12140 	}
12141 	/*
12142 	 * Remove 0-spi if it's 0, or move everything behind
12143 	 * the UDP header over it and forward to ESP via
12144 	 * ip_proto_input().
12145 	 */
12146 	if (udp->udp_nat_t_endpoint) {
12147 		if (mctl_present) {
12148 			/* mctl_present *shouldn't* happen. */
12149 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
12150 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
12151 			    &ipss->ipsec_dropper);
12152 			*first_mpp = NULL;
12153 			return (B_FALSE);
12154 		}
12155 
12156 		/* "ill" is "recv_ill" in actuality. */
12157 		if (!zero_spi_check(q, *mpp, ire, ill, ipss))
12158 			return (B_FALSE);
12159 
12160 		/* Else continue like a normal UDP packet. */
12161 	}
12162 
12163 	/*
12164 	 * We make the checks as below since we are in the fast path
12165 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12166 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12167 	 */
12168 	if (connp->conn_recvif || connp->conn_recvslla ||
12169 	    connp->conn_ip_recvpktinfo) {
12170 		if (connp->conn_recvif) {
12171 			in_flags = IPF_RECVIF;
12172 		}
12173 		/*
12174 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12175 		 * so the flag passed to ip_add_info is based on IP version
12176 		 * of connp.
12177 		 */
12178 		if (connp->conn_ip_recvpktinfo) {
12179 			if (connp->conn_af_isv6) {
12180 				/*
12181 				 * V6 only needs index
12182 				 */
12183 				in_flags |= IPF_RECVIF;
12184 			} else {
12185 				/*
12186 				 * V4 needs index + matching address.
12187 				 */
12188 				in_flags |= IPF_RECVADDR;
12189 			}
12190 		}
12191 		if (connp->conn_recvslla) {
12192 			in_flags |= IPF_RECVSLLA;
12193 		}
12194 		/*
12195 		 * since in_flags are being set ill will be
12196 		 * referenced in ip_add_info, so it better not
12197 		 * be NULL.
12198 		 */
12199 		/*
12200 		 * the actual data will be contained in b_cont
12201 		 * upon successful return of the following call.
12202 		 * If the call fails then the original mblk is
12203 		 * returned.
12204 		 */
12205 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12206 		    ipst);
12207 	}
12208 
12209 	return (B_TRUE);
12210 }
12211 
12212 /*
12213  * Fragmentation reassembly.  Each ILL has a hash table for
12214  * queuing packets undergoing reassembly for all IPIFs
12215  * associated with the ILL.  The hash is based on the packet
12216  * IP ident field.  The ILL frag hash table was allocated
12217  * as a timer block at the time the ILL was created.  Whenever
12218  * there is anything on the reassembly queue, the timer will
12219  * be running.  Returns B_TRUE if successful else B_FALSE;
12220  * frees mp on failure.
12221  */
12222 static boolean_t
12223 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12224     uint32_t *cksum_val, uint16_t *cksum_flags)
12225 {
12226 	uint32_t	frag_offset_flags;
12227 	ill_t		*ill = (ill_t *)q->q_ptr;
12228 	mblk_t		*mp = *mpp;
12229 	mblk_t		*t_mp;
12230 	ipaddr_t	dst;
12231 	uint8_t		proto = ipha->ipha_protocol;
12232 	uint32_t	sum_val;
12233 	uint16_t	sum_flags;
12234 	ipf_t		*ipf;
12235 	ipf_t		**ipfp;
12236 	ipfb_t		*ipfb;
12237 	uint16_t	ident;
12238 	uint32_t	offset;
12239 	ipaddr_t	src;
12240 	uint_t		hdr_length;
12241 	uint32_t	end;
12242 	mblk_t		*mp1;
12243 	mblk_t		*tail_mp;
12244 	size_t		count;
12245 	size_t		msg_len;
12246 	uint8_t		ecn_info = 0;
12247 	uint32_t	packet_size;
12248 	boolean_t	pruned = B_FALSE;
12249 	ip_stack_t *ipst = ill->ill_ipst;
12250 
12251 	if (cksum_val != NULL)
12252 		*cksum_val = 0;
12253 	if (cksum_flags != NULL)
12254 		*cksum_flags = 0;
12255 
12256 	/*
12257 	 * Drop the fragmented as early as possible, if
12258 	 * we don't have resource(s) to re-assemble.
12259 	 */
12260 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12261 		freemsg(mp);
12262 		return (B_FALSE);
12263 	}
12264 
12265 	/* Check for fragmentation offset; return if there's none */
12266 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12267 	    (IPH_MF | IPH_OFFSET)) == 0)
12268 		return (B_TRUE);
12269 
12270 	/*
12271 	 * We utilize hardware computed checksum info only for UDP since
12272 	 * IP fragmentation is a normal occurence for the protocol.  In
12273 	 * addition, checksum offload support for IP fragments carrying
12274 	 * UDP payload is commonly implemented across network adapters.
12275 	 */
12276 	ASSERT(ill != NULL);
12277 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12278 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12279 		mblk_t *mp1 = mp->b_cont;
12280 		int32_t len;
12281 
12282 		/* Record checksum information from the packet */
12283 		sum_val = (uint32_t)DB_CKSUM16(mp);
12284 		sum_flags = DB_CKSUMFLAGS(mp);
12285 
12286 		/* IP payload offset from beginning of mblk */
12287 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12288 
12289 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12290 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12291 		    offset >= DB_CKSUMSTART(mp) &&
12292 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12293 			uint32_t adj;
12294 			/*
12295 			 * Partial checksum has been calculated by hardware
12296 			 * and attached to the packet; in addition, any
12297 			 * prepended extraneous data is even byte aligned.
12298 			 * If any such data exists, we adjust the checksum;
12299 			 * this would also handle any postpended data.
12300 			 */
12301 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12302 			    mp, mp1, len, adj);
12303 
12304 			/* One's complement subtract extraneous checksum */
12305 			if (adj >= sum_val)
12306 				sum_val = ~(adj - sum_val) & 0xFFFF;
12307 			else
12308 				sum_val -= adj;
12309 		}
12310 	} else {
12311 		sum_val = 0;
12312 		sum_flags = 0;
12313 	}
12314 
12315 	/* Clear hardware checksumming flag */
12316 	DB_CKSUMFLAGS(mp) = 0;
12317 
12318 	ident = ipha->ipha_ident;
12319 	offset = (frag_offset_flags << 3) & 0xFFFF;
12320 	src = ipha->ipha_src;
12321 	dst = ipha->ipha_dst;
12322 	hdr_length = IPH_HDR_LENGTH(ipha);
12323 	end = ntohs(ipha->ipha_length) - hdr_length;
12324 
12325 	/* If end == 0 then we have a packet with no data, so just free it */
12326 	if (end == 0) {
12327 		freemsg(mp);
12328 		return (B_FALSE);
12329 	}
12330 
12331 	/* Record the ECN field info. */
12332 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12333 	if (offset != 0) {
12334 		/*
12335 		 * If this isn't the first piece, strip the header, and
12336 		 * add the offset to the end value.
12337 		 */
12338 		mp->b_rptr += hdr_length;
12339 		end += offset;
12340 	}
12341 
12342 	msg_len = MBLKSIZE(mp);
12343 	tail_mp = mp;
12344 	while (tail_mp->b_cont != NULL) {
12345 		tail_mp = tail_mp->b_cont;
12346 		msg_len += MBLKSIZE(tail_mp);
12347 	}
12348 
12349 	/* If the reassembly list for this ILL will get too big, prune it */
12350 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12351 	    ipst->ips_ip_reass_queue_bytes) {
12352 		ill_frag_prune(ill,
12353 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12354 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12355 		pruned = B_TRUE;
12356 	}
12357 
12358 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12359 	mutex_enter(&ipfb->ipfb_lock);
12360 
12361 	ipfp = &ipfb->ipfb_ipf;
12362 	/* Try to find an existing fragment queue for this packet. */
12363 	for (;;) {
12364 		ipf = ipfp[0];
12365 		if (ipf != NULL) {
12366 			/*
12367 			 * It has to match on ident and src/dst address.
12368 			 */
12369 			if (ipf->ipf_ident == ident &&
12370 			    ipf->ipf_src == src &&
12371 			    ipf->ipf_dst == dst &&
12372 			    ipf->ipf_protocol == proto) {
12373 				/*
12374 				 * If we have received too many
12375 				 * duplicate fragments for this packet
12376 				 * free it.
12377 				 */
12378 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12379 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12380 					freemsg(mp);
12381 					mutex_exit(&ipfb->ipfb_lock);
12382 					return (B_FALSE);
12383 				}
12384 				/* Found it. */
12385 				break;
12386 			}
12387 			ipfp = &ipf->ipf_hash_next;
12388 			continue;
12389 		}
12390 
12391 		/*
12392 		 * If we pruned the list, do we want to store this new
12393 		 * fragment?. We apply an optimization here based on the
12394 		 * fact that most fragments will be received in order.
12395 		 * So if the offset of this incoming fragment is zero,
12396 		 * it is the first fragment of a new packet. We will
12397 		 * keep it.  Otherwise drop the fragment, as we have
12398 		 * probably pruned the packet already (since the
12399 		 * packet cannot be found).
12400 		 */
12401 		if (pruned && offset != 0) {
12402 			mutex_exit(&ipfb->ipfb_lock);
12403 			freemsg(mp);
12404 			return (B_FALSE);
12405 		}
12406 
12407 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12408 			/*
12409 			 * Too many fragmented packets in this hash
12410 			 * bucket. Free the oldest.
12411 			 */
12412 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12413 		}
12414 
12415 		/* New guy.  Allocate a frag message. */
12416 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12417 		if (mp1 == NULL) {
12418 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12419 			freemsg(mp);
12420 reass_done:
12421 			mutex_exit(&ipfb->ipfb_lock);
12422 			return (B_FALSE);
12423 		}
12424 
12425 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12426 		mp1->b_cont = mp;
12427 
12428 		/* Initialize the fragment header. */
12429 		ipf = (ipf_t *)mp1->b_rptr;
12430 		ipf->ipf_mp = mp1;
12431 		ipf->ipf_ptphn = ipfp;
12432 		ipfp[0] = ipf;
12433 		ipf->ipf_hash_next = NULL;
12434 		ipf->ipf_ident = ident;
12435 		ipf->ipf_protocol = proto;
12436 		ipf->ipf_src = src;
12437 		ipf->ipf_dst = dst;
12438 		ipf->ipf_nf_hdr_len = 0;
12439 		/* Record reassembly start time. */
12440 		ipf->ipf_timestamp = gethrestime_sec();
12441 		/* Record ipf generation and account for frag header */
12442 		ipf->ipf_gen = ill->ill_ipf_gen++;
12443 		ipf->ipf_count = MBLKSIZE(mp1);
12444 		ipf->ipf_last_frag_seen = B_FALSE;
12445 		ipf->ipf_ecn = ecn_info;
12446 		ipf->ipf_num_dups = 0;
12447 		ipfb->ipfb_frag_pkts++;
12448 		ipf->ipf_checksum = 0;
12449 		ipf->ipf_checksum_flags = 0;
12450 
12451 		/* Store checksum value in fragment header */
12452 		if (sum_flags != 0) {
12453 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12454 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12455 			ipf->ipf_checksum = sum_val;
12456 			ipf->ipf_checksum_flags = sum_flags;
12457 		}
12458 
12459 		/*
12460 		 * We handle reassembly two ways.  In the easy case,
12461 		 * where all the fragments show up in order, we do
12462 		 * minimal bookkeeping, and just clip new pieces on
12463 		 * the end.  If we ever see a hole, then we go off
12464 		 * to ip_reassemble which has to mark the pieces and
12465 		 * keep track of the number of holes, etc.  Obviously,
12466 		 * the point of having both mechanisms is so we can
12467 		 * handle the easy case as efficiently as possible.
12468 		 */
12469 		if (offset == 0) {
12470 			/* Easy case, in-order reassembly so far. */
12471 			ipf->ipf_count += msg_len;
12472 			ipf->ipf_tail_mp = tail_mp;
12473 			/*
12474 			 * Keep track of next expected offset in
12475 			 * ipf_end.
12476 			 */
12477 			ipf->ipf_end = end;
12478 			ipf->ipf_nf_hdr_len = hdr_length;
12479 		} else {
12480 			/* Hard case, hole at the beginning. */
12481 			ipf->ipf_tail_mp = NULL;
12482 			/*
12483 			 * ipf_end == 0 means that we have given up
12484 			 * on easy reassembly.
12485 			 */
12486 			ipf->ipf_end = 0;
12487 
12488 			/* Forget checksum offload from now on */
12489 			ipf->ipf_checksum_flags = 0;
12490 
12491 			/*
12492 			 * ipf_hole_cnt is set by ip_reassemble.
12493 			 * ipf_count is updated by ip_reassemble.
12494 			 * No need to check for return value here
12495 			 * as we don't expect reassembly to complete
12496 			 * or fail for the first fragment itself.
12497 			 */
12498 			(void) ip_reassemble(mp, ipf,
12499 			    (frag_offset_flags & IPH_OFFSET) << 3,
12500 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12501 		}
12502 		/* Update per ipfb and ill byte counts */
12503 		ipfb->ipfb_count += ipf->ipf_count;
12504 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12505 		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
12506 		/* If the frag timer wasn't already going, start it. */
12507 		mutex_enter(&ill->ill_lock);
12508 		ill_frag_timer_start(ill);
12509 		mutex_exit(&ill->ill_lock);
12510 		goto reass_done;
12511 	}
12512 
12513 	/*
12514 	 * If the packet's flag has changed (it could be coming up
12515 	 * from an interface different than the previous, therefore
12516 	 * possibly different checksum capability), then forget about
12517 	 * any stored checksum states.  Otherwise add the value to
12518 	 * the existing one stored in the fragment header.
12519 	 */
12520 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12521 		sum_val += ipf->ipf_checksum;
12522 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12523 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12524 		ipf->ipf_checksum = sum_val;
12525 	} else if (ipf->ipf_checksum_flags != 0) {
12526 		/* Forget checksum offload from now on */
12527 		ipf->ipf_checksum_flags = 0;
12528 	}
12529 
12530 	/*
12531 	 * We have a new piece of a datagram which is already being
12532 	 * reassembled.  Update the ECN info if all IP fragments
12533 	 * are ECN capable.  If there is one which is not, clear
12534 	 * all the info.  If there is at least one which has CE
12535 	 * code point, IP needs to report that up to transport.
12536 	 */
12537 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12538 		if (ecn_info == IPH_ECN_CE)
12539 			ipf->ipf_ecn = IPH_ECN_CE;
12540 	} else {
12541 		ipf->ipf_ecn = IPH_ECN_NECT;
12542 	}
12543 	if (offset && ipf->ipf_end == offset) {
12544 		/* The new fragment fits at the end */
12545 		ipf->ipf_tail_mp->b_cont = mp;
12546 		/* Update the byte count */
12547 		ipf->ipf_count += msg_len;
12548 		/* Update per ipfb and ill byte counts */
12549 		ipfb->ipfb_count += msg_len;
12550 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12551 		atomic_add_32(&ill->ill_frag_count, msg_len);
12552 		if (frag_offset_flags & IPH_MF) {
12553 			/* More to come. */
12554 			ipf->ipf_end = end;
12555 			ipf->ipf_tail_mp = tail_mp;
12556 			goto reass_done;
12557 		}
12558 	} else {
12559 		/* Go do the hard cases. */
12560 		int ret;
12561 
12562 		if (offset == 0)
12563 			ipf->ipf_nf_hdr_len = hdr_length;
12564 
12565 		/* Save current byte count */
12566 		count = ipf->ipf_count;
12567 		ret = ip_reassemble(mp, ipf,
12568 		    (frag_offset_flags & IPH_OFFSET) << 3,
12569 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12570 		/* Count of bytes added and subtracted (freeb()ed) */
12571 		count = ipf->ipf_count - count;
12572 		if (count) {
12573 			/* Update per ipfb and ill byte counts */
12574 			ipfb->ipfb_count += count;
12575 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12576 			atomic_add_32(&ill->ill_frag_count, count);
12577 		}
12578 		if (ret == IP_REASS_PARTIAL) {
12579 			goto reass_done;
12580 		} else if (ret == IP_REASS_FAILED) {
12581 			/* Reassembly failed. Free up all resources */
12582 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12583 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12584 				IP_REASS_SET_START(t_mp, 0);
12585 				IP_REASS_SET_END(t_mp, 0);
12586 			}
12587 			freemsg(mp);
12588 			goto reass_done;
12589 		}
12590 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12591 	}
12592 	/*
12593 	 * We have completed reassembly.  Unhook the frag header from
12594 	 * the reassembly list.
12595 	 *
12596 	 * Before we free the frag header, record the ECN info
12597 	 * to report back to the transport.
12598 	 */
12599 	ecn_info = ipf->ipf_ecn;
12600 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12601 	ipfp = ipf->ipf_ptphn;
12602 
12603 	/* We need to supply these to caller */
12604 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12605 		sum_val = ipf->ipf_checksum;
12606 	else
12607 		sum_val = 0;
12608 
12609 	mp1 = ipf->ipf_mp;
12610 	count = ipf->ipf_count;
12611 	ipf = ipf->ipf_hash_next;
12612 	if (ipf != NULL)
12613 		ipf->ipf_ptphn = ipfp;
12614 	ipfp[0] = ipf;
12615 	atomic_add_32(&ill->ill_frag_count, -count);
12616 	ASSERT(ipfb->ipfb_count >= count);
12617 	ipfb->ipfb_count -= count;
12618 	ipfb->ipfb_frag_pkts--;
12619 	mutex_exit(&ipfb->ipfb_lock);
12620 	/* Ditch the frag header. */
12621 	mp = mp1->b_cont;
12622 
12623 	freeb(mp1);
12624 
12625 	/* Restore original IP length in header. */
12626 	packet_size = (uint32_t)msgdsize(mp);
12627 	if (packet_size > IP_MAXPACKET) {
12628 		freemsg(mp);
12629 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12630 		return (B_FALSE);
12631 	}
12632 
12633 	if (DB_REF(mp) > 1) {
12634 		mblk_t *mp2 = copymsg(mp);
12635 
12636 		freemsg(mp);
12637 		if (mp2 == NULL) {
12638 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12639 			return (B_FALSE);
12640 		}
12641 		mp = mp2;
12642 	}
12643 	ipha = (ipha_t *)mp->b_rptr;
12644 
12645 	ipha->ipha_length = htons((uint16_t)packet_size);
12646 	/* We're now complete, zip the frag state */
12647 	ipha->ipha_fragment_offset_and_flags = 0;
12648 	/* Record the ECN info. */
12649 	ipha->ipha_type_of_service &= 0xFC;
12650 	ipha->ipha_type_of_service |= ecn_info;
12651 	*mpp = mp;
12652 
12653 	/* Reassembly is successful; return checksum information if needed */
12654 	if (cksum_val != NULL)
12655 		*cksum_val = sum_val;
12656 	if (cksum_flags != NULL)
12657 		*cksum_flags = sum_flags;
12658 
12659 	return (B_TRUE);
12660 }
12661 
12662 /*
12663  * Perform ip header check sum update local options.
12664  * return B_TRUE if all is well, else return B_FALSE and release
12665  * the mp. caller is responsible for decrementing ire ref cnt.
12666  */
12667 static boolean_t
12668 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12669     ip_stack_t *ipst)
12670 {
12671 	mblk_t		*first_mp;
12672 	boolean_t	mctl_present;
12673 	uint16_t	sum;
12674 
12675 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12676 	/*
12677 	 * Don't do the checksum if it has gone through AH/ESP
12678 	 * processing.
12679 	 */
12680 	if (!mctl_present) {
12681 		sum = ip_csum_hdr(ipha);
12682 		if (sum != 0) {
12683 			if (ill != NULL) {
12684 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12685 			} else {
12686 				BUMP_MIB(&ipst->ips_ip_mib,
12687 				    ipIfStatsInCksumErrs);
12688 			}
12689 			freemsg(first_mp);
12690 			return (B_FALSE);
12691 		}
12692 	}
12693 
12694 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12695 		if (mctl_present)
12696 			freeb(first_mp);
12697 		return (B_FALSE);
12698 	}
12699 
12700 	return (B_TRUE);
12701 }
12702 
12703 /*
12704  * All udp packet are delivered to the local host via this routine.
12705  */
12706 void
12707 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12708     ill_t *recv_ill)
12709 {
12710 	uint32_t	sum;
12711 	uint32_t	u1;
12712 	boolean_t	mctl_present;
12713 	conn_t		*connp;
12714 	mblk_t		*first_mp;
12715 	uint16_t	*up;
12716 	ill_t		*ill = (ill_t *)q->q_ptr;
12717 	uint16_t	reass_hck_flags = 0;
12718 	ip_stack_t	*ipst;
12719 
12720 	ASSERT(recv_ill != NULL);
12721 	ipst = recv_ill->ill_ipst;
12722 
12723 #define	rptr    ((uchar_t *)ipha)
12724 
12725 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12726 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12727 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12728 	ASSERT(ill != NULL);
12729 
12730 	/*
12731 	 * FAST PATH for udp packets
12732 	 */
12733 
12734 	/* u1 is # words of IP options */
12735 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12736 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12737 
12738 	/* IP options present */
12739 	if (u1 != 0)
12740 		goto ipoptions;
12741 
12742 	/* Check the IP header checksum.  */
12743 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12744 		/* Clear the IP header h/w cksum flag */
12745 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12746 	} else if (!mctl_present) {
12747 		/*
12748 		 * Don't verify header checksum if this packet is coming
12749 		 * back from AH/ESP as we already did it.
12750 		 */
12751 #define	uph	((uint16_t *)ipha)
12752 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12753 		    uph[6] + uph[7] + uph[8] + uph[9];
12754 #undef	uph
12755 		/* finish doing IP checksum */
12756 		sum = (sum & 0xFFFF) + (sum >> 16);
12757 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12758 		if (sum != 0 && sum != 0xFFFF) {
12759 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12760 			freemsg(first_mp);
12761 			return;
12762 		}
12763 	}
12764 
12765 	/*
12766 	 * Count for SNMP of inbound packets for ire.
12767 	 * if mctl is present this might be a secure packet and
12768 	 * has already been counted for in ip_proto_input().
12769 	 */
12770 	if (!mctl_present) {
12771 		UPDATE_IB_PKT_COUNT(ire);
12772 		ire->ire_last_used_time = lbolt;
12773 	}
12774 
12775 	/* packet part of fragmented IP packet? */
12776 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12777 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12778 		goto fragmented;
12779 	}
12780 
12781 	/* u1 = IP header length (20 bytes) */
12782 	u1 = IP_SIMPLE_HDR_LENGTH;
12783 
12784 	/* packet does not contain complete IP & UDP headers */
12785 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12786 		goto udppullup;
12787 
12788 	/* up points to UDP header */
12789 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12790 #define	iphs    ((uint16_t *)ipha)
12791 
12792 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12793 	if (up[3] != 0) {
12794 		mblk_t *mp1 = mp->b_cont;
12795 		boolean_t cksum_err;
12796 		uint16_t hck_flags = 0;
12797 
12798 		/* Pseudo-header checksum */
12799 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12800 		    iphs[9] + up[2];
12801 
12802 		/*
12803 		 * Revert to software checksum calculation if the interface
12804 		 * isn't capable of checksum offload or if IPsec is present.
12805 		 */
12806 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12807 			hck_flags = DB_CKSUMFLAGS(mp);
12808 
12809 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12810 			IP_STAT(ipst, ip_in_sw_cksum);
12811 
12812 		IP_CKSUM_RECV(hck_flags, u1,
12813 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12814 		    (int32_t)((uchar_t *)up - rptr),
12815 		    mp, mp1, cksum_err);
12816 
12817 		if (cksum_err) {
12818 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12819 			if (hck_flags & HCK_FULLCKSUM)
12820 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12821 			else if (hck_flags & HCK_PARTIALCKSUM)
12822 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12823 			else
12824 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12825 
12826 			freemsg(first_mp);
12827 			return;
12828 		}
12829 	}
12830 
12831 	/* Non-fragmented broadcast or multicast packet? */
12832 	if (ire->ire_type == IRE_BROADCAST)
12833 		goto udpslowpath;
12834 
12835 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12836 	    ire->ire_zoneid, ipst)) != NULL) {
12837 		ASSERT(connp->conn_upq != NULL);
12838 		IP_STAT(ipst, ip_udp_fast_path);
12839 
12840 		if (CONN_UDP_FLOWCTLD(connp)) {
12841 			freemsg(mp);
12842 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12843 		} else {
12844 			if (!mctl_present) {
12845 				BUMP_MIB(ill->ill_ip_mib,
12846 				    ipIfStatsHCInDelivers);
12847 			}
12848 			/*
12849 			 * mp and first_mp can change.
12850 			 */
12851 			if (ip_udp_check(q, connp, recv_ill,
12852 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12853 				/* Send it upstream */
12854 				(connp->conn_recv)(connp, mp, NULL);
12855 			}
12856 		}
12857 		/*
12858 		 * freeb() cannot deal with null mblk being passed
12859 		 * in and first_mp can be set to null in the call
12860 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12861 		 */
12862 		if (mctl_present && first_mp != NULL) {
12863 			freeb(first_mp);
12864 		}
12865 		CONN_DEC_REF(connp);
12866 		return;
12867 	}
12868 
12869 	/*
12870 	 * if we got here we know the packet is not fragmented and
12871 	 * has no options. The classifier could not find a conn_t and
12872 	 * most likely its an icmp packet so send it through slow path.
12873 	 */
12874 
12875 	goto udpslowpath;
12876 
12877 ipoptions:
12878 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12879 		goto slow_done;
12880 	}
12881 
12882 	UPDATE_IB_PKT_COUNT(ire);
12883 	ire->ire_last_used_time = lbolt;
12884 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12885 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12886 fragmented:
12887 		/*
12888 		 * "sum" and "reass_hck_flags" are non-zero if the
12889 		 * reassembled packet has a valid hardware computed
12890 		 * checksum information associated with it.
12891 		 */
12892 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12893 			goto slow_done;
12894 		/*
12895 		 * Make sure that first_mp points back to mp as
12896 		 * the mp we came in with could have changed in
12897 		 * ip_rput_fragment().
12898 		 */
12899 		ASSERT(!mctl_present);
12900 		ipha = (ipha_t *)mp->b_rptr;
12901 		first_mp = mp;
12902 	}
12903 
12904 	/* Now we have a complete datagram, destined for this machine. */
12905 	u1 = IPH_HDR_LENGTH(ipha);
12906 	/* Pull up the UDP header, if necessary. */
12907 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12908 udppullup:
12909 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12910 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12911 			freemsg(first_mp);
12912 			goto slow_done;
12913 		}
12914 		ipha = (ipha_t *)mp->b_rptr;
12915 	}
12916 
12917 	/*
12918 	 * Validate the checksum for the reassembled packet; for the
12919 	 * pullup case we calculate the payload checksum in software.
12920 	 */
12921 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12922 	if (up[3] != 0) {
12923 		boolean_t cksum_err;
12924 
12925 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12926 			IP_STAT(ipst, ip_in_sw_cksum);
12927 
12928 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12929 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12930 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12931 		    iphs[9] + up[2], sum, cksum_err);
12932 
12933 		if (cksum_err) {
12934 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12935 
12936 			if (reass_hck_flags & HCK_FULLCKSUM)
12937 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12938 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12939 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12940 			else
12941 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12942 
12943 			freemsg(first_mp);
12944 			goto slow_done;
12945 		}
12946 	}
12947 udpslowpath:
12948 
12949 	/* Clear hardware checksum flag to be safe */
12950 	DB_CKSUMFLAGS(mp) = 0;
12951 
12952 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12953 	    (ire->ire_type == IRE_BROADCAST),
12954 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12955 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12956 
12957 slow_done:
12958 	IP_STAT(ipst, ip_udp_slow_path);
12959 	return;
12960 
12961 #undef  iphs
12962 #undef  rptr
12963 }
12964 
12965 /* ARGSUSED */
12966 static mblk_t *
12967 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12968     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12969     ill_rx_ring_t *ill_ring)
12970 {
12971 	conn_t		*connp;
12972 	uint32_t	sum;
12973 	uint32_t	u1;
12974 	uint16_t	*up;
12975 	int		offset;
12976 	ssize_t		len;
12977 	mblk_t		*mp1;
12978 	boolean_t	syn_present = B_FALSE;
12979 	tcph_t		*tcph;
12980 	uint_t		ip_hdr_len;
12981 	ill_t		*ill = (ill_t *)q->q_ptr;
12982 	zoneid_t	zoneid = ire->ire_zoneid;
12983 	boolean_t	cksum_err;
12984 	uint16_t	hck_flags = 0;
12985 	ip_stack_t	*ipst = recv_ill->ill_ipst;
12986 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12987 
12988 #define	rptr	((uchar_t *)ipha)
12989 
12990 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12991 	ASSERT(ill != NULL);
12992 
12993 	/*
12994 	 * FAST PATH for tcp packets
12995 	 */
12996 
12997 	/* u1 is # words of IP options */
12998 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12999 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13000 
13001 	/* IP options present */
13002 	if (u1) {
13003 		goto ipoptions;
13004 	} else if (!mctl_present) {
13005 		/* Check the IP header checksum.  */
13006 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13007 			/* Clear the IP header h/w cksum flag */
13008 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
13009 		} else if (!mctl_present) {
13010 			/*
13011 			 * Don't verify header checksum if this packet
13012 			 * is coming back from AH/ESP as we already did it.
13013 			 */
13014 #define	uph	((uint16_t *)ipha)
13015 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13016 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13017 #undef	uph
13018 			/* finish doing IP checksum */
13019 			sum = (sum & 0xFFFF) + (sum >> 16);
13020 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13021 			if (sum != 0 && sum != 0xFFFF) {
13022 				BUMP_MIB(ill->ill_ip_mib,
13023 				    ipIfStatsInCksumErrs);
13024 				goto error;
13025 			}
13026 		}
13027 	}
13028 
13029 	if (!mctl_present) {
13030 		UPDATE_IB_PKT_COUNT(ire);
13031 		ire->ire_last_used_time = lbolt;
13032 	}
13033 
13034 	/* packet part of fragmented IP packet? */
13035 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13036 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13037 		goto fragmented;
13038 	}
13039 
13040 	/* u1 = IP header length (20 bytes) */
13041 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
13042 
13043 	/* does packet contain IP+TCP headers? */
13044 	len = mp->b_wptr - rptr;
13045 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
13046 		IP_STAT(ipst, ip_tcppullup);
13047 		goto tcppullup;
13048 	}
13049 
13050 	/* TCP options present? */
13051 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
13052 
13053 	/*
13054 	 * If options need to be pulled up, then goto tcpoptions.
13055 	 * otherwise we are still in the fast path
13056 	 */
13057 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
13058 		IP_STAT(ipst, ip_tcpoptions);
13059 		goto tcpoptions;
13060 	}
13061 
13062 	/* multiple mblks of tcp data? */
13063 	if ((mp1 = mp->b_cont) != NULL) {
13064 		/* more then two? */
13065 		if (mp1->b_cont != NULL) {
13066 			IP_STAT(ipst, ip_multipkttcp);
13067 			goto multipkttcp;
13068 		}
13069 		len += mp1->b_wptr - mp1->b_rptr;
13070 	}
13071 
13072 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13073 
13074 	/* part of pseudo checksum */
13075 
13076 	/* TCP datagram length */
13077 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13078 
13079 #define	iphs    ((uint16_t *)ipha)
13080 
13081 #ifdef	_BIG_ENDIAN
13082 	u1 += IPPROTO_TCP;
13083 #else
13084 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13085 #endif
13086 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13087 
13088 	/*
13089 	 * Revert to software checksum calculation if the interface
13090 	 * isn't capable of checksum offload or if IPsec is present.
13091 	 */
13092 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
13093 		hck_flags = DB_CKSUMFLAGS(mp);
13094 
13095 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13096 		IP_STAT(ipst, ip_in_sw_cksum);
13097 
13098 	IP_CKSUM_RECV(hck_flags, u1,
13099 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13100 	    (int32_t)((uchar_t *)up - rptr),
13101 	    mp, mp1, cksum_err);
13102 
13103 	if (cksum_err) {
13104 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13105 
13106 		if (hck_flags & HCK_FULLCKSUM)
13107 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13108 		else if (hck_flags & HCK_PARTIALCKSUM)
13109 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13110 		else
13111 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13112 
13113 		goto error;
13114 	}
13115 
13116 try_again:
13117 
13118 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13119 	    zoneid, ipst)) == NULL) {
13120 		/* Send the TH_RST */
13121 		goto no_conn;
13122 	}
13123 
13124 	/*
13125 	 * TCP FAST PATH for AF_INET socket.
13126 	 *
13127 	 * TCP fast path to avoid extra work. An AF_INET socket type
13128 	 * does not have facility to receive extra information via
13129 	 * ip_process or ip_add_info. Also, when the connection was
13130 	 * established, we made a check if this connection is impacted
13131 	 * by any global IPsec policy or per connection policy (a
13132 	 * policy that comes in effect later will not apply to this
13133 	 * connection). Since all this can be determined at the
13134 	 * connection establishment time, a quick check of flags
13135 	 * can avoid extra work.
13136 	 */
13137 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13138 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13139 		ASSERT(first_mp == mp);
13140 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13141 		SET_SQUEUE(mp, tcp_rput_data, connp);
13142 		return (mp);
13143 	}
13144 
13145 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13146 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
13147 		if (IPCL_IS_TCP(connp)) {
13148 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13149 			DB_CKSUMSTART(mp) =
13150 			    (intptr_t)ip_squeue_get(ill_ring);
13151 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13152 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13153 				BUMP_MIB(ill->ill_ip_mib,
13154 				    ipIfStatsHCInDelivers);
13155 				SET_SQUEUE(mp, connp->conn_recv, connp);
13156 				return (mp);
13157 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13158 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13159 				BUMP_MIB(ill->ill_ip_mib,
13160 				    ipIfStatsHCInDelivers);
13161 				ip_squeue_enter_unbound++;
13162 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13163 				    connp);
13164 				return (mp);
13165 			}
13166 			syn_present = B_TRUE;
13167 		}
13168 
13169 	}
13170 
13171 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13172 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13173 
13174 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13175 		/* No need to send this packet to TCP */
13176 		if ((flags & TH_RST) || (flags & TH_URG)) {
13177 			CONN_DEC_REF(connp);
13178 			freemsg(first_mp);
13179 			return (NULL);
13180 		}
13181 		if (flags & TH_ACK) {
13182 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
13183 			    ipst->ips_netstack->netstack_tcp, connp);
13184 			CONN_DEC_REF(connp);
13185 			return (NULL);
13186 		}
13187 
13188 		CONN_DEC_REF(connp);
13189 		freemsg(first_mp);
13190 		return (NULL);
13191 	}
13192 
13193 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13194 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13195 		    ipha, NULL, mctl_present);
13196 		if (first_mp == NULL) {
13197 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13198 			CONN_DEC_REF(connp);
13199 			return (NULL);
13200 		}
13201 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13202 			ASSERT(syn_present);
13203 			if (mctl_present) {
13204 				ASSERT(first_mp != mp);
13205 				first_mp->b_datap->db_struioflag |=
13206 				    STRUIO_POLICY;
13207 			} else {
13208 				ASSERT(first_mp == mp);
13209 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13210 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13211 			}
13212 		} else {
13213 			/*
13214 			 * Discard first_mp early since we're dealing with a
13215 			 * fully-connected conn_t and tcp doesn't do policy in
13216 			 * this case.
13217 			 */
13218 			if (mctl_present) {
13219 				freeb(first_mp);
13220 				mctl_present = B_FALSE;
13221 			}
13222 			first_mp = mp;
13223 		}
13224 	}
13225 
13226 	/* Initiate IPPF processing for fastpath */
13227 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13228 		uint32_t	ill_index;
13229 
13230 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13231 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13232 		if (mp == NULL) {
13233 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13234 			    "deferred/dropped during IPPF processing\n"));
13235 			CONN_DEC_REF(connp);
13236 			if (mctl_present)
13237 				freeb(first_mp);
13238 			return (NULL);
13239 		} else if (mctl_present) {
13240 			/*
13241 			 * ip_process might return a new mp.
13242 			 */
13243 			ASSERT(first_mp != mp);
13244 			first_mp->b_cont = mp;
13245 		} else {
13246 			first_mp = mp;
13247 		}
13248 
13249 	}
13250 
13251 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13252 		/*
13253 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13254 		 * make sure IPF_RECVIF is passed to ip_add_info.
13255 		 */
13256 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13257 		    IPCL_ZONEID(connp), ipst);
13258 		if (mp == NULL) {
13259 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13260 			CONN_DEC_REF(connp);
13261 			if (mctl_present)
13262 				freeb(first_mp);
13263 			return (NULL);
13264 		} else if (mctl_present) {
13265 			/*
13266 			 * ip_add_info might return a new mp.
13267 			 */
13268 			ASSERT(first_mp != mp);
13269 			first_mp->b_cont = mp;
13270 		} else {
13271 			first_mp = mp;
13272 		}
13273 	}
13274 
13275 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13276 	if (IPCL_IS_TCP(connp)) {
13277 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13278 		return (first_mp);
13279 	} else {
13280 		/* SOCK_RAW, IPPROTO_TCP case */
13281 		(connp->conn_recv)(connp, first_mp, NULL);
13282 		CONN_DEC_REF(connp);
13283 		return (NULL);
13284 	}
13285 
13286 no_conn:
13287 	/* Initiate IPPf processing, if needed. */
13288 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13289 		uint32_t ill_index;
13290 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13291 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13292 		if (first_mp == NULL) {
13293 			return (NULL);
13294 		}
13295 	}
13296 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13297 
13298 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13299 	    ipst->ips_netstack->netstack_tcp, NULL);
13300 	return (NULL);
13301 ipoptions:
13302 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13303 		goto slow_done;
13304 	}
13305 
13306 	UPDATE_IB_PKT_COUNT(ire);
13307 	ire->ire_last_used_time = lbolt;
13308 
13309 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13310 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13311 fragmented:
13312 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13313 			if (mctl_present)
13314 				freeb(first_mp);
13315 			goto slow_done;
13316 		}
13317 		/*
13318 		 * Make sure that first_mp points back to mp as
13319 		 * the mp we came in with could have changed in
13320 		 * ip_rput_fragment().
13321 		 */
13322 		ASSERT(!mctl_present);
13323 		ipha = (ipha_t *)mp->b_rptr;
13324 		first_mp = mp;
13325 	}
13326 
13327 	/* Now we have a complete datagram, destined for this machine. */
13328 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13329 
13330 	len = mp->b_wptr - mp->b_rptr;
13331 	/* Pull up a minimal TCP header, if necessary. */
13332 	if (len < (u1 + 20)) {
13333 tcppullup:
13334 		if (!pullupmsg(mp, u1 + 20)) {
13335 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13336 			goto error;
13337 		}
13338 		ipha = (ipha_t *)mp->b_rptr;
13339 		len = mp->b_wptr - mp->b_rptr;
13340 	}
13341 
13342 	/*
13343 	 * Extract the offset field from the TCP header.  As usual, we
13344 	 * try to help the compiler more than the reader.
13345 	 */
13346 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13347 	if (offset != 5) {
13348 tcpoptions:
13349 		if (offset < 5) {
13350 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13351 			goto error;
13352 		}
13353 		/*
13354 		 * There must be TCP options.
13355 		 * Make sure we can grab them.
13356 		 */
13357 		offset <<= 2;
13358 		offset += u1;
13359 		if (len < offset) {
13360 			if (!pullupmsg(mp, offset)) {
13361 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13362 				goto error;
13363 			}
13364 			ipha = (ipha_t *)mp->b_rptr;
13365 			len = mp->b_wptr - rptr;
13366 		}
13367 	}
13368 
13369 	/* Get the total packet length in len, including headers. */
13370 	if (mp->b_cont) {
13371 multipkttcp:
13372 		len = msgdsize(mp);
13373 	}
13374 
13375 	/*
13376 	 * Check the TCP checksum by pulling together the pseudo-
13377 	 * header checksum, and passing it to ip_csum to be added in
13378 	 * with the TCP datagram.
13379 	 *
13380 	 * Since we are not using the hwcksum if available we must
13381 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13382 	 * If either of these fails along the way the mblk is freed.
13383 	 * If this logic ever changes and mblk is reused to say send
13384 	 * ICMP's back, then this flag may need to be cleared in
13385 	 * other places as well.
13386 	 */
13387 	DB_CKSUMFLAGS(mp) = 0;
13388 
13389 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13390 
13391 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13392 #ifdef	_BIG_ENDIAN
13393 	u1 += IPPROTO_TCP;
13394 #else
13395 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13396 #endif
13397 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13398 	/*
13399 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13400 	 */
13401 	IP_STAT(ipst, ip_in_sw_cksum);
13402 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13403 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13404 		goto error;
13405 	}
13406 
13407 	IP_STAT(ipst, ip_tcp_slow_path);
13408 	goto try_again;
13409 #undef  iphs
13410 #undef  rptr
13411 
13412 error:
13413 	freemsg(first_mp);
13414 slow_done:
13415 	return (NULL);
13416 }
13417 
13418 /* ARGSUSED */
13419 static void
13420 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13421     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13422 {
13423 	conn_t		*connp;
13424 	uint32_t	sum;
13425 	uint32_t	u1;
13426 	ssize_t		len;
13427 	sctp_hdr_t	*sctph;
13428 	zoneid_t	zoneid = ire->ire_zoneid;
13429 	uint32_t	pktsum;
13430 	uint32_t	calcsum;
13431 	uint32_t	ports;
13432 	in6_addr_t	map_src, map_dst;
13433 	ill_t		*ill = (ill_t *)q->q_ptr;
13434 	ip_stack_t	*ipst;
13435 	sctp_stack_t	*sctps;
13436 	boolean_t	sctp_csum_err = B_FALSE;
13437 
13438 	ASSERT(recv_ill != NULL);
13439 	ipst = recv_ill->ill_ipst;
13440 	sctps = ipst->ips_netstack->netstack_sctp;
13441 
13442 #define	rptr	((uchar_t *)ipha)
13443 
13444 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13445 	ASSERT(ill != NULL);
13446 
13447 	/* u1 is # words of IP options */
13448 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13449 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13450 
13451 	/* IP options present */
13452 	if (u1 > 0) {
13453 		goto ipoptions;
13454 	} else {
13455 		/* Check the IP header checksum.  */
13456 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill) &&
13457 		    !mctl_present) {
13458 #define	uph	((uint16_t *)ipha)
13459 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13460 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13461 #undef	uph
13462 			/* finish doing IP checksum */
13463 			sum = (sum & 0xFFFF) + (sum >> 16);
13464 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13465 			/*
13466 			 * Don't verify header checksum if this packet
13467 			 * is coming back from AH/ESP as we already did it.
13468 			 */
13469 			if (sum != 0 && sum != 0xFFFF) {
13470 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13471 				goto error;
13472 			}
13473 		}
13474 		/*
13475 		 * Since there is no SCTP h/w cksum support yet, just
13476 		 * clear the flag.
13477 		 */
13478 		DB_CKSUMFLAGS(mp) = 0;
13479 	}
13480 
13481 	/*
13482 	 * Don't verify header checksum if this packet is coming
13483 	 * back from AH/ESP as we already did it.
13484 	 */
13485 	if (!mctl_present) {
13486 		UPDATE_IB_PKT_COUNT(ire);
13487 		ire->ire_last_used_time = lbolt;
13488 	}
13489 
13490 	/* packet part of fragmented IP packet? */
13491 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13492 	if (u1 & (IPH_MF | IPH_OFFSET))
13493 		goto fragmented;
13494 
13495 	/* u1 = IP header length (20 bytes) */
13496 	u1 = IP_SIMPLE_HDR_LENGTH;
13497 
13498 find_sctp_client:
13499 	/* Pullup if we don't have the sctp common header. */
13500 	len = MBLKL(mp);
13501 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13502 		if (mp->b_cont == NULL ||
13503 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13504 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13505 			goto error;
13506 		}
13507 		ipha = (ipha_t *)mp->b_rptr;
13508 		len = MBLKL(mp);
13509 	}
13510 
13511 	sctph = (sctp_hdr_t *)(rptr + u1);
13512 #ifdef	DEBUG
13513 	if (!skip_sctp_cksum) {
13514 #endif
13515 		pktsum = sctph->sh_chksum;
13516 		sctph->sh_chksum = 0;
13517 		calcsum = sctp_cksum(mp, u1);
13518 		sctph->sh_chksum = pktsum;
13519 		if (calcsum != pktsum)
13520 			sctp_csum_err = B_TRUE;
13521 #ifdef	DEBUG	/* skip_sctp_cksum */
13522 	}
13523 #endif
13524 	/* get the ports */
13525 	ports = *(uint32_t *)&sctph->sh_sport;
13526 
13527 	IRE_REFRELE(ire);
13528 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13529 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13530 	if (sctp_csum_err) {
13531 		/*
13532 		 * No potential sctp checksum errors go to the Sun
13533 		 * sctp stack however they might be Adler-32 summed
13534 		 * packets a userland stack bound to a raw IP socket
13535 		 * could reasonably use. Note though that Adler-32 is
13536 		 * a long deprecated algorithm and customer sctp
13537 		 * networks should eventually migrate to CRC-32 at
13538 		 * which time this facility should be removed.
13539 		 */
13540 		flags |= IP_FF_SCTP_CSUM_ERR;
13541 		goto no_conn;
13542 	}
13543 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13544 	    sctps)) == NULL) {
13545 		/* Check for raw socket or OOTB handling */
13546 		goto no_conn;
13547 	}
13548 
13549 	/* Found a client; up it goes */
13550 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13551 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13552 	return;
13553 
13554 no_conn:
13555 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13556 	    ports, mctl_present, flags, B_TRUE, zoneid);
13557 	return;
13558 
13559 ipoptions:
13560 	DB_CKSUMFLAGS(mp) = 0;
13561 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13562 		goto slow_done;
13563 
13564 	UPDATE_IB_PKT_COUNT(ire);
13565 	ire->ire_last_used_time = lbolt;
13566 
13567 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13568 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13569 fragmented:
13570 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13571 			goto slow_done;
13572 		/*
13573 		 * Make sure that first_mp points back to mp as
13574 		 * the mp we came in with could have changed in
13575 		 * ip_rput_fragment().
13576 		 */
13577 		ASSERT(!mctl_present);
13578 		ipha = (ipha_t *)mp->b_rptr;
13579 		first_mp = mp;
13580 	}
13581 
13582 	/* Now we have a complete datagram, destined for this machine. */
13583 	u1 = IPH_HDR_LENGTH(ipha);
13584 	goto find_sctp_client;
13585 #undef  iphs
13586 #undef  rptr
13587 
13588 error:
13589 	freemsg(first_mp);
13590 slow_done:
13591 	IRE_REFRELE(ire);
13592 }
13593 
13594 #define	VER_BITS	0xF0
13595 #define	VERSION_6	0x60
13596 
13597 static boolean_t
13598 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13599     ipaddr_t *dstp, ip_stack_t *ipst)
13600 {
13601 	uint_t	opt_len;
13602 	ipha_t *ipha;
13603 	ssize_t len;
13604 	uint_t	pkt_len;
13605 
13606 	ASSERT(ill != NULL);
13607 	IP_STAT(ipst, ip_ipoptions);
13608 	ipha = *iphapp;
13609 
13610 #define	rptr    ((uchar_t *)ipha)
13611 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13612 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13613 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13614 		freemsg(mp);
13615 		return (B_FALSE);
13616 	}
13617 
13618 	/* multiple mblk or too short */
13619 	pkt_len = ntohs(ipha->ipha_length);
13620 
13621 	/* Get the number of words of IP options in the IP header. */
13622 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13623 	if (opt_len) {
13624 		/* IP Options present!  Validate and process. */
13625 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13626 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13627 			goto done;
13628 		}
13629 		/*
13630 		 * Recompute complete header length and make sure we
13631 		 * have access to all of it.
13632 		 */
13633 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13634 		if (len > (mp->b_wptr - rptr)) {
13635 			if (len > pkt_len) {
13636 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13637 				goto done;
13638 			}
13639 			if (!pullupmsg(mp, len)) {
13640 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13641 				goto done;
13642 			}
13643 			ipha = (ipha_t *)mp->b_rptr;
13644 		}
13645 		/*
13646 		 * Go off to ip_rput_options which returns the next hop
13647 		 * destination address, which may have been affected
13648 		 * by source routing.
13649 		 */
13650 		IP_STAT(ipst, ip_opt);
13651 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13652 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13653 			return (B_FALSE);
13654 		}
13655 	}
13656 	*iphapp = ipha;
13657 	return (B_TRUE);
13658 done:
13659 	/* clear b_prev - used by ip_mroute_decap */
13660 	mp->b_prev = NULL;
13661 	freemsg(mp);
13662 	return (B_FALSE);
13663 #undef  rptr
13664 }
13665 
13666 /*
13667  * Deal with the fact that there is no ire for the destination.
13668  */
13669 static ire_t *
13670 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13671 {
13672 	ipha_t	*ipha;
13673 	ill_t	*ill;
13674 	ire_t	*ire;
13675 	ip_stack_t *ipst;
13676 	enum	ire_forward_action ret_action;
13677 
13678 	ipha = (ipha_t *)mp->b_rptr;
13679 	ill = (ill_t *)q->q_ptr;
13680 
13681 	ASSERT(ill != NULL);
13682 	ipst = ill->ill_ipst;
13683 
13684 	/*
13685 	 * No IRE for this destination, so it can't be for us.
13686 	 * Unless we are forwarding, drop the packet.
13687 	 * We have to let source routed packets through
13688 	 * since we don't yet know if they are 'ping -l'
13689 	 * packets i.e. if they will go out over the
13690 	 * same interface as they came in on.
13691 	 */
13692 	if (ll_multicast) {
13693 		freemsg(mp);
13694 		return (NULL);
13695 	}
13696 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13697 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13698 		freemsg(mp);
13699 		return (NULL);
13700 	}
13701 
13702 	/*
13703 	 * Mark this packet as having originated externally.
13704 	 *
13705 	 * For non-forwarding code path, ire_send later double
13706 	 * checks this interface to see if it is still exists
13707 	 * post-ARP resolution.
13708 	 *
13709 	 * Also, IPQOS uses this to differentiate between
13710 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13711 	 * QOS packet processing in ip_wput_attach_llhdr().
13712 	 * The QoS module can mark the b_band for a fastpath message
13713 	 * or the dl_priority field in a unitdata_req header for
13714 	 * CoS marking. This info can only be found in
13715 	 * ip_wput_attach_llhdr().
13716 	 */
13717 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13718 	/*
13719 	 * Clear the indication that this may have a hardware checksum
13720 	 * as we are not using it
13721 	 */
13722 	DB_CKSUMFLAGS(mp) = 0;
13723 
13724 	ire = ire_forward(dst, &ret_action, NULL, NULL,
13725 	    MBLK_GETLABEL(mp), ipst);
13726 
13727 	if (ire == NULL && ret_action == Forward_check_multirt) {
13728 		/* Let ip_newroute handle CGTP  */
13729 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13730 		return (NULL);
13731 	}
13732 
13733 	if (ire != NULL)
13734 		return (ire);
13735 
13736 	mp->b_prev = mp->b_next = 0;
13737 
13738 	if (ret_action == Forward_blackhole) {
13739 		freemsg(mp);
13740 		return (NULL);
13741 	}
13742 	/* send icmp unreachable */
13743 	q = WR(q);
13744 	/* Sent by forwarding path, and router is global zone */
13745 	if (ip_source_routed(ipha, ipst)) {
13746 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13747 		    GLOBAL_ZONEID, ipst);
13748 	} else {
13749 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13750 		    ipst);
13751 	}
13752 
13753 	return (NULL);
13754 
13755 }
13756 
13757 /*
13758  * check ip header length and align it.
13759  */
13760 static boolean_t
13761 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13762 {
13763 	ssize_t len;
13764 	ill_t *ill;
13765 	ipha_t	*ipha;
13766 
13767 	len = MBLKL(mp);
13768 
13769 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13770 		ill = (ill_t *)q->q_ptr;
13771 
13772 		if (!OK_32PTR(mp->b_rptr))
13773 			IP_STAT(ipst, ip_notaligned1);
13774 		else
13775 			IP_STAT(ipst, ip_notaligned2);
13776 		/* Guard against bogus device drivers */
13777 		if (len < 0) {
13778 			/* clear b_prev - used by ip_mroute_decap */
13779 			mp->b_prev = NULL;
13780 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13781 			freemsg(mp);
13782 			return (B_FALSE);
13783 		}
13784 
13785 		if (ip_rput_pullups++ == 0) {
13786 			ipha = (ipha_t *)mp->b_rptr;
13787 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13788 			    "ip_check_and_align_header: %s forced us to "
13789 			    " pullup pkt, hdr len %ld, hdr addr %p",
13790 			    ill->ill_name, len, (void *)ipha);
13791 		}
13792 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13793 			/* clear b_prev - used by ip_mroute_decap */
13794 			mp->b_prev = NULL;
13795 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13796 			freemsg(mp);
13797 			return (B_FALSE);
13798 		}
13799 	}
13800 	return (B_TRUE);
13801 }
13802 
13803 ire_t *
13804 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13805 {
13806 	ire_t		*new_ire;
13807 	ill_t		*ire_ill;
13808 	uint_t		ifindex;
13809 	ip_stack_t	*ipst = ill->ill_ipst;
13810 	boolean_t	strict_check = B_FALSE;
13811 
13812 	/*
13813 	 * This packet came in on an interface other than the one associated
13814 	 * with the first ire we found for the destination address. We do
13815 	 * another ire lookup here, using the ingress ill, to see if the
13816 	 * interface is in an interface group.
13817 	 * As long as the ills belong to the same group, we don't consider
13818 	 * them to be arriving on the wrong interface. Thus, if the switch
13819 	 * is doing inbound load spreading, we won't drop packets when the
13820 	 * ip*_strict_dst_multihoming switch is on. Note, the same holds true
13821 	 * for 'usesrc groups' where the destination address may belong to
13822 	 * another interface to allow multipathing to happen.
13823 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13824 	 * where the local address may not be unique. In this case we were
13825 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13826 	 * actually returned. The new lookup, which is more specific, should
13827 	 * only find the IRE_LOCAL associated with the ingress ill if one
13828 	 * exists.
13829 	 */
13830 
13831 	if (ire->ire_ipversion == IPV4_VERSION) {
13832 		if (ipst->ips_ip_strict_dst_multihoming)
13833 			strict_check = B_TRUE;
13834 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13835 		    ill->ill_ipif, ALL_ZONES, NULL,
13836 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13837 	} else {
13838 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13839 		if (ipst->ips_ipv6_strict_dst_multihoming)
13840 			strict_check = B_TRUE;
13841 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13842 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13843 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13844 	}
13845 	/*
13846 	 * If the same ire that was returned in ip_input() is found then this
13847 	 * is an indication that interface groups are in use. The packet
13848 	 * arrived on a different ill in the group than the one associated with
13849 	 * the destination address.  If a different ire was found then the same
13850 	 * IP address must be hosted on multiple ills. This is possible with
13851 	 * unnumbered point2point interfaces. We switch to use this new ire in
13852 	 * order to have accurate interface statistics.
13853 	 */
13854 	if (new_ire != NULL) {
13855 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13856 			ire_refrele(ire);
13857 			ire = new_ire;
13858 		} else {
13859 			ire_refrele(new_ire);
13860 		}
13861 		return (ire);
13862 	} else if ((ire->ire_rfq == NULL) &&
13863 	    (ire->ire_ipversion == IPV4_VERSION)) {
13864 		/*
13865 		 * The best match could have been the original ire which
13866 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13867 		 * the strict multihoming checks are irrelevant as we consider
13868 		 * local addresses hosted on lo0 to be interface agnostic. We
13869 		 * only expect a null ire_rfq on IREs which are associated with
13870 		 * lo0 hence we can return now.
13871 		 */
13872 		return (ire);
13873 	}
13874 
13875 	/*
13876 	 * Chase pointers once and store locally.
13877 	 */
13878 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13879 	    (ill_t *)(ire->ire_rfq->q_ptr);
13880 	ifindex = ill->ill_usesrc_ifindex;
13881 
13882 	/*
13883 	 * Check if it's a legal address on the 'usesrc' interface.
13884 	 */
13885 	if ((ifindex != 0) && (ire_ill != NULL) &&
13886 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13887 		return (ire);
13888 	}
13889 
13890 	/*
13891 	 * If the ip*_strict_dst_multihoming switch is on then we can
13892 	 * only accept this packet if the interface is marked as routing.
13893 	 */
13894 	if (!(strict_check))
13895 		return (ire);
13896 
13897 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13898 	    ILLF_ROUTER) != 0) {
13899 		return (ire);
13900 	}
13901 
13902 	ire_refrele(ire);
13903 	return (NULL);
13904 }
13905 
13906 ire_t *
13907 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13908 {
13909 	ipha_t	*ipha;
13910 	ire_t	*src_ire;
13911 	ill_t	*stq_ill;
13912 	uint_t	hlen;
13913 	uint_t	pkt_len;
13914 	uint32_t sum;
13915 	queue_t	*dev_q;
13916 	ip_stack_t *ipst = ill->ill_ipst;
13917 	mblk_t *fpmp;
13918 	enum	ire_forward_action ret_action;
13919 
13920 	ipha = (ipha_t *)mp->b_rptr;
13921 
13922 	if (ire != NULL &&
13923 	    ire->ire_zoneid != GLOBAL_ZONEID &&
13924 	    ire->ire_zoneid != ALL_ZONES) {
13925 		/*
13926 		 * Should only use IREs that are visible to the global
13927 		 * zone for forwarding.
13928 		 */
13929 		ire_refrele(ire);
13930 		ire = ire_cache_lookup(dst, GLOBAL_ZONEID, NULL, ipst);
13931 	}
13932 
13933 	/*
13934 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13935 	 * The loopback address check for both src and dst has already
13936 	 * been checked in ip_input
13937 	 */
13938 
13939 	if (dst == INADDR_ANY || CLASSD(ipha->ipha_src)) {
13940 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13941 		goto drop;
13942 	}
13943 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13944 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13945 
13946 	if (src_ire != NULL) {
13947 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13948 		ire_refrele(src_ire);
13949 		goto drop;
13950 	}
13951 
13952 	/* No ire cache of nexthop. So first create one  */
13953 	if (ire == NULL) {
13954 
13955 		ire = ire_forward(dst, &ret_action, NULL, NULL,
13956 		    NULL, ipst);
13957 		/*
13958 		 * We only come to ip_fast_forward if ip_cgtp_filter
13959 		 * is not set. So ire_forward() should not return with
13960 		 * Forward_check_multirt as the next action.
13961 		 */
13962 		ASSERT(ret_action != Forward_check_multirt);
13963 		if (ire == NULL) {
13964 			/* An attempt was made to forward the packet */
13965 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13966 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13967 			mp->b_prev = mp->b_next = 0;
13968 			/* send icmp unreachable */
13969 			/* Sent by forwarding path, and router is global zone */
13970 			if (ret_action == Forward_ret_icmp_err) {
13971 				if (ip_source_routed(ipha, ipst)) {
13972 					icmp_unreachable(ill->ill_wq, mp,
13973 					    ICMP_SOURCE_ROUTE_FAILED,
13974 					    GLOBAL_ZONEID, ipst);
13975 				} else {
13976 					icmp_unreachable(ill->ill_wq, mp,
13977 					    ICMP_HOST_UNREACHABLE,
13978 					    GLOBAL_ZONEID, ipst);
13979 				}
13980 			} else {
13981 				freemsg(mp);
13982 			}
13983 			return (NULL);
13984 		}
13985 	}
13986 
13987 	/*
13988 	 * Forwarding fastpath exception case:
13989 	 * If either of the follwoing case is true, we take
13990 	 * the slowpath
13991 	 *	o forwarding is not enabled
13992 	 *	o incoming and outgoing interface are the same, or the same
13993 	 *	  IPMP group
13994 	 *	o corresponding ire is in incomplete state
13995 	 *	o packet needs fragmentation
13996 	 *	o ARP cache is not resolved
13997 	 *
13998 	 * The codeflow from here on is thus:
13999 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
14000 	 */
14001 	pkt_len = ntohs(ipha->ipha_length);
14002 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
14003 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
14004 	    !(ill->ill_flags & ILLF_ROUTER) ||
14005 	    (ill == stq_ill) ||
14006 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
14007 	    (ire->ire_nce == NULL) ||
14008 	    (pkt_len > ire->ire_max_frag) ||
14009 	    ((fpmp = ire->ire_nce->nce_fp_mp) == NULL) ||
14010 	    ((hlen = MBLKL(fpmp)) > MBLKHEAD(mp)) ||
14011 	    ipha->ipha_ttl <= 1) {
14012 		ip_rput_process_forward(ill->ill_rq, mp, ire,
14013 		    ipha, ill, B_FALSE);
14014 		return (ire);
14015 	}
14016 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14017 
14018 	DTRACE_PROBE4(ip4__forwarding__start,
14019 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
14020 
14021 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
14022 	    ipst->ips_ipv4firewall_forwarding,
14023 	    ill, stq_ill, ipha, mp, mp, 0, ipst);
14024 
14025 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
14026 
14027 	if (mp == NULL)
14028 		goto drop;
14029 
14030 	mp->b_datap->db_struioun.cksum.flags = 0;
14031 	/* Adjust the checksum to reflect the ttl decrement. */
14032 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
14033 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
14034 	ipha->ipha_ttl--;
14035 
14036 	/*
14037 	 * Write the link layer header.  We can do this safely here,
14038 	 * because we have already tested to make sure that the IP
14039 	 * policy is not set, and that we have a fast path destination
14040 	 * header.
14041 	 */
14042 	mp->b_rptr -= hlen;
14043 	bcopy(fpmp->b_rptr, mp->b_rptr, hlen);
14044 
14045 	UPDATE_IB_PKT_COUNT(ire);
14046 	ire->ire_last_used_time = lbolt;
14047 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
14048 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14049 	UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets, pkt_len);
14050 
14051 	dev_q = ire->ire_stq->q_next;
14052 	if ((dev_q->q_next != NULL || dev_q->q_first != NULL) &&
14053 	    !canputnext(ire->ire_stq)) {
14054 		goto indiscard;
14055 	}
14056 	if (ILL_DLS_CAPABLE(stq_ill)) {
14057 		/*
14058 		 * Send the packet directly to DLD, where it
14059 		 * may be queued depending on the availability
14060 		 * of transmit resources at the media layer.
14061 		 */
14062 		IP_DLS_ILL_TX(stq_ill, ipha, mp, ipst, hlen);
14063 	} else {
14064 		DTRACE_PROBE4(ip4__physical__out__start,
14065 		    ill_t *, NULL, ill_t *, stq_ill,
14066 		    ipha_t *, ipha, mblk_t *, mp);
14067 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
14068 		    ipst->ips_ipv4firewall_physical_out,
14069 		    NULL, stq_ill, ipha, mp, mp, 0, ipst);
14070 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
14071 		if (mp == NULL)
14072 			goto drop;
14073 
14074 		DTRACE_IP7(send, mblk_t *, mp, conn_t *, NULL, void_ip_t *,
14075 		    ipha, __dtrace_ipsr_ill_t *, stq_ill, ipha_t *, ipha,
14076 		    ip6_t *, NULL, int, 0);
14077 
14078 		putnext(ire->ire_stq, mp);
14079 	}
14080 	return (ire);
14081 
14082 indiscard:
14083 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14084 drop:
14085 	if (mp != NULL)
14086 		freemsg(mp);
14087 	return (ire);
14088 
14089 }
14090 
14091 /*
14092  * This function is called in the forwarding slowpath, when
14093  * either the ire lacks the link-layer address, or the packet needs
14094  * further processing(eg. fragmentation), before transmission.
14095  */
14096 
14097 static void
14098 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14099     ill_t *ill, boolean_t ll_multicast)
14100 {
14101 	ill_group_t	*ill_group;
14102 	ill_group_t	*ire_group;
14103 	queue_t		*dev_q;
14104 	ire_t		*src_ire;
14105 	ip_stack_t	*ipst = ill->ill_ipst;
14106 
14107 	ASSERT(ire->ire_stq != NULL);
14108 
14109 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14110 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14111 
14112 	if (ll_multicast != 0) {
14113 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14114 		goto drop_pkt;
14115 	}
14116 
14117 	/*
14118 	 * check if ipha_src is a broadcast address. Note that this
14119 	 * check is redundant when we get here from ip_fast_forward()
14120 	 * which has already done this check. However, since we can
14121 	 * also get here from ip_rput_process_broadcast() or, for
14122 	 * for the slow path through ip_fast_forward(), we perform
14123 	 * the check again for code-reusability
14124 	 */
14125 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14126 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14127 	if (src_ire != NULL || ipha->ipha_dst == INADDR_ANY) {
14128 		if (src_ire != NULL)
14129 			ire_refrele(src_ire);
14130 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14131 		ip2dbg(("ip_rput_process_forward: Received packet with"
14132 		    " bad src/dst address on %s\n", ill->ill_name));
14133 		goto drop_pkt;
14134 	}
14135 
14136 	ill_group = ill->ill_group;
14137 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
14138 	/*
14139 	 * Check if we want to forward this one at this time.
14140 	 * We allow source routed packets on a host provided that
14141 	 * they go out the same interface or same interface group
14142 	 * as they came in on.
14143 	 *
14144 	 * XXX To be quicker, we may wish to not chase pointers to
14145 	 * get the ILLF_ROUTER flag and instead store the
14146 	 * forwarding policy in the ire.  An unfortunate
14147 	 * side-effect of that would be requiring an ire flush
14148 	 * whenever the ILLF_ROUTER flag changes.
14149 	 */
14150 	if (((ill->ill_flags &
14151 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
14152 	    ILLF_ROUTER) == 0) &&
14153 	    !(ip_source_routed(ipha, ipst) && (ire->ire_rfq == q ||
14154 	    (ill_group != NULL && ill_group == ire_group)))) {
14155 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14156 		if (ip_source_routed(ipha, ipst)) {
14157 			q = WR(q);
14158 			/*
14159 			 * Clear the indication that this may have
14160 			 * hardware checksum as we are not using it.
14161 			 */
14162 			DB_CKSUMFLAGS(mp) = 0;
14163 			/* Sent by forwarding path, and router is global zone */
14164 			icmp_unreachable(q, mp,
14165 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14166 			return;
14167 		}
14168 		goto drop_pkt;
14169 	}
14170 
14171 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14172 
14173 	/* Packet is being forwarded. Turning off hwcksum flag. */
14174 	DB_CKSUMFLAGS(mp) = 0;
14175 	if (ipst->ips_ip_g_send_redirects) {
14176 		/*
14177 		 * Check whether the incoming interface and outgoing
14178 		 * interface is part of the same group. If so,
14179 		 * send redirects.
14180 		 *
14181 		 * Check the source address to see if it originated
14182 		 * on the same logical subnet it is going back out on.
14183 		 * If so, we should be able to send it a redirect.
14184 		 * Avoid sending a redirect if the destination
14185 		 * is directly connected (i.e., ipha_dst is the same
14186 		 * as ire_gateway_addr or the ire_addr of the
14187 		 * nexthop IRE_CACHE ), or if the packet was source
14188 		 * routed out this interface.
14189 		 */
14190 		ipaddr_t src, nhop;
14191 		mblk_t	*mp1;
14192 		ire_t	*nhop_ire = NULL;
14193 
14194 		/*
14195 		 * Check whether ire_rfq and q are from the same ill
14196 		 * or if they are not same, they at least belong
14197 		 * to the same group. If so, send redirects.
14198 		 */
14199 		if ((ire->ire_rfq == q ||
14200 		    (ill_group != NULL && ill_group == ire_group)) &&
14201 		    !ip_source_routed(ipha, ipst)) {
14202 
14203 			nhop = (ire->ire_gateway_addr != 0 ?
14204 			    ire->ire_gateway_addr : ire->ire_addr);
14205 
14206 			if (ipha->ipha_dst == nhop) {
14207 				/*
14208 				 * We avoid sending a redirect if the
14209 				 * destination is directly connected
14210 				 * because it is possible that multiple
14211 				 * IP subnets may have been configured on
14212 				 * the link, and the source may not
14213 				 * be on the same subnet as ip destination,
14214 				 * even though they are on the same
14215 				 * physical link.
14216 				 */
14217 				goto sendit;
14218 			}
14219 
14220 			src = ipha->ipha_src;
14221 
14222 			/*
14223 			 * We look up the interface ire for the nexthop,
14224 			 * to see if ipha_src is in the same subnet
14225 			 * as the nexthop.
14226 			 *
14227 			 * Note that, if, in the future, IRE_CACHE entries
14228 			 * are obsoleted,  this lookup will not be needed,
14229 			 * as the ire passed to this function will be the
14230 			 * same as the nhop_ire computed below.
14231 			 */
14232 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14233 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14234 			    0, NULL, MATCH_IRE_TYPE, ipst);
14235 
14236 			if (nhop_ire != NULL) {
14237 				if ((src & nhop_ire->ire_mask) ==
14238 				    (nhop & nhop_ire->ire_mask)) {
14239 					/*
14240 					 * The source is directly connected.
14241 					 * Just copy the ip header (which is
14242 					 * in the first mblk)
14243 					 */
14244 					mp1 = copyb(mp);
14245 					if (mp1 != NULL) {
14246 						icmp_send_redirect(WR(q), mp1,
14247 						    nhop, ipst);
14248 					}
14249 				}
14250 				ire_refrele(nhop_ire);
14251 			}
14252 		}
14253 	}
14254 sendit:
14255 	dev_q = ire->ire_stq->q_next;
14256 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
14257 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14258 		freemsg(mp);
14259 		return;
14260 	}
14261 
14262 	ip_rput_forward(ire, ipha, mp, ill);
14263 	return;
14264 
14265 drop_pkt:
14266 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14267 	freemsg(mp);
14268 }
14269 
14270 ire_t *
14271 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14272     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14273 {
14274 	queue_t		*q;
14275 	uint16_t	hcksumflags;
14276 	ip_stack_t	*ipst = ill->ill_ipst;
14277 
14278 	q = *qp;
14279 
14280 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14281 
14282 	/*
14283 	 * Clear the indication that this may have hardware
14284 	 * checksum as we are not using it for forwarding.
14285 	 */
14286 	hcksumflags = DB_CKSUMFLAGS(mp);
14287 	DB_CKSUMFLAGS(mp) = 0;
14288 
14289 	/*
14290 	 * Directed broadcast forwarding: if the packet came in over a
14291 	 * different interface then it is routed out over we can forward it.
14292 	 */
14293 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14294 		ire_refrele(ire);
14295 		freemsg(mp);
14296 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14297 		return (NULL);
14298 	}
14299 	/*
14300 	 * For multicast we have set dst to be INADDR_BROADCAST
14301 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
14302 	 * only for broadcast packets.
14303 	 */
14304 	if (!CLASSD(ipha->ipha_dst)) {
14305 		ire_t *new_ire;
14306 		ipif_t *ipif;
14307 		/*
14308 		 * For ill groups, as the switch duplicates broadcasts
14309 		 * across all the ports, we need to filter out and
14310 		 * send up only one copy. There is one copy for every
14311 		 * broadcast address on each ill. Thus, we look for a
14312 		 * specific IRE on this ill and look at IRE_MARK_NORECV
14313 		 * later to see whether this ill is eligible to receive
14314 		 * them or not. ill_nominate_bcast_rcv() nominates only
14315 		 * one set of IREs for receiving.
14316 		 */
14317 
14318 		ipif = ipif_get_next_ipif(NULL, ill);
14319 		if (ipif == NULL) {
14320 			ire_refrele(ire);
14321 			freemsg(mp);
14322 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14323 			return (NULL);
14324 		}
14325 		new_ire = ire_ctable_lookup(dst, 0, 0,
14326 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14327 		ipif_refrele(ipif);
14328 
14329 		if (new_ire != NULL) {
14330 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
14331 				ire_refrele(ire);
14332 				ire_refrele(new_ire);
14333 				freemsg(mp);
14334 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14335 				return (NULL);
14336 			}
14337 			/*
14338 			 * In the special case of multirouted broadcast
14339 			 * packets, we unconditionally need to "gateway"
14340 			 * them to the appropriate interface here.
14341 			 * In the normal case, this cannot happen, because
14342 			 * there is no broadcast IRE tagged with the
14343 			 * RTF_MULTIRT flag.
14344 			 */
14345 			if (new_ire->ire_flags & RTF_MULTIRT) {
14346 				ire_refrele(new_ire);
14347 				if (ire->ire_rfq != NULL) {
14348 					q = ire->ire_rfq;
14349 					*qp = q;
14350 				}
14351 			} else {
14352 				ire_refrele(ire);
14353 				ire = new_ire;
14354 			}
14355 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14356 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14357 				/*
14358 				 * Free the message if
14359 				 * ip_g_forward_directed_bcast is turned
14360 				 * off for non-local broadcast.
14361 				 */
14362 				ire_refrele(ire);
14363 				freemsg(mp);
14364 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14365 				return (NULL);
14366 			}
14367 		} else {
14368 			/*
14369 			 * This CGTP packet successfully passed the
14370 			 * CGTP filter, but the related CGTP
14371 			 * broadcast IRE has not been found,
14372 			 * meaning that the redundant ipif is
14373 			 * probably down. However, if we discarded
14374 			 * this packet, its duplicate would be
14375 			 * filtered out by the CGTP filter so none
14376 			 * of them would get through. So we keep
14377 			 * going with this one.
14378 			 */
14379 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14380 			if (ire->ire_rfq != NULL) {
14381 				q = ire->ire_rfq;
14382 				*qp = q;
14383 			}
14384 		}
14385 	}
14386 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14387 		/*
14388 		 * Verify that there are not more then one
14389 		 * IRE_BROADCAST with this broadcast address which
14390 		 * has ire_stq set.
14391 		 * TODO: simplify, loop over all IRE's
14392 		 */
14393 		ire_t	*ire1;
14394 		int	num_stq = 0;
14395 		mblk_t	*mp1;
14396 
14397 		/* Find the first one with ire_stq set */
14398 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14399 		for (ire1 = ire; ire1 &&
14400 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14401 		    ire1 = ire1->ire_next)
14402 			;
14403 		if (ire1) {
14404 			ire_refrele(ire);
14405 			ire = ire1;
14406 			IRE_REFHOLD(ire);
14407 		}
14408 
14409 		/* Check if there are additional ones with stq set */
14410 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14411 			if (ire->ire_addr != ire1->ire_addr)
14412 				break;
14413 			if (ire1->ire_stq) {
14414 				num_stq++;
14415 				break;
14416 			}
14417 		}
14418 		rw_exit(&ire->ire_bucket->irb_lock);
14419 		if (num_stq == 1 && ire->ire_stq != NULL) {
14420 			ip1dbg(("ip_rput_process_broadcast: directed "
14421 			    "broadcast to 0x%x\n",
14422 			    ntohl(ire->ire_addr)));
14423 			mp1 = copymsg(mp);
14424 			if (mp1) {
14425 				switch (ipha->ipha_protocol) {
14426 				case IPPROTO_UDP:
14427 					ip_udp_input(q, mp1, ipha, ire, ill);
14428 					break;
14429 				default:
14430 					ip_proto_input(q, mp1, ipha, ire, ill,
14431 					    0);
14432 					break;
14433 				}
14434 			}
14435 			/*
14436 			 * Adjust ttl to 2 (1+1 - the forward engine
14437 			 * will decrement it by one.
14438 			 */
14439 			if (ip_csum_hdr(ipha)) {
14440 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14441 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14442 				freemsg(mp);
14443 				ire_refrele(ire);
14444 				return (NULL);
14445 			}
14446 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14447 			ipha->ipha_hdr_checksum = 0;
14448 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14449 			ip_rput_process_forward(q, mp, ire, ipha,
14450 			    ill, ll_multicast);
14451 			ire_refrele(ire);
14452 			return (NULL);
14453 		}
14454 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14455 		    ntohl(ire->ire_addr)));
14456 	}
14457 
14458 
14459 	/* Restore any hardware checksum flags */
14460 	DB_CKSUMFLAGS(mp) = hcksumflags;
14461 	return (ire);
14462 }
14463 
14464 /* ARGSUSED */
14465 static boolean_t
14466 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14467     int *ll_multicast, ipaddr_t *dstp)
14468 {
14469 	ip_stack_t	*ipst = ill->ill_ipst;
14470 
14471 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14472 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14473 	    ntohs(ipha->ipha_length));
14474 
14475 	/*
14476 	 * Forward packets only if we have joined the allmulti
14477 	 * group on this interface.
14478 	 */
14479 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14480 		int retval;
14481 
14482 		/*
14483 		 * Clear the indication that this may have hardware
14484 		 * checksum as we are not using it.
14485 		 */
14486 		DB_CKSUMFLAGS(mp) = 0;
14487 		retval = ip_mforward(ill, ipha, mp);
14488 		/* ip_mforward updates mib variables if needed */
14489 		/* clear b_prev - used by ip_mroute_decap */
14490 		mp->b_prev = NULL;
14491 
14492 		switch (retval) {
14493 		case 0:
14494 			/*
14495 			 * pkt is okay and arrived on phyint.
14496 			 *
14497 			 * If we are running as a multicast router
14498 			 * we need to see all IGMP and/or PIM packets.
14499 			 */
14500 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14501 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14502 				goto done;
14503 			}
14504 			break;
14505 		case -1:
14506 			/* pkt is mal-formed, toss it */
14507 			goto drop_pkt;
14508 		case 1:
14509 			/* pkt is okay and arrived on a tunnel */
14510 			/*
14511 			 * If we are running a multicast router
14512 			 *  we need to see all igmp packets.
14513 			 */
14514 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14515 				*dstp = INADDR_BROADCAST;
14516 				*ll_multicast = 1;
14517 				return (B_FALSE);
14518 			}
14519 
14520 			goto drop_pkt;
14521 		}
14522 	}
14523 
14524 	ILM_WALKER_HOLD(ill);
14525 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14526 		/*
14527 		 * This might just be caused by the fact that
14528 		 * multiple IP Multicast addresses map to the same
14529 		 * link layer multicast - no need to increment counter!
14530 		 */
14531 		ILM_WALKER_RELE(ill);
14532 		freemsg(mp);
14533 		return (B_TRUE);
14534 	}
14535 	ILM_WALKER_RELE(ill);
14536 done:
14537 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14538 	/*
14539 	 * This assumes the we deliver to all streams for multicast
14540 	 * and broadcast packets.
14541 	 */
14542 	*dstp = INADDR_BROADCAST;
14543 	*ll_multicast = 1;
14544 	return (B_FALSE);
14545 drop_pkt:
14546 	ip2dbg(("ip_rput: drop pkt\n"));
14547 	freemsg(mp);
14548 	return (B_TRUE);
14549 }
14550 
14551 /*
14552  * This function is used to both return an indication of whether or not
14553  * the packet received is a non-unicast packet (by way of the DL_UNITDATA_IND)
14554  * and in doing so, determine whether or not it is broadcast vs multicast.
14555  * For it to be a broadcast packet, we must have the appropriate mblk_t
14556  * hanging off the ill_t.  If this is either not present or doesn't match
14557  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
14558  * to be multicast.  Thus NICs that have no broadcast address (or no
14559  * capability for one, such as point to point links) cannot return as
14560  * the packet being broadcast.  The use of HPE_BROADCAST/HPE_MULTICAST as
14561  * the return values simplifies the current use of the return value of this
14562  * function, which is to pass through the multicast/broadcast characteristic
14563  * to consumers of the netinfo/pfhooks API.  While this is not cast in stone,
14564  * changing the return value to some other symbol demands the appropriate
14565  * "translation" when hpe_flags is set prior to calling hook_run() for
14566  * packet events.
14567  */
14568 int
14569 ip_get_dlpi_mbcast(ill_t *ill, mblk_t *mb)
14570 {
14571 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
14572 	mblk_t *bmp;
14573 
14574 	if (ind->dl_group_address) {
14575 		if (ind->dl_dest_addr_offset > sizeof (*ind) &&
14576 		    ind->dl_dest_addr_offset + ind->dl_dest_addr_length <
14577 		    MBLKL(mb) &&
14578 		    (bmp = ill->ill_bcast_mp) != NULL) {
14579 			dl_unitdata_req_t *dlur;
14580 			uint8_t *bphys_addr;
14581 
14582 			dlur = (dl_unitdata_req_t *)bmp->b_rptr;
14583 			if (ill->ill_sap_length < 0)
14584 				bphys_addr = (uchar_t *)dlur +
14585 				    dlur->dl_dest_addr_offset;
14586 			else
14587 				bphys_addr = (uchar_t *)dlur +
14588 				    dlur->dl_dest_addr_offset +
14589 				    ill->ill_sap_length;
14590 
14591 			if (bcmp(mb->b_rptr + ind->dl_dest_addr_offset,
14592 			    bphys_addr, ind->dl_dest_addr_length) == 0) {
14593 				return (HPE_BROADCAST);
14594 			}
14595 			return (HPE_MULTICAST);
14596 		}
14597 		return (HPE_MULTICAST);
14598 	}
14599 	return (0);
14600 }
14601 
14602 static boolean_t
14603 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14604     int *ll_multicast, mblk_t **mpp)
14605 {
14606 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14607 	boolean_t must_copy = B_FALSE;
14608 	struct iocblk   *iocp;
14609 	ipha_t		*ipha;
14610 	ip_stack_t	*ipst = ill->ill_ipst;
14611 
14612 #define	rptr    ((uchar_t *)ipha)
14613 
14614 	first_mp = *first_mpp;
14615 	mp = *mpp;
14616 
14617 	ASSERT(first_mp == mp);
14618 
14619 	/*
14620 	 * if db_ref > 1 then copymsg and free original. Packet may be
14621 	 * changed and do not want other entity who has a reference to this
14622 	 * message to trip over the changes. This is a blind change because
14623 	 * trying to catch all places that might change packet is too
14624 	 * difficult (since it may be a module above this one)
14625 	 *
14626 	 * This corresponds to the non-fast path case. We walk down the full
14627 	 * chain in this case, and check the db_ref count of all the dblks,
14628 	 * and do a copymsg if required. It is possible that the db_ref counts
14629 	 * of the data blocks in the mblk chain can be different.
14630 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14631 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14632 	 * 'snoop' is running.
14633 	 */
14634 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14635 		if (mp1->b_datap->db_ref > 1) {
14636 			must_copy = B_TRUE;
14637 			break;
14638 		}
14639 	}
14640 
14641 	if (must_copy) {
14642 		mp1 = copymsg(mp);
14643 		if (mp1 == NULL) {
14644 			for (mp1 = mp; mp1 != NULL;
14645 			    mp1 = mp1->b_cont) {
14646 				mp1->b_next = NULL;
14647 				mp1->b_prev = NULL;
14648 			}
14649 			freemsg(mp);
14650 			if (ill != NULL) {
14651 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14652 			} else {
14653 				BUMP_MIB(&ipst->ips_ip_mib,
14654 				    ipIfStatsInDiscards);
14655 			}
14656 			return (B_TRUE);
14657 		}
14658 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14659 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14660 			/* Copy b_prev - used by ip_mroute_decap */
14661 			to_mp->b_prev = from_mp->b_prev;
14662 			from_mp->b_prev = NULL;
14663 		}
14664 		*first_mpp = first_mp = mp1;
14665 		freemsg(mp);
14666 		mp = mp1;
14667 		*mpp = mp1;
14668 	}
14669 
14670 	ipha = (ipha_t *)mp->b_rptr;
14671 
14672 	/*
14673 	 * previous code has a case for M_DATA.
14674 	 * We want to check how that happens.
14675 	 */
14676 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14677 	switch (first_mp->b_datap->db_type) {
14678 	case M_PROTO:
14679 	case M_PCPROTO:
14680 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14681 		    DL_UNITDATA_IND) {
14682 			/* Go handle anything other than data elsewhere. */
14683 			ip_rput_dlpi(q, mp);
14684 			return (B_TRUE);
14685 		}
14686 
14687 		*ll_multicast = ip_get_dlpi_mbcast(ill, mp);
14688 		/* Ditch the DLPI header. */
14689 		mp1 = mp->b_cont;
14690 		ASSERT(first_mp == mp);
14691 		*first_mpp = mp1;
14692 		freeb(mp);
14693 		*mpp = mp1;
14694 		return (B_FALSE);
14695 	case M_IOCACK:
14696 		ip1dbg(("got iocack "));
14697 		iocp = (struct iocblk *)mp->b_rptr;
14698 		switch (iocp->ioc_cmd) {
14699 		case DL_IOC_HDR_INFO:
14700 			ill = (ill_t *)q->q_ptr;
14701 			ill_fastpath_ack(ill, mp);
14702 			return (B_TRUE);
14703 		case SIOCSTUNPARAM:
14704 		case OSIOCSTUNPARAM:
14705 			/* Go through qwriter_ip */
14706 			break;
14707 		case SIOCGTUNPARAM:
14708 		case OSIOCGTUNPARAM:
14709 			ip_rput_other(NULL, q, mp, NULL);
14710 			return (B_TRUE);
14711 		default:
14712 			putnext(q, mp);
14713 			return (B_TRUE);
14714 		}
14715 		/* FALLTHRU */
14716 	case M_ERROR:
14717 	case M_HANGUP:
14718 		/*
14719 		 * Since this is on the ill stream we unconditionally
14720 		 * bump up the refcount
14721 		 */
14722 		ill_refhold(ill);
14723 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14724 		return (B_TRUE);
14725 	case M_CTL:
14726 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14727 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14728 		    IPHADA_M_CTL)) {
14729 			/*
14730 			 * It's an IPsec accelerated packet.
14731 			 * Make sure that the ill from which we received the
14732 			 * packet has enabled IPsec hardware acceleration.
14733 			 */
14734 			if (!(ill->ill_capabilities &
14735 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14736 				/* IPsec kstats: bean counter */
14737 				freemsg(mp);
14738 				return (B_TRUE);
14739 			}
14740 
14741 			/*
14742 			 * Make mp point to the mblk following the M_CTL,
14743 			 * then process according to type of mp.
14744 			 * After this processing, first_mp will point to
14745 			 * the data-attributes and mp to the pkt following
14746 			 * the M_CTL.
14747 			 */
14748 			mp = first_mp->b_cont;
14749 			if (mp == NULL) {
14750 				freemsg(first_mp);
14751 				return (B_TRUE);
14752 			}
14753 			/*
14754 			 * A Hardware Accelerated packet can only be M_DATA
14755 			 * ESP or AH packet.
14756 			 */
14757 			if (mp->b_datap->db_type != M_DATA) {
14758 				/* non-M_DATA IPsec accelerated packet */
14759 				IPSECHW_DEBUG(IPSECHW_PKT,
14760 				    ("non-M_DATA IPsec accelerated pkt\n"));
14761 				freemsg(first_mp);
14762 				return (B_TRUE);
14763 			}
14764 			ipha = (ipha_t *)mp->b_rptr;
14765 			if (ipha->ipha_protocol != IPPROTO_AH &&
14766 			    ipha->ipha_protocol != IPPROTO_ESP) {
14767 				IPSECHW_DEBUG(IPSECHW_PKT,
14768 				    ("non-M_DATA IPsec accelerated pkt\n"));
14769 				freemsg(first_mp);
14770 				return (B_TRUE);
14771 			}
14772 			*mpp = mp;
14773 			return (B_FALSE);
14774 		}
14775 		putnext(q, mp);
14776 		return (B_TRUE);
14777 	case M_IOCNAK:
14778 		ip1dbg(("got iocnak "));
14779 		iocp = (struct iocblk *)mp->b_rptr;
14780 		switch (iocp->ioc_cmd) {
14781 		case SIOCSTUNPARAM:
14782 		case OSIOCSTUNPARAM:
14783 			/*
14784 			 * Since this is on the ill stream we unconditionally
14785 			 * bump up the refcount
14786 			 */
14787 			ill_refhold(ill);
14788 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14789 			return (B_TRUE);
14790 		case DL_IOC_HDR_INFO:
14791 		case SIOCGTUNPARAM:
14792 		case OSIOCGTUNPARAM:
14793 			ip_rput_other(NULL, q, mp, NULL);
14794 			return (B_TRUE);
14795 		default:
14796 			break;
14797 		}
14798 		/* FALLTHRU */
14799 	default:
14800 		putnext(q, mp);
14801 		return (B_TRUE);
14802 	}
14803 }
14804 
14805 /* Read side put procedure.  Packets coming from the wire arrive here. */
14806 void
14807 ip_rput(queue_t *q, mblk_t *mp)
14808 {
14809 	ill_t	*ill;
14810 	union DL_primitives *dl;
14811 
14812 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14813 
14814 	ill = (ill_t *)q->q_ptr;
14815 
14816 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14817 		/*
14818 		 * If things are opening or closing, only accept high-priority
14819 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14820 		 * created; on close, things hanging off the ill may have been
14821 		 * freed already.)
14822 		 */
14823 		dl = (union DL_primitives *)mp->b_rptr;
14824 		if (DB_TYPE(mp) != M_PCPROTO ||
14825 		    dl->dl_primitive == DL_UNITDATA_IND) {
14826 			/*
14827 			 * SIOC[GS]TUNPARAM ioctls can come here.
14828 			 */
14829 			inet_freemsg(mp);
14830 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14831 			    "ip_rput_end: q %p (%S)", q, "uninit");
14832 			return;
14833 		}
14834 	}
14835 
14836 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14837 	    "ip_rput_end: q %p (%S)", q, "end");
14838 
14839 	ip_input(ill, NULL, mp, NULL);
14840 }
14841 
14842 static mblk_t *
14843 ip_fix_dbref(ill_t *ill, mblk_t *mp)
14844 {
14845 	mblk_t *mp1;
14846 	boolean_t adjusted = B_FALSE;
14847 	ip_stack_t *ipst = ill->ill_ipst;
14848 
14849 	IP_STAT(ipst, ip_db_ref);
14850 	/*
14851 	 * The IP_RECVSLLA option depends on having the
14852 	 * link layer header. First check that:
14853 	 * a> the underlying device is of type ether,
14854 	 * since this option is currently supported only
14855 	 * over ethernet.
14856 	 * b> there is enough room to copy over the link
14857 	 * layer header.
14858 	 *
14859 	 * Once the checks are done, adjust rptr so that
14860 	 * the link layer header will be copied via
14861 	 * copymsg. Note that, IFT_ETHER may be returned
14862 	 * by some non-ethernet drivers but in this case
14863 	 * the second check will fail.
14864 	 */
14865 	if (ill->ill_type == IFT_ETHER &&
14866 	    (mp->b_rptr - mp->b_datap->db_base) >=
14867 	    sizeof (struct ether_header)) {
14868 		mp->b_rptr -= sizeof (struct ether_header);
14869 		adjusted = B_TRUE;
14870 	}
14871 	mp1 = copymsg(mp);
14872 
14873 	if (mp1 == NULL) {
14874 		mp->b_next = NULL;
14875 		/* clear b_prev - used by ip_mroute_decap */
14876 		mp->b_prev = NULL;
14877 		freemsg(mp);
14878 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14879 		return (NULL);
14880 	}
14881 
14882 	if (adjusted) {
14883 		/*
14884 		 * Copy is done. Restore the pointer in
14885 		 * the _new_ mblk
14886 		 */
14887 		mp1->b_rptr += sizeof (struct ether_header);
14888 	}
14889 
14890 	/* Copy b_prev - used by ip_mroute_decap */
14891 	mp1->b_prev = mp->b_prev;
14892 	mp->b_prev = NULL;
14893 
14894 	/* preserve the hardware checksum flags and data, if present */
14895 	if (DB_CKSUMFLAGS(mp) != 0) {
14896 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
14897 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
14898 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
14899 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
14900 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
14901 	}
14902 
14903 	freemsg(mp);
14904 	return (mp1);
14905 }
14906 
14907 /*
14908  * Direct read side procedure capable of dealing with chains. GLDv3 based
14909  * drivers call this function directly with mblk chains while STREAMS
14910  * read side procedure ip_rput() calls this for single packet with ip_ring
14911  * set to NULL to process one packet at a time.
14912  *
14913  * The ill will always be valid if this function is called directly from
14914  * the driver.
14915  *
14916  * If ip_input() is called from GLDv3:
14917  *
14918  *   - This must be a non-VLAN IP stream.
14919  *   - 'mp' is either an untagged or a special priority-tagged packet.
14920  *   - Any VLAN tag that was in the MAC header has been stripped.
14921  *
14922  * If the IP header in packet is not 32-bit aligned, every message in the
14923  * chain will be aligned before further operations. This is required on SPARC
14924  * platform.
14925  */
14926 /* ARGSUSED */
14927 void
14928 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14929     struct mac_header_info_s *mhip)
14930 {
14931 	ipaddr_t		dst = NULL;
14932 	ipaddr_t		prev_dst;
14933 	ire_t			*ire = NULL;
14934 	ipha_t			*ipha;
14935 	uint_t			pkt_len;
14936 	ssize_t			len;
14937 	uint_t			opt_len;
14938 	int			ll_multicast;
14939 	int			cgtp_flt_pkt;
14940 	queue_t			*q = ill->ill_rq;
14941 	squeue_t		*curr_sqp = NULL;
14942 	mblk_t 			*head = NULL;
14943 	mblk_t			*tail = NULL;
14944 	mblk_t			*first_mp;
14945 	mblk_t 			*mp;
14946 	mblk_t			*dmp;
14947 	int			cnt = 0;
14948 	ip_stack_t		*ipst = ill->ill_ipst;
14949 
14950 	ASSERT(mp_chain != NULL);
14951 	ASSERT(ill != NULL);
14952 
14953 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14954 
14955 #define	rptr	((uchar_t *)ipha)
14956 
14957 	while (mp_chain != NULL) {
14958 		first_mp = mp = mp_chain;
14959 		mp_chain = mp_chain->b_next;
14960 		mp->b_next = NULL;
14961 		ll_multicast = 0;
14962 
14963 		/*
14964 		 * We do ire caching from one iteration to
14965 		 * another. In the event the packet chain contains
14966 		 * all packets from the same dst, this caching saves
14967 		 * an ire_cache_lookup for each of the succeeding
14968 		 * packets in a packet chain.
14969 		 */
14970 		prev_dst = dst;
14971 
14972 		/*
14973 		 * if db_ref > 1 then copymsg and free original. Packet
14974 		 * may be changed and we do not want the other entity
14975 		 * who has a reference to this message to trip over the
14976 		 * changes. This is a blind change because trying to
14977 		 * catch all places that might change the packet is too
14978 		 * difficult.
14979 		 *
14980 		 * This corresponds to the fast path case, where we have
14981 		 * a chain of M_DATA mblks.  We check the db_ref count
14982 		 * of only the 1st data block in the mblk chain. There
14983 		 * doesn't seem to be a reason why a device driver would
14984 		 * send up data with varying db_ref counts in the mblk
14985 		 * chain. In any case the Fast path is a private
14986 		 * interface, and our drivers don't do such a thing.
14987 		 * Given the above assumption, there is no need to walk
14988 		 * down the entire mblk chain (which could have a
14989 		 * potential performance problem)
14990 		 */
14991 
14992 		if (DB_REF(mp) > 1) {
14993 			if ((mp = ip_fix_dbref(ill, mp)) == NULL)
14994 				continue;
14995 		}
14996 
14997 		/*
14998 		 * Check and align the IP header.
14999 		 */
15000 		first_mp = mp;
15001 		if (DB_TYPE(mp) == M_DATA) {
15002 			dmp = mp;
15003 		} else if (DB_TYPE(mp) == M_PROTO &&
15004 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
15005 			dmp = mp->b_cont;
15006 		} else {
15007 			dmp = NULL;
15008 		}
15009 		if (dmp != NULL) {
15010 			/*
15011 			 * IP header ptr not aligned?
15012 			 * OR IP header not complete in first mblk
15013 			 */
15014 			if (!OK_32PTR(dmp->b_rptr) ||
15015 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
15016 				if (!ip_check_and_align_header(q, dmp, ipst))
15017 					continue;
15018 			}
15019 		}
15020 
15021 		/*
15022 		 * ip_input fast path
15023 		 */
15024 
15025 		/* mblk type is not M_DATA */
15026 		if (DB_TYPE(mp) != M_DATA) {
15027 			if (ip_rput_process_notdata(q, &first_mp, ill,
15028 			    &ll_multicast, &mp))
15029 				continue;
15030 
15031 			/*
15032 			 * The only way we can get here is if we had a
15033 			 * packet that was either a DL_UNITDATA_IND or
15034 			 * an M_CTL for an IPsec accelerated packet.
15035 			 *
15036 			 * In either case, the first_mp will point to
15037 			 * the leading M_PROTO or M_CTL.
15038 			 */
15039 			ASSERT(first_mp != NULL);
15040 		} else if (mhip != NULL) {
15041 			/*
15042 			 * ll_multicast is set here so that it is ready
15043 			 * for easy use with FW_HOOKS().  ip_get_dlpi_mbcast
15044 			 * manipulates ll_multicast in the same fashion when
15045 			 * called from ip_rput_process_notdata.
15046 			 */
15047 			switch (mhip->mhi_dsttype) {
15048 			case MAC_ADDRTYPE_MULTICAST :
15049 				ll_multicast = HPE_MULTICAST;
15050 				break;
15051 			case MAC_ADDRTYPE_BROADCAST :
15052 				ll_multicast = HPE_BROADCAST;
15053 				break;
15054 			default :
15055 				break;
15056 			}
15057 		}
15058 
15059 		/* Make sure its an M_DATA and that its aligned */
15060 		ASSERT(DB_TYPE(mp) == M_DATA);
15061 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
15062 
15063 		ipha = (ipha_t *)mp->b_rptr;
15064 		len = mp->b_wptr - rptr;
15065 		pkt_len = ntohs(ipha->ipha_length);
15066 
15067 		/*
15068 		 * We must count all incoming packets, even if they end
15069 		 * up being dropped later on.
15070 		 */
15071 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15072 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15073 
15074 		/* multiple mblk or too short */
15075 		len -= pkt_len;
15076 		if (len != 0) {
15077 			/*
15078 			 * Make sure we have data length consistent
15079 			 * with the IP header.
15080 			 */
15081 			if (mp->b_cont == NULL) {
15082 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15083 					BUMP_MIB(ill->ill_ip_mib,
15084 					    ipIfStatsInHdrErrors);
15085 					ip2dbg(("ip_input: drop pkt\n"));
15086 					freemsg(mp);
15087 					continue;
15088 				}
15089 				mp->b_wptr = rptr + pkt_len;
15090 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
15091 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15092 					BUMP_MIB(ill->ill_ip_mib,
15093 					    ipIfStatsInHdrErrors);
15094 					ip2dbg(("ip_input: drop pkt\n"));
15095 					freemsg(mp);
15096 					continue;
15097 				}
15098 				(void) adjmsg(mp, -len);
15099 				IP_STAT(ipst, ip_multimblk3);
15100 			}
15101 		}
15102 
15103 		/* Obtain the dst of the current packet */
15104 		dst = ipha->ipha_dst;
15105 
15106 		DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL,
15107 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *,
15108 		    ipha, ip6_t *, NULL, int, 0);
15109 
15110 		/*
15111 		 * The following test for loopback is faster than
15112 		 * IP_LOOPBACK_ADDR(), because it avoids any bitwise
15113 		 * operations.
15114 		 * Note that these addresses are always in network byte order
15115 		 */
15116 		if (((*(uchar_t *)&ipha->ipha_dst) == 127) ||
15117 		    ((*(uchar_t *)&ipha->ipha_src) == 127)) {
15118 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
15119 			freemsg(mp);
15120 			continue;
15121 		}
15122 
15123 		/*
15124 		 * The event for packets being received from a 'physical'
15125 		 * interface is placed after validation of the source and/or
15126 		 * destination address as being local so that packets can be
15127 		 * redirected to loopback addresses using ipnat.
15128 		 */
15129 		DTRACE_PROBE4(ip4__physical__in__start,
15130 		    ill_t *, ill, ill_t *, NULL,
15131 		    ipha_t *, ipha, mblk_t *, first_mp);
15132 
15133 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15134 		    ipst->ips_ipv4firewall_physical_in,
15135 		    ill, NULL, ipha, first_mp, mp, ll_multicast, ipst);
15136 
15137 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15138 
15139 		if (first_mp == NULL) {
15140 			continue;
15141 		}
15142 		dst = ipha->ipha_dst;
15143 
15144 		/*
15145 		 * Attach any necessary label information to
15146 		 * this packet
15147 		 */
15148 		if (is_system_labeled() &&
15149 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15150 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15151 			freemsg(mp);
15152 			continue;
15153 		}
15154 
15155 		if (ipst->ips_ipobs_enabled) {
15156 			zoneid_t dzone;
15157 
15158 			/*
15159 			 * On the inbound path the src zone will be unknown as
15160 			 * this packet has come from the wire.
15161 			 */
15162 			dzone = ip_get_zoneid_v4(dst, mp, ipst, ALL_ZONES);
15163 			ipobs_hook(mp, IPOBS_HOOK_INBOUND, ALL_ZONES, dzone,
15164 			    ill, IPV4_VERSION, 0, ipst);
15165 		}
15166 
15167 		/*
15168 		 * Reuse the cached ire only if the ipha_dst of the previous
15169 		 * packet is the same as the current packet AND it is not
15170 		 * INADDR_ANY.
15171 		 */
15172 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15173 		    (ire != NULL)) {
15174 			ire_refrele(ire);
15175 			ire = NULL;
15176 		}
15177 
15178 		opt_len = ipha->ipha_version_and_hdr_length -
15179 		    IP_SIMPLE_HDR_VERSION;
15180 
15181 		/*
15182 		 * Check to see if we can take the fastpath.
15183 		 * That is possible if the following conditions are met
15184 		 *	o Tsol disabled
15185 		 *	o CGTP disabled
15186 		 *	o ipp_action_count is 0
15187 		 *	o no options in the packet
15188 		 *	o not a RSVP packet
15189 		 * 	o not a multicast packet
15190 		 *	o ill not in IP_DHCPINIT_IF mode
15191 		 */
15192 		if (!is_system_labeled() &&
15193 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
15194 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15195 		    !ll_multicast && !CLASSD(dst) && ill->ill_dhcpinit == 0) {
15196 			if (ire == NULL)
15197 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL,
15198 				    ipst);
15199 
15200 			/* incoming packet is for forwarding */
15201 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
15202 				ire = ip_fast_forward(ire, dst, ill, mp);
15203 				continue;
15204 			}
15205 			/* incoming packet is for local consumption */
15206 			if (ire->ire_type & IRE_LOCAL)
15207 				goto local;
15208 		}
15209 
15210 		/*
15211 		 * Disable ire caching for anything more complex
15212 		 * than the simple fast path case we checked for above.
15213 		 */
15214 		if (ire != NULL) {
15215 			ire_refrele(ire);
15216 			ire = NULL;
15217 		}
15218 
15219 		/*
15220 		 * Brutal hack for DHCPv4 unicast: RFC2131 allows a DHCP
15221 		 * server to unicast DHCP packets to a DHCP client using the
15222 		 * IP address it is offering to the client.  This can be
15223 		 * disabled through the "broadcast bit", but not all DHCP
15224 		 * servers honor that bit.  Therefore, to interoperate with as
15225 		 * many DHCP servers as possible, the DHCP client allows the
15226 		 * server to unicast, but we treat those packets as broadcast
15227 		 * here.  Note that we don't rewrite the packet itself since
15228 		 * (a) that would mess up the checksums and (b) the DHCP
15229 		 * client conn is bound to INADDR_ANY so ip_fanout_udp() will
15230 		 * hand it the packet regardless.
15231 		 */
15232 		if (ill->ill_dhcpinit != 0 &&
15233 		    IS_SIMPLE_IPH(ipha) && ipha->ipha_protocol == IPPROTO_UDP &&
15234 		    pullupmsg(mp, sizeof (ipha_t) + sizeof (udpha_t)) == 1) {
15235 			udpha_t *udpha;
15236 
15237 			/*
15238 			 * Reload ipha since pullupmsg() can change b_rptr.
15239 			 */
15240 			ipha = (ipha_t *)mp->b_rptr;
15241 			udpha = (udpha_t *)&ipha[1];
15242 
15243 			if (ntohs(udpha->uha_dst_port) == IPPORT_BOOTPC) {
15244 				DTRACE_PROBE2(ip4__dhcpinit__pkt, ill_t *, ill,
15245 				    mblk_t *, mp);
15246 				dst = INADDR_BROADCAST;
15247 			}
15248 		}
15249 
15250 		/* Full-blown slow path */
15251 		if (opt_len != 0) {
15252 			if (len != 0)
15253 				IP_STAT(ipst, ip_multimblk4);
15254 			else
15255 				IP_STAT(ipst, ip_ipoptions);
15256 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15257 			    &dst, ipst))
15258 				continue;
15259 		}
15260 
15261 		/*
15262 		 * Invoke the CGTP (multirouting) filtering module to process
15263 		 * the incoming packet. Packets identified as duplicates
15264 		 * must be discarded. Filtering is active only if the
15265 		 * the ip_cgtp_filter ndd variable is non-zero.
15266 		 */
15267 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15268 		if (ipst->ips_ip_cgtp_filter &&
15269 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15270 			netstackid_t stackid;
15271 
15272 			stackid = ipst->ips_netstack->netstack_stackid;
15273 			cgtp_flt_pkt =
15274 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15275 			    ill->ill_phyint->phyint_ifindex, mp);
15276 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15277 				freemsg(first_mp);
15278 				continue;
15279 			}
15280 		}
15281 
15282 		/*
15283 		 * If rsvpd is running, let RSVP daemon handle its processing
15284 		 * and forwarding of RSVP multicast/unicast packets.
15285 		 * If rsvpd is not running but mrouted is running, RSVP
15286 		 * multicast packets are forwarded as multicast traffic
15287 		 * and RSVP unicast packets are forwarded by unicast router.
15288 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15289 		 * packets are not forwarded, but the unicast packets are
15290 		 * forwarded like unicast traffic.
15291 		 */
15292 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15293 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15294 		    NULL) {
15295 			/* RSVP packet and rsvpd running. Treat as ours */
15296 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15297 			/*
15298 			 * This assumes that we deliver to all streams for
15299 			 * multicast and broadcast packets.
15300 			 * We have to force ll_multicast to 1 to handle the
15301 			 * M_DATA messages passed in from ip_mroute_decap.
15302 			 */
15303 			dst = INADDR_BROADCAST;
15304 			ll_multicast = 1;
15305 		} else if (CLASSD(dst)) {
15306 			/* packet is multicast */
15307 			mp->b_next = NULL;
15308 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15309 			    &ll_multicast, &dst))
15310 				continue;
15311 		}
15312 
15313 		if (ire == NULL) {
15314 			ire = ire_cache_lookup(dst, ALL_ZONES,
15315 			    MBLK_GETLABEL(mp), ipst);
15316 		}
15317 
15318 		if (ire != NULL && ire->ire_stq != NULL &&
15319 		    ire->ire_zoneid != GLOBAL_ZONEID &&
15320 		    ire->ire_zoneid != ALL_ZONES) {
15321 			/*
15322 			 * Should only use IREs that are visible from the
15323 			 * global zone for forwarding.
15324 			 */
15325 			ire_refrele(ire);
15326 			ire = ire_cache_lookup(dst, GLOBAL_ZONEID,
15327 			    MBLK_GETLABEL(mp), ipst);
15328 		}
15329 
15330 		if (ire == NULL) {
15331 			/*
15332 			 * No IRE for this destination, so it can't be for us.
15333 			 * Unless we are forwarding, drop the packet.
15334 			 * We have to let source routed packets through
15335 			 * since we don't yet know if they are 'ping -l'
15336 			 * packets i.e. if they will go out over the
15337 			 * same interface as they came in on.
15338 			 */
15339 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15340 			if (ire == NULL)
15341 				continue;
15342 		}
15343 
15344 		/*
15345 		 * Broadcast IRE may indicate either broadcast or
15346 		 * multicast packet
15347 		 */
15348 		if (ire->ire_type == IRE_BROADCAST) {
15349 			/*
15350 			 * Skip broadcast checks if packet is UDP multicast;
15351 			 * we'd rather not enter ip_rput_process_broadcast()
15352 			 * unless the packet is broadcast for real, since
15353 			 * that routine is a no-op for multicast.
15354 			 */
15355 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15356 			    !CLASSD(ipha->ipha_dst)) {
15357 				ire = ip_rput_process_broadcast(&q, mp,
15358 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15359 				    ll_multicast);
15360 				if (ire == NULL)
15361 					continue;
15362 			}
15363 		} else if (ire->ire_stq != NULL) {
15364 			/* fowarding? */
15365 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15366 			    ll_multicast);
15367 			/* ip_rput_process_forward consumed the packet */
15368 			continue;
15369 		}
15370 
15371 local:
15372 		/*
15373 		 * If the queue in the ire is different to the ingress queue
15374 		 * then we need to check to see if we can accept the packet.
15375 		 * Note that for multicast packets and broadcast packets sent
15376 		 * to a broadcast address which is shared between multiple
15377 		 * interfaces we should not do this since we just got a random
15378 		 * broadcast ire.
15379 		 */
15380 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15381 			if ((ire = ip_check_multihome(&ipha->ipha_dst, ire,
15382 			    ill)) == NULL) {
15383 				/* Drop packet */
15384 				BUMP_MIB(ill->ill_ip_mib,
15385 				    ipIfStatsForwProhibits);
15386 				freemsg(mp);
15387 				continue;
15388 			}
15389 			if (ire->ire_rfq != NULL)
15390 				q = ire->ire_rfq;
15391 		}
15392 
15393 		switch (ipha->ipha_protocol) {
15394 		case IPPROTO_TCP:
15395 			ASSERT(first_mp == mp);
15396 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15397 			    mp, 0, q, ip_ring)) != NULL) {
15398 				if (curr_sqp == NULL) {
15399 					curr_sqp = GET_SQUEUE(mp);
15400 					ASSERT(cnt == 0);
15401 					cnt++;
15402 					head = tail = mp;
15403 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15404 					ASSERT(tail != NULL);
15405 					cnt++;
15406 					tail->b_next = mp;
15407 					tail = mp;
15408 				} else {
15409 					/*
15410 					 * A different squeue. Send the
15411 					 * chain for the previous squeue on
15412 					 * its way. This shouldn't happen
15413 					 * often unless interrupt binding
15414 					 * changes.
15415 					 */
15416 					IP_STAT(ipst, ip_input_multi_squeue);
15417 					squeue_enter_chain(curr_sqp, head,
15418 					    tail, cnt, SQTAG_IP_INPUT);
15419 					curr_sqp = GET_SQUEUE(mp);
15420 					head = mp;
15421 					tail = mp;
15422 					cnt = 1;
15423 				}
15424 			}
15425 			continue;
15426 		case IPPROTO_UDP:
15427 			ASSERT(first_mp == mp);
15428 			ip_udp_input(q, mp, ipha, ire, ill);
15429 			continue;
15430 		case IPPROTO_SCTP:
15431 			ASSERT(first_mp == mp);
15432 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15433 			    q, dst);
15434 			/* ire has been released by ip_sctp_input */
15435 			ire = NULL;
15436 			continue;
15437 		default:
15438 			ip_proto_input(q, first_mp, ipha, ire, ill, 0);
15439 			continue;
15440 		}
15441 	}
15442 
15443 	if (ire != NULL)
15444 		ire_refrele(ire);
15445 
15446 	if (head != NULL)
15447 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
15448 
15449 	/*
15450 	 * This code is there just to make netperf/ttcp look good.
15451 	 *
15452 	 * Its possible that after being in polling mode (and having cleared
15453 	 * the backlog), squeues have turned the interrupt frequency higher
15454 	 * to improve latency at the expense of more CPU utilization (less
15455 	 * packets per interrupts or more number of interrupts). Workloads
15456 	 * like ttcp/netperf do manage to tickle polling once in a while
15457 	 * but for the remaining time, stay in higher interrupt mode since
15458 	 * their packet arrival rate is pretty uniform and this shows up
15459 	 * as higher CPU utilization. Since people care about CPU utilization
15460 	 * while running netperf/ttcp, turn the interrupt frequency back to
15461 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
15462 	 */
15463 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
15464 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
15465 			ip_ring->rr_poll_state &= ~ILL_POLLING;
15466 			ip_ring->rr_blank(ip_ring->rr_handle,
15467 			    ip_ring->rr_normal_blank_time,
15468 			    ip_ring->rr_normal_pkt_cnt);
15469 		}
15470 		}
15471 
15472 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15473 	    "ip_input_end: q %p (%S)", q, "end");
15474 #undef  rptr
15475 }
15476 
15477 static void
15478 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15479     t_uscalar_t err)
15480 {
15481 	if (dl_err == DL_SYSERR) {
15482 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15483 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15484 		    ill->ill_name, dl_primstr(prim), err);
15485 		return;
15486 	}
15487 
15488 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15489 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
15490 	    dl_errstr(dl_err));
15491 }
15492 
15493 /*
15494  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15495  * than DL_UNITDATA_IND messages. If we need to process this message
15496  * exclusively, we call qwriter_ip, in which case we also need to call
15497  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15498  */
15499 void
15500 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15501 {
15502 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15503 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15504 	ill_t		*ill = q->q_ptr;
15505 	t_uscalar_t	prim = dloa->dl_primitive;
15506 	t_uscalar_t	reqprim = DL_PRIM_INVAL;
15507 
15508 	ip1dbg(("ip_rput_dlpi"));
15509 
15510 	/*
15511 	 * If we received an ACK but didn't send a request for it, then it
15512 	 * can't be part of any pending operation; discard up-front.
15513 	 */
15514 	switch (prim) {
15515 	case DL_ERROR_ACK:
15516 		reqprim = dlea->dl_error_primitive;
15517 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
15518 		    "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
15519 		    reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
15520 		    dlea->dl_unix_errno));
15521 		break;
15522 	case DL_OK_ACK:
15523 		reqprim = dloa->dl_correct_primitive;
15524 		break;
15525 	case DL_INFO_ACK:
15526 		reqprim = DL_INFO_REQ;
15527 		break;
15528 	case DL_BIND_ACK:
15529 		reqprim = DL_BIND_REQ;
15530 		break;
15531 	case DL_PHYS_ADDR_ACK:
15532 		reqprim = DL_PHYS_ADDR_REQ;
15533 		break;
15534 	case DL_NOTIFY_ACK:
15535 		reqprim = DL_NOTIFY_REQ;
15536 		break;
15537 	case DL_CONTROL_ACK:
15538 		reqprim = DL_CONTROL_REQ;
15539 		break;
15540 	case DL_CAPABILITY_ACK:
15541 		reqprim = DL_CAPABILITY_REQ;
15542 		break;
15543 	}
15544 
15545 	if (prim != DL_NOTIFY_IND) {
15546 		if (reqprim == DL_PRIM_INVAL ||
15547 		    !ill_dlpi_pending(ill, reqprim)) {
15548 			/* Not a DLPI message we support or expected */
15549 			freemsg(mp);
15550 			return;
15551 		}
15552 		ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
15553 		    dl_primstr(reqprim)));
15554 	}
15555 
15556 	switch (reqprim) {
15557 	case DL_UNBIND_REQ:
15558 		/*
15559 		 * NOTE: we mark the unbind as complete even if we got a
15560 		 * DL_ERROR_ACK, since there's not much else we can do.
15561 		 */
15562 		mutex_enter(&ill->ill_lock);
15563 		ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15564 		cv_signal(&ill->ill_cv);
15565 		mutex_exit(&ill->ill_lock);
15566 		break;
15567 
15568 	case DL_ENABMULTI_REQ:
15569 		if (prim == DL_OK_ACK) {
15570 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15571 				ill->ill_dlpi_multicast_state = IDS_OK;
15572 		}
15573 		break;
15574 	}
15575 
15576 	/*
15577 	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
15578 	 * need to become writer to continue to process it.  Because an
15579 	 * exclusive operation doesn't complete until replies to all queued
15580 	 * DLPI messages have been received, we know we're in the middle of an
15581 	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
15582 	 *
15583 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15584 	 * Since this is on the ill stream we unconditionally bump up the
15585 	 * refcount without doing ILL_CAN_LOOKUP().
15586 	 */
15587 	ill_refhold(ill);
15588 	if (prim == DL_NOTIFY_IND)
15589 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15590 	else
15591 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15592 }
15593 
15594 /*
15595  * Handling of DLPI messages that require exclusive access to the ipsq.
15596  *
15597  * Need to do ill_pending_mp_release on ioctl completion, which could
15598  * happen here. (along with mi_copy_done)
15599  */
15600 /* ARGSUSED */
15601 static void
15602 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15603 {
15604 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15605 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15606 	int		err = 0;
15607 	ill_t		*ill;
15608 	ipif_t		*ipif = NULL;
15609 	mblk_t		*mp1 = NULL;
15610 	conn_t		*connp = NULL;
15611 	t_uscalar_t	paddrreq;
15612 	mblk_t		*mp_hw;
15613 	boolean_t	success;
15614 	boolean_t	ioctl_aborted = B_FALSE;
15615 	boolean_t	log = B_TRUE;
15616 	ip_stack_t		*ipst;
15617 
15618 	ip1dbg(("ip_rput_dlpi_writer .."));
15619 	ill = (ill_t *)q->q_ptr;
15620 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15621 
15622 	ASSERT(IAM_WRITER_ILL(ill));
15623 
15624 	ipst = ill->ill_ipst;
15625 
15626 	/*
15627 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15628 	 * both are null or non-null. However we can assert that only
15629 	 * after grabbing the ipsq_lock. So we don't make any assertion
15630 	 * here and in other places in the code.
15631 	 */
15632 	ipif = ipsq->ipsq_pending_ipif;
15633 	/*
15634 	 * The current ioctl could have been aborted by the user and a new
15635 	 * ioctl to bring up another ill could have started. We could still
15636 	 * get a response from the driver later.
15637 	 */
15638 	if (ipif != NULL && ipif->ipif_ill != ill)
15639 		ioctl_aborted = B_TRUE;
15640 
15641 	switch (dloa->dl_primitive) {
15642 	case DL_ERROR_ACK:
15643 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15644 		    dl_primstr(dlea->dl_error_primitive)));
15645 
15646 		switch (dlea->dl_error_primitive) {
15647 		case DL_DISABMULTI_REQ:
15648 			if (!ill->ill_isv6)
15649 				ipsq_current_finish(ipsq);
15650 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15651 			break;
15652 		case DL_PROMISCON_REQ:
15653 		case DL_PROMISCOFF_REQ:
15654 		case DL_UNBIND_REQ:
15655 		case DL_ATTACH_REQ:
15656 		case DL_INFO_REQ:
15657 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15658 			break;
15659 		case DL_NOTIFY_REQ:
15660 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15661 			log = B_FALSE;
15662 			break;
15663 		case DL_PHYS_ADDR_REQ:
15664 			/*
15665 			 * For IPv6 only, there are two additional
15666 			 * phys_addr_req's sent to the driver to get the
15667 			 * IPv6 token and lla. This allows IP to acquire
15668 			 * the hardware address format for a given interface
15669 			 * without having built in knowledge of the hardware
15670 			 * address. ill_phys_addr_pend keeps track of the last
15671 			 * DL_PAR sent so we know which response we are
15672 			 * dealing with. ill_dlpi_done will update
15673 			 * ill_phys_addr_pend when it sends the next req.
15674 			 * We don't complete the IOCTL until all three DL_PARs
15675 			 * have been attempted, so set *_len to 0 and break.
15676 			 */
15677 			paddrreq = ill->ill_phys_addr_pend;
15678 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15679 			if (paddrreq == DL_IPV6_TOKEN) {
15680 				ill->ill_token_length = 0;
15681 				log = B_FALSE;
15682 				break;
15683 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15684 				ill->ill_nd_lla_len = 0;
15685 				log = B_FALSE;
15686 				break;
15687 			}
15688 			/*
15689 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15690 			 * We presumably have an IOCTL hanging out waiting
15691 			 * for completion. Find it and complete the IOCTL
15692 			 * with the error noted.
15693 			 * However, ill_dl_phys was called on an ill queue
15694 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15695 			 * set. But the ioctl is known to be pending on ill_wq.
15696 			 */
15697 			if (!ill->ill_ifname_pending)
15698 				break;
15699 			ill->ill_ifname_pending = 0;
15700 			if (!ioctl_aborted)
15701 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15702 			if (mp1 != NULL) {
15703 				/*
15704 				 * This operation (SIOCSLIFNAME) must have
15705 				 * happened on the ill. Assert there is no conn
15706 				 */
15707 				ASSERT(connp == NULL);
15708 				q = ill->ill_wq;
15709 			}
15710 			break;
15711 		case DL_BIND_REQ:
15712 			ill_dlpi_done(ill, DL_BIND_REQ);
15713 			if (ill->ill_ifname_pending)
15714 				break;
15715 			/*
15716 			 * Something went wrong with the bind.  We presumably
15717 			 * have an IOCTL hanging out waiting for completion.
15718 			 * Find it, take down the interface that was coming
15719 			 * up, and complete the IOCTL with the error noted.
15720 			 */
15721 			if (!ioctl_aborted)
15722 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15723 			if (mp1 != NULL) {
15724 				/*
15725 				 * This operation (SIOCSLIFFLAGS) must have
15726 				 * happened from a conn.
15727 				 */
15728 				ASSERT(connp != NULL);
15729 				q = CONNP_TO_WQ(connp);
15730 				if (ill->ill_move_in_progress) {
15731 					ILL_CLEAR_MOVE(ill);
15732 				}
15733 				(void) ipif_down(ipif, NULL, NULL);
15734 				/* error is set below the switch */
15735 			}
15736 			break;
15737 		case DL_ENABMULTI_REQ:
15738 			if (!ill->ill_isv6)
15739 				ipsq_current_finish(ipsq);
15740 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15741 
15742 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15743 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15744 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15745 				ipif_t *ipif;
15746 
15747 				printf("ip: joining multicasts failed (%d)"
15748 				    " on %s - will use link layer "
15749 				    "broadcasts for multicast\n",
15750 				    dlea->dl_errno, ill->ill_name);
15751 
15752 				/*
15753 				 * Set up the multicast mapping alone.
15754 				 * writer, so ok to access ill->ill_ipif
15755 				 * without any lock.
15756 				 */
15757 				ipif = ill->ill_ipif;
15758 				mutex_enter(&ill->ill_phyint->phyint_lock);
15759 				ill->ill_phyint->phyint_flags |=
15760 				    PHYI_MULTI_BCAST;
15761 				mutex_exit(&ill->ill_phyint->phyint_lock);
15762 
15763 				if (!ill->ill_isv6) {
15764 					(void) ipif_arp_setup_multicast(ipif,
15765 					    NULL);
15766 				} else {
15767 					(void) ipif_ndp_setup_multicast(ipif,
15768 					    NULL);
15769 				}
15770 			}
15771 			freemsg(mp);	/* Don't want to pass this up */
15772 			return;
15773 
15774 		case DL_CAPABILITY_REQ:
15775 		case DL_CONTROL_REQ:
15776 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15777 			ill->ill_dlpi_capab_state = IDS_FAILED;
15778 			freemsg(mp);
15779 			return;
15780 		}
15781 		/*
15782 		 * Note the error for IOCTL completion (mp1 is set when
15783 		 * ready to complete ioctl). If ill_ifname_pending_err is
15784 		 * set, an error occured during plumbing (ill_ifname_pending),
15785 		 * so we want to report that error.
15786 		 *
15787 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15788 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15789 		 * expected to get errack'd if the driver doesn't support
15790 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15791 		 * if these error conditions are encountered.
15792 		 */
15793 		if (mp1 != NULL) {
15794 			if (ill->ill_ifname_pending_err != 0)  {
15795 				err = ill->ill_ifname_pending_err;
15796 				ill->ill_ifname_pending_err = 0;
15797 			} else {
15798 				err = dlea->dl_unix_errno ?
15799 				    dlea->dl_unix_errno : ENXIO;
15800 			}
15801 		/*
15802 		 * If we're plumbing an interface and an error hasn't already
15803 		 * been saved, set ill_ifname_pending_err to the error passed
15804 		 * up. Ignore the error if log is B_FALSE (see comment above).
15805 		 */
15806 		} else if (log && ill->ill_ifname_pending &&
15807 		    ill->ill_ifname_pending_err == 0) {
15808 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15809 			    dlea->dl_unix_errno : ENXIO;
15810 		}
15811 
15812 		if (log)
15813 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15814 			    dlea->dl_errno, dlea->dl_unix_errno);
15815 		break;
15816 	case DL_CAPABILITY_ACK:
15817 		/* Call a routine to handle this one. */
15818 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15819 		ill_capability_ack(ill, mp);
15820 
15821 		/*
15822 		 * If the ack is due to renegotiation, we will need to send
15823 		 * a new CAPABILITY_REQ to start the renegotiation.
15824 		 */
15825 		if (ill->ill_capab_reneg) {
15826 			ill->ill_capab_reneg = B_FALSE;
15827 			ill_capability_probe(ill);
15828 		}
15829 		break;
15830 	case DL_CONTROL_ACK:
15831 		/* We treat all of these as "fire and forget" */
15832 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15833 		break;
15834 	case DL_INFO_ACK:
15835 		/* Call a routine to handle this one. */
15836 		ill_dlpi_done(ill, DL_INFO_REQ);
15837 		ip_ll_subnet_defaults(ill, mp);
15838 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15839 		return;
15840 	case DL_BIND_ACK:
15841 		/*
15842 		 * We should have an IOCTL waiting on this unless
15843 		 * sent by ill_dl_phys, in which case just return
15844 		 */
15845 		ill_dlpi_done(ill, DL_BIND_REQ);
15846 		if (ill->ill_ifname_pending)
15847 			break;
15848 
15849 		if (!ioctl_aborted)
15850 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15851 		if (mp1 == NULL)
15852 			break;
15853 		/*
15854 		 * Because mp1 was added by ill_dl_up(), and it always
15855 		 * passes a valid connp, connp must be valid here.
15856 		 */
15857 		ASSERT(connp != NULL);
15858 		q = CONNP_TO_WQ(connp);
15859 
15860 		/*
15861 		 * We are exclusive. So nothing can change even after
15862 		 * we get the pending mp. If need be we can put it back
15863 		 * and restart, as in calling ipif_arp_up()  below.
15864 		 */
15865 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15866 
15867 		mutex_enter(&ill->ill_lock);
15868 		ill->ill_dl_up = 1;
15869 		ill_nic_event_dispatch(ill, 0, NE_UP, NULL, 0);
15870 		mutex_exit(&ill->ill_lock);
15871 
15872 		/*
15873 		 * Now bring up the resolver; when that is complete, we'll
15874 		 * create IREs.  Note that we intentionally mirror what
15875 		 * ipif_up() would have done, because we got here by way of
15876 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15877 		 */
15878 		if (ill->ill_isv6) {
15879 			/*
15880 			 * v6 interfaces.
15881 			 * Unlike ARP which has to do another bind
15882 			 * and attach, once we get here we are
15883 			 * done with NDP. Except in the case of
15884 			 * ILLF_XRESOLV, in which case we send an
15885 			 * AR_INTERFACE_UP to the external resolver.
15886 			 * If all goes well, the ioctl will complete
15887 			 * in ip_rput(). If there's an error, we
15888 			 * complete it here.
15889 			 */
15890 			if ((err = ipif_ndp_up(ipif)) == 0) {
15891 				if (ill->ill_flags & ILLF_XRESOLV) {
15892 					mutex_enter(&connp->conn_lock);
15893 					mutex_enter(&ill->ill_lock);
15894 					success = ipsq_pending_mp_add(
15895 					    connp, ipif, q, mp1, 0);
15896 					mutex_exit(&ill->ill_lock);
15897 					mutex_exit(&connp->conn_lock);
15898 					if (success) {
15899 						err = ipif_resolver_up(ipif,
15900 						    Res_act_initial);
15901 						if (err == EINPROGRESS) {
15902 							freemsg(mp);
15903 							return;
15904 						}
15905 						ASSERT(err != 0);
15906 						mp1 = ipsq_pending_mp_get(ipsq,
15907 						    &connp);
15908 						ASSERT(mp1 != NULL);
15909 					} else {
15910 						/* conn has started closing */
15911 						err = EINTR;
15912 					}
15913 				} else { /* Non XRESOLV interface */
15914 					(void) ipif_resolver_up(ipif,
15915 					    Res_act_initial);
15916 					err = ipif_up_done_v6(ipif);
15917 				}
15918 			}
15919 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
15920 			/*
15921 			 * ARP and other v4 external resolvers.
15922 			 * Leave the pending mblk intact so that
15923 			 * the ioctl completes in ip_rput().
15924 			 */
15925 			mutex_enter(&connp->conn_lock);
15926 			mutex_enter(&ill->ill_lock);
15927 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
15928 			mutex_exit(&ill->ill_lock);
15929 			mutex_exit(&connp->conn_lock);
15930 			if (success) {
15931 				err = ipif_resolver_up(ipif, Res_act_initial);
15932 				if (err == EINPROGRESS) {
15933 					freemsg(mp);
15934 					return;
15935 				}
15936 				ASSERT(err != 0);
15937 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15938 			} else {
15939 				/* The conn has started closing */
15940 				err = EINTR;
15941 			}
15942 		} else {
15943 			/*
15944 			 * This one is complete. Reply to pending ioctl.
15945 			 */
15946 			(void) ipif_resolver_up(ipif, Res_act_initial);
15947 			err = ipif_up_done(ipif);
15948 		}
15949 
15950 		if ((err == 0) && (ill->ill_up_ipifs)) {
15951 			err = ill_up_ipifs(ill, q, mp1);
15952 			if (err == EINPROGRESS) {
15953 				freemsg(mp);
15954 				return;
15955 			}
15956 		}
15957 
15958 		if (ill->ill_up_ipifs) {
15959 			ill_group_cleanup(ill);
15960 		}
15961 
15962 		break;
15963 	case DL_NOTIFY_IND: {
15964 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
15965 		ire_t *ire;
15966 		boolean_t need_ire_walk_v4 = B_FALSE;
15967 		boolean_t need_ire_walk_v6 = B_FALSE;
15968 
15969 		switch (notify->dl_notification) {
15970 		case DL_NOTE_PHYS_ADDR:
15971 			err = ill_set_phys_addr(ill, mp);
15972 			break;
15973 
15974 		case DL_NOTE_FASTPATH_FLUSH:
15975 			ill_fastpath_flush(ill);
15976 			break;
15977 
15978 		case DL_NOTE_SDU_SIZE:
15979 			/*
15980 			 * Change the MTU size of the interface, of all
15981 			 * attached ipif's, and of all relevant ire's.  The
15982 			 * new value's a uint32_t at notify->dl_data.
15983 			 * Mtu change Vs. new ire creation - protocol below.
15984 			 *
15985 			 * a Mark the ipif as IPIF_CHANGING.
15986 			 * b Set the new mtu in the ipif.
15987 			 * c Change the ire_max_frag on all affected ires
15988 			 * d Unmark the IPIF_CHANGING
15989 			 *
15990 			 * To see how the protocol works, assume an interface
15991 			 * route is also being added simultaneously by
15992 			 * ip_rt_add and let 'ipif' be the ipif referenced by
15993 			 * the ire. If the ire is created before step a,
15994 			 * it will be cleaned up by step c. If the ire is
15995 			 * created after step d, it will see the new value of
15996 			 * ipif_mtu. Any attempt to create the ire between
15997 			 * steps a to d will fail because of the IPIF_CHANGING
15998 			 * flag. Note that ire_create() is passed a pointer to
15999 			 * the ipif_mtu, and not the value. During ire_add
16000 			 * under the bucket lock, the ire_max_frag of the
16001 			 * new ire being created is set from the ipif/ire from
16002 			 * which it is being derived.
16003 			 */
16004 			mutex_enter(&ill->ill_lock);
16005 			ill->ill_max_frag = (uint_t)notify->dl_data;
16006 
16007 			/*
16008 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
16009 			 * leave it alone
16010 			 */
16011 			if (ill->ill_mtu_userspecified) {
16012 				mutex_exit(&ill->ill_lock);
16013 				break;
16014 			}
16015 			ill->ill_max_mtu = ill->ill_max_frag;
16016 			if (ill->ill_isv6) {
16017 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
16018 					ill->ill_max_mtu = IPV6_MIN_MTU;
16019 			} else {
16020 				if (ill->ill_max_mtu < IP_MIN_MTU)
16021 					ill->ill_max_mtu = IP_MIN_MTU;
16022 			}
16023 			for (ipif = ill->ill_ipif; ipif != NULL;
16024 			    ipif = ipif->ipif_next) {
16025 				/*
16026 				 * Don't override the mtu if the user
16027 				 * has explicitly set it.
16028 				 */
16029 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
16030 					continue;
16031 				ipif->ipif_mtu = (uint_t)notify->dl_data;
16032 				if (ipif->ipif_isv6)
16033 					ire = ipif_to_ire_v6(ipif);
16034 				else
16035 					ire = ipif_to_ire(ipif);
16036 				if (ire != NULL) {
16037 					ire->ire_max_frag = ipif->ipif_mtu;
16038 					ire_refrele(ire);
16039 				}
16040 				if (ipif->ipif_flags & IPIF_UP) {
16041 					if (ill->ill_isv6)
16042 						need_ire_walk_v6 = B_TRUE;
16043 					else
16044 						need_ire_walk_v4 = B_TRUE;
16045 				}
16046 			}
16047 			mutex_exit(&ill->ill_lock);
16048 			if (need_ire_walk_v4)
16049 				ire_walk_v4(ill_mtu_change, (char *)ill,
16050 				    ALL_ZONES, ipst);
16051 			if (need_ire_walk_v6)
16052 				ire_walk_v6(ill_mtu_change, (char *)ill,
16053 				    ALL_ZONES, ipst);
16054 			break;
16055 		case DL_NOTE_LINK_UP:
16056 		case DL_NOTE_LINK_DOWN: {
16057 			/*
16058 			 * We are writer. ill / phyint / ipsq assocs stable.
16059 			 * The RUNNING flag reflects the state of the link.
16060 			 */
16061 			phyint_t *phyint = ill->ill_phyint;
16062 			uint64_t new_phyint_flags;
16063 			boolean_t changed = B_FALSE;
16064 			boolean_t went_up;
16065 
16066 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
16067 			mutex_enter(&phyint->phyint_lock);
16068 			new_phyint_flags = went_up ?
16069 			    phyint->phyint_flags | PHYI_RUNNING :
16070 			    phyint->phyint_flags & ~PHYI_RUNNING;
16071 			if (new_phyint_flags != phyint->phyint_flags) {
16072 				phyint->phyint_flags = new_phyint_flags;
16073 				changed = B_TRUE;
16074 			}
16075 			mutex_exit(&phyint->phyint_lock);
16076 			/*
16077 			 * ill_restart_dad handles the DAD restart and routing
16078 			 * socket notification logic.
16079 			 */
16080 			if (changed) {
16081 				ill_restart_dad(phyint->phyint_illv4, went_up);
16082 				ill_restart_dad(phyint->phyint_illv6, went_up);
16083 			}
16084 			break;
16085 		}
16086 		case DL_NOTE_PROMISC_ON_PHYS:
16087 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16088 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
16089 			mutex_enter(&ill->ill_lock);
16090 			ill->ill_promisc_on_phys = B_TRUE;
16091 			mutex_exit(&ill->ill_lock);
16092 			break;
16093 		case DL_NOTE_PROMISC_OFF_PHYS:
16094 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16095 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16096 			mutex_enter(&ill->ill_lock);
16097 			ill->ill_promisc_on_phys = B_FALSE;
16098 			mutex_exit(&ill->ill_lock);
16099 			break;
16100 		case DL_NOTE_CAPAB_RENEG:
16101 			/*
16102 			 * Something changed on the driver side.
16103 			 * It wants us to renegotiate the capabilities
16104 			 * on this ill. One possible cause is the aggregation
16105 			 * interface under us where a port got added or
16106 			 * went away.
16107 			 *
16108 			 * If the capability negotiation is already done
16109 			 * or is in progress, reset the capabilities and
16110 			 * mark the ill's ill_capab_reneg to be B_TRUE,
16111 			 * so that when the ack comes back, we can start
16112 			 * the renegotiation process.
16113 			 *
16114 			 * Note that if ill_capab_reneg is already B_TRUE
16115 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
16116 			 * the capability resetting request has been sent
16117 			 * and the renegotiation has not been started yet;
16118 			 * nothing needs to be done in this case.
16119 			 */
16120 			if (ill->ill_dlpi_capab_state != IDS_UNKNOWN) {
16121 				ill_capability_reset(ill);
16122 				ill->ill_capab_reneg = B_TRUE;
16123 			}
16124 			break;
16125 		default:
16126 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16127 			    "type 0x%x for DL_NOTIFY_IND\n",
16128 			    notify->dl_notification));
16129 			break;
16130 		}
16131 
16132 		/*
16133 		 * As this is an asynchronous operation, we
16134 		 * should not call ill_dlpi_done
16135 		 */
16136 		break;
16137 	}
16138 	case DL_NOTIFY_ACK: {
16139 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16140 
16141 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16142 			ill->ill_note_link = 1;
16143 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16144 		break;
16145 	}
16146 	case DL_PHYS_ADDR_ACK: {
16147 		/*
16148 		 * As part of plumbing the interface via SIOCSLIFNAME,
16149 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16150 		 * whose answers we receive here.  As each answer is received,
16151 		 * we call ill_dlpi_done() to dispatch the next request as
16152 		 * we're processing the current one.  Once all answers have
16153 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16154 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16155 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16156 		 * available, but we know the ioctl is pending on ill_wq.)
16157 		 */
16158 		uint_t paddrlen, paddroff;
16159 
16160 		paddrreq = ill->ill_phys_addr_pend;
16161 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16162 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16163 
16164 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16165 		if (paddrreq == DL_IPV6_TOKEN) {
16166 			/*
16167 			 * bcopy to low-order bits of ill_token
16168 			 *
16169 			 * XXX Temporary hack - currently, all known tokens
16170 			 * are 64 bits, so I'll cheat for the moment.
16171 			 */
16172 			bcopy(mp->b_rptr + paddroff,
16173 			    &ill->ill_token.s6_addr32[2], paddrlen);
16174 			ill->ill_token_length = paddrlen;
16175 			break;
16176 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16177 			ASSERT(ill->ill_nd_lla_mp == NULL);
16178 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16179 			mp = NULL;
16180 			break;
16181 		}
16182 
16183 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16184 		ASSERT(ill->ill_phys_addr_mp == NULL);
16185 		if (!ill->ill_ifname_pending)
16186 			break;
16187 		ill->ill_ifname_pending = 0;
16188 		if (!ioctl_aborted)
16189 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16190 		if (mp1 != NULL) {
16191 			ASSERT(connp == NULL);
16192 			q = ill->ill_wq;
16193 		}
16194 		/*
16195 		 * If any error acks received during the plumbing sequence,
16196 		 * ill_ifname_pending_err will be set. Break out and send up
16197 		 * the error to the pending ioctl.
16198 		 */
16199 		if (ill->ill_ifname_pending_err != 0) {
16200 			err = ill->ill_ifname_pending_err;
16201 			ill->ill_ifname_pending_err = 0;
16202 			break;
16203 		}
16204 
16205 		ill->ill_phys_addr_mp = mp;
16206 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16207 		mp = NULL;
16208 
16209 		/*
16210 		 * If paddrlen is zero, the DLPI provider doesn't support
16211 		 * physical addresses.  The other two tests were historical
16212 		 * workarounds for bugs in our former PPP implementation, but
16213 		 * now other things have grown dependencies on them -- e.g.,
16214 		 * the tun module specifies a dl_addr_length of zero in its
16215 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16216 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16217 		 * but only after careful testing ensures that all dependent
16218 		 * broken DLPI providers have been fixed.
16219 		 */
16220 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16221 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16222 			ill->ill_phys_addr = NULL;
16223 		} else if (paddrlen != ill->ill_phys_addr_length) {
16224 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16225 			    paddrlen, ill->ill_phys_addr_length));
16226 			err = EINVAL;
16227 			break;
16228 		}
16229 
16230 		if (ill->ill_nd_lla_mp == NULL) {
16231 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16232 				err = ENOMEM;
16233 				break;
16234 			}
16235 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16236 		}
16237 
16238 		/*
16239 		 * Set the interface token.  If the zeroth interface address
16240 		 * is unspecified, then set it to the link local address.
16241 		 */
16242 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16243 			(void) ill_setdefaulttoken(ill);
16244 
16245 		ASSERT(ill->ill_ipif->ipif_id == 0);
16246 		if (ipif != NULL &&
16247 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16248 			(void) ipif_setlinklocal(ipif);
16249 		}
16250 		break;
16251 	}
16252 	case DL_OK_ACK:
16253 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16254 		    dl_primstr((int)dloa->dl_correct_primitive),
16255 		    dloa->dl_correct_primitive));
16256 		switch (dloa->dl_correct_primitive) {
16257 		case DL_ENABMULTI_REQ:
16258 		case DL_DISABMULTI_REQ:
16259 			if (!ill->ill_isv6)
16260 				ipsq_current_finish(ipsq);
16261 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16262 			break;
16263 		case DL_PROMISCON_REQ:
16264 		case DL_PROMISCOFF_REQ:
16265 		case DL_UNBIND_REQ:
16266 		case DL_ATTACH_REQ:
16267 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16268 			break;
16269 		}
16270 		break;
16271 	default:
16272 		break;
16273 	}
16274 
16275 	freemsg(mp);
16276 	if (mp1 != NULL) {
16277 		/*
16278 		 * The operation must complete without EINPROGRESS
16279 		 * since ipsq_pending_mp_get() has removed the mblk
16280 		 * from ipsq_pending_mp.  Otherwise, the operation
16281 		 * will be stuck forever in the ipsq.
16282 		 */
16283 		ASSERT(err != EINPROGRESS);
16284 
16285 		switch (ipsq->ipsq_current_ioctl) {
16286 		case 0:
16287 			ipsq_current_finish(ipsq);
16288 			break;
16289 
16290 		case SIOCLIFADDIF:
16291 		case SIOCSLIFNAME:
16292 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16293 			break;
16294 
16295 		default:
16296 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16297 			break;
16298 		}
16299 	}
16300 }
16301 
16302 /*
16303  * ip_rput_other is called by ip_rput to handle messages modifying the global
16304  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16305  */
16306 /* ARGSUSED */
16307 void
16308 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16309 {
16310 	ill_t		*ill;
16311 	struct iocblk	*iocp;
16312 	mblk_t		*mp1;
16313 	conn_t		*connp = NULL;
16314 
16315 	ip1dbg(("ip_rput_other "));
16316 	ill = (ill_t *)q->q_ptr;
16317 	/*
16318 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16319 	 * in which case ipsq is NULL.
16320 	 */
16321 	if (ipsq != NULL) {
16322 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16323 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16324 	}
16325 
16326 	switch (mp->b_datap->db_type) {
16327 	case M_ERROR:
16328 	case M_HANGUP:
16329 		/*
16330 		 * The device has a problem.  We force the ILL down.  It can
16331 		 * be brought up again manually using SIOCSIFFLAGS (via
16332 		 * ifconfig or equivalent).
16333 		 */
16334 		ASSERT(ipsq != NULL);
16335 		if (mp->b_rptr < mp->b_wptr)
16336 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16337 		if (ill->ill_error == 0)
16338 			ill->ill_error = ENXIO;
16339 		if (!ill_down_start(q, mp))
16340 			return;
16341 		ipif_all_down_tail(ipsq, q, mp, NULL);
16342 		break;
16343 	case M_IOCACK:
16344 		iocp = (struct iocblk *)mp->b_rptr;
16345 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16346 		switch (iocp->ioc_cmd) {
16347 		case SIOCSTUNPARAM:
16348 		case OSIOCSTUNPARAM:
16349 			ASSERT(ipsq != NULL);
16350 			/*
16351 			 * Finish socket ioctl passed through to tun.
16352 			 * We should have an IOCTL waiting on this.
16353 			 */
16354 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16355 			if (ill->ill_isv6) {
16356 				struct iftun_req *ta;
16357 
16358 				/*
16359 				 * if a source or destination is
16360 				 * being set, try and set the link
16361 				 * local address for the tunnel
16362 				 */
16363 				ta = (struct iftun_req *)mp->b_cont->
16364 				    b_cont->b_rptr;
16365 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16366 					ipif_set_tun_llink(ill, ta);
16367 				}
16368 
16369 			}
16370 			if (mp1 != NULL) {
16371 				/*
16372 				 * Now copy back the b_next/b_prev used by
16373 				 * mi code for the mi_copy* functions.
16374 				 * See ip_sioctl_tunparam() for the reason.
16375 				 * Also protect against missing b_cont.
16376 				 */
16377 				if (mp->b_cont != NULL) {
16378 					mp->b_cont->b_next =
16379 					    mp1->b_cont->b_next;
16380 					mp->b_cont->b_prev =
16381 					    mp1->b_cont->b_prev;
16382 				}
16383 				inet_freemsg(mp1);
16384 				ASSERT(connp != NULL);
16385 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16386 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16387 			} else {
16388 				ASSERT(connp == NULL);
16389 				putnext(q, mp);
16390 			}
16391 			break;
16392 		case SIOCGTUNPARAM:
16393 		case OSIOCGTUNPARAM:
16394 			/*
16395 			 * This is really M_IOCDATA from the tunnel driver.
16396 			 * convert back and complete the ioctl.
16397 			 * We should have an IOCTL waiting on this.
16398 			 */
16399 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16400 			if (mp1) {
16401 				/*
16402 				 * Now copy back the b_next/b_prev used by
16403 				 * mi code for the mi_copy* functions.
16404 				 * See ip_sioctl_tunparam() for the reason.
16405 				 * Also protect against missing b_cont.
16406 				 */
16407 				if (mp->b_cont != NULL) {
16408 					mp->b_cont->b_next =
16409 					    mp1->b_cont->b_next;
16410 					mp->b_cont->b_prev =
16411 					    mp1->b_cont->b_prev;
16412 				}
16413 				inet_freemsg(mp1);
16414 				if (iocp->ioc_error == 0)
16415 					mp->b_datap->db_type = M_IOCDATA;
16416 				ASSERT(connp != NULL);
16417 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16418 				    iocp->ioc_error, COPYOUT, NULL);
16419 			} else {
16420 				ASSERT(connp == NULL);
16421 				putnext(q, mp);
16422 			}
16423 			break;
16424 		default:
16425 			break;
16426 		}
16427 		break;
16428 	case M_IOCNAK:
16429 		iocp = (struct iocblk *)mp->b_rptr;
16430 
16431 		switch (iocp->ioc_cmd) {
16432 			int mode;
16433 
16434 		case DL_IOC_HDR_INFO:
16435 			/*
16436 			 * If this was the first attempt turn of the
16437 			 * fastpath probing.
16438 			 */
16439 			mutex_enter(&ill->ill_lock);
16440 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16441 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16442 				mutex_exit(&ill->ill_lock);
16443 				ill_fastpath_nack(ill);
16444 				ip1dbg(("ip_rput: DLPI fastpath off on "
16445 				    "interface %s\n",
16446 				    ill->ill_name));
16447 			} else {
16448 				mutex_exit(&ill->ill_lock);
16449 			}
16450 			freemsg(mp);
16451 			break;
16452 		case SIOCSTUNPARAM:
16453 		case OSIOCSTUNPARAM:
16454 			ASSERT(ipsq != NULL);
16455 			/*
16456 			 * Finish socket ioctl passed through to tun
16457 			 * We should have an IOCTL waiting on this.
16458 			 */
16459 			/* FALLTHRU */
16460 		case SIOCGTUNPARAM:
16461 		case OSIOCGTUNPARAM:
16462 			/*
16463 			 * This is really M_IOCDATA from the tunnel driver.
16464 			 * convert back and complete the ioctl.
16465 			 * We should have an IOCTL waiting on this.
16466 			 */
16467 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16468 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16469 				mp1 = ill_pending_mp_get(ill, &connp,
16470 				    iocp->ioc_id);
16471 				mode = COPYOUT;
16472 				ipsq = NULL;
16473 			} else {
16474 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16475 				mode = NO_COPYOUT;
16476 			}
16477 			if (mp1 != NULL) {
16478 				/*
16479 				 * Now copy back the b_next/b_prev used by
16480 				 * mi code for the mi_copy* functions.
16481 				 * See ip_sioctl_tunparam() for the reason.
16482 				 * Also protect against missing b_cont.
16483 				 */
16484 				if (mp->b_cont != NULL) {
16485 					mp->b_cont->b_next =
16486 					    mp1->b_cont->b_next;
16487 					mp->b_cont->b_prev =
16488 					    mp1->b_cont->b_prev;
16489 				}
16490 				inet_freemsg(mp1);
16491 				if (iocp->ioc_error == 0)
16492 					iocp->ioc_error = EINVAL;
16493 				ASSERT(connp != NULL);
16494 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16495 				    iocp->ioc_error, mode, ipsq);
16496 			} else {
16497 				ASSERT(connp == NULL);
16498 				putnext(q, mp);
16499 			}
16500 			break;
16501 		default:
16502 			break;
16503 		}
16504 	default:
16505 		break;
16506 	}
16507 }
16508 
16509 /*
16510  * NOTE : This function does not ire_refrele the ire argument passed in.
16511  *
16512  * IPQoS notes
16513  * IP policy is invoked twice for a forwarded packet, once on the read side
16514  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16515  * enabled. An additional parameter, in_ill, has been added for this purpose.
16516  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16517  * because ip_mroute drops this information.
16518  *
16519  */
16520 void
16521 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16522 {
16523 	uint32_t	old_pkt_len;
16524 	uint32_t	pkt_len;
16525 	queue_t	*q;
16526 	uint32_t	sum;
16527 #define	rptr	((uchar_t *)ipha)
16528 	uint32_t	max_frag;
16529 	uint32_t	ill_index;
16530 	ill_t		*out_ill;
16531 	mib2_ipIfStatsEntry_t *mibptr;
16532 	ip_stack_t	*ipst = ((ill_t *)(ire->ire_stq->q_ptr))->ill_ipst;
16533 
16534 	/* Get the ill_index of the incoming ILL */
16535 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16536 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16537 
16538 	/* Initiate Read side IPPF processing */
16539 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16540 		ip_process(IPP_FWD_IN, &mp, ill_index);
16541 		if (mp == NULL) {
16542 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16543 			    "during IPPF processing\n"));
16544 			return;
16545 		}
16546 	}
16547 
16548 	/* Adjust the checksum to reflect the ttl decrement. */
16549 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16550 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16551 
16552 	if (ipha->ipha_ttl-- <= 1) {
16553 		if (ip_csum_hdr(ipha)) {
16554 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16555 			goto drop_pkt;
16556 		}
16557 		/*
16558 		 * Note: ire_stq this will be NULL for multicast
16559 		 * datagrams using the long path through arp (the IRE
16560 		 * is not an IRE_CACHE). This should not cause
16561 		 * problems since we don't generate ICMP errors for
16562 		 * multicast packets.
16563 		 */
16564 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16565 		q = ire->ire_stq;
16566 		if (q != NULL) {
16567 			/* Sent by forwarding path, and router is global zone */
16568 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16569 			    GLOBAL_ZONEID, ipst);
16570 		} else
16571 			freemsg(mp);
16572 		return;
16573 	}
16574 
16575 	/*
16576 	 * Don't forward if the interface is down
16577 	 */
16578 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16579 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16580 		ip2dbg(("ip_rput_forward:interface is down\n"));
16581 		goto drop_pkt;
16582 	}
16583 
16584 	/* Get the ill_index of the outgoing ILL */
16585 	out_ill = ire_to_ill(ire);
16586 	ill_index = out_ill->ill_phyint->phyint_ifindex;
16587 
16588 	DTRACE_PROBE4(ip4__forwarding__start,
16589 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16590 
16591 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16592 	    ipst->ips_ipv4firewall_forwarding,
16593 	    in_ill, out_ill, ipha, mp, mp, 0, ipst);
16594 
16595 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16596 
16597 	if (mp == NULL)
16598 		return;
16599 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16600 
16601 	if (is_system_labeled()) {
16602 		mblk_t *mp1;
16603 
16604 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16605 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16606 			goto drop_pkt;
16607 		}
16608 		/* Size may have changed */
16609 		mp = mp1;
16610 		ipha = (ipha_t *)mp->b_rptr;
16611 		pkt_len = ntohs(ipha->ipha_length);
16612 	}
16613 
16614 	/* Check if there are options to update */
16615 	if (!IS_SIMPLE_IPH(ipha)) {
16616 		if (ip_csum_hdr(ipha)) {
16617 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16618 			goto drop_pkt;
16619 		}
16620 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16621 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16622 			return;
16623 		}
16624 
16625 		ipha->ipha_hdr_checksum = 0;
16626 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16627 	}
16628 	max_frag = ire->ire_max_frag;
16629 	if (pkt_len > max_frag) {
16630 		/*
16631 		 * It needs fragging on its way out.  We haven't
16632 		 * verified the header checksum yet.  Since we
16633 		 * are going to put a surely good checksum in the
16634 		 * outgoing header, we have to make sure that it
16635 		 * was good coming in.
16636 		 */
16637 		if (ip_csum_hdr(ipha)) {
16638 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16639 			goto drop_pkt;
16640 		}
16641 		/* Initiate Write side IPPF processing */
16642 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16643 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16644 			if (mp == NULL) {
16645 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16646 				    " during IPPF processing\n"));
16647 				return;
16648 			}
16649 		}
16650 		/*
16651 		 * Handle labeled packet resizing.
16652 		 *
16653 		 * If we have added a label, inform ip_wput_frag() of its
16654 		 * effect on the MTU for ICMP messages.
16655 		 */
16656 		if (pkt_len > old_pkt_len) {
16657 			uint32_t secopt_size;
16658 
16659 			secopt_size = pkt_len - old_pkt_len;
16660 			if (secopt_size < max_frag)
16661 				max_frag -= secopt_size;
16662 		}
16663 
16664 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
16665 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16666 		return;
16667 	}
16668 
16669 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16670 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16671 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16672 	    ipst->ips_ipv4firewall_physical_out,
16673 	    NULL, out_ill, ipha, mp, mp, 0, ipst);
16674 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16675 	if (mp == NULL)
16676 		return;
16677 
16678 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16679 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16680 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16681 	/* ip_xmit_v4 always consumes the packet */
16682 	return;
16683 
16684 drop_pkt:;
16685 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16686 	freemsg(mp);
16687 #undef	rptr
16688 }
16689 
16690 void
16691 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16692 {
16693 	ire_t	*ire;
16694 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16695 
16696 	ASSERT(!ipif->ipif_isv6);
16697 	/*
16698 	 * Find an IRE which matches the destination and the outgoing
16699 	 * queue in the cache table. All we need is an IRE_CACHE which
16700 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16701 	 * then it is enough to have some IRE_CACHE in the group.
16702 	 */
16703 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16704 		dst = ipif->ipif_pp_dst_addr;
16705 
16706 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16707 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR, ipst);
16708 	if (ire == NULL) {
16709 		/*
16710 		 * Mark this packet to make it be delivered to
16711 		 * ip_rput_forward after the new ire has been
16712 		 * created.
16713 		 */
16714 		mp->b_prev = NULL;
16715 		mp->b_next = mp;
16716 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16717 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16718 	} else {
16719 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16720 		IRE_REFRELE(ire);
16721 	}
16722 }
16723 
16724 /* Update any source route, record route or timestamp options */
16725 static int
16726 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16727 {
16728 	ipoptp_t	opts;
16729 	uchar_t		*opt;
16730 	uint8_t		optval;
16731 	uint8_t		optlen;
16732 	ipaddr_t	dst;
16733 	uint32_t	ts;
16734 	ire_t		*dst_ire = NULL;
16735 	ire_t		*tmp_ire = NULL;
16736 	timestruc_t	now;
16737 
16738 	ip2dbg(("ip_rput_forward_options\n"));
16739 	dst = ipha->ipha_dst;
16740 	for (optval = ipoptp_first(&opts, ipha);
16741 	    optval != IPOPT_EOL;
16742 	    optval = ipoptp_next(&opts)) {
16743 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16744 		opt = opts.ipoptp_cur;
16745 		optlen = opts.ipoptp_len;
16746 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16747 		    optval, opts.ipoptp_len));
16748 		switch (optval) {
16749 			uint32_t off;
16750 		case IPOPT_SSRR:
16751 		case IPOPT_LSRR:
16752 			/* Check if adminstratively disabled */
16753 			if (!ipst->ips_ip_forward_src_routed) {
16754 				if (ire->ire_stq != NULL) {
16755 					/*
16756 					 * Sent by forwarding path, and router
16757 					 * is global zone
16758 					 */
16759 					icmp_unreachable(ire->ire_stq, mp,
16760 					    ICMP_SOURCE_ROUTE_FAILED,
16761 					    GLOBAL_ZONEID, ipst);
16762 				} else {
16763 					ip0dbg(("ip_rput_forward_options: "
16764 					    "unable to send unreach\n"));
16765 					freemsg(mp);
16766 				}
16767 				return (-1);
16768 			}
16769 
16770 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16771 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16772 			if (dst_ire == NULL) {
16773 				/*
16774 				 * Must be partial since ip_rput_options
16775 				 * checked for strict.
16776 				 */
16777 				break;
16778 			}
16779 			off = opt[IPOPT_OFFSET];
16780 			off--;
16781 		redo_srr:
16782 			if (optlen < IP_ADDR_LEN ||
16783 			    off > optlen - IP_ADDR_LEN) {
16784 				/* End of source route */
16785 				ip1dbg((
16786 				    "ip_rput_forward_options: end of SR\n"));
16787 				ire_refrele(dst_ire);
16788 				break;
16789 			}
16790 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16791 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16792 			    IP_ADDR_LEN);
16793 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16794 			    ntohl(dst)));
16795 
16796 			/*
16797 			 * Check if our address is present more than
16798 			 * once as consecutive hops in source route.
16799 			 */
16800 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16801 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16802 			if (tmp_ire != NULL) {
16803 				ire_refrele(tmp_ire);
16804 				off += IP_ADDR_LEN;
16805 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16806 				goto redo_srr;
16807 			}
16808 			ipha->ipha_dst = dst;
16809 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16810 			ire_refrele(dst_ire);
16811 			break;
16812 		case IPOPT_RR:
16813 			off = opt[IPOPT_OFFSET];
16814 			off--;
16815 			if (optlen < IP_ADDR_LEN ||
16816 			    off > optlen - IP_ADDR_LEN) {
16817 				/* No more room - ignore */
16818 				ip1dbg((
16819 				    "ip_rput_forward_options: end of RR\n"));
16820 				break;
16821 			}
16822 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16823 			    IP_ADDR_LEN);
16824 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16825 			break;
16826 		case IPOPT_TS:
16827 			/* Insert timestamp if there is room */
16828 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16829 			case IPOPT_TS_TSONLY:
16830 				off = IPOPT_TS_TIMELEN;
16831 				break;
16832 			case IPOPT_TS_PRESPEC:
16833 			case IPOPT_TS_PRESPEC_RFC791:
16834 				/* Verify that the address matched */
16835 				off = opt[IPOPT_OFFSET] - 1;
16836 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16837 				dst_ire = ire_ctable_lookup(dst, 0,
16838 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16839 				    MATCH_IRE_TYPE, ipst);
16840 				if (dst_ire == NULL) {
16841 					/* Not for us */
16842 					break;
16843 				}
16844 				ire_refrele(dst_ire);
16845 				/* FALLTHRU */
16846 			case IPOPT_TS_TSANDADDR:
16847 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16848 				break;
16849 			default:
16850 				/*
16851 				 * ip_*put_options should have already
16852 				 * dropped this packet.
16853 				 */
16854 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16855 				    "unknown IT - bug in ip_rput_options?\n");
16856 				return (0);	/* Keep "lint" happy */
16857 			}
16858 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16859 				/* Increase overflow counter */
16860 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16861 				opt[IPOPT_POS_OV_FLG] =
16862 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16863 				    (off << 4));
16864 				break;
16865 			}
16866 			off = opt[IPOPT_OFFSET] - 1;
16867 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16868 			case IPOPT_TS_PRESPEC:
16869 			case IPOPT_TS_PRESPEC_RFC791:
16870 			case IPOPT_TS_TSANDADDR:
16871 				bcopy(&ire->ire_src_addr,
16872 				    (char *)opt + off, IP_ADDR_LEN);
16873 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16874 				/* FALLTHRU */
16875 			case IPOPT_TS_TSONLY:
16876 				off = opt[IPOPT_OFFSET] - 1;
16877 				/* Compute # of milliseconds since midnight */
16878 				gethrestime(&now);
16879 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16880 				    now.tv_nsec / (NANOSEC / MILLISEC);
16881 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16882 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16883 				break;
16884 			}
16885 			break;
16886 		}
16887 	}
16888 	return (0);
16889 }
16890 
16891 /*
16892  * This is called after processing at least one of AH/ESP headers.
16893  *
16894  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16895  * the actual, physical interface on which the packet was received,
16896  * but, when ip_strict_dst_multihoming is set to 1, could be the
16897  * interface which had the ipha_dst configured when the packet went
16898  * through ip_rput. The ill_index corresponding to the recv_ill
16899  * is saved in ipsec_in_rill_index
16900  *
16901  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
16902  * cannot assume "ire" points to valid data for any IPv6 cases.
16903  */
16904 void
16905 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16906 {
16907 	mblk_t *mp;
16908 	ipaddr_t dst;
16909 	in6_addr_t *v6dstp;
16910 	ipha_t *ipha;
16911 	ip6_t *ip6h;
16912 	ipsec_in_t *ii;
16913 	boolean_t ill_need_rele = B_FALSE;
16914 	boolean_t rill_need_rele = B_FALSE;
16915 	boolean_t ire_need_rele = B_FALSE;
16916 	netstack_t	*ns;
16917 	ip_stack_t	*ipst;
16918 
16919 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16920 	ASSERT(ii->ipsec_in_ill_index != 0);
16921 	ns = ii->ipsec_in_ns;
16922 	ASSERT(ii->ipsec_in_ns != NULL);
16923 	ipst = ns->netstack_ip;
16924 
16925 	mp = ipsec_mp->b_cont;
16926 	ASSERT(mp != NULL);
16927 
16928 
16929 	if (ill == NULL) {
16930 		ASSERT(recv_ill == NULL);
16931 		/*
16932 		 * We need to get the original queue on which ip_rput_local
16933 		 * or ip_rput_data_v6 was called.
16934 		 */
16935 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16936 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
16937 		ill_need_rele = B_TRUE;
16938 
16939 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16940 			recv_ill = ill_lookup_on_ifindex(
16941 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16942 			    NULL, NULL, NULL, NULL, ipst);
16943 			rill_need_rele = B_TRUE;
16944 		} else {
16945 			recv_ill = ill;
16946 		}
16947 
16948 		if ((ill == NULL) || (recv_ill == NULL)) {
16949 			ip0dbg(("ip_fanout_proto_again: interface "
16950 			    "disappeared\n"));
16951 			if (ill != NULL)
16952 				ill_refrele(ill);
16953 			if (recv_ill != NULL)
16954 				ill_refrele(recv_ill);
16955 			freemsg(ipsec_mp);
16956 			return;
16957 		}
16958 	}
16959 
16960 	ASSERT(ill != NULL && recv_ill != NULL);
16961 
16962 	if (mp->b_datap->db_type == M_CTL) {
16963 		/*
16964 		 * AH/ESP is returning the ICMP message after
16965 		 * removing their headers. Fanout again till
16966 		 * it gets to the right protocol.
16967 		 */
16968 		if (ii->ipsec_in_v4) {
16969 			icmph_t *icmph;
16970 			int iph_hdr_length;
16971 			int hdr_length;
16972 
16973 			ipha = (ipha_t *)mp->b_rptr;
16974 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
16975 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
16976 			ipha = (ipha_t *)&icmph[1];
16977 			hdr_length = IPH_HDR_LENGTH(ipha);
16978 			/*
16979 			 * icmp_inbound_error_fanout may need to do pullupmsg.
16980 			 * Reset the type to M_DATA.
16981 			 */
16982 			mp->b_datap->db_type = M_DATA;
16983 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
16984 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
16985 			    B_FALSE, ill, ii->ipsec_in_zoneid);
16986 		} else {
16987 			icmp6_t *icmp6;
16988 			int hdr_length;
16989 
16990 			ip6h = (ip6_t *)mp->b_rptr;
16991 			/* Don't call hdr_length_v6() unless you have to. */
16992 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
16993 				hdr_length = ip_hdr_length_v6(mp, ip6h);
16994 			else
16995 				hdr_length = IPV6_HDR_LEN;
16996 
16997 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
16998 			/*
16999 			 * icmp_inbound_error_fanout_v6 may need to do
17000 			 * pullupmsg.  Reset the type to M_DATA.
17001 			 */
17002 			mp->b_datap->db_type = M_DATA;
17003 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
17004 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
17005 		}
17006 		if (ill_need_rele)
17007 			ill_refrele(ill);
17008 		if (rill_need_rele)
17009 			ill_refrele(recv_ill);
17010 		return;
17011 	}
17012 
17013 	if (ii->ipsec_in_v4) {
17014 		ipha = (ipha_t *)mp->b_rptr;
17015 		dst = ipha->ipha_dst;
17016 		if (CLASSD(dst)) {
17017 			/*
17018 			 * Multicast has to be delivered to all streams.
17019 			 */
17020 			dst = INADDR_BROADCAST;
17021 		}
17022 
17023 		if (ire == NULL) {
17024 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
17025 			    MBLK_GETLABEL(mp), ipst);
17026 			if (ire == NULL) {
17027 				if (ill_need_rele)
17028 					ill_refrele(ill);
17029 				if (rill_need_rele)
17030 					ill_refrele(recv_ill);
17031 				ip1dbg(("ip_fanout_proto_again: "
17032 				    "IRE not found"));
17033 				freemsg(ipsec_mp);
17034 				return;
17035 			}
17036 			ire_need_rele = B_TRUE;
17037 		}
17038 
17039 		switch (ipha->ipha_protocol) {
17040 			case IPPROTO_UDP:
17041 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
17042 				    recv_ill);
17043 				if (ire_need_rele)
17044 					ire_refrele(ire);
17045 				break;
17046 			case IPPROTO_TCP:
17047 				if (!ire_need_rele)
17048 					IRE_REFHOLD(ire);
17049 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
17050 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
17051 				IRE_REFRELE(ire);
17052 				if (mp != NULL)
17053 					squeue_enter_chain(GET_SQUEUE(mp), mp,
17054 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
17055 				break;
17056 			case IPPROTO_SCTP:
17057 				if (!ire_need_rele)
17058 					IRE_REFHOLD(ire);
17059 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
17060 				    ipsec_mp, 0, ill->ill_rq, dst);
17061 				break;
17062 			default:
17063 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
17064 				    recv_ill, 0);
17065 				if (ire_need_rele)
17066 					ire_refrele(ire);
17067 				break;
17068 		}
17069 	} else {
17070 		uint32_t rput_flags = 0;
17071 
17072 		ip6h = (ip6_t *)mp->b_rptr;
17073 		v6dstp = &ip6h->ip6_dst;
17074 		/*
17075 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
17076 		 * address.
17077 		 *
17078 		 * Currently, we don't store that state in the IPSEC_IN
17079 		 * message, and we may need to.
17080 		 */
17081 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
17082 		    IP6_IN_LLMCAST : 0);
17083 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
17084 		    NULL, NULL);
17085 	}
17086 	if (ill_need_rele)
17087 		ill_refrele(ill);
17088 	if (rill_need_rele)
17089 		ill_refrele(recv_ill);
17090 }
17091 
17092 /*
17093  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
17094  * returns 'true' if there are still fragments left on the queue, in
17095  * which case we restart the timer.
17096  */
17097 void
17098 ill_frag_timer(void *arg)
17099 {
17100 	ill_t	*ill = (ill_t *)arg;
17101 	boolean_t frag_pending;
17102 	ip_stack_t	*ipst = ill->ill_ipst;
17103 
17104 	mutex_enter(&ill->ill_lock);
17105 	ASSERT(!ill->ill_fragtimer_executing);
17106 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17107 		ill->ill_frag_timer_id = 0;
17108 		mutex_exit(&ill->ill_lock);
17109 		return;
17110 	}
17111 	ill->ill_fragtimer_executing = 1;
17112 	mutex_exit(&ill->ill_lock);
17113 
17114 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
17115 
17116 	/*
17117 	 * Restart the timer, if we have fragments pending or if someone
17118 	 * wanted us to be scheduled again.
17119 	 */
17120 	mutex_enter(&ill->ill_lock);
17121 	ill->ill_fragtimer_executing = 0;
17122 	ill->ill_frag_timer_id = 0;
17123 	if (frag_pending || ill->ill_fragtimer_needrestart)
17124 		ill_frag_timer_start(ill);
17125 	mutex_exit(&ill->ill_lock);
17126 }
17127 
17128 void
17129 ill_frag_timer_start(ill_t *ill)
17130 {
17131 	ip_stack_t	*ipst = ill->ill_ipst;
17132 
17133 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17134 
17135 	/* If the ill is closing or opening don't proceed */
17136 	if (ill->ill_state_flags & ILL_CONDEMNED)
17137 		return;
17138 
17139 	if (ill->ill_fragtimer_executing) {
17140 		/*
17141 		 * ill_frag_timer is currently executing. Just record the
17142 		 * the fact that we want the timer to be restarted.
17143 		 * ill_frag_timer will post a timeout before it returns,
17144 		 * ensuring it will be called again.
17145 		 */
17146 		ill->ill_fragtimer_needrestart = 1;
17147 		return;
17148 	}
17149 
17150 	if (ill->ill_frag_timer_id == 0) {
17151 		/*
17152 		 * The timer is neither running nor is the timeout handler
17153 		 * executing. Post a timeout so that ill_frag_timer will be
17154 		 * called
17155 		 */
17156 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17157 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
17158 		ill->ill_fragtimer_needrestart = 0;
17159 	}
17160 }
17161 
17162 /*
17163  * This routine is needed for loopback when forwarding multicasts.
17164  *
17165  * IPQoS Notes:
17166  * IPPF processing is done in fanout routines.
17167  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17168  * processing for IPsec packets is done when it comes back in clear.
17169  * NOTE : The callers of this function need to do the ire_refrele for the
17170  *	  ire that is being passed in.
17171  */
17172 void
17173 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17174     ill_t *recv_ill, uint32_t esp_udp_ports)
17175 {
17176 	boolean_t esp_in_udp_packet = (esp_udp_ports != 0);
17177 	ill_t	*ill = (ill_t *)q->q_ptr;
17178 	uint32_t	sum;
17179 	uint32_t	u1;
17180 	uint32_t	u2;
17181 	int		hdr_length;
17182 	boolean_t	mctl_present;
17183 	mblk_t		*first_mp = mp;
17184 	mblk_t		*hada_mp = NULL;
17185 	ipha_t		*inner_ipha;
17186 	ip_stack_t	*ipst;
17187 
17188 	ASSERT(recv_ill != NULL);
17189 	ipst = recv_ill->ill_ipst;
17190 
17191 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17192 	    "ip_rput_locl_start: q %p", q);
17193 
17194 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17195 	ASSERT(ill != NULL);
17196 
17197 
17198 #define	rptr	((uchar_t *)ipha)
17199 #define	iphs	((uint16_t *)ipha)
17200 
17201 	/*
17202 	 * no UDP or TCP packet should come here anymore.
17203 	 */
17204 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
17205 	    ipha->ipha_protocol != IPPROTO_UDP);
17206 
17207 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17208 	if (mctl_present &&
17209 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17210 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17211 
17212 		/*
17213 		 * It's an IPsec accelerated packet.
17214 		 * Keep a pointer to the data attributes around until
17215 		 * we allocate the ipsec_info_t.
17216 		 */
17217 		IPSECHW_DEBUG(IPSECHW_PKT,
17218 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17219 		hada_mp = first_mp;
17220 		hada_mp->b_cont = NULL;
17221 		/*
17222 		 * Since it is accelerated, it comes directly from
17223 		 * the ill and the data attributes is followed by
17224 		 * the packet data.
17225 		 */
17226 		ASSERT(mp->b_datap->db_type != M_CTL);
17227 		first_mp = mp;
17228 		mctl_present = B_FALSE;
17229 	}
17230 
17231 	/*
17232 	 * IF M_CTL is not present, then ipsec_in_is_secure
17233 	 * should return B_TRUE. There is a case where loopback
17234 	 * packets has an M_CTL in the front with all the
17235 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17236 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17237 	 * packets never comes here, it is safe to ASSERT the
17238 	 * following.
17239 	 */
17240 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17241 
17242 	/*
17243 	 * Also, we should never have an mctl_present if this is an
17244 	 * ESP-in-UDP packet.
17245 	 */
17246 	ASSERT(!mctl_present || !esp_in_udp_packet);
17247 
17248 
17249 	/* u1 is # words of IP options */
17250 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17251 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17252 
17253 	/*
17254 	 * Don't verify header checksum if we just removed UDP header or
17255 	 * packet is coming back from AH/ESP.
17256 	 */
17257 	if (!esp_in_udp_packet && !mctl_present) {
17258 		if (u1) {
17259 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17260 				if (hada_mp != NULL)
17261 					freemsg(hada_mp);
17262 				return;
17263 			}
17264 		} else {
17265 			/* Check the IP header checksum.  */
17266 #define	uph	((uint16_t *)ipha)
17267 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17268 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17269 #undef  uph
17270 			/* finish doing IP checksum */
17271 			sum = (sum & 0xFFFF) + (sum >> 16);
17272 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17273 			if (sum && sum != 0xFFFF) {
17274 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17275 				goto drop_pkt;
17276 			}
17277 		}
17278 	}
17279 
17280 	/*
17281 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17282 	 * might be called more than once for secure packets, count only
17283 	 * the first time.
17284 	 */
17285 	if (!mctl_present) {
17286 		UPDATE_IB_PKT_COUNT(ire);
17287 		ire->ire_last_used_time = lbolt;
17288 	}
17289 
17290 	/* Check for fragmentation offset. */
17291 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17292 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17293 	if (u1) {
17294 		/*
17295 		 * We re-assemble fragments before we do the AH/ESP
17296 		 * processing. Thus, M_CTL should not be present
17297 		 * while we are re-assembling.
17298 		 */
17299 		ASSERT(!mctl_present);
17300 		ASSERT(first_mp == mp);
17301 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
17302 			return;
17303 		}
17304 		/*
17305 		 * Make sure that first_mp points back to mp as
17306 		 * the mp we came in with could have changed in
17307 		 * ip_rput_fragment().
17308 		 */
17309 		ipha = (ipha_t *)mp->b_rptr;
17310 		first_mp = mp;
17311 	}
17312 
17313 	/*
17314 	 * Clear hardware checksumming flag as it is currently only
17315 	 * used by TCP and UDP.
17316 	 */
17317 	DB_CKSUMFLAGS(mp) = 0;
17318 
17319 	/* Now we have a complete datagram, destined for this machine. */
17320 	u1 = IPH_HDR_LENGTH(ipha);
17321 	switch (ipha->ipha_protocol) {
17322 	case IPPROTO_ICMP: {
17323 		ire_t		*ire_zone;
17324 		ilm_t		*ilm;
17325 		mblk_t		*mp1;
17326 		zoneid_t	last_zoneid;
17327 
17328 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17329 			ASSERT(ire->ire_type == IRE_BROADCAST);
17330 			/*
17331 			 * Inactive/Failed interfaces are not supposed to
17332 			 * respond to the multicast packets.
17333 			 */
17334 			if (ill_is_probeonly(ill)) {
17335 				freemsg(first_mp);
17336 				return;
17337 			}
17338 
17339 			/*
17340 			 * In the multicast case, applications may have joined
17341 			 * the group from different zones, so we need to deliver
17342 			 * the packet to each of them. Loop through the
17343 			 * multicast memberships structures (ilm) on the receive
17344 			 * ill and send a copy of the packet up each matching
17345 			 * one. However, we don't do this for multicasts sent on
17346 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17347 			 * they must stay in the sender's zone.
17348 			 *
17349 			 * ilm_add_v6() ensures that ilms in the same zone are
17350 			 * contiguous in the ill_ilm list. We use this property
17351 			 * to avoid sending duplicates needed when two
17352 			 * applications in the same zone join the same group on
17353 			 * different logical interfaces: we ignore the ilm if
17354 			 * its zoneid is the same as the last matching one.
17355 			 * In addition, the sending of the packet for
17356 			 * ire_zoneid is delayed until all of the other ilms
17357 			 * have been exhausted.
17358 			 */
17359 			last_zoneid = -1;
17360 			ILM_WALKER_HOLD(recv_ill);
17361 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17362 			    ilm = ilm->ilm_next) {
17363 				if ((ilm->ilm_flags & ILM_DELETED) ||
17364 				    ipha->ipha_dst != ilm->ilm_addr ||
17365 				    ilm->ilm_zoneid == last_zoneid ||
17366 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17367 				    ilm->ilm_zoneid == ALL_ZONES ||
17368 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17369 					continue;
17370 				mp1 = ip_copymsg(first_mp);
17371 				if (mp1 == NULL)
17372 					continue;
17373 				icmp_inbound(q, mp1, B_TRUE, ill,
17374 				    0, sum, mctl_present, B_TRUE,
17375 				    recv_ill, ilm->ilm_zoneid);
17376 				last_zoneid = ilm->ilm_zoneid;
17377 			}
17378 			ILM_WALKER_RELE(recv_ill);
17379 		} else if (ire->ire_type == IRE_BROADCAST) {
17380 			/*
17381 			 * In the broadcast case, there may be many zones
17382 			 * which need a copy of the packet delivered to them.
17383 			 * There is one IRE_BROADCAST per broadcast address
17384 			 * and per zone; we walk those using a helper function.
17385 			 * In addition, the sending of the packet for ire is
17386 			 * delayed until all of the other ires have been
17387 			 * processed.
17388 			 */
17389 			IRB_REFHOLD(ire->ire_bucket);
17390 			ire_zone = NULL;
17391 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17392 			    ire)) != NULL) {
17393 				mp1 = ip_copymsg(first_mp);
17394 				if (mp1 == NULL)
17395 					continue;
17396 
17397 				UPDATE_IB_PKT_COUNT(ire_zone);
17398 				ire_zone->ire_last_used_time = lbolt;
17399 				icmp_inbound(q, mp1, B_TRUE, ill,
17400 				    0, sum, mctl_present, B_TRUE,
17401 				    recv_ill, ire_zone->ire_zoneid);
17402 			}
17403 			IRB_REFRELE(ire->ire_bucket);
17404 		}
17405 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17406 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17407 		    ire->ire_zoneid);
17408 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17409 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17410 		return;
17411 	}
17412 	case IPPROTO_IGMP:
17413 		/*
17414 		 * If we are not willing to accept IGMP packets in clear,
17415 		 * then check with global policy.
17416 		 */
17417 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17418 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17419 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17420 			if (first_mp == NULL)
17421 				return;
17422 		}
17423 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17424 			freemsg(first_mp);
17425 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17426 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17427 			return;
17428 		}
17429 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17430 			/* Bad packet - discarded by igmp_input */
17431 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17432 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17433 			if (mctl_present)
17434 				freeb(first_mp);
17435 			return;
17436 		}
17437 		/*
17438 		 * igmp_input() may have returned the pulled up message.
17439 		 * So first_mp and ipha need to be reinitialized.
17440 		 */
17441 		ipha = (ipha_t *)mp->b_rptr;
17442 		if (mctl_present)
17443 			first_mp->b_cont = mp;
17444 		else
17445 			first_mp = mp;
17446 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17447 		    connf_head != NULL) {
17448 			/* No user-level listener for IGMP packets */
17449 			goto drop_pkt;
17450 		}
17451 		/* deliver to local raw users */
17452 		break;
17453 	case IPPROTO_PIM:
17454 		/*
17455 		 * If we are not willing to accept PIM packets in clear,
17456 		 * then check with global policy.
17457 		 */
17458 		if (ipst->ips_pim_accept_clear_messages == 0) {
17459 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17460 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17461 			if (first_mp == NULL)
17462 				return;
17463 		}
17464 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17465 			freemsg(first_mp);
17466 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17467 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17468 			return;
17469 		}
17470 		if (pim_input(q, mp, ill) != 0) {
17471 			/* Bad packet - discarded by pim_input */
17472 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17473 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17474 			if (mctl_present)
17475 				freeb(first_mp);
17476 			return;
17477 		}
17478 
17479 		/*
17480 		 * pim_input() may have pulled up the message so ipha needs to
17481 		 * be reinitialized.
17482 		 */
17483 		ipha = (ipha_t *)mp->b_rptr;
17484 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17485 		    connf_head != NULL) {
17486 			/* No user-level listener for PIM packets */
17487 			goto drop_pkt;
17488 		}
17489 		/* deliver to local raw users */
17490 		break;
17491 	case IPPROTO_ENCAP:
17492 		/*
17493 		 * Handle self-encapsulated packets (IP-in-IP where
17494 		 * the inner addresses == the outer addresses).
17495 		 */
17496 		hdr_length = IPH_HDR_LENGTH(ipha);
17497 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17498 		    mp->b_wptr) {
17499 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17500 			    sizeof (ipha_t) - mp->b_rptr)) {
17501 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17502 				freemsg(first_mp);
17503 				return;
17504 			}
17505 			ipha = (ipha_t *)mp->b_rptr;
17506 		}
17507 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17508 		/*
17509 		 * Check the sanity of the inner IP header.
17510 		 */
17511 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17512 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17513 			freemsg(first_mp);
17514 			return;
17515 		}
17516 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17517 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17518 			freemsg(first_mp);
17519 			return;
17520 		}
17521 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17522 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17523 			ipsec_in_t *ii;
17524 
17525 			/*
17526 			 * Self-encapsulated tunnel packet. Remove
17527 			 * the outer IP header and fanout again.
17528 			 * We also need to make sure that the inner
17529 			 * header is pulled up until options.
17530 			 */
17531 			mp->b_rptr = (uchar_t *)inner_ipha;
17532 			ipha = inner_ipha;
17533 			hdr_length = IPH_HDR_LENGTH(ipha);
17534 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17535 				if (!pullupmsg(mp, (uchar_t *)ipha +
17536 				    + hdr_length - mp->b_rptr)) {
17537 					freemsg(first_mp);
17538 					return;
17539 				}
17540 				ipha = (ipha_t *)mp->b_rptr;
17541 			}
17542 			if (hdr_length > sizeof (ipha_t)) {
17543 				/* We got options on the inner packet. */
17544 				ipaddr_t dst = ipha->ipha_dst;
17545 
17546 				if (ip_rput_options(q, mp, ipha, &dst, ipst) ==
17547 				    -1) {
17548 					/* Bad options! */
17549 					return;
17550 				}
17551 				if (dst != ipha->ipha_dst) {
17552 					/*
17553 					 * Someone put a source-route in
17554 					 * the inside header of a self-
17555 					 * encapsulated packet.  Drop it
17556 					 * with extreme prejudice and let
17557 					 * the sender know.
17558 					 */
17559 					icmp_unreachable(q, first_mp,
17560 					    ICMP_SOURCE_ROUTE_FAILED,
17561 					    recv_ill->ill_zoneid, ipst);
17562 					return;
17563 				}
17564 			}
17565 			if (!mctl_present) {
17566 				ASSERT(first_mp == mp);
17567 				/*
17568 				 * This means that somebody is sending
17569 				 * Self-encapsualted packets without AH/ESP.
17570 				 * If AH/ESP was present, we would have already
17571 				 * allocated the first_mp.
17572 				 *
17573 				 * Send this packet to find a tunnel endpoint.
17574 				 * if I can't find one, an ICMP
17575 				 * PROTOCOL_UNREACHABLE will get sent.
17576 				 */
17577 				goto fanout;
17578 			}
17579 			/*
17580 			 * We generally store the ill_index if we need to
17581 			 * do IPsec processing as we lose the ill queue when
17582 			 * we come back. But in this case, we never should
17583 			 * have to store the ill_index here as it should have
17584 			 * been stored previously when we processed the
17585 			 * AH/ESP header in this routine or for non-ipsec
17586 			 * cases, we still have the queue. But for some bad
17587 			 * packets from the wire, we can get to IPsec after
17588 			 * this and we better store the index for that case.
17589 			 */
17590 			ill = (ill_t *)q->q_ptr;
17591 			ii = (ipsec_in_t *)first_mp->b_rptr;
17592 			ii->ipsec_in_ill_index =
17593 			    ill->ill_phyint->phyint_ifindex;
17594 			ii->ipsec_in_rill_index =
17595 			    recv_ill->ill_phyint->phyint_ifindex;
17596 			if (ii->ipsec_in_decaps) {
17597 				/*
17598 				 * This packet is self-encapsulated multiple
17599 				 * times. We don't want to recurse infinitely.
17600 				 * To keep it simple, drop the packet.
17601 				 */
17602 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17603 				freemsg(first_mp);
17604 				return;
17605 			}
17606 			ii->ipsec_in_decaps = B_TRUE;
17607 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17608 			    ire);
17609 			return;
17610 		}
17611 		break;
17612 	case IPPROTO_AH:
17613 	case IPPROTO_ESP: {
17614 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17615 
17616 		/*
17617 		 * Fast path for AH/ESP. If this is the first time
17618 		 * we are sending a datagram to AH/ESP, allocate
17619 		 * a IPSEC_IN message and prepend it. Otherwise,
17620 		 * just fanout.
17621 		 */
17622 
17623 		int ipsec_rc;
17624 		ipsec_in_t *ii;
17625 		netstack_t *ns = ipst->ips_netstack;
17626 
17627 		IP_STAT(ipst, ipsec_proto_ahesp);
17628 		if (!mctl_present) {
17629 			ASSERT(first_mp == mp);
17630 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17631 			if (first_mp == NULL) {
17632 				ip1dbg(("ip_proto_input: IPSEC_IN "
17633 				    "allocation failure.\n"));
17634 				freemsg(hada_mp); /* okay ifnull */
17635 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17636 				freemsg(mp);
17637 				return;
17638 			}
17639 			/*
17640 			 * Store the ill_index so that when we come back
17641 			 * from IPsec we ride on the same queue.
17642 			 */
17643 			ill = (ill_t *)q->q_ptr;
17644 			ii = (ipsec_in_t *)first_mp->b_rptr;
17645 			ii->ipsec_in_ill_index =
17646 			    ill->ill_phyint->phyint_ifindex;
17647 			ii->ipsec_in_rill_index =
17648 			    recv_ill->ill_phyint->phyint_ifindex;
17649 			first_mp->b_cont = mp;
17650 			/*
17651 			 * Cache hardware acceleration info.
17652 			 */
17653 			if (hada_mp != NULL) {
17654 				IPSECHW_DEBUG(IPSECHW_PKT,
17655 				    ("ip_rput_local: caching data attr.\n"));
17656 				ii->ipsec_in_accelerated = B_TRUE;
17657 				ii->ipsec_in_da = hada_mp;
17658 				hada_mp = NULL;
17659 			}
17660 		} else {
17661 			ii = (ipsec_in_t *)first_mp->b_rptr;
17662 		}
17663 
17664 		ii->ipsec_in_esp_udp_ports = esp_udp_ports;
17665 
17666 		if (!ipsec_loaded(ipss)) {
17667 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17668 			    ire->ire_zoneid, ipst);
17669 			return;
17670 		}
17671 
17672 		ns = ipst->ips_netstack;
17673 		/* select inbound SA and have IPsec process the pkt */
17674 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17675 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17676 			boolean_t esp_in_udp_sa;
17677 			if (esph == NULL)
17678 				return;
17679 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17680 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17681 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
17682 			    IPSA_F_NATT) != 0);
17683 			/*
17684 			 * The following is a fancy, but quick, way of saying:
17685 			 * ESP-in-UDP SA and Raw ESP packet --> drop
17686 			 *    OR
17687 			 * ESP SA and ESP-in-UDP packet --> drop
17688 			 */
17689 			if (esp_in_udp_sa != esp_in_udp_packet) {
17690 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17691 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
17692 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
17693 				    &ns->netstack_ipsec->ipsec_dropper);
17694 				return;
17695 			}
17696 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17697 			    first_mp, esph);
17698 		} else {
17699 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17700 			if (ah == NULL)
17701 				return;
17702 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17703 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17704 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17705 			    first_mp, ah);
17706 		}
17707 
17708 		switch (ipsec_rc) {
17709 		case IPSEC_STATUS_SUCCESS:
17710 			break;
17711 		case IPSEC_STATUS_FAILED:
17712 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17713 			/* FALLTHRU */
17714 		case IPSEC_STATUS_PENDING:
17715 			return;
17716 		}
17717 		/* we're done with IPsec processing, send it up */
17718 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17719 		return;
17720 	}
17721 	default:
17722 		break;
17723 	}
17724 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17725 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17726 		    ire->ire_zoneid));
17727 		goto drop_pkt;
17728 	}
17729 	/*
17730 	 * Handle protocols with which IP is less intimate.  There
17731 	 * can be more than one stream bound to a particular
17732 	 * protocol.  When this is the case, each one gets a copy
17733 	 * of any incoming packets.
17734 	 */
17735 fanout:
17736 	ip_fanout_proto(q, first_mp, ill, ipha,
17737 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17738 	    B_TRUE, recv_ill, ire->ire_zoneid);
17739 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17740 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17741 	return;
17742 
17743 drop_pkt:
17744 	freemsg(first_mp);
17745 	if (hada_mp != NULL)
17746 		freeb(hada_mp);
17747 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17748 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17749 #undef	rptr
17750 #undef  iphs
17751 
17752 }
17753 
17754 /*
17755  * Update any source route, record route or timestamp options.
17756  * Check that we are at end of strict source route.
17757  * The options have already been checked for sanity in ip_rput_options().
17758  */
17759 static boolean_t
17760 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17761     ip_stack_t *ipst)
17762 {
17763 	ipoptp_t	opts;
17764 	uchar_t		*opt;
17765 	uint8_t		optval;
17766 	uint8_t		optlen;
17767 	ipaddr_t	dst;
17768 	uint32_t	ts;
17769 	ire_t		*dst_ire;
17770 	timestruc_t	now;
17771 	zoneid_t	zoneid;
17772 	ill_t		*ill;
17773 
17774 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17775 
17776 	ip2dbg(("ip_rput_local_options\n"));
17777 
17778 	for (optval = ipoptp_first(&opts, ipha);
17779 	    optval != IPOPT_EOL;
17780 	    optval = ipoptp_next(&opts)) {
17781 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17782 		opt = opts.ipoptp_cur;
17783 		optlen = opts.ipoptp_len;
17784 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17785 		    optval, optlen));
17786 		switch (optval) {
17787 			uint32_t off;
17788 		case IPOPT_SSRR:
17789 		case IPOPT_LSRR:
17790 			off = opt[IPOPT_OFFSET];
17791 			off--;
17792 			if (optlen < IP_ADDR_LEN ||
17793 			    off > optlen - IP_ADDR_LEN) {
17794 				/* End of source route */
17795 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17796 				break;
17797 			}
17798 			/*
17799 			 * This will only happen if two consecutive entries
17800 			 * in the source route contains our address or if
17801 			 * it is a packet with a loose source route which
17802 			 * reaches us before consuming the whole source route
17803 			 */
17804 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17805 			if (optval == IPOPT_SSRR) {
17806 				goto bad_src_route;
17807 			}
17808 			/*
17809 			 * Hack: instead of dropping the packet truncate the
17810 			 * source route to what has been used by filling the
17811 			 * rest with IPOPT_NOP.
17812 			 */
17813 			opt[IPOPT_OLEN] = (uint8_t)off;
17814 			while (off < optlen) {
17815 				opt[off++] = IPOPT_NOP;
17816 			}
17817 			break;
17818 		case IPOPT_RR:
17819 			off = opt[IPOPT_OFFSET];
17820 			off--;
17821 			if (optlen < IP_ADDR_LEN ||
17822 			    off > optlen - IP_ADDR_LEN) {
17823 				/* No more room - ignore */
17824 				ip1dbg((
17825 				    "ip_rput_local_options: end of RR\n"));
17826 				break;
17827 			}
17828 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17829 			    IP_ADDR_LEN);
17830 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17831 			break;
17832 		case IPOPT_TS:
17833 			/* Insert timestamp if there is romm */
17834 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17835 			case IPOPT_TS_TSONLY:
17836 				off = IPOPT_TS_TIMELEN;
17837 				break;
17838 			case IPOPT_TS_PRESPEC:
17839 			case IPOPT_TS_PRESPEC_RFC791:
17840 				/* Verify that the address matched */
17841 				off = opt[IPOPT_OFFSET] - 1;
17842 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17843 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17844 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
17845 				    ipst);
17846 				if (dst_ire == NULL) {
17847 					/* Not for us */
17848 					break;
17849 				}
17850 				ire_refrele(dst_ire);
17851 				/* FALLTHRU */
17852 			case IPOPT_TS_TSANDADDR:
17853 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17854 				break;
17855 			default:
17856 				/*
17857 				 * ip_*put_options should have already
17858 				 * dropped this packet.
17859 				 */
17860 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17861 				    "unknown IT - bug in ip_rput_options?\n");
17862 				return (B_TRUE);	/* Keep "lint" happy */
17863 			}
17864 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17865 				/* Increase overflow counter */
17866 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17867 				opt[IPOPT_POS_OV_FLG] =
17868 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17869 				    (off << 4));
17870 				break;
17871 			}
17872 			off = opt[IPOPT_OFFSET] - 1;
17873 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17874 			case IPOPT_TS_PRESPEC:
17875 			case IPOPT_TS_PRESPEC_RFC791:
17876 			case IPOPT_TS_TSANDADDR:
17877 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17878 				    IP_ADDR_LEN);
17879 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17880 				/* FALLTHRU */
17881 			case IPOPT_TS_TSONLY:
17882 				off = opt[IPOPT_OFFSET] - 1;
17883 				/* Compute # of milliseconds since midnight */
17884 				gethrestime(&now);
17885 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17886 				    now.tv_nsec / (NANOSEC / MILLISEC);
17887 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17888 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17889 				break;
17890 			}
17891 			break;
17892 		}
17893 	}
17894 	return (B_TRUE);
17895 
17896 bad_src_route:
17897 	q = WR(q);
17898 	if (q->q_next != NULL)
17899 		ill = q->q_ptr;
17900 	else
17901 		ill = NULL;
17902 
17903 	/* make sure we clear any indication of a hardware checksum */
17904 	DB_CKSUMFLAGS(mp) = 0;
17905 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
17906 	if (zoneid == ALL_ZONES)
17907 		freemsg(mp);
17908 	else
17909 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17910 	return (B_FALSE);
17911 
17912 }
17913 
17914 /*
17915  * Process IP options in an inbound packet.  If an option affects the
17916  * effective destination address, return the next hop address via dstp.
17917  * Returns -1 if something fails in which case an ICMP error has been sent
17918  * and mp freed.
17919  */
17920 static int
17921 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
17922     ip_stack_t *ipst)
17923 {
17924 	ipoptp_t	opts;
17925 	uchar_t		*opt;
17926 	uint8_t		optval;
17927 	uint8_t		optlen;
17928 	ipaddr_t	dst;
17929 	intptr_t	code = 0;
17930 	ire_t		*ire = NULL;
17931 	zoneid_t	zoneid;
17932 	ill_t		*ill;
17933 
17934 	ip2dbg(("ip_rput_options\n"));
17935 	dst = ipha->ipha_dst;
17936 	for (optval = ipoptp_first(&opts, ipha);
17937 	    optval != IPOPT_EOL;
17938 	    optval = ipoptp_next(&opts)) {
17939 		opt = opts.ipoptp_cur;
17940 		optlen = opts.ipoptp_len;
17941 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17942 		    optval, optlen));
17943 		/*
17944 		 * Note: we need to verify the checksum before we
17945 		 * modify anything thus this routine only extracts the next
17946 		 * hop dst from any source route.
17947 		 */
17948 		switch (optval) {
17949 			uint32_t off;
17950 		case IPOPT_SSRR:
17951 		case IPOPT_LSRR:
17952 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17953 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17954 			if (ire == NULL) {
17955 				if (optval == IPOPT_SSRR) {
17956 					ip1dbg(("ip_rput_options: not next"
17957 					    " strict source route 0x%x\n",
17958 					    ntohl(dst)));
17959 					code = (char *)&ipha->ipha_dst -
17960 					    (char *)ipha;
17961 					goto param_prob; /* RouterReq's */
17962 				}
17963 				ip2dbg(("ip_rput_options: "
17964 				    "not next source route 0x%x\n",
17965 				    ntohl(dst)));
17966 				break;
17967 			}
17968 			ire_refrele(ire);
17969 
17970 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17971 				ip1dbg((
17972 				    "ip_rput_options: bad option offset\n"));
17973 				code = (char *)&opt[IPOPT_OLEN] -
17974 				    (char *)ipha;
17975 				goto param_prob;
17976 			}
17977 			off = opt[IPOPT_OFFSET];
17978 			off--;
17979 		redo_srr:
17980 			if (optlen < IP_ADDR_LEN ||
17981 			    off > optlen - IP_ADDR_LEN) {
17982 				/* End of source route */
17983 				ip1dbg(("ip_rput_options: end of SR\n"));
17984 				break;
17985 			}
17986 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17987 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
17988 			    ntohl(dst)));
17989 
17990 			/*
17991 			 * Check if our address is present more than
17992 			 * once as consecutive hops in source route.
17993 			 * XXX verify per-interface ip_forwarding
17994 			 * for source route?
17995 			 */
17996 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17997 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17998 
17999 			if (ire != NULL) {
18000 				ire_refrele(ire);
18001 				off += IP_ADDR_LEN;
18002 				goto redo_srr;
18003 			}
18004 
18005 			if (dst == htonl(INADDR_LOOPBACK)) {
18006 				ip1dbg(("ip_rput_options: loopback addr in "
18007 				    "source route!\n"));
18008 				goto bad_src_route;
18009 			}
18010 			/*
18011 			 * For strict: verify that dst is directly
18012 			 * reachable.
18013 			 */
18014 			if (optval == IPOPT_SSRR) {
18015 				ire = ire_ftable_lookup(dst, 0, 0,
18016 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
18017 				    MBLK_GETLABEL(mp),
18018 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
18019 				if (ire == NULL) {
18020 					ip1dbg(("ip_rput_options: SSRR not "
18021 					    "directly reachable: 0x%x\n",
18022 					    ntohl(dst)));
18023 					goto bad_src_route;
18024 				}
18025 				ire_refrele(ire);
18026 			}
18027 			/*
18028 			 * Defer update of the offset and the record route
18029 			 * until the packet is forwarded.
18030 			 */
18031 			break;
18032 		case IPOPT_RR:
18033 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18034 				ip1dbg((
18035 				    "ip_rput_options: bad option offset\n"));
18036 				code = (char *)&opt[IPOPT_OLEN] -
18037 				    (char *)ipha;
18038 				goto param_prob;
18039 			}
18040 			break;
18041 		case IPOPT_TS:
18042 			/*
18043 			 * Verify that length >= 5 and that there is either
18044 			 * room for another timestamp or that the overflow
18045 			 * counter is not maxed out.
18046 			 */
18047 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
18048 			if (optlen < IPOPT_MINLEN_IT) {
18049 				goto param_prob;
18050 			}
18051 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18052 				ip1dbg((
18053 				    "ip_rput_options: bad option offset\n"));
18054 				code = (char *)&opt[IPOPT_OFFSET] -
18055 				    (char *)ipha;
18056 				goto param_prob;
18057 			}
18058 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18059 			case IPOPT_TS_TSONLY:
18060 				off = IPOPT_TS_TIMELEN;
18061 				break;
18062 			case IPOPT_TS_TSANDADDR:
18063 			case IPOPT_TS_PRESPEC:
18064 			case IPOPT_TS_PRESPEC_RFC791:
18065 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18066 				break;
18067 			default:
18068 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
18069 				    (char *)ipha;
18070 				goto param_prob;
18071 			}
18072 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
18073 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
18074 				/*
18075 				 * No room and the overflow counter is 15
18076 				 * already.
18077 				 */
18078 				goto param_prob;
18079 			}
18080 			break;
18081 		}
18082 	}
18083 
18084 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
18085 		*dstp = dst;
18086 		return (0);
18087 	}
18088 
18089 	ip1dbg(("ip_rput_options: error processing IP options."));
18090 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
18091 
18092 param_prob:
18093 	q = WR(q);
18094 	if (q->q_next != NULL)
18095 		ill = q->q_ptr;
18096 	else
18097 		ill = NULL;
18098 
18099 	/* make sure we clear any indication of a hardware checksum */
18100 	DB_CKSUMFLAGS(mp) = 0;
18101 	/* Don't know whether this is for non-global or global/forwarding */
18102 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18103 	if (zoneid == ALL_ZONES)
18104 		freemsg(mp);
18105 	else
18106 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
18107 	return (-1);
18108 
18109 bad_src_route:
18110 	q = WR(q);
18111 	if (q->q_next != NULL)
18112 		ill = q->q_ptr;
18113 	else
18114 		ill = NULL;
18115 
18116 	/* make sure we clear any indication of a hardware checksum */
18117 	DB_CKSUMFLAGS(mp) = 0;
18118 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18119 	if (zoneid == ALL_ZONES)
18120 		freemsg(mp);
18121 	else
18122 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18123 	return (-1);
18124 }
18125 
18126 /*
18127  * IP & ICMP info in >=14 msg's ...
18128  *  - ip fixed part (mib2_ip_t)
18129  *  - icmp fixed part (mib2_icmp_t)
18130  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18131  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18132  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18133  *  - ipRouteAttributeTable (ip 102)	labeled routes
18134  *  - ip multicast membership (ip_member_t)
18135  *  - ip multicast source filtering (ip_grpsrc_t)
18136  *  - igmp fixed part (struct igmpstat)
18137  *  - multicast routing stats (struct mrtstat)
18138  *  - multicast routing vifs (array of struct vifctl)
18139  *  - multicast routing routes (array of struct mfcctl)
18140  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18141  *					One per ill plus one generic
18142  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18143  *					One per ill plus one generic
18144  *  - ipv6RouteEntry			all IPv6 IREs
18145  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18146  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18147  *  - ipv6AddrEntry			all IPv6 ipifs
18148  *  - ipv6 multicast membership (ipv6_member_t)
18149  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18150  *
18151  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18152  *
18153  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18154  * already filled in by the caller.
18155  * Return value of 0 indicates that no messages were sent and caller
18156  * should free mpctl.
18157  */
18158 int
18159 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
18160 {
18161 	ip_stack_t *ipst;
18162 	sctp_stack_t *sctps;
18163 
18164 	if (q->q_next != NULL) {
18165 		ipst = ILLQ_TO_IPST(q);
18166 	} else {
18167 		ipst = CONNQ_TO_IPST(q);
18168 	}
18169 	ASSERT(ipst != NULL);
18170 	sctps = ipst->ips_netstack->netstack_sctp;
18171 
18172 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18173 		return (0);
18174 	}
18175 
18176 	/*
18177 	 * For the purposes of the (broken) packet shell use
18178 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
18179 	 * to make TCP and UDP appear first in the list of mib items.
18180 	 * TBD: We could expand this and use it in netstat so that
18181 	 * the kernel doesn't have to produce large tables (connections,
18182 	 * routes, etc) when netstat only wants the statistics or a particular
18183 	 * table.
18184 	 */
18185 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
18186 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
18187 			return (1);
18188 		}
18189 	}
18190 
18191 	if (level != MIB2_TCP) {
18192 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
18193 			return (1);
18194 		}
18195 	}
18196 
18197 	if (level != MIB2_UDP) {
18198 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
18199 			return (1);
18200 		}
18201 	}
18202 
18203 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18204 	    ipst)) == NULL) {
18205 		return (1);
18206 	}
18207 
18208 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18209 		return (1);
18210 	}
18211 
18212 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18213 		return (1);
18214 	}
18215 
18216 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18217 		return (1);
18218 	}
18219 
18220 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18221 		return (1);
18222 	}
18223 
18224 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18225 		return (1);
18226 	}
18227 
18228 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18229 		return (1);
18230 	}
18231 
18232 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18233 		return (1);
18234 	}
18235 
18236 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18237 		return (1);
18238 	}
18239 
18240 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18241 		return (1);
18242 	}
18243 
18244 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18245 		return (1);
18246 	}
18247 
18248 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18249 		return (1);
18250 	}
18251 
18252 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18253 		return (1);
18254 	}
18255 
18256 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18257 		return (1);
18258 	}
18259 
18260 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, ipst)) == NULL) {
18261 		return (1);
18262 	}
18263 
18264 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, ipst);
18265 	if (mpctl == NULL) {
18266 		return (1);
18267 	}
18268 
18269 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18270 		return (1);
18271 	}
18272 	freemsg(mpctl);
18273 	return (1);
18274 }
18275 
18276 
18277 /* Get global (legacy) IPv4 statistics */
18278 static mblk_t *
18279 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18280     ip_stack_t *ipst)
18281 {
18282 	mib2_ip_t		old_ip_mib;
18283 	struct opthdr		*optp;
18284 	mblk_t			*mp2ctl;
18285 
18286 	/*
18287 	 * make a copy of the original message
18288 	 */
18289 	mp2ctl = copymsg(mpctl);
18290 
18291 	/* fixed length IP structure... */
18292 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18293 	optp->level = MIB2_IP;
18294 	optp->name = 0;
18295 	SET_MIB(old_ip_mib.ipForwarding,
18296 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18297 	SET_MIB(old_ip_mib.ipDefaultTTL,
18298 	    (uint32_t)ipst->ips_ip_def_ttl);
18299 	SET_MIB(old_ip_mib.ipReasmTimeout,
18300 	    ipst->ips_ip_g_frag_timeout);
18301 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18302 	    sizeof (mib2_ipAddrEntry_t));
18303 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18304 	    sizeof (mib2_ipRouteEntry_t));
18305 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18306 	    sizeof (mib2_ipNetToMediaEntry_t));
18307 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18308 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18309 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18310 	    sizeof (mib2_ipAttributeEntry_t));
18311 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18312 
18313 	/*
18314 	 * Grab the statistics from the new IP MIB
18315 	 */
18316 	SET_MIB(old_ip_mib.ipInReceives,
18317 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18318 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18319 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18320 	SET_MIB(old_ip_mib.ipForwDatagrams,
18321 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18322 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18323 	    ipmib->ipIfStatsInUnknownProtos);
18324 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18325 	SET_MIB(old_ip_mib.ipInDelivers,
18326 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18327 	SET_MIB(old_ip_mib.ipOutRequests,
18328 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18329 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18330 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18331 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18332 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18333 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18334 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18335 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18336 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18337 
18338 	/* ipRoutingDiscards is not being used */
18339 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18340 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18341 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18342 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18343 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18344 	    ipmib->ipIfStatsReasmDuplicates);
18345 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18346 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18347 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18348 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18349 	SET_MIB(old_ip_mib.rawipInOverflows,
18350 	    ipmib->rawipIfStatsInOverflows);
18351 
18352 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18353 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18354 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18355 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18356 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18357 	    ipmib->ipIfStatsOutSwitchIPVersion);
18358 
18359 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18360 	    (int)sizeof (old_ip_mib))) {
18361 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18362 		    (uint_t)sizeof (old_ip_mib)));
18363 	}
18364 
18365 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18366 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18367 	    (int)optp->level, (int)optp->name, (int)optp->len));
18368 	qreply(q, mpctl);
18369 	return (mp2ctl);
18370 }
18371 
18372 /* Per interface IPv4 statistics */
18373 static mblk_t *
18374 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18375 {
18376 	struct opthdr		*optp;
18377 	mblk_t			*mp2ctl;
18378 	ill_t			*ill;
18379 	ill_walk_context_t	ctx;
18380 	mblk_t			*mp_tail = NULL;
18381 	mib2_ipIfStatsEntry_t	global_ip_mib;
18382 
18383 	/*
18384 	 * Make a copy of the original message
18385 	 */
18386 	mp2ctl = copymsg(mpctl);
18387 
18388 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18389 	optp->level = MIB2_IP;
18390 	optp->name = MIB2_IP_TRAFFIC_STATS;
18391 	/* Include "unknown interface" ip_mib */
18392 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18393 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18394 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18395 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18396 	    (ipst->ips_ip_g_forward ? 1 : 2));
18397 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18398 	    (uint32_t)ipst->ips_ip_def_ttl);
18399 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18400 	    sizeof (mib2_ipIfStatsEntry_t));
18401 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18402 	    sizeof (mib2_ipAddrEntry_t));
18403 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18404 	    sizeof (mib2_ipRouteEntry_t));
18405 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18406 	    sizeof (mib2_ipNetToMediaEntry_t));
18407 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18408 	    sizeof (ip_member_t));
18409 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18410 	    sizeof (ip_grpsrc_t));
18411 
18412 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18413 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18414 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18415 		    "failed to allocate %u bytes\n",
18416 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18417 	}
18418 
18419 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18420 
18421 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18422 	ill = ILL_START_WALK_V4(&ctx, ipst);
18423 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18424 		ill->ill_ip_mib->ipIfStatsIfIndex =
18425 		    ill->ill_phyint->phyint_ifindex;
18426 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18427 		    (ipst->ips_ip_g_forward ? 1 : 2));
18428 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18429 		    (uint32_t)ipst->ips_ip_def_ttl);
18430 
18431 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18432 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18433 		    (char *)ill->ill_ip_mib,
18434 		    (int)sizeof (*ill->ill_ip_mib))) {
18435 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18436 			    "failed to allocate %u bytes\n",
18437 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18438 		}
18439 	}
18440 	rw_exit(&ipst->ips_ill_g_lock);
18441 
18442 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18443 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18444 	    "level %d, name %d, len %d\n",
18445 	    (int)optp->level, (int)optp->name, (int)optp->len));
18446 	qreply(q, mpctl);
18447 
18448 	if (mp2ctl == NULL)
18449 		return (NULL);
18450 
18451 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18452 }
18453 
18454 /* Global IPv4 ICMP statistics */
18455 static mblk_t *
18456 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18457 {
18458 	struct opthdr		*optp;
18459 	mblk_t			*mp2ctl;
18460 
18461 	/*
18462 	 * Make a copy of the original message
18463 	 */
18464 	mp2ctl = copymsg(mpctl);
18465 
18466 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18467 	optp->level = MIB2_ICMP;
18468 	optp->name = 0;
18469 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18470 	    (int)sizeof (ipst->ips_icmp_mib))) {
18471 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18472 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18473 	}
18474 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18475 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18476 	    (int)optp->level, (int)optp->name, (int)optp->len));
18477 	qreply(q, mpctl);
18478 	return (mp2ctl);
18479 }
18480 
18481 /* Global IPv4 IGMP statistics */
18482 static mblk_t *
18483 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18484 {
18485 	struct opthdr		*optp;
18486 	mblk_t			*mp2ctl;
18487 
18488 	/*
18489 	 * make a copy of the original message
18490 	 */
18491 	mp2ctl = copymsg(mpctl);
18492 
18493 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18494 	optp->level = EXPER_IGMP;
18495 	optp->name = 0;
18496 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18497 	    (int)sizeof (ipst->ips_igmpstat))) {
18498 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18499 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18500 	}
18501 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18502 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18503 	    (int)optp->level, (int)optp->name, (int)optp->len));
18504 	qreply(q, mpctl);
18505 	return (mp2ctl);
18506 }
18507 
18508 /* Global IPv4 Multicast Routing statistics */
18509 static mblk_t *
18510 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18511 {
18512 	struct opthdr		*optp;
18513 	mblk_t			*mp2ctl;
18514 
18515 	/*
18516 	 * make a copy of the original message
18517 	 */
18518 	mp2ctl = copymsg(mpctl);
18519 
18520 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18521 	optp->level = EXPER_DVMRP;
18522 	optp->name = 0;
18523 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18524 		ip0dbg(("ip_mroute_stats: failed\n"));
18525 	}
18526 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18527 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18528 	    (int)optp->level, (int)optp->name, (int)optp->len));
18529 	qreply(q, mpctl);
18530 	return (mp2ctl);
18531 }
18532 
18533 /* IPv4 address information */
18534 static mblk_t *
18535 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18536 {
18537 	struct opthdr		*optp;
18538 	mblk_t			*mp2ctl;
18539 	mblk_t			*mp_tail = NULL;
18540 	ill_t			*ill;
18541 	ipif_t			*ipif;
18542 	uint_t			bitval;
18543 	mib2_ipAddrEntry_t	mae;
18544 	zoneid_t		zoneid;
18545 	ill_walk_context_t ctx;
18546 
18547 	/*
18548 	 * make a copy of the original message
18549 	 */
18550 	mp2ctl = copymsg(mpctl);
18551 
18552 	/* ipAddrEntryTable */
18553 
18554 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18555 	optp->level = MIB2_IP;
18556 	optp->name = MIB2_IP_ADDR;
18557 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18558 
18559 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18560 	ill = ILL_START_WALK_V4(&ctx, ipst);
18561 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18562 		for (ipif = ill->ill_ipif; ipif != NULL;
18563 		    ipif = ipif->ipif_next) {
18564 			if (ipif->ipif_zoneid != zoneid &&
18565 			    ipif->ipif_zoneid != ALL_ZONES)
18566 				continue;
18567 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18568 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18569 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18570 
18571 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18572 			    OCTET_LENGTH);
18573 			mae.ipAdEntIfIndex.o_length =
18574 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18575 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18576 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18577 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18578 			mae.ipAdEntInfo.ae_subnet_len =
18579 			    ip_mask_to_plen(ipif->ipif_net_mask);
18580 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18581 			for (bitval = 1;
18582 			    bitval &&
18583 			    !(bitval & ipif->ipif_brd_addr);
18584 			    bitval <<= 1)
18585 				noop;
18586 			mae.ipAdEntBcastAddr = bitval;
18587 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18588 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18589 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18590 			mae.ipAdEntInfo.ae_broadcast_addr =
18591 			    ipif->ipif_brd_addr;
18592 			mae.ipAdEntInfo.ae_pp_dst_addr =
18593 			    ipif->ipif_pp_dst_addr;
18594 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18595 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18596 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18597 
18598 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18599 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18600 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18601 				    "allocate %u bytes\n",
18602 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18603 			}
18604 		}
18605 	}
18606 	rw_exit(&ipst->ips_ill_g_lock);
18607 
18608 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18609 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18610 	    (int)optp->level, (int)optp->name, (int)optp->len));
18611 	qreply(q, mpctl);
18612 	return (mp2ctl);
18613 }
18614 
18615 /* IPv6 address information */
18616 static mblk_t *
18617 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18618 {
18619 	struct opthdr		*optp;
18620 	mblk_t			*mp2ctl;
18621 	mblk_t			*mp_tail = NULL;
18622 	ill_t			*ill;
18623 	ipif_t			*ipif;
18624 	mib2_ipv6AddrEntry_t	mae6;
18625 	zoneid_t		zoneid;
18626 	ill_walk_context_t	ctx;
18627 
18628 	/*
18629 	 * make a copy of the original message
18630 	 */
18631 	mp2ctl = copymsg(mpctl);
18632 
18633 	/* ipv6AddrEntryTable */
18634 
18635 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18636 	optp->level = MIB2_IP6;
18637 	optp->name = MIB2_IP6_ADDR;
18638 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18639 
18640 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18641 	ill = ILL_START_WALK_V6(&ctx, ipst);
18642 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18643 		for (ipif = ill->ill_ipif; ipif != NULL;
18644 		    ipif = ipif->ipif_next) {
18645 			if (ipif->ipif_zoneid != zoneid &&
18646 			    ipif->ipif_zoneid != ALL_ZONES)
18647 				continue;
18648 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18649 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18650 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18651 
18652 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18653 			    OCTET_LENGTH);
18654 			mae6.ipv6AddrIfIndex.o_length =
18655 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18656 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18657 			mae6.ipv6AddrPfxLength =
18658 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18659 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18660 			mae6.ipv6AddrInfo.ae_subnet_len =
18661 			    mae6.ipv6AddrPfxLength;
18662 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18663 
18664 			/* Type: stateless(1), stateful(2), unknown(3) */
18665 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18666 				mae6.ipv6AddrType = 1;
18667 			else
18668 				mae6.ipv6AddrType = 2;
18669 			/* Anycast: true(1), false(2) */
18670 			if (ipif->ipif_flags & IPIF_ANYCAST)
18671 				mae6.ipv6AddrAnycastFlag = 1;
18672 			else
18673 				mae6.ipv6AddrAnycastFlag = 2;
18674 
18675 			/*
18676 			 * Address status: preferred(1), deprecated(2),
18677 			 * invalid(3), inaccessible(4), unknown(5)
18678 			 */
18679 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18680 				mae6.ipv6AddrStatus = 3;
18681 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18682 				mae6.ipv6AddrStatus = 2;
18683 			else
18684 				mae6.ipv6AddrStatus = 1;
18685 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18686 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18687 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18688 			    ipif->ipif_v6pp_dst_addr;
18689 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18690 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18691 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18692 			mae6.ipv6AddrIdentifier = ill->ill_token;
18693 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18694 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18695 			mae6.ipv6AddrRetransmitTime =
18696 			    ill->ill_reachable_retrans_time;
18697 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18698 			    (char *)&mae6,
18699 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18700 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18701 				    "allocate %u bytes\n",
18702 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18703 			}
18704 		}
18705 	}
18706 	rw_exit(&ipst->ips_ill_g_lock);
18707 
18708 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18709 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18710 	    (int)optp->level, (int)optp->name, (int)optp->len));
18711 	qreply(q, mpctl);
18712 	return (mp2ctl);
18713 }
18714 
18715 /* IPv4 multicast group membership. */
18716 static mblk_t *
18717 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18718 {
18719 	struct opthdr		*optp;
18720 	mblk_t			*mp2ctl;
18721 	ill_t			*ill;
18722 	ipif_t			*ipif;
18723 	ilm_t			*ilm;
18724 	ip_member_t		ipm;
18725 	mblk_t			*mp_tail = NULL;
18726 	ill_walk_context_t	ctx;
18727 	zoneid_t		zoneid;
18728 
18729 	/*
18730 	 * make a copy of the original message
18731 	 */
18732 	mp2ctl = copymsg(mpctl);
18733 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18734 
18735 	/* ipGroupMember table */
18736 	optp = (struct opthdr *)&mpctl->b_rptr[
18737 	    sizeof (struct T_optmgmt_ack)];
18738 	optp->level = MIB2_IP;
18739 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18740 
18741 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18742 	ill = ILL_START_WALK_V4(&ctx, ipst);
18743 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18744 		ILM_WALKER_HOLD(ill);
18745 		for (ipif = ill->ill_ipif; ipif != NULL;
18746 		    ipif = ipif->ipif_next) {
18747 			if (ipif->ipif_zoneid != zoneid &&
18748 			    ipif->ipif_zoneid != ALL_ZONES)
18749 				continue;	/* not this zone */
18750 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
18751 			    OCTET_LENGTH);
18752 			ipm.ipGroupMemberIfIndex.o_length =
18753 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18754 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18755 				ASSERT(ilm->ilm_ipif != NULL);
18756 				ASSERT(ilm->ilm_ill == NULL);
18757 				if (ilm->ilm_ipif != ipif)
18758 					continue;
18759 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18760 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18761 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18762 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18763 				    (char *)&ipm, (int)sizeof (ipm))) {
18764 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18765 					    "failed to allocate %u bytes\n",
18766 					    (uint_t)sizeof (ipm)));
18767 				}
18768 			}
18769 		}
18770 		ILM_WALKER_RELE(ill);
18771 	}
18772 	rw_exit(&ipst->ips_ill_g_lock);
18773 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18774 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18775 	    (int)optp->level, (int)optp->name, (int)optp->len));
18776 	qreply(q, mpctl);
18777 	return (mp2ctl);
18778 }
18779 
18780 /* IPv6 multicast group membership. */
18781 static mblk_t *
18782 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18783 {
18784 	struct opthdr		*optp;
18785 	mblk_t			*mp2ctl;
18786 	ill_t			*ill;
18787 	ilm_t			*ilm;
18788 	ipv6_member_t		ipm6;
18789 	mblk_t			*mp_tail = NULL;
18790 	ill_walk_context_t	ctx;
18791 	zoneid_t		zoneid;
18792 
18793 	/*
18794 	 * make a copy of the original message
18795 	 */
18796 	mp2ctl = copymsg(mpctl);
18797 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18798 
18799 	/* ip6GroupMember table */
18800 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18801 	optp->level = MIB2_IP6;
18802 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18803 
18804 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18805 	ill = ILL_START_WALK_V6(&ctx, ipst);
18806 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18807 		ILM_WALKER_HOLD(ill);
18808 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18809 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18810 			ASSERT(ilm->ilm_ipif == NULL);
18811 			ASSERT(ilm->ilm_ill != NULL);
18812 			if (ilm->ilm_zoneid != zoneid)
18813 				continue;	/* not this zone */
18814 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18815 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18816 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18817 			if (!snmp_append_data2(mpctl->b_cont,
18818 			    &mp_tail,
18819 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18820 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18821 				    "failed to allocate %u bytes\n",
18822 				    (uint_t)sizeof (ipm6)));
18823 			}
18824 		}
18825 		ILM_WALKER_RELE(ill);
18826 	}
18827 	rw_exit(&ipst->ips_ill_g_lock);
18828 
18829 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18830 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18831 	    (int)optp->level, (int)optp->name, (int)optp->len));
18832 	qreply(q, mpctl);
18833 	return (mp2ctl);
18834 }
18835 
18836 /* IP multicast filtered sources */
18837 static mblk_t *
18838 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18839 {
18840 	struct opthdr		*optp;
18841 	mblk_t			*mp2ctl;
18842 	ill_t			*ill;
18843 	ipif_t			*ipif;
18844 	ilm_t			*ilm;
18845 	ip_grpsrc_t		ips;
18846 	mblk_t			*mp_tail = NULL;
18847 	ill_walk_context_t	ctx;
18848 	zoneid_t		zoneid;
18849 	int			i;
18850 	slist_t			*sl;
18851 
18852 	/*
18853 	 * make a copy of the original message
18854 	 */
18855 	mp2ctl = copymsg(mpctl);
18856 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18857 
18858 	/* ipGroupSource table */
18859 	optp = (struct opthdr *)&mpctl->b_rptr[
18860 	    sizeof (struct T_optmgmt_ack)];
18861 	optp->level = MIB2_IP;
18862 	optp->name = EXPER_IP_GROUP_SOURCES;
18863 
18864 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18865 	ill = ILL_START_WALK_V4(&ctx, ipst);
18866 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18867 		ILM_WALKER_HOLD(ill);
18868 		for (ipif = ill->ill_ipif; ipif != NULL;
18869 		    ipif = ipif->ipif_next) {
18870 			if (ipif->ipif_zoneid != zoneid)
18871 				continue;	/* not this zone */
18872 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
18873 			    OCTET_LENGTH);
18874 			ips.ipGroupSourceIfIndex.o_length =
18875 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18876 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18877 				ASSERT(ilm->ilm_ipif != NULL);
18878 				ASSERT(ilm->ilm_ill == NULL);
18879 				sl = ilm->ilm_filter;
18880 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18881 					continue;
18882 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18883 				for (i = 0; i < sl->sl_numsrc; i++) {
18884 					if (!IN6_IS_ADDR_V4MAPPED(
18885 					    &sl->sl_addr[i]))
18886 						continue;
18887 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18888 					    ips.ipGroupSourceAddress);
18889 					if (snmp_append_data2(mpctl->b_cont,
18890 					    &mp_tail, (char *)&ips,
18891 					    (int)sizeof (ips)) == 0) {
18892 						ip1dbg(("ip_snmp_get_mib2_"
18893 						    "ip_group_src: failed to "
18894 						    "allocate %u bytes\n",
18895 						    (uint_t)sizeof (ips)));
18896 					}
18897 				}
18898 			}
18899 		}
18900 		ILM_WALKER_RELE(ill);
18901 	}
18902 	rw_exit(&ipst->ips_ill_g_lock);
18903 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18904 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18905 	    (int)optp->level, (int)optp->name, (int)optp->len));
18906 	qreply(q, mpctl);
18907 	return (mp2ctl);
18908 }
18909 
18910 /* IPv6 multicast filtered sources. */
18911 static mblk_t *
18912 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18913 {
18914 	struct opthdr		*optp;
18915 	mblk_t			*mp2ctl;
18916 	ill_t			*ill;
18917 	ilm_t			*ilm;
18918 	ipv6_grpsrc_t		ips6;
18919 	mblk_t			*mp_tail = NULL;
18920 	ill_walk_context_t	ctx;
18921 	zoneid_t		zoneid;
18922 	int			i;
18923 	slist_t			*sl;
18924 
18925 	/*
18926 	 * make a copy of the original message
18927 	 */
18928 	mp2ctl = copymsg(mpctl);
18929 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18930 
18931 	/* ip6GroupMember table */
18932 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18933 	optp->level = MIB2_IP6;
18934 	optp->name = EXPER_IP6_GROUP_SOURCES;
18935 
18936 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18937 	ill = ILL_START_WALK_V6(&ctx, ipst);
18938 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18939 		ILM_WALKER_HOLD(ill);
18940 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18941 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18942 			ASSERT(ilm->ilm_ipif == NULL);
18943 			ASSERT(ilm->ilm_ill != NULL);
18944 			sl = ilm->ilm_filter;
18945 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18946 				continue;
18947 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18948 			for (i = 0; i < sl->sl_numsrc; i++) {
18949 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18950 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18951 				    (char *)&ips6, (int)sizeof (ips6))) {
18952 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18953 					    "group_src: failed to allocate "
18954 					    "%u bytes\n",
18955 					    (uint_t)sizeof (ips6)));
18956 				}
18957 			}
18958 		}
18959 		ILM_WALKER_RELE(ill);
18960 	}
18961 	rw_exit(&ipst->ips_ill_g_lock);
18962 
18963 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18964 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18965 	    (int)optp->level, (int)optp->name, (int)optp->len));
18966 	qreply(q, mpctl);
18967 	return (mp2ctl);
18968 }
18969 
18970 /* Multicast routing virtual interface table. */
18971 static mblk_t *
18972 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18973 {
18974 	struct opthdr		*optp;
18975 	mblk_t			*mp2ctl;
18976 
18977 	/*
18978 	 * make a copy of the original message
18979 	 */
18980 	mp2ctl = copymsg(mpctl);
18981 
18982 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18983 	optp->level = EXPER_DVMRP;
18984 	optp->name = EXPER_DVMRP_VIF;
18985 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
18986 		ip0dbg(("ip_mroute_vif: failed\n"));
18987 	}
18988 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18989 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
18990 	    (int)optp->level, (int)optp->name, (int)optp->len));
18991 	qreply(q, mpctl);
18992 	return (mp2ctl);
18993 }
18994 
18995 /* Multicast routing table. */
18996 static mblk_t *
18997 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18998 {
18999 	struct opthdr		*optp;
19000 	mblk_t			*mp2ctl;
19001 
19002 	/*
19003 	 * make a copy of the original message
19004 	 */
19005 	mp2ctl = copymsg(mpctl);
19006 
19007 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19008 	optp->level = EXPER_DVMRP;
19009 	optp->name = EXPER_DVMRP_MRT;
19010 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
19011 		ip0dbg(("ip_mroute_mrt: failed\n"));
19012 	}
19013 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19014 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
19015 	    (int)optp->level, (int)optp->name, (int)optp->len));
19016 	qreply(q, mpctl);
19017 	return (mp2ctl);
19018 }
19019 
19020 /*
19021  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
19022  * in one IRE walk.
19023  */
19024 static mblk_t *
19025 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19026 {
19027 	struct opthdr	*optp;
19028 	mblk_t		*mp2ctl;	/* Returned */
19029 	mblk_t		*mp3ctl;	/* nettomedia */
19030 	mblk_t		*mp4ctl;	/* routeattrs */
19031 	iproutedata_t	ird;
19032 	zoneid_t	zoneid;
19033 
19034 	/*
19035 	 * make copies of the original message
19036 	 *	- mp2ctl is returned unchanged to the caller for his use
19037 	 *	- mpctl is sent upstream as ipRouteEntryTable
19038 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
19039 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
19040 	 */
19041 	mp2ctl = copymsg(mpctl);
19042 	mp3ctl = copymsg(mpctl);
19043 	mp4ctl = copymsg(mpctl);
19044 	if (mp3ctl == NULL || mp4ctl == NULL) {
19045 		freemsg(mp4ctl);
19046 		freemsg(mp3ctl);
19047 		freemsg(mp2ctl);
19048 		freemsg(mpctl);
19049 		return (NULL);
19050 	}
19051 
19052 	bzero(&ird, sizeof (ird));
19053 
19054 	ird.ird_route.lp_head = mpctl->b_cont;
19055 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19056 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19057 
19058 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19059 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
19060 
19061 	/* ipRouteEntryTable in mpctl */
19062 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19063 	optp->level = MIB2_IP;
19064 	optp->name = MIB2_IP_ROUTE;
19065 	optp->len = msgdsize(ird.ird_route.lp_head);
19066 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19067 	    (int)optp->level, (int)optp->name, (int)optp->len));
19068 	qreply(q, mpctl);
19069 
19070 	/* ipNetToMediaEntryTable in mp3ctl */
19071 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19072 	optp->level = MIB2_IP;
19073 	optp->name = MIB2_IP_MEDIA;
19074 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19075 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19076 	    (int)optp->level, (int)optp->name, (int)optp->len));
19077 	qreply(q, mp3ctl);
19078 
19079 	/* ipRouteAttributeTable in mp4ctl */
19080 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19081 	optp->level = MIB2_IP;
19082 	optp->name = EXPER_IP_RTATTR;
19083 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19084 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19085 	    (int)optp->level, (int)optp->name, (int)optp->len));
19086 	if (optp->len == 0)
19087 		freemsg(mp4ctl);
19088 	else
19089 		qreply(q, mp4ctl);
19090 
19091 	return (mp2ctl);
19092 }
19093 
19094 /*
19095  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
19096  * ipv6NetToMediaEntryTable in an NDP walk.
19097  */
19098 static mblk_t *
19099 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19100 {
19101 	struct opthdr	*optp;
19102 	mblk_t		*mp2ctl;	/* Returned */
19103 	mblk_t		*mp3ctl;	/* nettomedia */
19104 	mblk_t		*mp4ctl;	/* routeattrs */
19105 	iproutedata_t	ird;
19106 	zoneid_t	zoneid;
19107 
19108 	/*
19109 	 * make copies of the original message
19110 	 *	- mp2ctl is returned unchanged to the caller for his use
19111 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19112 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19113 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19114 	 */
19115 	mp2ctl = copymsg(mpctl);
19116 	mp3ctl = copymsg(mpctl);
19117 	mp4ctl = copymsg(mpctl);
19118 	if (mp3ctl == NULL || mp4ctl == NULL) {
19119 		freemsg(mp4ctl);
19120 		freemsg(mp3ctl);
19121 		freemsg(mp2ctl);
19122 		freemsg(mpctl);
19123 		return (NULL);
19124 	}
19125 
19126 	bzero(&ird, sizeof (ird));
19127 
19128 	ird.ird_route.lp_head = mpctl->b_cont;
19129 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19130 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19131 
19132 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19133 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19134 
19135 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19136 	optp->level = MIB2_IP6;
19137 	optp->name = MIB2_IP6_ROUTE;
19138 	optp->len = msgdsize(ird.ird_route.lp_head);
19139 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19140 	    (int)optp->level, (int)optp->name, (int)optp->len));
19141 	qreply(q, mpctl);
19142 
19143 	/* ipv6NetToMediaEntryTable in mp3ctl */
19144 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19145 
19146 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19147 	optp->level = MIB2_IP6;
19148 	optp->name = MIB2_IP6_MEDIA;
19149 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19150 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19151 	    (int)optp->level, (int)optp->name, (int)optp->len));
19152 	qreply(q, mp3ctl);
19153 
19154 	/* ipv6RouteAttributeTable in mp4ctl */
19155 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19156 	optp->level = MIB2_IP6;
19157 	optp->name = EXPER_IP_RTATTR;
19158 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19159 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19160 	    (int)optp->level, (int)optp->name, (int)optp->len));
19161 	if (optp->len == 0)
19162 		freemsg(mp4ctl);
19163 	else
19164 		qreply(q, mp4ctl);
19165 
19166 	return (mp2ctl);
19167 }
19168 
19169 /*
19170  * IPv6 mib: One per ill
19171  */
19172 static mblk_t *
19173 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19174 {
19175 	struct opthdr		*optp;
19176 	mblk_t			*mp2ctl;
19177 	ill_t			*ill;
19178 	ill_walk_context_t	ctx;
19179 	mblk_t			*mp_tail = NULL;
19180 
19181 	/*
19182 	 * Make a copy of the original message
19183 	 */
19184 	mp2ctl = copymsg(mpctl);
19185 
19186 	/* fixed length IPv6 structure ... */
19187 
19188 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19189 	optp->level = MIB2_IP6;
19190 	optp->name = 0;
19191 	/* Include "unknown interface" ip6_mib */
19192 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19193 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19194 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19195 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19196 	    ipst->ips_ipv6_forward ? 1 : 2);
19197 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19198 	    ipst->ips_ipv6_def_hops);
19199 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19200 	    sizeof (mib2_ipIfStatsEntry_t));
19201 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19202 	    sizeof (mib2_ipv6AddrEntry_t));
19203 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19204 	    sizeof (mib2_ipv6RouteEntry_t));
19205 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19206 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19207 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19208 	    sizeof (ipv6_member_t));
19209 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19210 	    sizeof (ipv6_grpsrc_t));
19211 
19212 	/*
19213 	 * Synchronize 64- and 32-bit counters
19214 	 */
19215 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19216 	    ipIfStatsHCInReceives);
19217 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19218 	    ipIfStatsHCInDelivers);
19219 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19220 	    ipIfStatsHCOutRequests);
19221 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19222 	    ipIfStatsHCOutForwDatagrams);
19223 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19224 	    ipIfStatsHCOutMcastPkts);
19225 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19226 	    ipIfStatsHCInMcastPkts);
19227 
19228 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19229 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19230 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19231 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19232 	}
19233 
19234 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19235 	ill = ILL_START_WALK_V6(&ctx, ipst);
19236 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19237 		ill->ill_ip_mib->ipIfStatsIfIndex =
19238 		    ill->ill_phyint->phyint_ifindex;
19239 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19240 		    ipst->ips_ipv6_forward ? 1 : 2);
19241 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19242 		    ill->ill_max_hops);
19243 
19244 		/*
19245 		 * Synchronize 64- and 32-bit counters
19246 		 */
19247 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19248 		    ipIfStatsHCInReceives);
19249 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19250 		    ipIfStatsHCInDelivers);
19251 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19252 		    ipIfStatsHCOutRequests);
19253 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19254 		    ipIfStatsHCOutForwDatagrams);
19255 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19256 		    ipIfStatsHCOutMcastPkts);
19257 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19258 		    ipIfStatsHCInMcastPkts);
19259 
19260 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19261 		    (char *)ill->ill_ip_mib,
19262 		    (int)sizeof (*ill->ill_ip_mib))) {
19263 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19264 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19265 		}
19266 	}
19267 	rw_exit(&ipst->ips_ill_g_lock);
19268 
19269 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19270 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19271 	    (int)optp->level, (int)optp->name, (int)optp->len));
19272 	qreply(q, mpctl);
19273 	return (mp2ctl);
19274 }
19275 
19276 /*
19277  * ICMPv6 mib: One per ill
19278  */
19279 static mblk_t *
19280 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19281 {
19282 	struct opthdr		*optp;
19283 	mblk_t			*mp2ctl;
19284 	ill_t			*ill;
19285 	ill_walk_context_t	ctx;
19286 	mblk_t			*mp_tail = NULL;
19287 	/*
19288 	 * Make a copy of the original message
19289 	 */
19290 	mp2ctl = copymsg(mpctl);
19291 
19292 	/* fixed length ICMPv6 structure ... */
19293 
19294 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19295 	optp->level = MIB2_ICMP6;
19296 	optp->name = 0;
19297 	/* Include "unknown interface" icmp6_mib */
19298 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19299 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19300 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19301 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19302 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19303 	    (char *)&ipst->ips_icmp6_mib,
19304 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19305 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19306 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19307 	}
19308 
19309 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19310 	ill = ILL_START_WALK_V6(&ctx, ipst);
19311 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19312 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19313 		    ill->ill_phyint->phyint_ifindex;
19314 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19315 		    (char *)ill->ill_icmp6_mib,
19316 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19317 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19318 			    "%u bytes\n",
19319 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19320 		}
19321 	}
19322 	rw_exit(&ipst->ips_ill_g_lock);
19323 
19324 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19325 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19326 	    (int)optp->level, (int)optp->name, (int)optp->len));
19327 	qreply(q, mpctl);
19328 	return (mp2ctl);
19329 }
19330 
19331 /*
19332  * ire_walk routine to create both ipRouteEntryTable and
19333  * ipRouteAttributeTable in one IRE walk
19334  */
19335 static void
19336 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19337 {
19338 	ill_t				*ill;
19339 	ipif_t				*ipif;
19340 	mib2_ipRouteEntry_t		*re;
19341 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19342 	ipaddr_t			gw_addr;
19343 	tsol_ire_gw_secattr_t		*attrp;
19344 	tsol_gc_t			*gc = NULL;
19345 	tsol_gcgrp_t			*gcgrp = NULL;
19346 	uint_t				sacnt = 0;
19347 	int				i;
19348 
19349 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19350 
19351 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19352 		return;
19353 
19354 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19355 		mutex_enter(&attrp->igsa_lock);
19356 		if ((gc = attrp->igsa_gc) != NULL) {
19357 			gcgrp = gc->gc_grp;
19358 			ASSERT(gcgrp != NULL);
19359 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19360 			sacnt = 1;
19361 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19362 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19363 			gc = gcgrp->gcgrp_head;
19364 			sacnt = gcgrp->gcgrp_count;
19365 		}
19366 		mutex_exit(&attrp->igsa_lock);
19367 
19368 		/* do nothing if there's no gc to report */
19369 		if (gc == NULL) {
19370 			ASSERT(sacnt == 0);
19371 			if (gcgrp != NULL) {
19372 				/* we might as well drop the lock now */
19373 				rw_exit(&gcgrp->gcgrp_rwlock);
19374 				gcgrp = NULL;
19375 			}
19376 			attrp = NULL;
19377 		}
19378 
19379 		ASSERT(gc == NULL || (gcgrp != NULL &&
19380 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19381 	}
19382 	ASSERT(sacnt == 0 || gc != NULL);
19383 
19384 	if (sacnt != 0 &&
19385 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19386 		kmem_free(re, sizeof (*re));
19387 		rw_exit(&gcgrp->gcgrp_rwlock);
19388 		return;
19389 	}
19390 
19391 	/*
19392 	 * Return all IRE types for route table... let caller pick and choose
19393 	 */
19394 	re->ipRouteDest = ire->ire_addr;
19395 	ipif = ire->ire_ipif;
19396 	re->ipRouteIfIndex.o_length = 0;
19397 	if (ire->ire_type == IRE_CACHE) {
19398 		ill = (ill_t *)ire->ire_stq->q_ptr;
19399 		re->ipRouteIfIndex.o_length =
19400 		    ill->ill_name_length == 0 ? 0 :
19401 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19402 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19403 		    re->ipRouteIfIndex.o_length);
19404 	} else if (ipif != NULL) {
19405 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19406 		re->ipRouteIfIndex.o_length =
19407 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19408 	}
19409 	re->ipRouteMetric1 = -1;
19410 	re->ipRouteMetric2 = -1;
19411 	re->ipRouteMetric3 = -1;
19412 	re->ipRouteMetric4 = -1;
19413 
19414 	gw_addr = ire->ire_gateway_addr;
19415 
19416 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19417 		re->ipRouteNextHop = ire->ire_src_addr;
19418 	else
19419 		re->ipRouteNextHop = gw_addr;
19420 	/* indirect(4), direct(3), or invalid(2) */
19421 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19422 		re->ipRouteType = 2;
19423 	else
19424 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19425 	re->ipRouteProto = -1;
19426 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19427 	re->ipRouteMask = ire->ire_mask;
19428 	re->ipRouteMetric5 = -1;
19429 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19430 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19431 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19432 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19433 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19434 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19435 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19436 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19437 
19438 	if (ire->ire_flags & RTF_DYNAMIC) {
19439 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19440 	} else {
19441 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19442 	}
19443 
19444 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19445 	    (char *)re, (int)sizeof (*re))) {
19446 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19447 		    (uint_t)sizeof (*re)));
19448 	}
19449 
19450 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19451 		iaeptr->iae_routeidx = ird->ird_idx;
19452 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19453 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19454 	}
19455 
19456 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19457 	    (char *)iae, sacnt * sizeof (*iae))) {
19458 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19459 		    (unsigned)(sacnt * sizeof (*iae))));
19460 	}
19461 
19462 	/* bump route index for next pass */
19463 	ird->ird_idx++;
19464 
19465 	kmem_free(re, sizeof (*re));
19466 	if (sacnt != 0)
19467 		kmem_free(iae, sacnt * sizeof (*iae));
19468 
19469 	if (gcgrp != NULL)
19470 		rw_exit(&gcgrp->gcgrp_rwlock);
19471 }
19472 
19473 /*
19474  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19475  */
19476 static void
19477 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19478 {
19479 	ill_t				*ill;
19480 	ipif_t				*ipif;
19481 	mib2_ipv6RouteEntry_t		*re;
19482 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19483 	in6_addr_t			gw_addr_v6;
19484 	tsol_ire_gw_secattr_t		*attrp;
19485 	tsol_gc_t			*gc = NULL;
19486 	tsol_gcgrp_t			*gcgrp = NULL;
19487 	uint_t				sacnt = 0;
19488 	int				i;
19489 
19490 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19491 
19492 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19493 		return;
19494 
19495 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19496 		mutex_enter(&attrp->igsa_lock);
19497 		if ((gc = attrp->igsa_gc) != NULL) {
19498 			gcgrp = gc->gc_grp;
19499 			ASSERT(gcgrp != NULL);
19500 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19501 			sacnt = 1;
19502 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19503 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19504 			gc = gcgrp->gcgrp_head;
19505 			sacnt = gcgrp->gcgrp_count;
19506 		}
19507 		mutex_exit(&attrp->igsa_lock);
19508 
19509 		/* do nothing if there's no gc to report */
19510 		if (gc == NULL) {
19511 			ASSERT(sacnt == 0);
19512 			if (gcgrp != NULL) {
19513 				/* we might as well drop the lock now */
19514 				rw_exit(&gcgrp->gcgrp_rwlock);
19515 				gcgrp = NULL;
19516 			}
19517 			attrp = NULL;
19518 		}
19519 
19520 		ASSERT(gc == NULL || (gcgrp != NULL &&
19521 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19522 	}
19523 	ASSERT(sacnt == 0 || gc != NULL);
19524 
19525 	if (sacnt != 0 &&
19526 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19527 		kmem_free(re, sizeof (*re));
19528 		rw_exit(&gcgrp->gcgrp_rwlock);
19529 		return;
19530 	}
19531 
19532 	/*
19533 	 * Return all IRE types for route table... let caller pick and choose
19534 	 */
19535 	re->ipv6RouteDest = ire->ire_addr_v6;
19536 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19537 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19538 	re->ipv6RouteIfIndex.o_length = 0;
19539 	ipif = ire->ire_ipif;
19540 	if (ire->ire_type == IRE_CACHE) {
19541 		ill = (ill_t *)ire->ire_stq->q_ptr;
19542 		re->ipv6RouteIfIndex.o_length =
19543 		    ill->ill_name_length == 0 ? 0 :
19544 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19545 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19546 		    re->ipv6RouteIfIndex.o_length);
19547 	} else if (ipif != NULL) {
19548 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19549 		re->ipv6RouteIfIndex.o_length =
19550 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19551 	}
19552 
19553 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19554 
19555 	mutex_enter(&ire->ire_lock);
19556 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19557 	mutex_exit(&ire->ire_lock);
19558 
19559 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19560 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19561 	else
19562 		re->ipv6RouteNextHop = gw_addr_v6;
19563 
19564 	/* remote(4), local(3), or discard(2) */
19565 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19566 		re->ipv6RouteType = 2;
19567 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19568 		re->ipv6RouteType = 3;
19569 	else
19570 		re->ipv6RouteType = 4;
19571 
19572 	re->ipv6RouteProtocol	= -1;
19573 	re->ipv6RoutePolicy	= 0;
19574 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19575 	re->ipv6RouteNextHopRDI	= 0;
19576 	re->ipv6RouteWeight	= 0;
19577 	re->ipv6RouteMetric	= 0;
19578 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19579 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19580 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19581 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19582 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19583 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19584 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19585 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19586 
19587 	if (ire->ire_flags & RTF_DYNAMIC) {
19588 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19589 	} else {
19590 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19591 	}
19592 
19593 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19594 	    (char *)re, (int)sizeof (*re))) {
19595 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19596 		    (uint_t)sizeof (*re)));
19597 	}
19598 
19599 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19600 		iaeptr->iae_routeidx = ird->ird_idx;
19601 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19602 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19603 	}
19604 
19605 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19606 	    (char *)iae, sacnt * sizeof (*iae))) {
19607 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19608 		    (unsigned)(sacnt * sizeof (*iae))));
19609 	}
19610 
19611 	/* bump route index for next pass */
19612 	ird->ird_idx++;
19613 
19614 	kmem_free(re, sizeof (*re));
19615 	if (sacnt != 0)
19616 		kmem_free(iae, sacnt * sizeof (*iae));
19617 
19618 	if (gcgrp != NULL)
19619 		rw_exit(&gcgrp->gcgrp_rwlock);
19620 }
19621 
19622 /*
19623  * ndp_walk routine to create ipv6NetToMediaEntryTable
19624  */
19625 static int
19626 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19627 {
19628 	ill_t				*ill;
19629 	mib2_ipv6NetToMediaEntry_t	ntme;
19630 	dl_unitdata_req_t		*dl;
19631 
19632 	ill = nce->nce_ill;
19633 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19634 		return (0);
19635 
19636 	/*
19637 	 * Neighbor cache entry attached to IRE with on-link
19638 	 * destination.
19639 	 */
19640 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19641 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19642 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19643 	    (nce->nce_res_mp != NULL)) {
19644 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19645 		ntme.ipv6NetToMediaPhysAddress.o_length =
19646 		    dl->dl_dest_addr_length;
19647 	} else {
19648 		ntme.ipv6NetToMediaPhysAddress.o_length =
19649 		    ill->ill_phys_addr_length;
19650 	}
19651 	if (nce->nce_res_mp != NULL) {
19652 		bcopy((char *)nce->nce_res_mp->b_rptr +
19653 		    NCE_LL_ADDR_OFFSET(ill),
19654 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19655 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19656 	} else {
19657 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19658 		    ill->ill_phys_addr_length);
19659 	}
19660 	/*
19661 	 * Note: Returns ND_* states. Should be:
19662 	 * reachable(1), stale(2), delay(3), probe(4),
19663 	 * invalid(5), unknown(6)
19664 	 */
19665 	ntme.ipv6NetToMediaState = nce->nce_state;
19666 	ntme.ipv6NetToMediaLastUpdated = 0;
19667 
19668 	/* other(1), dynamic(2), static(3), local(4) */
19669 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19670 		ntme.ipv6NetToMediaType = 4;
19671 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19672 		ntme.ipv6NetToMediaType = 1;
19673 	} else {
19674 		ntme.ipv6NetToMediaType = 2;
19675 	}
19676 
19677 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19678 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19679 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19680 		    (uint_t)sizeof (ntme)));
19681 	}
19682 	return (0);
19683 }
19684 
19685 /*
19686  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19687  */
19688 /* ARGSUSED */
19689 int
19690 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19691 {
19692 	switch (level) {
19693 	case MIB2_IP:
19694 	case MIB2_ICMP:
19695 		switch (name) {
19696 		default:
19697 			break;
19698 		}
19699 		return (1);
19700 	default:
19701 		return (1);
19702 	}
19703 }
19704 
19705 /*
19706  * When there exists both a 64- and 32-bit counter of a particular type
19707  * (i.e., InReceives), only the 64-bit counters are added.
19708  */
19709 void
19710 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19711 {
19712 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19713 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19714 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19715 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19716 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19717 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19718 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19719 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19720 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19721 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19722 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19723 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19724 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19725 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19726 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19727 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19728 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19729 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19730 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19731 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19732 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19733 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19734 	    o2->ipIfStatsInWrongIPVersion);
19735 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19736 	    o2->ipIfStatsInWrongIPVersion);
19737 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19738 	    o2->ipIfStatsOutSwitchIPVersion);
19739 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19740 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19741 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19742 	    o2->ipIfStatsHCInForwDatagrams);
19743 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19744 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19745 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19746 	    o2->ipIfStatsHCOutForwDatagrams);
19747 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19748 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19749 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19750 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19751 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19752 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19753 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19754 	    o2->ipIfStatsHCOutMcastOctets);
19755 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19756 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19757 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19758 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19759 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19760 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19761 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19762 }
19763 
19764 void
19765 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19766 {
19767 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19768 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19769 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19770 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19771 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19772 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19773 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19774 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19775 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19776 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19777 	    o2->ipv6IfIcmpInRouterSolicits);
19778 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19779 	    o2->ipv6IfIcmpInRouterAdvertisements);
19780 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19781 	    o2->ipv6IfIcmpInNeighborSolicits);
19782 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19783 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19784 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19785 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19786 	    o2->ipv6IfIcmpInGroupMembQueries);
19787 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19788 	    o2->ipv6IfIcmpInGroupMembResponses);
19789 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19790 	    o2->ipv6IfIcmpInGroupMembReductions);
19791 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19792 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19793 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19794 	    o2->ipv6IfIcmpOutDestUnreachs);
19795 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19796 	    o2->ipv6IfIcmpOutAdminProhibs);
19797 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19798 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19799 	    o2->ipv6IfIcmpOutParmProblems);
19800 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19801 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19802 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19803 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19804 	    o2->ipv6IfIcmpOutRouterSolicits);
19805 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19806 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19807 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19808 	    o2->ipv6IfIcmpOutNeighborSolicits);
19809 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19810 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19811 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19812 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19813 	    o2->ipv6IfIcmpOutGroupMembQueries);
19814 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19815 	    o2->ipv6IfIcmpOutGroupMembResponses);
19816 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19817 	    o2->ipv6IfIcmpOutGroupMembReductions);
19818 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19819 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19820 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19821 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19822 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19823 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19824 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19825 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19826 	    o2->ipv6IfIcmpInGroupMembTotal);
19827 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19828 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19829 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19830 	    o2->ipv6IfIcmpInGroupMembBadReports);
19831 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19832 	    o2->ipv6IfIcmpInGroupMembOurReports);
19833 }
19834 
19835 /*
19836  * Called before the options are updated to check if this packet will
19837  * be source routed from here.
19838  * This routine assumes that the options are well formed i.e. that they
19839  * have already been checked.
19840  */
19841 static boolean_t
19842 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
19843 {
19844 	ipoptp_t	opts;
19845 	uchar_t		*opt;
19846 	uint8_t		optval;
19847 	uint8_t		optlen;
19848 	ipaddr_t	dst;
19849 	ire_t		*ire;
19850 
19851 	if (IS_SIMPLE_IPH(ipha)) {
19852 		ip2dbg(("not source routed\n"));
19853 		return (B_FALSE);
19854 	}
19855 	dst = ipha->ipha_dst;
19856 	for (optval = ipoptp_first(&opts, ipha);
19857 	    optval != IPOPT_EOL;
19858 	    optval = ipoptp_next(&opts)) {
19859 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19860 		opt = opts.ipoptp_cur;
19861 		optlen = opts.ipoptp_len;
19862 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19863 		    optval, optlen));
19864 		switch (optval) {
19865 			uint32_t off;
19866 		case IPOPT_SSRR:
19867 		case IPOPT_LSRR:
19868 			/*
19869 			 * If dst is one of our addresses and there are some
19870 			 * entries left in the source route return (true).
19871 			 */
19872 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19873 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
19874 			if (ire == NULL) {
19875 				ip2dbg(("ip_source_routed: not next"
19876 				    " source route 0x%x\n",
19877 				    ntohl(dst)));
19878 				return (B_FALSE);
19879 			}
19880 			ire_refrele(ire);
19881 			off = opt[IPOPT_OFFSET];
19882 			off--;
19883 			if (optlen < IP_ADDR_LEN ||
19884 			    off > optlen - IP_ADDR_LEN) {
19885 				/* End of source route */
19886 				ip1dbg(("ip_source_routed: end of SR\n"));
19887 				return (B_FALSE);
19888 			}
19889 			return (B_TRUE);
19890 		}
19891 	}
19892 	ip2dbg(("not source routed\n"));
19893 	return (B_FALSE);
19894 }
19895 
19896 /*
19897  * Check if the packet contains any source route.
19898  */
19899 static boolean_t
19900 ip_source_route_included(ipha_t *ipha)
19901 {
19902 	ipoptp_t	opts;
19903 	uint8_t		optval;
19904 
19905 	if (IS_SIMPLE_IPH(ipha))
19906 		return (B_FALSE);
19907 	for (optval = ipoptp_first(&opts, ipha);
19908 	    optval != IPOPT_EOL;
19909 	    optval = ipoptp_next(&opts)) {
19910 		switch (optval) {
19911 		case IPOPT_SSRR:
19912 		case IPOPT_LSRR:
19913 			return (B_TRUE);
19914 		}
19915 	}
19916 	return (B_FALSE);
19917 }
19918 
19919 /*
19920  * Called when the IRE expiration timer fires.
19921  */
19922 void
19923 ip_trash_timer_expire(void *args)
19924 {
19925 	int			flush_flag = 0;
19926 	ire_expire_arg_t	iea;
19927 	ip_stack_t		*ipst = (ip_stack_t *)args;
19928 
19929 	iea.iea_ipst = ipst;	/* No netstack_hold */
19930 
19931 	/*
19932 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19933 	 * This lock makes sure that a new invocation of this function
19934 	 * that occurs due to an almost immediate timer firing will not
19935 	 * progress beyond this point until the current invocation is done
19936 	 */
19937 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19938 	ipst->ips_ip_ire_expire_id = 0;
19939 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19940 
19941 	/* Periodic timer */
19942 	if (ipst->ips_ip_ire_arp_time_elapsed >=
19943 	    ipst->ips_ip_ire_arp_interval) {
19944 		/*
19945 		 * Remove all IRE_CACHE entries since they might
19946 		 * contain arp information.
19947 		 */
19948 		flush_flag |= FLUSH_ARP_TIME;
19949 		ipst->ips_ip_ire_arp_time_elapsed = 0;
19950 		IP_STAT(ipst, ip_ire_arp_timer_expired);
19951 	}
19952 	if (ipst->ips_ip_ire_rd_time_elapsed >=
19953 	    ipst->ips_ip_ire_redir_interval) {
19954 		/* Remove all redirects */
19955 		flush_flag |= FLUSH_REDIRECT_TIME;
19956 		ipst->ips_ip_ire_rd_time_elapsed = 0;
19957 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
19958 	}
19959 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
19960 	    ipst->ips_ip_ire_pathmtu_interval) {
19961 		/* Increase path mtu */
19962 		flush_flag |= FLUSH_MTU_TIME;
19963 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
19964 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
19965 	}
19966 
19967 	/*
19968 	 * Optimize for the case when there are no redirects in the
19969 	 * ftable, that is, no need to walk the ftable in that case.
19970 	 */
19971 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
19972 		iea.iea_flush_flag = flush_flag;
19973 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
19974 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
19975 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
19976 		    NULL, ALL_ZONES, ipst);
19977 	}
19978 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
19979 	    ipst->ips_ip_redirect_cnt > 0) {
19980 		iea.iea_flush_flag = flush_flag;
19981 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
19982 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
19983 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
19984 	}
19985 	if (flush_flag & FLUSH_MTU_TIME) {
19986 		/*
19987 		 * Walk all IPv6 IRE's and update them
19988 		 * Note that ARP and redirect timers are not
19989 		 * needed since NUD handles stale entries.
19990 		 */
19991 		flush_flag = FLUSH_MTU_TIME;
19992 		iea.iea_flush_flag = flush_flag;
19993 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
19994 		    ALL_ZONES, ipst);
19995 	}
19996 
19997 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
19998 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
19999 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
20000 
20001 	/*
20002 	 * Hold the lock to serialize timeout calls and prevent
20003 	 * stale values in ip_ire_expire_id. Otherwise it is possible
20004 	 * for the timer to fire and a new invocation of this function
20005 	 * to start before the return value of timeout has been stored
20006 	 * in ip_ire_expire_id by the current invocation.
20007 	 */
20008 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20009 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
20010 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
20011 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20012 }
20013 
20014 /*
20015  * Called by the memory allocator subsystem directly, when the system
20016  * is running low on memory.
20017  */
20018 /* ARGSUSED */
20019 void
20020 ip_trash_ire_reclaim(void *args)
20021 {
20022 	netstack_handle_t nh;
20023 	netstack_t *ns;
20024 
20025 	netstack_next_init(&nh);
20026 	while ((ns = netstack_next(&nh)) != NULL) {
20027 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
20028 		netstack_rele(ns);
20029 	}
20030 	netstack_next_fini(&nh);
20031 }
20032 
20033 static void
20034 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
20035 {
20036 	ire_cache_count_t icc;
20037 	ire_cache_reclaim_t icr;
20038 	ncc_cache_count_t ncc;
20039 	nce_cache_reclaim_t ncr;
20040 	uint_t delete_cnt;
20041 	/*
20042 	 * Memory reclaim call back.
20043 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
20044 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
20045 	 * entries, determine what fraction to free for
20046 	 * each category of IRE_CACHE entries giving absolute priority
20047 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
20048 	 * entry will be freed unless all offlink entries are freed).
20049 	 */
20050 	icc.icc_total = 0;
20051 	icc.icc_unused = 0;
20052 	icc.icc_offlink = 0;
20053 	icc.icc_pmtu = 0;
20054 	icc.icc_onlink = 0;
20055 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20056 
20057 	/*
20058 	 * Free NCEs for IPv6 like the onlink ires.
20059 	 */
20060 	ncc.ncc_total = 0;
20061 	ncc.ncc_host = 0;
20062 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
20063 
20064 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
20065 	    icc.icc_pmtu + icc.icc_onlink);
20066 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
20067 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
20068 	if (delete_cnt == 0)
20069 		return;
20070 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
20071 	/* Always delete all unused offlink entries */
20072 	icr.icr_ipst = ipst;
20073 	icr.icr_unused = 1;
20074 	if (delete_cnt <= icc.icc_unused) {
20075 		/*
20076 		 * Only need to free unused entries.  In other words,
20077 		 * there are enough unused entries to free to meet our
20078 		 * target number of freed ire cache entries.
20079 		 */
20080 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
20081 		ncr.ncr_host = 0;
20082 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
20083 		/*
20084 		 * Only need to free unused entries, plus a fraction of offlink
20085 		 * entries.  It follows from the first if statement that
20086 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
20087 		 */
20088 		delete_cnt -= icc.icc_unused;
20089 		/* Round up # deleted by truncating fraction */
20090 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
20091 		icr.icr_pmtu = icr.icr_onlink = 0;
20092 		ncr.ncr_host = 0;
20093 	} else if (delete_cnt <=
20094 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
20095 		/*
20096 		 * Free all unused and offlink entries, plus a fraction of
20097 		 * pmtu entries.  It follows from the previous if statement
20098 		 * that icc_pmtu is non-zero, and that
20099 		 * delete_cnt != icc_unused + icc_offlink.
20100 		 */
20101 		icr.icr_offlink = 1;
20102 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
20103 		/* Round up # deleted by truncating fraction */
20104 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20105 		icr.icr_onlink = 0;
20106 		ncr.ncr_host = 0;
20107 	} else {
20108 		/*
20109 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20110 		 * of onlink entries.  If we're here, then we know that
20111 		 * icc_onlink is non-zero, and that
20112 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20113 		 */
20114 		icr.icr_offlink = icr.icr_pmtu = 1;
20115 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20116 		    icc.icc_pmtu;
20117 		/* Round up # deleted by truncating fraction */
20118 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20119 		/* Using the same delete fraction as for onlink IREs */
20120 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20121 	}
20122 #ifdef DEBUG
20123 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20124 	    "fractions %d/%d/%d/%d\n",
20125 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20126 	    icc.icc_unused, icc.icc_offlink,
20127 	    icc.icc_pmtu, icc.icc_onlink,
20128 	    icr.icr_unused, icr.icr_offlink,
20129 	    icr.icr_pmtu, icr.icr_onlink));
20130 #endif
20131 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20132 	if (ncr.ncr_host != 0)
20133 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20134 		    (uchar_t *)&ncr, ipst);
20135 #ifdef DEBUG
20136 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20137 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20138 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20139 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20140 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20141 	    icc.icc_pmtu, icc.icc_onlink));
20142 #endif
20143 }
20144 
20145 /*
20146  * ip_unbind is called when a copy of an unbind request is received from the
20147  * upper level protocol.  We remove this conn from any fanout hash list it is
20148  * on, and zero out the bind information.  No reply is expected up above.
20149  */
20150 mblk_t *
20151 ip_unbind(queue_t *q, mblk_t *mp)
20152 {
20153 	conn_t  *connp = Q_TO_CONN(q);
20154 
20155 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20156 
20157 	if (is_system_labeled() && connp->conn_anon_port) {
20158 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20159 		    connp->conn_mlp_type, connp->conn_ulp,
20160 		    ntohs(connp->conn_lport), B_FALSE);
20161 		connp->conn_anon_port = 0;
20162 	}
20163 	connp->conn_mlp_type = mlptSingle;
20164 
20165 	ipcl_hash_remove(connp);
20166 
20167 	ASSERT(mp->b_cont == NULL);
20168 	/*
20169 	 * Convert mp into a T_OK_ACK
20170 	 */
20171 	mp = mi_tpi_ok_ack_alloc(mp);
20172 
20173 	/*
20174 	 * should not happen in practice... T_OK_ACK is smaller than the
20175 	 * original message.
20176 	 */
20177 	if (mp == NULL)
20178 		return (NULL);
20179 
20180 	return (mp);
20181 }
20182 
20183 /*
20184  * Write side put procedure.  Outbound data, IOCTLs, responses from
20185  * resolvers, etc, come down through here.
20186  *
20187  * arg2 is always a queue_t *.
20188  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20189  * the zoneid.
20190  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20191  */
20192 void
20193 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20194 {
20195 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20196 }
20197 
20198 void
20199 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20200     ip_opt_info_t *infop)
20201 {
20202 	conn_t		*connp = NULL;
20203 	queue_t		*q = (queue_t *)arg2;
20204 	ipha_t		*ipha;
20205 #define	rptr	((uchar_t *)ipha)
20206 	ire_t		*ire = NULL;
20207 	ire_t		*sctp_ire = NULL;
20208 	uint32_t	v_hlen_tos_len;
20209 	ipaddr_t	dst;
20210 	mblk_t		*first_mp = NULL;
20211 	boolean_t	mctl_present;
20212 	ipsec_out_t	*io;
20213 	int		match_flags;
20214 	ill_t		*attach_ill = NULL;
20215 					/* Bind to IPIF_NOFAILOVER ill etc. */
20216 	ill_t		*xmit_ill = NULL;	/* IP_PKTINFO etc. */
20217 	ipif_t		*dst_ipif;
20218 	boolean_t	multirt_need_resolve = B_FALSE;
20219 	mblk_t		*copy_mp = NULL;
20220 	int		err;
20221 	zoneid_t	zoneid;
20222 	boolean_t	need_decref = B_FALSE;
20223 	boolean_t	ignore_dontroute = B_FALSE;
20224 	boolean_t	ignore_nexthop = B_FALSE;
20225 	boolean_t	ip_nexthop = B_FALSE;
20226 	ipaddr_t	nexthop_addr;
20227 	ip_stack_t	*ipst;
20228 
20229 #ifdef	_BIG_ENDIAN
20230 #define	V_HLEN	(v_hlen_tos_len >> 24)
20231 #else
20232 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20233 #endif
20234 
20235 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20236 	    "ip_wput_start: q %p", q);
20237 
20238 	/*
20239 	 * ip_wput fast path
20240 	 */
20241 
20242 	/* is packet from ARP ? */
20243 	if (q->q_next != NULL) {
20244 		zoneid = (zoneid_t)(uintptr_t)arg;
20245 		goto qnext;
20246 	}
20247 
20248 	connp = (conn_t *)arg;
20249 	ASSERT(connp != NULL);
20250 	zoneid = connp->conn_zoneid;
20251 	ipst = connp->conn_netstack->netstack_ip;
20252 
20253 	/* is queue flow controlled? */
20254 	if ((q->q_first != NULL || connp->conn_draining) &&
20255 	    (caller == IP_WPUT)) {
20256 		ASSERT(!need_decref);
20257 		(void) putq(q, mp);
20258 		return;
20259 	}
20260 
20261 	/* Multidata transmit? */
20262 	if (DB_TYPE(mp) == M_MULTIDATA) {
20263 		/*
20264 		 * We should never get here, since all Multidata messages
20265 		 * originating from tcp should have been directed over to
20266 		 * tcp_multisend() in the first place.
20267 		 */
20268 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20269 		freemsg(mp);
20270 		return;
20271 	} else if (DB_TYPE(mp) != M_DATA)
20272 		goto notdata;
20273 
20274 	if (mp->b_flag & MSGHASREF) {
20275 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20276 		mp->b_flag &= ~MSGHASREF;
20277 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20278 		need_decref = B_TRUE;
20279 	}
20280 	ipha = (ipha_t *)mp->b_rptr;
20281 
20282 	/* is IP header non-aligned or mblk smaller than basic IP header */
20283 #ifndef SAFETY_BEFORE_SPEED
20284 	if (!OK_32PTR(rptr) ||
20285 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20286 		goto hdrtoosmall;
20287 #endif
20288 
20289 	ASSERT(OK_32PTR(ipha));
20290 
20291 	/*
20292 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20293 	 * wrong version, we'll catch it again in ip_output_v6.
20294 	 *
20295 	 * Note that this is *only* locally-generated output here, and never
20296 	 * forwarded data, and that we need to deal only with transports that
20297 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20298 	 * label.)
20299 	 */
20300 	if (is_system_labeled() &&
20301 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20302 	    !connp->conn_ulp_labeled) {
20303 		err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20304 		    connp->conn_mac_exempt, ipst);
20305 		ipha = (ipha_t *)mp->b_rptr;
20306 		if (err != 0) {
20307 			first_mp = mp;
20308 			if (err == EINVAL)
20309 				goto icmp_parameter_problem;
20310 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20311 			goto discard_pkt;
20312 		}
20313 	}
20314 
20315 	ASSERT(infop != NULL);
20316 
20317 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20318 		/*
20319 		 * IP_PKTINFO ancillary option is present.
20320 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20321 		 * allows using address of any zone as the source address.
20322 		 */
20323 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20324 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20325 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20326 		if (ire == NULL)
20327 			goto drop_pkt;
20328 		ire_refrele(ire);
20329 		ire = NULL;
20330 	}
20331 
20332 	/*
20333 	 * IP_DONTFAILOVER_IF and IP_BOUND_IF have precedence over ill index
20334 	 * passed in IP_PKTINFO.
20335 	 */
20336 	if (infop->ip_opt_ill_index != 0 &&
20337 	    connp->conn_outgoing_ill == NULL &&
20338 	    connp->conn_nofailover_ill == NULL) {
20339 
20340 		xmit_ill = ill_lookup_on_ifindex(
20341 		    infop->ip_opt_ill_index, B_FALSE, NULL, NULL, NULL, NULL,
20342 		    ipst);
20343 
20344 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20345 			goto drop_pkt;
20346 		/*
20347 		 * check that there is an ipif belonging
20348 		 * to our zone. IPCL_ZONEID is not used because
20349 		 * IP_ALLZONES option is valid only when the ill is
20350 		 * accessible from all zones i.e has a valid ipif in
20351 		 * all zones.
20352 		 */
20353 		if (!ipif_lookup_zoneid_group(xmit_ill, zoneid, 0, NULL)) {
20354 			goto drop_pkt;
20355 		}
20356 	}
20357 
20358 	/*
20359 	 * If there is a policy, try to attach an ipsec_out in
20360 	 * the front. At the end, first_mp either points to a
20361 	 * M_DATA message or IPSEC_OUT message linked to a
20362 	 * M_DATA message. We have to do it now as we might
20363 	 * lose the "conn" if we go through ip_newroute.
20364 	 */
20365 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20366 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20367 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20368 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20369 			if (need_decref)
20370 				CONN_DEC_REF(connp);
20371 			return;
20372 		} else {
20373 			ASSERT(mp->b_datap->db_type == M_CTL);
20374 			first_mp = mp;
20375 			mp = mp->b_cont;
20376 			mctl_present = B_TRUE;
20377 		}
20378 	} else {
20379 		first_mp = mp;
20380 		mctl_present = B_FALSE;
20381 	}
20382 
20383 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20384 
20385 	/* is wrong version or IP options present */
20386 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20387 		goto version_hdrlen_check;
20388 	dst = ipha->ipha_dst;
20389 
20390 	if (connp->conn_nofailover_ill != NULL) {
20391 		attach_ill = conn_get_held_ill(connp,
20392 		    &connp->conn_nofailover_ill, &err);
20393 		if (err == ILL_LOOKUP_FAILED) {
20394 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20395 			if (need_decref)
20396 				CONN_DEC_REF(connp);
20397 			freemsg(first_mp);
20398 			return;
20399 		}
20400 	}
20401 
20402 	/* If IP_BOUND_IF has been set, use that ill. */
20403 	if (connp->conn_outgoing_ill != NULL) {
20404 		xmit_ill = conn_get_held_ill(connp,
20405 		    &connp->conn_outgoing_ill, &err);
20406 		if (err == ILL_LOOKUP_FAILED)
20407 			goto drop_pkt;
20408 
20409 		goto send_from_ill;
20410 	}
20411 
20412 	/* is packet multicast? */
20413 	if (CLASSD(dst))
20414 		goto multicast;
20415 
20416 	/*
20417 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20418 	 * takes precedence over conn_dontroute and conn_nexthop_set
20419 	 */
20420 	if (xmit_ill != NULL)
20421 		goto send_from_ill;
20422 
20423 	if (connp->conn_dontroute || connp->conn_nexthop_set) {
20424 		/*
20425 		 * If the destination is a broadcast, local, or loopback
20426 		 * address, SO_DONTROUTE and IP_NEXTHOP go through the
20427 		 * standard path.
20428 		 */
20429 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20430 		if ((ire == NULL) || (ire->ire_type &
20431 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK)) == 0) {
20432 			if (ire != NULL) {
20433 				ire_refrele(ire);
20434 				/* No more access to ire */
20435 				ire = NULL;
20436 			}
20437 			/*
20438 			 * bypass routing checks and go directly to interface.
20439 			 */
20440 			if (connp->conn_dontroute)
20441 				goto dontroute;
20442 
20443 			ASSERT(connp->conn_nexthop_set);
20444 			ip_nexthop = B_TRUE;
20445 			nexthop_addr = connp->conn_nexthop_v4;
20446 			goto send_from_ill;
20447 		}
20448 
20449 		/* Must be a broadcast, a loopback or a local ire */
20450 		ire_refrele(ire);
20451 		/* No more access to ire */
20452 		ire = NULL;
20453 	}
20454 
20455 	if (attach_ill != NULL)
20456 		goto send_from_ill;
20457 
20458 	/*
20459 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20460 	 * this for the tcp global queue and listen end point
20461 	 * as it does not really have a real destination to
20462 	 * talk to.  This is also true for SCTP.
20463 	 */
20464 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20465 	    !connp->conn_fully_bound) {
20466 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20467 		if (ire == NULL)
20468 			goto noirefound;
20469 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20470 		    "ip_wput_end: q %p (%S)", q, "end");
20471 
20472 		/*
20473 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20474 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20475 		 */
20476 		if (ire->ire_flags & RTF_MULTIRT) {
20477 
20478 			/*
20479 			 * Force the TTL of multirouted packets if required.
20480 			 * The TTL of such packets is bounded by the
20481 			 * ip_multirt_ttl ndd variable.
20482 			 */
20483 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20484 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20485 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20486 				    "(was %d), dst 0x%08x\n",
20487 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20488 				    ntohl(ire->ire_addr)));
20489 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20490 			}
20491 			/*
20492 			 * We look at this point if there are pending
20493 			 * unresolved routes. ire_multirt_resolvable()
20494 			 * checks in O(n) that all IRE_OFFSUBNET ire
20495 			 * entries for the packet's destination and
20496 			 * flagged RTF_MULTIRT are currently resolved.
20497 			 * If some remain unresolved, we make a copy
20498 			 * of the current message. It will be used
20499 			 * to initiate additional route resolutions.
20500 			 */
20501 			multirt_need_resolve =
20502 			    ire_multirt_need_resolve(ire->ire_addr,
20503 			    MBLK_GETLABEL(first_mp), ipst);
20504 			ip2dbg(("ip_wput[TCP]: ire %p, "
20505 			    "multirt_need_resolve %d, first_mp %p\n",
20506 			    (void *)ire, multirt_need_resolve,
20507 			    (void *)first_mp));
20508 			if (multirt_need_resolve) {
20509 				copy_mp = copymsg(first_mp);
20510 				if (copy_mp != NULL) {
20511 					MULTIRT_DEBUG_TAG(copy_mp);
20512 				}
20513 			}
20514 		}
20515 
20516 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20517 
20518 		/*
20519 		 * Try to resolve another multiroute if
20520 		 * ire_multirt_need_resolve() deemed it necessary.
20521 		 */
20522 		if (copy_mp != NULL)
20523 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20524 		if (need_decref)
20525 			CONN_DEC_REF(connp);
20526 		return;
20527 	}
20528 
20529 	/*
20530 	 * Access to conn_ire_cache. (protected by conn_lock)
20531 	 *
20532 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20533 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20534 	 * send a packet or two with the IRE_CACHE that is going away.
20535 	 * Access to the ire requires an ire refhold on the ire prior to
20536 	 * its use since an interface unplumb thread may delete the cached
20537 	 * ire and release the refhold at any time.
20538 	 *
20539 	 * Caching an ire in the conn_ire_cache
20540 	 *
20541 	 * o Caching an ire pointer in the conn requires a strict check for
20542 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20543 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20544 	 * in the conn is done after making sure under the bucket lock that the
20545 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20546 	 * caching an ire after the unplumb thread has cleaned up the conn.
20547 	 * If the conn does not send a packet subsequently the unplumb thread
20548 	 * will be hanging waiting for the ire count to drop to zero.
20549 	 *
20550 	 * o We also need to atomically test for a null conn_ire_cache and
20551 	 * set the conn_ire_cache under the the protection of the conn_lock
20552 	 * to avoid races among concurrent threads trying to simultaneously
20553 	 * cache an ire in the conn_ire_cache.
20554 	 */
20555 	mutex_enter(&connp->conn_lock);
20556 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20557 
20558 	if (ire != NULL && ire->ire_addr == dst &&
20559 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20560 
20561 		IRE_REFHOLD(ire);
20562 		mutex_exit(&connp->conn_lock);
20563 
20564 	} else {
20565 		boolean_t cached = B_FALSE;
20566 		connp->conn_ire_cache = NULL;
20567 		mutex_exit(&connp->conn_lock);
20568 		/* Release the old ire */
20569 		if (ire != NULL && sctp_ire == NULL)
20570 			IRE_REFRELE_NOTR(ire);
20571 
20572 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20573 		if (ire == NULL)
20574 			goto noirefound;
20575 		IRE_REFHOLD_NOTR(ire);
20576 
20577 		mutex_enter(&connp->conn_lock);
20578 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20579 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20580 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20581 				if (connp->conn_ulp == IPPROTO_TCP)
20582 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20583 				connp->conn_ire_cache = ire;
20584 				cached = B_TRUE;
20585 			}
20586 			rw_exit(&ire->ire_bucket->irb_lock);
20587 		}
20588 		mutex_exit(&connp->conn_lock);
20589 
20590 		/*
20591 		 * We can continue to use the ire but since it was
20592 		 * not cached, we should drop the extra reference.
20593 		 */
20594 		if (!cached)
20595 			IRE_REFRELE_NOTR(ire);
20596 	}
20597 
20598 
20599 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20600 	    "ip_wput_end: q %p (%S)", q, "end");
20601 
20602 	/*
20603 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20604 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20605 	 */
20606 	if (ire->ire_flags & RTF_MULTIRT) {
20607 
20608 		/*
20609 		 * Force the TTL of multirouted packets if required.
20610 		 * The TTL of such packets is bounded by the
20611 		 * ip_multirt_ttl ndd variable.
20612 		 */
20613 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20614 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20615 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20616 			    "(was %d), dst 0x%08x\n",
20617 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20618 			    ntohl(ire->ire_addr)));
20619 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20620 		}
20621 
20622 		/*
20623 		 * At this point, we check to see if there are any pending
20624 		 * unresolved routes. ire_multirt_resolvable()
20625 		 * checks in O(n) that all IRE_OFFSUBNET ire
20626 		 * entries for the packet's destination and
20627 		 * flagged RTF_MULTIRT are currently resolved.
20628 		 * If some remain unresolved, we make a copy
20629 		 * of the current message. It will be used
20630 		 * to initiate additional route resolutions.
20631 		 */
20632 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20633 		    MBLK_GETLABEL(first_mp), ipst);
20634 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20635 		    "multirt_need_resolve %d, first_mp %p\n",
20636 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20637 		if (multirt_need_resolve) {
20638 			copy_mp = copymsg(first_mp);
20639 			if (copy_mp != NULL) {
20640 				MULTIRT_DEBUG_TAG(copy_mp);
20641 			}
20642 		}
20643 	}
20644 
20645 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20646 
20647 	/*
20648 	 * Try to resolve another multiroute if
20649 	 * ire_multirt_resolvable() deemed it necessary
20650 	 */
20651 	if (copy_mp != NULL)
20652 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20653 	if (need_decref)
20654 		CONN_DEC_REF(connp);
20655 	return;
20656 
20657 qnext:
20658 	/*
20659 	 * Upper Level Protocols pass down complete IP datagrams
20660 	 * as M_DATA messages.	Everything else is a sideshow.
20661 	 *
20662 	 * 1) We could be re-entering ip_wput because of ip_neworute
20663 	 *    in which case we could have a IPSEC_OUT message. We
20664 	 *    need to pass through ip_wput like other datagrams and
20665 	 *    hence cannot branch to ip_wput_nondata.
20666 	 *
20667 	 * 2) ARP, AH, ESP, and other clients who are on the module
20668 	 *    instance of IP stream, give us something to deal with.
20669 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20670 	 *
20671 	 * 3) ICMP replies also could come here.
20672 	 */
20673 	ipst = ILLQ_TO_IPST(q);
20674 
20675 	if (DB_TYPE(mp) != M_DATA) {
20676 notdata:
20677 		if (DB_TYPE(mp) == M_CTL) {
20678 			/*
20679 			 * M_CTL messages are used by ARP, AH and ESP to
20680 			 * communicate with IP. We deal with IPSEC_IN and
20681 			 * IPSEC_OUT here. ip_wput_nondata handles other
20682 			 * cases.
20683 			 */
20684 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20685 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20686 				first_mp = mp->b_cont;
20687 				first_mp->b_flag &= ~MSGHASREF;
20688 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20689 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20690 				CONN_DEC_REF(connp);
20691 				connp = NULL;
20692 			}
20693 			if (ii->ipsec_info_type == IPSEC_IN) {
20694 				/*
20695 				 * Either this message goes back to
20696 				 * IPsec for further processing or to
20697 				 * ULP after policy checks.
20698 				 */
20699 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20700 				return;
20701 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20702 				io = (ipsec_out_t *)ii;
20703 				if (io->ipsec_out_proc_begin) {
20704 					/*
20705 					 * IPsec processing has already started.
20706 					 * Complete it.
20707 					 * IPQoS notes: We don't care what is
20708 					 * in ipsec_out_ill_index since this
20709 					 * won't be processed for IPQoS policies
20710 					 * in ipsec_out_process.
20711 					 */
20712 					ipsec_out_process(q, mp, NULL,
20713 					    io->ipsec_out_ill_index);
20714 					return;
20715 				} else {
20716 					connp = (q->q_next != NULL) ?
20717 					    NULL : Q_TO_CONN(q);
20718 					first_mp = mp;
20719 					mp = mp->b_cont;
20720 					mctl_present = B_TRUE;
20721 				}
20722 				zoneid = io->ipsec_out_zoneid;
20723 				ASSERT(zoneid != ALL_ZONES);
20724 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20725 				/*
20726 				 * It's an IPsec control message requesting
20727 				 * an SADB update to be sent to the IPsec
20728 				 * hardware acceleration capable ills.
20729 				 */
20730 				ipsec_ctl_t *ipsec_ctl =
20731 				    (ipsec_ctl_t *)mp->b_rptr;
20732 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20733 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20734 				mblk_t *cmp = mp->b_cont;
20735 
20736 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20737 				ASSERT(cmp != NULL);
20738 
20739 				freeb(mp);
20740 				ill_ipsec_capab_send_all(satype, cmp, sa,
20741 				    ipst->ips_netstack);
20742 				return;
20743 			} else {
20744 				/*
20745 				 * This must be ARP or special TSOL signaling.
20746 				 */
20747 				ip_wput_nondata(NULL, q, mp, NULL);
20748 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20749 				    "ip_wput_end: q %p (%S)", q, "nondata");
20750 				return;
20751 			}
20752 		} else {
20753 			/*
20754 			 * This must be non-(ARP/AH/ESP) messages.
20755 			 */
20756 			ASSERT(!need_decref);
20757 			ip_wput_nondata(NULL, q, mp, NULL);
20758 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20759 			    "ip_wput_end: q %p (%S)", q, "nondata");
20760 			return;
20761 		}
20762 	} else {
20763 		first_mp = mp;
20764 		mctl_present = B_FALSE;
20765 	}
20766 
20767 	ASSERT(first_mp != NULL);
20768 	/*
20769 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20770 	 * to make sure that this packet goes out on the same interface it
20771 	 * came in. We handle that here.
20772 	 */
20773 	if (mctl_present) {
20774 		uint_t ifindex;
20775 
20776 		io = (ipsec_out_t *)first_mp->b_rptr;
20777 		if (io->ipsec_out_attach_if || io->ipsec_out_ip_nexthop) {
20778 			/*
20779 			 * We may have lost the conn context if we are
20780 			 * coming here from ip_newroute(). Copy the
20781 			 * nexthop information.
20782 			 */
20783 			if (io->ipsec_out_ip_nexthop) {
20784 				ip_nexthop = B_TRUE;
20785 				nexthop_addr = io->ipsec_out_nexthop_addr;
20786 
20787 				ipha = (ipha_t *)mp->b_rptr;
20788 				dst = ipha->ipha_dst;
20789 				goto send_from_ill;
20790 			} else {
20791 				ASSERT(io->ipsec_out_ill_index != 0);
20792 				ifindex = io->ipsec_out_ill_index;
20793 				attach_ill = ill_lookup_on_ifindex(ifindex,
20794 				    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20795 				if (attach_ill == NULL) {
20796 					ASSERT(xmit_ill == NULL);
20797 					ip1dbg(("ip_output: bad ifindex for "
20798 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20799 					    ifindex));
20800 					freemsg(first_mp);
20801 					BUMP_MIB(&ipst->ips_ip_mib,
20802 					    ipIfStatsOutDiscards);
20803 					ASSERT(!need_decref);
20804 					return;
20805 				}
20806 			}
20807 		}
20808 	}
20809 
20810 	ASSERT(xmit_ill == NULL);
20811 
20812 	/* We have a complete IP datagram heading outbound. */
20813 	ipha = (ipha_t *)mp->b_rptr;
20814 
20815 #ifndef SPEED_BEFORE_SAFETY
20816 	/*
20817 	 * Make sure we have a full-word aligned message and that at least
20818 	 * a simple IP header is accessible in the first message.  If not,
20819 	 * try a pullup.  For labeled systems we need to always take this
20820 	 * path as M_CTLs are "notdata" but have trailing data to process.
20821 	 */
20822 	if (!OK_32PTR(rptr) ||
20823 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH || is_system_labeled()) {
20824 hdrtoosmall:
20825 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20826 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20827 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20828 			if (first_mp == NULL)
20829 				first_mp = mp;
20830 			goto discard_pkt;
20831 		}
20832 
20833 		/* This function assumes that mp points to an IPv4 packet. */
20834 		if (is_system_labeled() && q->q_next == NULL &&
20835 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20836 		    !connp->conn_ulp_labeled) {
20837 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20838 			    connp->conn_mac_exempt, ipst);
20839 			ipha = (ipha_t *)mp->b_rptr;
20840 			if (first_mp != NULL)
20841 				first_mp->b_cont = mp;
20842 			if (err != 0) {
20843 				if (first_mp == NULL)
20844 					first_mp = mp;
20845 				if (err == EINVAL)
20846 					goto icmp_parameter_problem;
20847 				ip2dbg(("ip_wput: label check failed (%d)\n",
20848 				    err));
20849 				goto discard_pkt;
20850 			}
20851 		}
20852 
20853 		ipha = (ipha_t *)mp->b_rptr;
20854 		if (first_mp == NULL) {
20855 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20856 			/*
20857 			 * If we got here because of "goto hdrtoosmall"
20858 			 * We need to attach a IPSEC_OUT.
20859 			 */
20860 			if (connp->conn_out_enforce_policy) {
20861 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
20862 				    NULL, ipha->ipha_protocol,
20863 				    ipst->ips_netstack)) == NULL)) {
20864 					BUMP_MIB(&ipst->ips_ip_mib,
20865 					    ipIfStatsOutDiscards);
20866 					if (need_decref)
20867 						CONN_DEC_REF(connp);
20868 					return;
20869 				} else {
20870 					ASSERT(mp->b_datap->db_type == M_CTL);
20871 					first_mp = mp;
20872 					mp = mp->b_cont;
20873 					mctl_present = B_TRUE;
20874 				}
20875 			} else {
20876 				first_mp = mp;
20877 				mctl_present = B_FALSE;
20878 			}
20879 		}
20880 	}
20881 #endif
20882 
20883 	/* Most of the code below is written for speed, not readability */
20884 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20885 
20886 	/*
20887 	 * If ip_newroute() fails, we're going to need a full
20888 	 * header for the icmp wraparound.
20889 	 */
20890 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20891 		uint_t	v_hlen;
20892 version_hdrlen_check:
20893 		ASSERT(first_mp != NULL);
20894 		v_hlen = V_HLEN;
20895 		/*
20896 		 * siphon off IPv6 packets coming down from transport
20897 		 * layer modules here.
20898 		 * Note: high-order bit carries NUD reachability confirmation
20899 		 */
20900 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20901 			/*
20902 			 * FIXME: assume that callers of ip_output* call
20903 			 * the right version?
20904 			 */
20905 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
20906 			ASSERT(xmit_ill == NULL);
20907 			if (attach_ill != NULL)
20908 				ill_refrele(attach_ill);
20909 			if (need_decref)
20910 				mp->b_flag |= MSGHASREF;
20911 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20912 			return;
20913 		}
20914 
20915 		if ((v_hlen >> 4) != IP_VERSION) {
20916 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20917 			    "ip_wput_end: q %p (%S)", q, "badvers");
20918 			goto discard_pkt;
20919 		}
20920 		/*
20921 		 * Is the header length at least 20 bytes?
20922 		 *
20923 		 * Are there enough bytes accessible in the header?  If
20924 		 * not, try a pullup.
20925 		 */
20926 		v_hlen &= 0xF;
20927 		v_hlen <<= 2;
20928 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20929 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20930 			    "ip_wput_end: q %p (%S)", q, "badlen");
20931 			goto discard_pkt;
20932 		}
20933 		if (v_hlen > (mp->b_wptr - rptr)) {
20934 			if (!pullupmsg(mp, v_hlen)) {
20935 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20936 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20937 				goto discard_pkt;
20938 			}
20939 			ipha = (ipha_t *)mp->b_rptr;
20940 		}
20941 		/*
20942 		 * Move first entry from any source route into ipha_dst and
20943 		 * verify the options
20944 		 */
20945 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
20946 		    zoneid, ipst)) {
20947 			ASSERT(xmit_ill == NULL);
20948 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20949 			if (attach_ill != NULL)
20950 				ill_refrele(attach_ill);
20951 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20952 			    "ip_wput_end: q %p (%S)", q, "badopts");
20953 			if (need_decref)
20954 				CONN_DEC_REF(connp);
20955 			return;
20956 		}
20957 	}
20958 	dst = ipha->ipha_dst;
20959 
20960 	/*
20961 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20962 	 * we have to run the packet through ip_newroute which will take
20963 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
20964 	 * a resolver, or assigning a default gateway, etc.
20965 	 */
20966 	if (CLASSD(dst)) {
20967 		ipif_t	*ipif;
20968 		uint32_t setsrc = 0;
20969 
20970 multicast:
20971 		ASSERT(first_mp != NULL);
20972 		ip2dbg(("ip_wput: CLASSD\n"));
20973 		if (connp == NULL) {
20974 			/*
20975 			 * Use the first good ipif on the ill.
20976 			 * XXX Should this ever happen? (Appears
20977 			 * to show up with just ppp and no ethernet due
20978 			 * to in.rdisc.)
20979 			 * However, ire_send should be able to
20980 			 * call ip_wput_ire directly.
20981 			 *
20982 			 * XXX Also, this can happen for ICMP and other packets
20983 			 * with multicast source addresses.  Perhaps we should
20984 			 * fix things so that we drop the packet in question,
20985 			 * but for now, just run with it.
20986 			 */
20987 			ill_t *ill = (ill_t *)q->q_ptr;
20988 
20989 			/*
20990 			 * Don't honor attach_if for this case. If ill
20991 			 * is part of the group, ipif could belong to
20992 			 * any ill and we cannot maintain attach_ill
20993 			 * and ipif_ill same anymore and the assert
20994 			 * below would fail.
20995 			 */
20996 			if (mctl_present && io->ipsec_out_attach_if) {
20997 				io->ipsec_out_ill_index = 0;
20998 				io->ipsec_out_attach_if = B_FALSE;
20999 				ASSERT(attach_ill != NULL);
21000 				ill_refrele(attach_ill);
21001 				attach_ill = NULL;
21002 			}
21003 
21004 			ASSERT(attach_ill == NULL);
21005 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
21006 			if (ipif == NULL) {
21007 				if (need_decref)
21008 					CONN_DEC_REF(connp);
21009 				freemsg(first_mp);
21010 				return;
21011 			}
21012 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
21013 			    ntohl(dst), ill->ill_name));
21014 		} else {
21015 			/*
21016 			 * The order of precedence is IP_BOUND_IF, IP_PKTINFO
21017 			 * and IP_MULTICAST_IF.  The block comment above this
21018 			 * function explains the locking mechanism used here.
21019 			 */
21020 			if (xmit_ill == NULL) {
21021 				xmit_ill = conn_get_held_ill(connp,
21022 				    &connp->conn_outgoing_ill, &err);
21023 				if (err == ILL_LOOKUP_FAILED) {
21024 					ip1dbg(("ip_wput: No ill for "
21025 					    "IP_BOUND_IF\n"));
21026 					BUMP_MIB(&ipst->ips_ip_mib,
21027 					    ipIfStatsOutNoRoutes);
21028 					goto drop_pkt;
21029 				}
21030 			}
21031 
21032 			if (xmit_ill == NULL) {
21033 				ipif = conn_get_held_ipif(connp,
21034 				    &connp->conn_multicast_ipif, &err);
21035 				if (err == IPIF_LOOKUP_FAILED) {
21036 					ip1dbg(("ip_wput: No ipif for "
21037 					    "multicast\n"));
21038 					BUMP_MIB(&ipst->ips_ip_mib,
21039 					    ipIfStatsOutNoRoutes);
21040 					goto drop_pkt;
21041 				}
21042 			}
21043 			if (xmit_ill != NULL) {
21044 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21045 				if (ipif == NULL) {
21046 					ip1dbg(("ip_wput: No ipif for "
21047 					    "xmit_ill\n"));
21048 					BUMP_MIB(&ipst->ips_ip_mib,
21049 					    ipIfStatsOutNoRoutes);
21050 					goto drop_pkt;
21051 				}
21052 			} else if (ipif == NULL || ipif->ipif_isv6) {
21053 				/*
21054 				 * We must do this ipif determination here
21055 				 * else we could pass through ip_newroute
21056 				 * and come back here without the conn context.
21057 				 *
21058 				 * Note: we do late binding i.e. we bind to
21059 				 * the interface when the first packet is sent.
21060 				 * For performance reasons we do not rebind on
21061 				 * each packet but keep the binding until the
21062 				 * next IP_MULTICAST_IF option.
21063 				 *
21064 				 * conn_multicast_{ipif,ill} are shared between
21065 				 * IPv4 and IPv6 and AF_INET6 sockets can
21066 				 * send both IPv4 and IPv6 packets. Hence
21067 				 * we have to check that "isv6" matches above.
21068 				 */
21069 				if (ipif != NULL)
21070 					ipif_refrele(ipif);
21071 				ipif = ipif_lookup_group(dst, zoneid, ipst);
21072 				if (ipif == NULL) {
21073 					ip1dbg(("ip_wput: No ipif for "
21074 					    "multicast\n"));
21075 					BUMP_MIB(&ipst->ips_ip_mib,
21076 					    ipIfStatsOutNoRoutes);
21077 					goto drop_pkt;
21078 				}
21079 				err = conn_set_held_ipif(connp,
21080 				    &connp->conn_multicast_ipif, ipif);
21081 				if (err == IPIF_LOOKUP_FAILED) {
21082 					ipif_refrele(ipif);
21083 					ip1dbg(("ip_wput: No ipif for "
21084 					    "multicast\n"));
21085 					BUMP_MIB(&ipst->ips_ip_mib,
21086 					    ipIfStatsOutNoRoutes);
21087 					goto drop_pkt;
21088 				}
21089 			}
21090 		}
21091 		ASSERT(!ipif->ipif_isv6);
21092 		/*
21093 		 * As we may lose the conn by the time we reach ip_wput_ire,
21094 		 * we copy conn_multicast_loop and conn_dontroute on to an
21095 		 * ipsec_out. In case if this datagram goes out secure,
21096 		 * we need the ill_index also. Copy that also into the
21097 		 * ipsec_out.
21098 		 */
21099 		if (mctl_present) {
21100 			io = (ipsec_out_t *)first_mp->b_rptr;
21101 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21102 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21103 		} else {
21104 			ASSERT(mp == first_mp);
21105 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21106 			    BPRI_HI)) == NULL) {
21107 				ipif_refrele(ipif);
21108 				first_mp = mp;
21109 				goto discard_pkt;
21110 			}
21111 			first_mp->b_datap->db_type = M_CTL;
21112 			first_mp->b_wptr += sizeof (ipsec_info_t);
21113 			/* ipsec_out_secure is B_FALSE now */
21114 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21115 			io = (ipsec_out_t *)first_mp->b_rptr;
21116 			io->ipsec_out_type = IPSEC_OUT;
21117 			io->ipsec_out_len = sizeof (ipsec_out_t);
21118 			io->ipsec_out_use_global_policy = B_TRUE;
21119 			io->ipsec_out_ns = ipst->ips_netstack;
21120 			first_mp->b_cont = mp;
21121 			mctl_present = B_TRUE;
21122 		}
21123 		if (attach_ill != NULL) {
21124 			ASSERT(attach_ill == ipif->ipif_ill);
21125 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21126 
21127 			/*
21128 			 * Check if we need an ire that will not be
21129 			 * looked up by anybody else i.e. HIDDEN.
21130 			 */
21131 			if (ill_is_probeonly(attach_ill)) {
21132 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21133 			}
21134 			io->ipsec_out_ill_index =
21135 			    attach_ill->ill_phyint->phyint_ifindex;
21136 			io->ipsec_out_attach_if = B_TRUE;
21137 		} else {
21138 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21139 			io->ipsec_out_ill_index =
21140 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21141 		}
21142 		if (connp != NULL) {
21143 			io->ipsec_out_multicast_loop =
21144 			    connp->conn_multicast_loop;
21145 			io->ipsec_out_dontroute = connp->conn_dontroute;
21146 			io->ipsec_out_zoneid = connp->conn_zoneid;
21147 		}
21148 		/*
21149 		 * If the application uses IP_MULTICAST_IF with
21150 		 * different logical addresses of the same ILL, we
21151 		 * need to make sure that the soruce address of
21152 		 * the packet matches the logical IP address used
21153 		 * in the option. We do it by initializing ipha_src
21154 		 * here. This should keep IPsec also happy as
21155 		 * when we return from IPsec processing, we don't
21156 		 * have to worry about getting the right address on
21157 		 * the packet. Thus it is sufficient to look for
21158 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21159 		 * MATCH_IRE_IPIF.
21160 		 *
21161 		 * NOTE : We need to do it for non-secure case also as
21162 		 * this might go out secure if there is a global policy
21163 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
21164 		 * address, the source should be initialized already and
21165 		 * hence we won't be initializing here.
21166 		 *
21167 		 * As we do not have the ire yet, it is possible that
21168 		 * we set the source address here and then later discover
21169 		 * that the ire implies the source address to be assigned
21170 		 * through the RTF_SETSRC flag.
21171 		 * In that case, the setsrc variable will remind us
21172 		 * that overwritting the source address by the one
21173 		 * of the RTF_SETSRC-flagged ire is allowed.
21174 		 */
21175 		if (ipha->ipha_src == INADDR_ANY &&
21176 		    (connp == NULL || !connp->conn_unspec_src)) {
21177 			ipha->ipha_src = ipif->ipif_src_addr;
21178 			setsrc = RTF_SETSRC;
21179 		}
21180 		/*
21181 		 * Find an IRE which matches the destination and the outgoing
21182 		 * queue (i.e. the outgoing interface.)
21183 		 * For loopback use a unicast IP address for
21184 		 * the ire lookup.
21185 		 */
21186 		if (IS_LOOPBACK(ipif->ipif_ill))
21187 			dst = ipif->ipif_lcl_addr;
21188 
21189 		/*
21190 		 * If xmit_ill is set, we branch out to ip_newroute_ipif.
21191 		 * We don't need to lookup ire in ctable as the packet
21192 		 * needs to be sent to the destination through the specified
21193 		 * ill irrespective of ires in the cache table.
21194 		 */
21195 		ire = NULL;
21196 		if (xmit_ill == NULL) {
21197 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21198 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21199 		}
21200 
21201 		/*
21202 		 * refrele attach_ill as its not needed anymore.
21203 		 */
21204 		if (attach_ill != NULL) {
21205 			ill_refrele(attach_ill);
21206 			attach_ill = NULL;
21207 		}
21208 
21209 		if (ire == NULL) {
21210 			/*
21211 			 * Multicast loopback and multicast forwarding is
21212 			 * done in ip_wput_ire.
21213 			 *
21214 			 * Mark this packet to make it be delivered to
21215 			 * ip_wput_ire after the new ire has been
21216 			 * created.
21217 			 *
21218 			 * The call to ip_newroute_ipif takes into account
21219 			 * the setsrc reminder. In any case, we take care
21220 			 * of the RTF_MULTIRT flag.
21221 			 */
21222 			mp->b_prev = mp->b_next = NULL;
21223 			if (xmit_ill == NULL ||
21224 			    xmit_ill->ill_ipif_up_count > 0) {
21225 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21226 				    setsrc | RTF_MULTIRT, zoneid, infop);
21227 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21228 				    "ip_wput_end: q %p (%S)", q, "noire");
21229 			} else {
21230 				freemsg(first_mp);
21231 			}
21232 			ipif_refrele(ipif);
21233 			if (xmit_ill != NULL)
21234 				ill_refrele(xmit_ill);
21235 			if (need_decref)
21236 				CONN_DEC_REF(connp);
21237 			return;
21238 		}
21239 
21240 		ipif_refrele(ipif);
21241 		ipif = NULL;
21242 		ASSERT(xmit_ill == NULL);
21243 
21244 		/*
21245 		 * Honor the RTF_SETSRC flag for multicast packets,
21246 		 * if allowed by the setsrc reminder.
21247 		 */
21248 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21249 			ipha->ipha_src = ire->ire_src_addr;
21250 		}
21251 
21252 		/*
21253 		 * Unconditionally force the TTL to 1 for
21254 		 * multirouted multicast packets:
21255 		 * multirouted multicast should not cross
21256 		 * multicast routers.
21257 		 */
21258 		if (ire->ire_flags & RTF_MULTIRT) {
21259 			if (ipha->ipha_ttl > 1) {
21260 				ip2dbg(("ip_wput: forcing multicast "
21261 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21262 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21263 				ipha->ipha_ttl = 1;
21264 			}
21265 		}
21266 	} else {
21267 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
21268 		if ((ire != NULL) && (ire->ire_type &
21269 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21270 			ignore_dontroute = B_TRUE;
21271 			ignore_nexthop = B_TRUE;
21272 		}
21273 		if (ire != NULL) {
21274 			ire_refrele(ire);
21275 			ire = NULL;
21276 		}
21277 		/*
21278 		 * Guard against coming in from arp in which case conn is NULL.
21279 		 * Also guard against non M_DATA with dontroute set but
21280 		 * destined to local, loopback or broadcast addresses.
21281 		 */
21282 		if (connp != NULL && connp->conn_dontroute &&
21283 		    !ignore_dontroute) {
21284 dontroute:
21285 			/*
21286 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21287 			 * routing protocols from seeing false direct
21288 			 * connectivity.
21289 			 */
21290 			ipha->ipha_ttl = 1;
21291 
21292 			/* If suitable ipif not found, drop packet */
21293 			dst_ipif = ipif_lookup_onlink_addr(dst, zoneid, ipst);
21294 			if (dst_ipif == NULL) {
21295 noroute:
21296 				ip1dbg(("ip_wput: no route for dst using"
21297 				    " SO_DONTROUTE\n"));
21298 				BUMP_MIB(&ipst->ips_ip_mib,
21299 				    ipIfStatsOutNoRoutes);
21300 				mp->b_prev = mp->b_next = NULL;
21301 				if (first_mp == NULL)
21302 					first_mp = mp;
21303 				goto drop_pkt;
21304 			} else {
21305 				/*
21306 				 * If suitable ipif has been found, set
21307 				 * xmit_ill to the corresponding
21308 				 * ipif_ill because we'll be using the
21309 				 * send_from_ill logic below.
21310 				 */
21311 				ASSERT(xmit_ill == NULL);
21312 				xmit_ill = dst_ipif->ipif_ill;
21313 				mutex_enter(&xmit_ill->ill_lock);
21314 				if (!ILL_CAN_LOOKUP(xmit_ill)) {
21315 					mutex_exit(&xmit_ill->ill_lock);
21316 					xmit_ill = NULL;
21317 					ipif_refrele(dst_ipif);
21318 					goto noroute;
21319 				}
21320 				ill_refhold_locked(xmit_ill);
21321 				mutex_exit(&xmit_ill->ill_lock);
21322 				ipif_refrele(dst_ipif);
21323 			}
21324 		}
21325 		/*
21326 		 * If we are bound to IPIF_NOFAILOVER address, look for
21327 		 * an IRE_CACHE matching the ill.
21328 		 */
21329 send_from_ill:
21330 		if (attach_ill != NULL) {
21331 			ipif_t	*attach_ipif;
21332 
21333 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21334 
21335 			/*
21336 			 * Check if we need an ire that will not be
21337 			 * looked up by anybody else i.e. HIDDEN.
21338 			 */
21339 			if (ill_is_probeonly(attach_ill)) {
21340 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21341 			}
21342 
21343 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
21344 			if (attach_ipif == NULL) {
21345 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
21346 				goto discard_pkt;
21347 			}
21348 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
21349 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21350 			ipif_refrele(attach_ipif);
21351 		} else if (xmit_ill != NULL) {
21352 			ipif_t *ipif;
21353 
21354 			/*
21355 			 * Mark this packet as originated locally
21356 			 */
21357 			mp->b_prev = mp->b_next = NULL;
21358 
21359 			/*
21360 			 * Could be SO_DONTROUTE case also.
21361 			 * Verify that at least one ipif is up on the ill.
21362 			 */
21363 			if (xmit_ill->ill_ipif_up_count == 0) {
21364 				ip1dbg(("ip_output: xmit_ill %s is down\n",
21365 				    xmit_ill->ill_name));
21366 				goto drop_pkt;
21367 			}
21368 
21369 			ipif = ipif_get_next_ipif(NULL, xmit_ill);
21370 			if (ipif == NULL) {
21371 				ip1dbg(("ip_output: xmit_ill %s NULL ipif\n",
21372 				    xmit_ill->ill_name));
21373 				goto drop_pkt;
21374 			}
21375 
21376 			/*
21377 			 * Look for a ire that is part of the group,
21378 			 * if found use it else call ip_newroute_ipif.
21379 			 * IPCL_ZONEID is not used for matching because
21380 			 * IP_ALLZONES option is valid only when the
21381 			 * ill is accessible from all zones i.e has a
21382 			 * valid ipif in all zones.
21383 			 */
21384 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21385 			ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21386 			    MBLK_GETLABEL(mp), match_flags, ipst);
21387 			/*
21388 			 * If an ire exists use it or else create
21389 			 * an ire but don't add it to the cache.
21390 			 * Adding an ire may cause issues with
21391 			 * asymmetric routing.
21392 			 * In case of multiroute always act as if
21393 			 * ire does not exist.
21394 			 */
21395 			if (ire == NULL || ire->ire_flags & RTF_MULTIRT) {
21396 				if (ire != NULL)
21397 					ire_refrele(ire);
21398 				ip_newroute_ipif(q, first_mp, ipif,
21399 				    dst, connp, 0, zoneid, infop);
21400 				ipif_refrele(ipif);
21401 				ip1dbg(("ip_output: xmit_ill via %s\n",
21402 				    xmit_ill->ill_name));
21403 				ill_refrele(xmit_ill);
21404 				if (need_decref)
21405 					CONN_DEC_REF(connp);
21406 				return;
21407 			}
21408 			ipif_refrele(ipif);
21409 		} else if (ip_nexthop || (connp != NULL &&
21410 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21411 			if (!ip_nexthop) {
21412 				ip_nexthop = B_TRUE;
21413 				nexthop_addr = connp->conn_nexthop_v4;
21414 			}
21415 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21416 			    MATCH_IRE_GW;
21417 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21418 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21419 		} else {
21420 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp),
21421 			    ipst);
21422 		}
21423 		if (!ire) {
21424 			/*
21425 			 * Make sure we don't load spread if this
21426 			 * is IPIF_NOFAILOVER case.
21427 			 */
21428 			if ((attach_ill != NULL) ||
21429 			    (ip_nexthop && !ignore_nexthop)) {
21430 				if (mctl_present) {
21431 					io = (ipsec_out_t *)first_mp->b_rptr;
21432 					ASSERT(first_mp->b_datap->db_type ==
21433 					    M_CTL);
21434 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21435 				} else {
21436 					ASSERT(mp == first_mp);
21437 					first_mp = allocb(
21438 					    sizeof (ipsec_info_t), BPRI_HI);
21439 					if (first_mp == NULL) {
21440 						first_mp = mp;
21441 						goto discard_pkt;
21442 					}
21443 					first_mp->b_datap->db_type = M_CTL;
21444 					first_mp->b_wptr +=
21445 					    sizeof (ipsec_info_t);
21446 					/* ipsec_out_secure is B_FALSE now */
21447 					bzero(first_mp->b_rptr,
21448 					    sizeof (ipsec_info_t));
21449 					io = (ipsec_out_t *)first_mp->b_rptr;
21450 					io->ipsec_out_type = IPSEC_OUT;
21451 					io->ipsec_out_len =
21452 					    sizeof (ipsec_out_t);
21453 					io->ipsec_out_use_global_policy =
21454 					    B_TRUE;
21455 					io->ipsec_out_ns = ipst->ips_netstack;
21456 					first_mp->b_cont = mp;
21457 					mctl_present = B_TRUE;
21458 				}
21459 				if (attach_ill != NULL) {
21460 					io->ipsec_out_ill_index = attach_ill->
21461 					    ill_phyint->phyint_ifindex;
21462 					io->ipsec_out_attach_if = B_TRUE;
21463 				} else {
21464 					io->ipsec_out_ip_nexthop = ip_nexthop;
21465 					io->ipsec_out_nexthop_addr =
21466 					    nexthop_addr;
21467 				}
21468 			}
21469 noirefound:
21470 			/*
21471 			 * Mark this packet as having originated on
21472 			 * this machine.  This will be noted in
21473 			 * ire_add_then_send, which needs to know
21474 			 * whether to run it back through ip_wput or
21475 			 * ip_rput following successful resolution.
21476 			 */
21477 			mp->b_prev = NULL;
21478 			mp->b_next = NULL;
21479 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21480 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21481 			    "ip_wput_end: q %p (%S)", q, "newroute");
21482 			if (attach_ill != NULL)
21483 				ill_refrele(attach_ill);
21484 			if (xmit_ill != NULL)
21485 				ill_refrele(xmit_ill);
21486 			if (need_decref)
21487 				CONN_DEC_REF(connp);
21488 			return;
21489 		}
21490 	}
21491 
21492 	/* We now know where we are going with it. */
21493 
21494 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21495 	    "ip_wput_end: q %p (%S)", q, "end");
21496 
21497 	/*
21498 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21499 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21500 	 */
21501 	if (ire->ire_flags & RTF_MULTIRT) {
21502 		/*
21503 		 * Force the TTL of multirouted packets if required.
21504 		 * The TTL of such packets is bounded by the
21505 		 * ip_multirt_ttl ndd variable.
21506 		 */
21507 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21508 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21509 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21510 			    "(was %d), dst 0x%08x\n",
21511 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21512 			    ntohl(ire->ire_addr)));
21513 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21514 		}
21515 		/*
21516 		 * At this point, we check to see if there are any pending
21517 		 * unresolved routes. ire_multirt_resolvable()
21518 		 * checks in O(n) that all IRE_OFFSUBNET ire
21519 		 * entries for the packet's destination and
21520 		 * flagged RTF_MULTIRT are currently resolved.
21521 		 * If some remain unresolved, we make a copy
21522 		 * of the current message. It will be used
21523 		 * to initiate additional route resolutions.
21524 		 */
21525 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21526 		    MBLK_GETLABEL(first_mp), ipst);
21527 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21528 		    "multirt_need_resolve %d, first_mp %p\n",
21529 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21530 		if (multirt_need_resolve) {
21531 			copy_mp = copymsg(first_mp);
21532 			if (copy_mp != NULL) {
21533 				MULTIRT_DEBUG_TAG(copy_mp);
21534 			}
21535 		}
21536 	}
21537 
21538 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21539 	/*
21540 	 * Try to resolve another multiroute if
21541 	 * ire_multirt_resolvable() deemed it necessary.
21542 	 * At this point, we need to distinguish
21543 	 * multicasts from other packets. For multicasts,
21544 	 * we call ip_newroute_ipif() and request that both
21545 	 * multirouting and setsrc flags are checked.
21546 	 */
21547 	if (copy_mp != NULL) {
21548 		if (CLASSD(dst)) {
21549 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21550 			if (ipif) {
21551 				ASSERT(infop->ip_opt_ill_index == 0);
21552 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21553 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21554 				ipif_refrele(ipif);
21555 			} else {
21556 				MULTIRT_DEBUG_UNTAG(copy_mp);
21557 				freemsg(copy_mp);
21558 				copy_mp = NULL;
21559 			}
21560 		} else {
21561 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21562 		}
21563 	}
21564 	if (attach_ill != NULL)
21565 		ill_refrele(attach_ill);
21566 	if (xmit_ill != NULL)
21567 		ill_refrele(xmit_ill);
21568 	if (need_decref)
21569 		CONN_DEC_REF(connp);
21570 	return;
21571 
21572 icmp_parameter_problem:
21573 	/* could not have originated externally */
21574 	ASSERT(mp->b_prev == NULL);
21575 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21576 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21577 		/* it's the IP header length that's in trouble */
21578 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21579 		first_mp = NULL;
21580 	}
21581 
21582 discard_pkt:
21583 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21584 drop_pkt:
21585 	ip1dbg(("ip_wput: dropped packet\n"));
21586 	if (ire != NULL)
21587 		ire_refrele(ire);
21588 	if (need_decref)
21589 		CONN_DEC_REF(connp);
21590 	freemsg(first_mp);
21591 	if (attach_ill != NULL)
21592 		ill_refrele(attach_ill);
21593 	if (xmit_ill != NULL)
21594 		ill_refrele(xmit_ill);
21595 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21596 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21597 }
21598 
21599 /*
21600  * If this is a conn_t queue, then we pass in the conn. This includes the
21601  * zoneid.
21602  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21603  * in which case we use the global zoneid since those are all part of
21604  * the global zone.
21605  */
21606 void
21607 ip_wput(queue_t *q, mblk_t *mp)
21608 {
21609 	if (CONN_Q(q))
21610 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21611 	else
21612 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21613 }
21614 
21615 /*
21616  *
21617  * The following rules must be observed when accessing any ipif or ill
21618  * that has been cached in the conn. Typically conn_nofailover_ill,
21619  * conn_outgoing_ill, conn_multicast_ipif and conn_multicast_ill.
21620  *
21621  * Access: The ipif or ill pointed to from the conn can be accessed under
21622  * the protection of the conn_lock or after it has been refheld under the
21623  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21624  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21625  * The reason for this is that a concurrent unplumb could actually be
21626  * cleaning up these cached pointers by walking the conns and might have
21627  * finished cleaning up the conn in question. The macros check that an
21628  * unplumb has not yet started on the ipif or ill.
21629  *
21630  * Caching: An ipif or ill pointer may be cached in the conn only after
21631  * making sure that an unplumb has not started. So the caching is done
21632  * while holding both the conn_lock and the ill_lock and after using the
21633  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21634  * flag before starting the cleanup of conns.
21635  *
21636  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21637  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21638  * or a reference to the ipif or a reference to an ire that references the
21639  * ipif. An ipif does not change its ill except for failover/failback. Since
21640  * failover/failback happens only after bringing down the ipif and making sure
21641  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
21642  * the above holds.
21643  */
21644 ipif_t *
21645 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21646 {
21647 	ipif_t	*ipif;
21648 	ill_t	*ill;
21649 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21650 
21651 	*err = 0;
21652 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21653 	mutex_enter(&connp->conn_lock);
21654 	ipif = *ipifp;
21655 	if (ipif != NULL) {
21656 		ill = ipif->ipif_ill;
21657 		mutex_enter(&ill->ill_lock);
21658 		if (IPIF_CAN_LOOKUP(ipif)) {
21659 			ipif_refhold_locked(ipif);
21660 			mutex_exit(&ill->ill_lock);
21661 			mutex_exit(&connp->conn_lock);
21662 			rw_exit(&ipst->ips_ill_g_lock);
21663 			return (ipif);
21664 		} else {
21665 			*err = IPIF_LOOKUP_FAILED;
21666 		}
21667 		mutex_exit(&ill->ill_lock);
21668 	}
21669 	mutex_exit(&connp->conn_lock);
21670 	rw_exit(&ipst->ips_ill_g_lock);
21671 	return (NULL);
21672 }
21673 
21674 ill_t *
21675 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21676 {
21677 	ill_t	*ill;
21678 
21679 	*err = 0;
21680 	mutex_enter(&connp->conn_lock);
21681 	ill = *illp;
21682 	if (ill != NULL) {
21683 		mutex_enter(&ill->ill_lock);
21684 		if (ILL_CAN_LOOKUP(ill)) {
21685 			ill_refhold_locked(ill);
21686 			mutex_exit(&ill->ill_lock);
21687 			mutex_exit(&connp->conn_lock);
21688 			return (ill);
21689 		} else {
21690 			*err = ILL_LOOKUP_FAILED;
21691 		}
21692 		mutex_exit(&ill->ill_lock);
21693 	}
21694 	mutex_exit(&connp->conn_lock);
21695 	return (NULL);
21696 }
21697 
21698 static int
21699 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21700 {
21701 	ill_t	*ill;
21702 
21703 	ill = ipif->ipif_ill;
21704 	mutex_enter(&connp->conn_lock);
21705 	mutex_enter(&ill->ill_lock);
21706 	if (IPIF_CAN_LOOKUP(ipif)) {
21707 		*ipifp = ipif;
21708 		mutex_exit(&ill->ill_lock);
21709 		mutex_exit(&connp->conn_lock);
21710 		return (0);
21711 	}
21712 	mutex_exit(&ill->ill_lock);
21713 	mutex_exit(&connp->conn_lock);
21714 	return (IPIF_LOOKUP_FAILED);
21715 }
21716 
21717 /*
21718  * This is called if the outbound datagram needs fragmentation.
21719  *
21720  * NOTE : This function does not ire_refrele the ire argument passed in.
21721  */
21722 static void
21723 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21724     ip_stack_t *ipst)
21725 {
21726 	ipha_t		*ipha;
21727 	mblk_t		*mp;
21728 	uint32_t	v_hlen_tos_len;
21729 	uint32_t	max_frag;
21730 	uint32_t	frag_flag;
21731 	boolean_t	dont_use;
21732 
21733 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21734 		mp = ipsec_mp->b_cont;
21735 	} else {
21736 		mp = ipsec_mp;
21737 	}
21738 
21739 	ipha = (ipha_t *)mp->b_rptr;
21740 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21741 
21742 #ifdef	_BIG_ENDIAN
21743 #define	V_HLEN	(v_hlen_tos_len >> 24)
21744 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21745 #else
21746 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21747 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21748 #endif
21749 
21750 #ifndef SPEED_BEFORE_SAFETY
21751 	/*
21752 	 * Check that ipha_length is consistent with
21753 	 * the mblk length
21754 	 */
21755 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21756 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21757 		    LENGTH, msgdsize(mp)));
21758 		freemsg(ipsec_mp);
21759 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21760 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21761 		    "packet length mismatch");
21762 		return;
21763 	}
21764 #endif
21765 	/*
21766 	 * Don't use frag_flag if pre-built packet or source
21767 	 * routed or if multicast (since multicast packets do not solicit
21768 	 * ICMP "packet too big" messages). Get the values of
21769 	 * max_frag and frag_flag atomically by acquiring the
21770 	 * ire_lock.
21771 	 */
21772 	mutex_enter(&ire->ire_lock);
21773 	max_frag = ire->ire_max_frag;
21774 	frag_flag = ire->ire_frag_flag;
21775 	mutex_exit(&ire->ire_lock);
21776 
21777 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21778 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21779 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21780 
21781 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21782 	    (dont_use ? 0 : frag_flag), zoneid, ipst);
21783 }
21784 
21785 /*
21786  * Used for deciding the MSS size for the upper layer. Thus
21787  * we need to check the outbound policy values in the conn.
21788  */
21789 int
21790 conn_ipsec_length(conn_t *connp)
21791 {
21792 	ipsec_latch_t *ipl;
21793 
21794 	ipl = connp->conn_latch;
21795 	if (ipl == NULL)
21796 		return (0);
21797 
21798 	if (ipl->ipl_out_policy == NULL)
21799 		return (0);
21800 
21801 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21802 }
21803 
21804 /*
21805  * Returns an estimate of the IPsec headers size. This is used if
21806  * we don't want to call into IPsec to get the exact size.
21807  */
21808 int
21809 ipsec_out_extra_length(mblk_t *ipsec_mp)
21810 {
21811 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21812 	ipsec_action_t *a;
21813 
21814 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21815 	if (!io->ipsec_out_secure)
21816 		return (0);
21817 
21818 	a = io->ipsec_out_act;
21819 
21820 	if (a == NULL) {
21821 		ASSERT(io->ipsec_out_policy != NULL);
21822 		a = io->ipsec_out_policy->ipsp_act;
21823 	}
21824 	ASSERT(a != NULL);
21825 
21826 	return (a->ipa_ovhd);
21827 }
21828 
21829 /*
21830  * Returns an estimate of the IPsec headers size. This is used if
21831  * we don't want to call into IPsec to get the exact size.
21832  */
21833 int
21834 ipsec_in_extra_length(mblk_t *ipsec_mp)
21835 {
21836 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21837 	ipsec_action_t *a;
21838 
21839 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21840 
21841 	a = ii->ipsec_in_action;
21842 	return (a == NULL ? 0 : a->ipa_ovhd);
21843 }
21844 
21845 /*
21846  * If there are any source route options, return the true final
21847  * destination. Otherwise, return the destination.
21848  */
21849 ipaddr_t
21850 ip_get_dst(ipha_t *ipha)
21851 {
21852 	ipoptp_t	opts;
21853 	uchar_t		*opt;
21854 	uint8_t		optval;
21855 	uint8_t		optlen;
21856 	ipaddr_t	dst;
21857 	uint32_t off;
21858 
21859 	dst = ipha->ipha_dst;
21860 
21861 	if (IS_SIMPLE_IPH(ipha))
21862 		return (dst);
21863 
21864 	for (optval = ipoptp_first(&opts, ipha);
21865 	    optval != IPOPT_EOL;
21866 	    optval = ipoptp_next(&opts)) {
21867 		opt = opts.ipoptp_cur;
21868 		optlen = opts.ipoptp_len;
21869 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21870 		switch (optval) {
21871 		case IPOPT_SSRR:
21872 		case IPOPT_LSRR:
21873 			off = opt[IPOPT_OFFSET];
21874 			/*
21875 			 * If one of the conditions is true, it means
21876 			 * end of options and dst already has the right
21877 			 * value.
21878 			 */
21879 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21880 				off = optlen - IP_ADDR_LEN;
21881 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21882 			}
21883 			return (dst);
21884 		default:
21885 			break;
21886 		}
21887 	}
21888 
21889 	return (dst);
21890 }
21891 
21892 mblk_t *
21893 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21894     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21895 {
21896 	ipsec_out_t	*io;
21897 	mblk_t		*first_mp;
21898 	boolean_t policy_present;
21899 	ip_stack_t	*ipst;
21900 	ipsec_stack_t	*ipss;
21901 
21902 	ASSERT(ire != NULL);
21903 	ipst = ire->ire_ipst;
21904 	ipss = ipst->ips_netstack->netstack_ipsec;
21905 
21906 	first_mp = mp;
21907 	if (mp->b_datap->db_type == M_CTL) {
21908 		io = (ipsec_out_t *)first_mp->b_rptr;
21909 		/*
21910 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21911 		 *
21912 		 * 1) There is per-socket policy (including cached global
21913 		 *    policy) or a policy on the IP-in-IP tunnel.
21914 		 * 2) There is no per-socket policy, but it is
21915 		 *    a multicast packet that needs to go out
21916 		 *    on a specific interface. This is the case
21917 		 *    where (ip_wput and ip_wput_multicast) attaches
21918 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21919 		 *
21920 		 * In case (2) we check with global policy to
21921 		 * see if there is a match and set the ill_index
21922 		 * appropriately so that we can lookup the ire
21923 		 * properly in ip_wput_ipsec_out.
21924 		 */
21925 
21926 		/*
21927 		 * ipsec_out_use_global_policy is set to B_FALSE
21928 		 * in ipsec_in_to_out(). Refer to that function for
21929 		 * details.
21930 		 */
21931 		if ((io->ipsec_out_latch == NULL) &&
21932 		    (io->ipsec_out_use_global_policy)) {
21933 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21934 			    ire, connp, unspec_src, zoneid));
21935 		}
21936 		if (!io->ipsec_out_secure) {
21937 			/*
21938 			 * If this is not a secure packet, drop
21939 			 * the IPSEC_OUT mp and treat it as a clear
21940 			 * packet. This happens when we are sending
21941 			 * a ICMP reply back to a clear packet. See
21942 			 * ipsec_in_to_out() for details.
21943 			 */
21944 			mp = first_mp->b_cont;
21945 			freeb(first_mp);
21946 		}
21947 		return (mp);
21948 	}
21949 	/*
21950 	 * See whether we need to attach a global policy here. We
21951 	 * don't depend on the conn (as it could be null) for deciding
21952 	 * what policy this datagram should go through because it
21953 	 * should have happened in ip_wput if there was some
21954 	 * policy. This normally happens for connections which are not
21955 	 * fully bound preventing us from caching policies in
21956 	 * ip_bind. Packets coming from the TCP listener/global queue
21957 	 * - which are non-hard_bound - could also be affected by
21958 	 * applying policy here.
21959 	 *
21960 	 * If this packet is coming from tcp global queue or listener,
21961 	 * we will be applying policy here.  This may not be *right*
21962 	 * if these packets are coming from the detached connection as
21963 	 * it could have gone in clear before. This happens only if a
21964 	 * TCP connection started when there is no policy and somebody
21965 	 * added policy before it became detached. Thus packets of the
21966 	 * detached connection could go out secure and the other end
21967 	 * would drop it because it will be expecting in clear. The
21968 	 * converse is not true i.e if somebody starts a TCP
21969 	 * connection and deletes the policy, all the packets will
21970 	 * still go out with the policy that existed before deleting
21971 	 * because ip_unbind sends up policy information which is used
21972 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21973 	 * TCP to attach a dummy IPSEC_OUT and set
21974 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21975 	 * affect performance for normal cases, we are not doing it.
21976 	 * Thus, set policy before starting any TCP connections.
21977 	 *
21978 	 * NOTE - We might apply policy even for a hard bound connection
21979 	 * - for which we cached policy in ip_bind - if somebody added
21980 	 * global policy after we inherited the policy in ip_bind.
21981 	 * This means that the packets that were going out in clear
21982 	 * previously would start going secure and hence get dropped
21983 	 * on the other side. To fix this, TCP attaches a dummy
21984 	 * ipsec_out and make sure that we don't apply global policy.
21985 	 */
21986 	if (ipha != NULL)
21987 		policy_present = ipss->ipsec_outbound_v4_policy_present;
21988 	else
21989 		policy_present = ipss->ipsec_outbound_v6_policy_present;
21990 	if (!policy_present)
21991 		return (mp);
21992 
21993 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21994 	    zoneid));
21995 }
21996 
21997 ire_t *
21998 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
21999 {
22000 	ipaddr_t addr;
22001 	ire_t *save_ire;
22002 	irb_t *irb;
22003 	ill_group_t *illgrp;
22004 	int	err;
22005 
22006 	save_ire = ire;
22007 	addr = ire->ire_addr;
22008 
22009 	ASSERT(ire->ire_type == IRE_BROADCAST);
22010 
22011 	illgrp = connp->conn_outgoing_ill->ill_group;
22012 	if (illgrp == NULL) {
22013 		*conn_outgoing_ill = conn_get_held_ill(connp,
22014 		    &connp->conn_outgoing_ill, &err);
22015 		if (err == ILL_LOOKUP_FAILED) {
22016 			ire_refrele(save_ire);
22017 			return (NULL);
22018 		}
22019 		return (save_ire);
22020 	}
22021 	/*
22022 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
22023 	 * If it is part of the group, we need to send on the ire
22024 	 * that has been cleared of IRE_MARK_NORECV and that belongs
22025 	 * to this group. This is okay as IP_BOUND_IF really means
22026 	 * any ill in the group. We depend on the fact that the
22027 	 * first ire in the group is always cleared of IRE_MARK_NORECV
22028 	 * if such an ire exists. This is possible only if you have
22029 	 * at least one ill in the group that has not failed.
22030 	 *
22031 	 * First get to the ire that matches the address and group.
22032 	 *
22033 	 * We don't look for an ire with a matching zoneid because a given zone
22034 	 * won't always have broadcast ires on all ills in the group.
22035 	 */
22036 	irb = ire->ire_bucket;
22037 	rw_enter(&irb->irb_lock, RW_READER);
22038 	if (ire->ire_marks & IRE_MARK_NORECV) {
22039 		/*
22040 		 * If the current zone only has an ire broadcast for this
22041 		 * address marked NORECV, the ire we want is ahead in the
22042 		 * bucket, so we look it up deliberately ignoring the zoneid.
22043 		 */
22044 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
22045 			if (ire->ire_addr != addr)
22046 				continue;
22047 			/* skip over deleted ires */
22048 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
22049 				continue;
22050 		}
22051 	}
22052 	while (ire != NULL) {
22053 		/*
22054 		 * If a new interface is coming up, we could end up
22055 		 * seeing the loopback ire and the non-loopback ire
22056 		 * may not have been added yet. So check for ire_stq
22057 		 */
22058 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
22059 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
22060 			break;
22061 		}
22062 		ire = ire->ire_next;
22063 	}
22064 	if (ire != NULL && ire->ire_addr == addr &&
22065 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
22066 		IRE_REFHOLD(ire);
22067 		rw_exit(&irb->irb_lock);
22068 		ire_refrele(save_ire);
22069 		*conn_outgoing_ill = ire_to_ill(ire);
22070 		/*
22071 		 * Refhold the ill to make the conn_outgoing_ill
22072 		 * independent of the ire. ip_wput_ire goes in a loop
22073 		 * and may refrele the ire. Since we have an ire at this
22074 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
22075 		 */
22076 		ill_refhold(*conn_outgoing_ill);
22077 		return (ire);
22078 	}
22079 	rw_exit(&irb->irb_lock);
22080 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
22081 	/*
22082 	 * If we can't find a suitable ire, return the original ire.
22083 	 */
22084 	return (save_ire);
22085 }
22086 
22087 /*
22088  * This function does the ire_refrele of the ire passed in as the
22089  * argument. As this function looks up more ires i.e broadcast ires,
22090  * it needs to REFRELE them. Currently, for simplicity we don't
22091  * differentiate the one passed in and looked up here. We always
22092  * REFRELE.
22093  * IPQoS Notes:
22094  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
22095  * IPsec packets are done in ipsec_out_process.
22096  *
22097  */
22098 void
22099 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
22100     zoneid_t zoneid)
22101 {
22102 	ipha_t		*ipha;
22103 #define	rptr	((uchar_t *)ipha)
22104 	queue_t		*stq;
22105 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
22106 	uint32_t	v_hlen_tos_len;
22107 	uint32_t	ttl_protocol;
22108 	ipaddr_t	src;
22109 	ipaddr_t	dst;
22110 	uint32_t	cksum;
22111 	ipaddr_t	orig_src;
22112 	ire_t		*ire1;
22113 	mblk_t		*next_mp;
22114 	uint_t		hlen;
22115 	uint16_t	*up;
22116 	uint32_t	max_frag = ire->ire_max_frag;
22117 	ill_t		*ill = ire_to_ill(ire);
22118 	int		clusterwide;
22119 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
22120 	int		ipsec_len;
22121 	mblk_t		*first_mp;
22122 	ipsec_out_t	*io;
22123 	boolean_t	conn_dontroute;		/* conn value for multicast */
22124 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
22125 	boolean_t	multicast_forward;	/* Should we forward ? */
22126 	boolean_t	unspec_src;
22127 	ill_t		*conn_outgoing_ill = NULL;
22128 	ill_t		*ire_ill;
22129 	ill_t		*ire1_ill;
22130 	ill_t		*out_ill;
22131 	uint32_t 	ill_index = 0;
22132 	boolean_t	multirt_send = B_FALSE;
22133 	int		err;
22134 	ipxmit_state_t	pktxmit_state;
22135 	ip_stack_t	*ipst = ire->ire_ipst;
22136 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22137 
22138 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22139 	    "ip_wput_ire_start: q %p", q);
22140 
22141 	multicast_forward = B_FALSE;
22142 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22143 
22144 	if (ire->ire_flags & RTF_MULTIRT) {
22145 		/*
22146 		 * Multirouting case. The bucket where ire is stored
22147 		 * probably holds other RTF_MULTIRT flagged ire
22148 		 * to the destination. In this call to ip_wput_ire,
22149 		 * we attempt to send the packet through all
22150 		 * those ires. Thus, we first ensure that ire is the
22151 		 * first RTF_MULTIRT ire in the bucket,
22152 		 * before walking the ire list.
22153 		 */
22154 		ire_t *first_ire;
22155 		irb_t *irb = ire->ire_bucket;
22156 		ASSERT(irb != NULL);
22157 
22158 		/* Make sure we do not omit any multiroute ire. */
22159 		IRB_REFHOLD(irb);
22160 		for (first_ire = irb->irb_ire;
22161 		    first_ire != NULL;
22162 		    first_ire = first_ire->ire_next) {
22163 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22164 			    (first_ire->ire_addr == ire->ire_addr) &&
22165 			    !(first_ire->ire_marks &
22166 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
22167 				break;
22168 			}
22169 		}
22170 
22171 		if ((first_ire != NULL) && (first_ire != ire)) {
22172 			IRE_REFHOLD(first_ire);
22173 			ire_refrele(ire);
22174 			ire = first_ire;
22175 			ill = ire_to_ill(ire);
22176 		}
22177 		IRB_REFRELE(irb);
22178 	}
22179 
22180 	/*
22181 	 * conn_outgoing_ill variable is used only in the broadcast loop.
22182 	 * for performance we don't grab the mutexs in the fastpath
22183 	 */
22184 	if ((connp != NULL) &&
22185 	    (ire->ire_type == IRE_BROADCAST) &&
22186 	    ((connp->conn_nofailover_ill != NULL) ||
22187 	    (connp->conn_outgoing_ill != NULL))) {
22188 		/*
22189 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
22190 		 * option. So, see if this endpoint is bound to a
22191 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
22192 		 * that if the interface is failed, we will still send
22193 		 * the packet on the same ill which is what we want.
22194 		 */
22195 		conn_outgoing_ill = conn_get_held_ill(connp,
22196 		    &connp->conn_nofailover_ill, &err);
22197 		if (err == ILL_LOOKUP_FAILED) {
22198 			ire_refrele(ire);
22199 			freemsg(mp);
22200 			return;
22201 		}
22202 		if (conn_outgoing_ill == NULL) {
22203 			/*
22204 			 * Choose a good ill in the group to send the
22205 			 * packets on.
22206 			 */
22207 			ire = conn_set_outgoing_ill(connp, ire,
22208 			    &conn_outgoing_ill);
22209 			if (ire == NULL) {
22210 				freemsg(mp);
22211 				return;
22212 			}
22213 		}
22214 	}
22215 
22216 	if (mp->b_datap->db_type != M_CTL) {
22217 		ipha = (ipha_t *)mp->b_rptr;
22218 	} else {
22219 		io = (ipsec_out_t *)mp->b_rptr;
22220 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22221 		ASSERT(zoneid == io->ipsec_out_zoneid);
22222 		ASSERT(zoneid != ALL_ZONES);
22223 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22224 		dst = ipha->ipha_dst;
22225 		/*
22226 		 * For the multicast case, ipsec_out carries conn_dontroute and
22227 		 * conn_multicast_loop as conn may not be available here. We
22228 		 * need this for multicast loopback and forwarding which is done
22229 		 * later in the code.
22230 		 */
22231 		if (CLASSD(dst)) {
22232 			conn_dontroute = io->ipsec_out_dontroute;
22233 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22234 			/*
22235 			 * If conn_dontroute is not set or conn_multicast_loop
22236 			 * is set, we need to do forwarding/loopback. For
22237 			 * datagrams from ip_wput_multicast, conn_dontroute is
22238 			 * set to B_TRUE and conn_multicast_loop is set to
22239 			 * B_FALSE so that we neither do forwarding nor
22240 			 * loopback.
22241 			 */
22242 			if (!conn_dontroute || conn_multicast_loop)
22243 				multicast_forward = B_TRUE;
22244 		}
22245 	}
22246 
22247 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22248 	    ire->ire_zoneid != ALL_ZONES) {
22249 		/*
22250 		 * When a zone sends a packet to another zone, we try to deliver
22251 		 * the packet under the same conditions as if the destination
22252 		 * was a real node on the network. To do so, we look for a
22253 		 * matching route in the forwarding table.
22254 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22255 		 * ip_newroute() does.
22256 		 * Note that IRE_LOCAL are special, since they are used
22257 		 * when the zoneid doesn't match in some cases. This means that
22258 		 * we need to handle ipha_src differently since ire_src_addr
22259 		 * belongs to the receiving zone instead of the sending zone.
22260 		 * When ip_restrict_interzone_loopback is set, then
22261 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22262 		 * for loopback between zones when the logical "Ethernet" would
22263 		 * have looped them back.
22264 		 */
22265 		ire_t *src_ire;
22266 
22267 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22268 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22269 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22270 		if (src_ire != NULL &&
22271 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22272 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22273 		    ire_local_same_ill_group(ire, src_ire))) {
22274 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22275 				ipha->ipha_src = src_ire->ire_src_addr;
22276 			ire_refrele(src_ire);
22277 		} else {
22278 			ire_refrele(ire);
22279 			if (conn_outgoing_ill != NULL)
22280 				ill_refrele(conn_outgoing_ill);
22281 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22282 			if (src_ire != NULL) {
22283 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22284 					ire_refrele(src_ire);
22285 					freemsg(mp);
22286 					return;
22287 				}
22288 				ire_refrele(src_ire);
22289 			}
22290 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22291 				/* Failed */
22292 				freemsg(mp);
22293 				return;
22294 			}
22295 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22296 			    ipst);
22297 			return;
22298 		}
22299 	}
22300 
22301 	if (mp->b_datap->db_type == M_CTL ||
22302 	    ipss->ipsec_outbound_v4_policy_present) {
22303 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22304 		    unspec_src, zoneid);
22305 		if (mp == NULL) {
22306 			ire_refrele(ire);
22307 			if (conn_outgoing_ill != NULL)
22308 				ill_refrele(conn_outgoing_ill);
22309 			return;
22310 		}
22311 		/*
22312 		 * Trusted Extensions supports all-zones interfaces, so
22313 		 * zoneid == ALL_ZONES is valid, but IPsec maps ALL_ZONES to
22314 		 * the global zone.
22315 		 */
22316 		if (zoneid == ALL_ZONES && mp->b_datap->db_type == M_CTL) {
22317 			io = (ipsec_out_t *)mp->b_rptr;
22318 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
22319 			zoneid = io->ipsec_out_zoneid;
22320 		}
22321 	}
22322 
22323 	first_mp = mp;
22324 	ipsec_len = 0;
22325 
22326 	if (first_mp->b_datap->db_type == M_CTL) {
22327 		io = (ipsec_out_t *)first_mp->b_rptr;
22328 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22329 		mp = first_mp->b_cont;
22330 		ipsec_len = ipsec_out_extra_length(first_mp);
22331 		ASSERT(ipsec_len >= 0);
22332 		/* We already picked up the zoneid from the M_CTL above */
22333 		ASSERT(zoneid == io->ipsec_out_zoneid);
22334 		ASSERT(zoneid != ALL_ZONES);
22335 
22336 		/*
22337 		 * Drop M_CTL here if IPsec processing is not needed.
22338 		 * (Non-IPsec use of M_CTL extracted any information it
22339 		 * needed above).
22340 		 */
22341 		if (ipsec_len == 0) {
22342 			freeb(first_mp);
22343 			first_mp = mp;
22344 		}
22345 	}
22346 
22347 	/*
22348 	 * Fast path for ip_wput_ire
22349 	 */
22350 
22351 	ipha = (ipha_t *)mp->b_rptr;
22352 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22353 	dst = ipha->ipha_dst;
22354 
22355 	/*
22356 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22357 	 * if the socket is a SOCK_RAW type. The transport checksum should
22358 	 * be provided in the pre-built packet, so we don't need to compute it.
22359 	 * Also, other application set flags, like DF, should not be altered.
22360 	 * Other transport MUST pass down zero.
22361 	 */
22362 	ip_hdr_included = ipha->ipha_ident;
22363 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22364 
22365 	if (CLASSD(dst)) {
22366 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22367 		    ntohl(dst),
22368 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22369 		    ntohl(ire->ire_addr)));
22370 	}
22371 
22372 /* Macros to extract header fields from data already in registers */
22373 #ifdef	_BIG_ENDIAN
22374 #define	V_HLEN	(v_hlen_tos_len >> 24)
22375 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22376 #define	PROTO	(ttl_protocol & 0xFF)
22377 #else
22378 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22379 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22380 #define	PROTO	(ttl_protocol >> 8)
22381 #endif
22382 
22383 
22384 	orig_src = src = ipha->ipha_src;
22385 	/* (The loop back to "another" is explained down below.) */
22386 another:;
22387 	/*
22388 	 * Assign an ident value for this packet.  We assign idents on
22389 	 * a per destination basis out of the IRE.  There could be
22390 	 * other threads targeting the same destination, so we have to
22391 	 * arrange for a atomic increment.  Note that we use a 32-bit
22392 	 * atomic add because it has better performance than its
22393 	 * 16-bit sibling.
22394 	 *
22395 	 * If running in cluster mode and if the source address
22396 	 * belongs to a replicated service then vector through
22397 	 * cl_inet_ipident vector to allocate ip identifier
22398 	 * NOTE: This is a contract private interface with the
22399 	 * clustering group.
22400 	 */
22401 	clusterwide = 0;
22402 	if (cl_inet_ipident) {
22403 		ASSERT(cl_inet_isclusterwide);
22404 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
22405 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
22406 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
22407 			    AF_INET, (uint8_t *)(uintptr_t)src,
22408 			    (uint8_t *)(uintptr_t)dst);
22409 			clusterwide = 1;
22410 		}
22411 	}
22412 	if (!clusterwide) {
22413 		ipha->ipha_ident =
22414 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22415 	}
22416 
22417 #ifndef _BIG_ENDIAN
22418 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22419 #endif
22420 
22421 	/*
22422 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22423 	 * This is needed to obey conn_unspec_src when packets go through
22424 	 * ip_newroute + arp.
22425 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22426 	 */
22427 	if (src == INADDR_ANY && !unspec_src) {
22428 		/*
22429 		 * Assign the appropriate source address from the IRE if none
22430 		 * was specified.
22431 		 */
22432 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22433 
22434 		/*
22435 		 * With IP multipathing, broadcast packets are sent on the ire
22436 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
22437 		 * the group. However, this ire might not be in the same zone so
22438 		 * we can't always use its source address. We look for a
22439 		 * broadcast ire in the same group and in the right zone.
22440 		 */
22441 		if (ire->ire_type == IRE_BROADCAST &&
22442 		    ire->ire_zoneid != zoneid) {
22443 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
22444 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
22445 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
22446 			if (src_ire != NULL) {
22447 				src = src_ire->ire_src_addr;
22448 				ire_refrele(src_ire);
22449 			} else {
22450 				ire_refrele(ire);
22451 				if (conn_outgoing_ill != NULL)
22452 					ill_refrele(conn_outgoing_ill);
22453 				freemsg(first_mp);
22454 				if (ill != NULL) {
22455 					BUMP_MIB(ill->ill_ip_mib,
22456 					    ipIfStatsOutDiscards);
22457 				} else {
22458 					BUMP_MIB(&ipst->ips_ip_mib,
22459 					    ipIfStatsOutDiscards);
22460 				}
22461 				return;
22462 			}
22463 		} else {
22464 			src = ire->ire_src_addr;
22465 		}
22466 
22467 		if (connp == NULL) {
22468 			ip1dbg(("ip_wput_ire: no connp and no src "
22469 			    "address for dst 0x%x, using src 0x%x\n",
22470 			    ntohl(dst),
22471 			    ntohl(src)));
22472 		}
22473 		ipha->ipha_src = src;
22474 	}
22475 	stq = ire->ire_stq;
22476 
22477 	/*
22478 	 * We only allow ire chains for broadcasts since there will
22479 	 * be multiple IRE_CACHE entries for the same multicast
22480 	 * address (one per ipif).
22481 	 */
22482 	next_mp = NULL;
22483 
22484 	/* broadcast packet */
22485 	if (ire->ire_type == IRE_BROADCAST)
22486 		goto broadcast;
22487 
22488 	/* loopback ? */
22489 	if (stq == NULL)
22490 		goto nullstq;
22491 
22492 	/* The ill_index for outbound ILL */
22493 	ill_index = Q_TO_INDEX(stq);
22494 
22495 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22496 	ttl_protocol = ((uint16_t *)ipha)[4];
22497 
22498 	/* pseudo checksum (do it in parts for IP header checksum) */
22499 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22500 
22501 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22502 		queue_t *dev_q = stq->q_next;
22503 
22504 		/* flow controlled */
22505 		if ((dev_q->q_next || dev_q->q_first) &&
22506 		    !canput(dev_q))
22507 			goto blocked;
22508 		if ((PROTO == IPPROTO_UDP) &&
22509 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22510 			hlen = (V_HLEN & 0xF) << 2;
22511 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22512 			if (*up != 0) {
22513 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22514 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22515 				/* Software checksum? */
22516 				if (DB_CKSUMFLAGS(mp) == 0) {
22517 					IP_STAT(ipst, ip_out_sw_cksum);
22518 					IP_STAT_UPDATE(ipst,
22519 					    ip_udp_out_sw_cksum_bytes,
22520 					    LENGTH - hlen);
22521 				}
22522 			}
22523 		}
22524 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22525 		hlen = (V_HLEN & 0xF) << 2;
22526 		if (PROTO == IPPROTO_TCP) {
22527 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22528 			/*
22529 			 * The packet header is processed once and for all, even
22530 			 * in the multirouting case. We disable hardware
22531 			 * checksum if the packet is multirouted, as it will be
22532 			 * replicated via several interfaces, and not all of
22533 			 * them may have this capability.
22534 			 */
22535 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22536 			    LENGTH, max_frag, ipsec_len, cksum);
22537 			/* Software checksum? */
22538 			if (DB_CKSUMFLAGS(mp) == 0) {
22539 				IP_STAT(ipst, ip_out_sw_cksum);
22540 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22541 				    LENGTH - hlen);
22542 			}
22543 		} else {
22544 			sctp_hdr_t	*sctph;
22545 
22546 			ASSERT(PROTO == IPPROTO_SCTP);
22547 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22548 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22549 			/*
22550 			 * Zero out the checksum field to ensure proper
22551 			 * checksum calculation.
22552 			 */
22553 			sctph->sh_chksum = 0;
22554 #ifdef	DEBUG
22555 			if (!skip_sctp_cksum)
22556 #endif
22557 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22558 		}
22559 	}
22560 
22561 	/*
22562 	 * If this is a multicast packet and originated from ip_wput
22563 	 * we need to do loopback and forwarding checks. If it comes
22564 	 * from ip_wput_multicast, we SHOULD not do this.
22565 	 */
22566 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22567 
22568 	/* checksum */
22569 	cksum += ttl_protocol;
22570 
22571 	/* fragment the packet */
22572 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22573 		goto fragmentit;
22574 	/*
22575 	 * Don't use frag_flag if packet is pre-built or source
22576 	 * routed or if multicast (since multicast packets do
22577 	 * not solicit ICMP "packet too big" messages).
22578 	 */
22579 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22580 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22581 	    !ip_source_route_included(ipha)) &&
22582 	    !CLASSD(ipha->ipha_dst))
22583 		ipha->ipha_fragment_offset_and_flags |=
22584 		    htons(ire->ire_frag_flag);
22585 
22586 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22587 		/* calculate IP header checksum */
22588 		cksum += ipha->ipha_ident;
22589 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22590 		cksum += ipha->ipha_fragment_offset_and_flags;
22591 
22592 		/* IP options present */
22593 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22594 		if (hlen)
22595 			goto checksumoptions;
22596 
22597 		/* calculate hdr checksum */
22598 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22599 		cksum = ~(cksum + (cksum >> 16));
22600 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22601 	}
22602 	if (ipsec_len != 0) {
22603 		/*
22604 		 * We will do the rest of the processing after
22605 		 * we come back from IPsec in ip_wput_ipsec_out().
22606 		 */
22607 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22608 
22609 		io = (ipsec_out_t *)first_mp->b_rptr;
22610 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
22611 		    ill_phyint->phyint_ifindex;
22612 
22613 		ipsec_out_process(q, first_mp, ire, ill_index);
22614 		ire_refrele(ire);
22615 		if (conn_outgoing_ill != NULL)
22616 			ill_refrele(conn_outgoing_ill);
22617 		return;
22618 	}
22619 
22620 	/*
22621 	 * In most cases, the emission loop below is entered only
22622 	 * once. Only in the case where the ire holds the
22623 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22624 	 * flagged ires in the bucket, and send the packet
22625 	 * through all crossed RTF_MULTIRT routes.
22626 	 */
22627 	if (ire->ire_flags & RTF_MULTIRT) {
22628 		multirt_send = B_TRUE;
22629 	}
22630 	do {
22631 		if (multirt_send) {
22632 			irb_t *irb;
22633 			/*
22634 			 * We are in a multiple send case, need to get
22635 			 * the next ire and make a duplicate of the packet.
22636 			 * ire1 holds here the next ire to process in the
22637 			 * bucket. If multirouting is expected,
22638 			 * any non-RTF_MULTIRT ire that has the
22639 			 * right destination address is ignored.
22640 			 */
22641 			irb = ire->ire_bucket;
22642 			ASSERT(irb != NULL);
22643 
22644 			IRB_REFHOLD(irb);
22645 			for (ire1 = ire->ire_next;
22646 			    ire1 != NULL;
22647 			    ire1 = ire1->ire_next) {
22648 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22649 					continue;
22650 				if (ire1->ire_addr != ire->ire_addr)
22651 					continue;
22652 				if (ire1->ire_marks &
22653 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22654 					continue;
22655 
22656 				/* Got one */
22657 				IRE_REFHOLD(ire1);
22658 				break;
22659 			}
22660 			IRB_REFRELE(irb);
22661 
22662 			if (ire1 != NULL) {
22663 				next_mp = copyb(mp);
22664 				if ((next_mp == NULL) ||
22665 				    ((mp->b_cont != NULL) &&
22666 				    ((next_mp->b_cont =
22667 				    dupmsg(mp->b_cont)) == NULL))) {
22668 					freemsg(next_mp);
22669 					next_mp = NULL;
22670 					ire_refrele(ire1);
22671 					ire1 = NULL;
22672 				}
22673 			}
22674 
22675 			/* Last multiroute ire; don't loop anymore. */
22676 			if (ire1 == NULL) {
22677 				multirt_send = B_FALSE;
22678 			}
22679 		}
22680 
22681 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22682 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22683 		    mblk_t *, mp);
22684 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22685 		    ipst->ips_ipv4firewall_physical_out,
22686 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, 0, ipst);
22687 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22688 		if (mp == NULL)
22689 			goto release_ire_and_ill;
22690 
22691 		if (ipst->ips_ipobs_enabled) {
22692 			zoneid_t szone;
22693 
22694 			/*
22695 			 * On the outbound path the destination zone will be
22696 			 * unknown as we're sending this packet out on the
22697 			 * wire.
22698 			 */
22699 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
22700 			    ALL_ZONES);
22701 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
22702 			    ire->ire_ipif->ipif_ill, IPV4_VERSION, 0, ipst);
22703 		}
22704 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22705 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22706 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
22707 		if ((pktxmit_state == SEND_FAILED) ||
22708 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22709 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22710 			    "- packet dropped\n"));
22711 release_ire_and_ill:
22712 			ire_refrele(ire);
22713 			if (next_mp != NULL) {
22714 				freemsg(next_mp);
22715 				ire_refrele(ire1);
22716 			}
22717 			if (conn_outgoing_ill != NULL)
22718 				ill_refrele(conn_outgoing_ill);
22719 			return;
22720 		}
22721 
22722 		if (CLASSD(dst)) {
22723 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22724 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22725 			    LENGTH);
22726 		}
22727 
22728 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22729 		    "ip_wput_ire_end: q %p (%S)",
22730 		    q, "last copy out");
22731 		IRE_REFRELE(ire);
22732 
22733 		if (multirt_send) {
22734 			ASSERT(ire1);
22735 			/*
22736 			 * Proceed with the next RTF_MULTIRT ire,
22737 			 * Also set up the send-to queue accordingly.
22738 			 */
22739 			ire = ire1;
22740 			ire1 = NULL;
22741 			stq = ire->ire_stq;
22742 			mp = next_mp;
22743 			next_mp = NULL;
22744 			ipha = (ipha_t *)mp->b_rptr;
22745 			ill_index = Q_TO_INDEX(stq);
22746 			ill = (ill_t *)stq->q_ptr;
22747 		}
22748 	} while (multirt_send);
22749 	if (conn_outgoing_ill != NULL)
22750 		ill_refrele(conn_outgoing_ill);
22751 	return;
22752 
22753 	/*
22754 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22755 	 */
22756 broadcast:
22757 	{
22758 		/*
22759 		 * To avoid broadcast storms, we usually set the TTL to 1 for
22760 		 * broadcasts.  However, if SO_DONTROUTE isn't set, this value
22761 		 * can be overridden stack-wide through the ip_broadcast_ttl
22762 		 * ndd tunable, or on a per-connection basis through the
22763 		 * IP_BROADCAST_TTL socket option.
22764 		 *
22765 		 * In the event that we are replying to incoming ICMP packets,
22766 		 * connp could be NULL.
22767 		 */
22768 		ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22769 		if (connp != NULL) {
22770 			if (connp->conn_dontroute)
22771 				ipha->ipha_ttl = 1;
22772 			else if (connp->conn_broadcast_ttl != 0)
22773 				ipha->ipha_ttl = connp->conn_broadcast_ttl;
22774 		}
22775 
22776 		/*
22777 		 * Note that we are not doing a IRB_REFHOLD here.
22778 		 * Actually we don't care if the list changes i.e
22779 		 * if somebody deletes an IRE from the list while
22780 		 * we drop the lock, the next time we come around
22781 		 * ire_next will be NULL and hence we won't send
22782 		 * out multiple copies which is fine.
22783 		 */
22784 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22785 		ire1 = ire->ire_next;
22786 		if (conn_outgoing_ill != NULL) {
22787 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22788 				ASSERT(ire1 == ire->ire_next);
22789 				if (ire1 != NULL && ire1->ire_addr == dst) {
22790 					ire_refrele(ire);
22791 					ire = ire1;
22792 					IRE_REFHOLD(ire);
22793 					ire1 = ire->ire_next;
22794 					continue;
22795 				}
22796 				rw_exit(&ire->ire_bucket->irb_lock);
22797 				/* Did not find a matching ill */
22798 				ip1dbg(("ip_wput_ire: broadcast with no "
22799 				    "matching IP_BOUND_IF ill %s dst %x\n",
22800 				    conn_outgoing_ill->ill_name, dst));
22801 				freemsg(first_mp);
22802 				if (ire != NULL)
22803 					ire_refrele(ire);
22804 				ill_refrele(conn_outgoing_ill);
22805 				return;
22806 			}
22807 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22808 			/*
22809 			 * If the next IRE has the same address and is not one
22810 			 * of the two copies that we need to send, try to see
22811 			 * whether this copy should be sent at all. This
22812 			 * assumes that we insert loopbacks first and then
22813 			 * non-loopbacks. This is acheived by inserting the
22814 			 * loopback always before non-loopback.
22815 			 * This is used to send a single copy of a broadcast
22816 			 * packet out all physical interfaces that have an
22817 			 * matching IRE_BROADCAST while also looping
22818 			 * back one copy (to ip_wput_local) for each
22819 			 * matching physical interface. However, we avoid
22820 			 * sending packets out different logical that match by
22821 			 * having ipif_up/ipif_down supress duplicate
22822 			 * IRE_BROADCASTS.
22823 			 *
22824 			 * This feature is currently used to get broadcasts
22825 			 * sent to multiple interfaces, when the broadcast
22826 			 * address being used applies to multiple interfaces.
22827 			 * For example, a whole net broadcast will be
22828 			 * replicated on every connected subnet of
22829 			 * the target net.
22830 			 *
22831 			 * Each zone has its own set of IRE_BROADCASTs, so that
22832 			 * we're able to distribute inbound packets to multiple
22833 			 * zones who share a broadcast address. We avoid looping
22834 			 * back outbound packets in different zones but on the
22835 			 * same ill, as the application would see duplicates.
22836 			 *
22837 			 * If the interfaces are part of the same group,
22838 			 * we would want to send only one copy out for
22839 			 * whole group.
22840 			 *
22841 			 * This logic assumes that ire_add_v4() groups the
22842 			 * IRE_BROADCAST entries so that those with the same
22843 			 * ire_addr and ill_group are kept together.
22844 			 */
22845 			ire_ill = ire->ire_ipif->ipif_ill;
22846 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22847 				if (ire_ill->ill_group != NULL &&
22848 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22849 					/*
22850 					 * If the current zone only has an ire
22851 					 * broadcast for this address marked
22852 					 * NORECV, the ire we want is ahead in
22853 					 * the bucket, so we look it up
22854 					 * deliberately ignoring the zoneid.
22855 					 */
22856 					for (ire1 = ire->ire_bucket->irb_ire;
22857 					    ire1 != NULL;
22858 					    ire1 = ire1->ire_next) {
22859 						ire1_ill =
22860 						    ire1->ire_ipif->ipif_ill;
22861 						if (ire1->ire_addr != dst)
22862 							continue;
22863 						/* skip over the current ire */
22864 						if (ire1 == ire)
22865 							continue;
22866 						/* skip over deleted ires */
22867 						if (ire1->ire_marks &
22868 						    IRE_MARK_CONDEMNED)
22869 							continue;
22870 						/*
22871 						 * non-loopback ire in our
22872 						 * group: use it for the next
22873 						 * pass in the loop
22874 						 */
22875 						if (ire1->ire_stq != NULL &&
22876 						    ire1_ill->ill_group ==
22877 						    ire_ill->ill_group)
22878 							break;
22879 					}
22880 				}
22881 			} else {
22882 				while (ire1 != NULL && ire1->ire_addr == dst) {
22883 					ire1_ill = ire1->ire_ipif->ipif_ill;
22884 					/*
22885 					 * We can have two broadcast ires on the
22886 					 * same ill in different zones; here
22887 					 * we'll send a copy of the packet on
22888 					 * each ill and the fanout code will
22889 					 * call conn_wantpacket() to check that
22890 					 * the zone has the broadcast address
22891 					 * configured on the ill. If the two
22892 					 * ires are in the same group we only
22893 					 * send one copy up.
22894 					 */
22895 					if (ire1_ill != ire_ill &&
22896 					    (ire1_ill->ill_group == NULL ||
22897 					    ire_ill->ill_group == NULL ||
22898 					    ire1_ill->ill_group !=
22899 					    ire_ill->ill_group)) {
22900 						break;
22901 					}
22902 					ire1 = ire1->ire_next;
22903 				}
22904 			}
22905 		}
22906 		ASSERT(multirt_send == B_FALSE);
22907 		if (ire1 != NULL && ire1->ire_addr == dst) {
22908 			if ((ire->ire_flags & RTF_MULTIRT) &&
22909 			    (ire1->ire_flags & RTF_MULTIRT)) {
22910 				/*
22911 				 * We are in the multirouting case.
22912 				 * The message must be sent at least
22913 				 * on both ires. These ires have been
22914 				 * inserted AFTER the standard ones
22915 				 * in ip_rt_add(). There are thus no
22916 				 * other ire entries for the destination
22917 				 * address in the rest of the bucket
22918 				 * that do not have the RTF_MULTIRT
22919 				 * flag. We don't process a copy
22920 				 * of the message here. This will be
22921 				 * done in the final sending loop.
22922 				 */
22923 				multirt_send = B_TRUE;
22924 			} else {
22925 				next_mp = ip_copymsg(first_mp);
22926 				if (next_mp != NULL)
22927 					IRE_REFHOLD(ire1);
22928 			}
22929 		}
22930 		rw_exit(&ire->ire_bucket->irb_lock);
22931 	}
22932 
22933 	if (stq) {
22934 		/*
22935 		 * A non-NULL send-to queue means this packet is going
22936 		 * out of this machine.
22937 		 */
22938 		out_ill = (ill_t *)stq->q_ptr;
22939 
22940 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22941 		ttl_protocol = ((uint16_t *)ipha)[4];
22942 		/*
22943 		 * We accumulate the pseudo header checksum in cksum.
22944 		 * This is pretty hairy code, so watch close.  One
22945 		 * thing to keep in mind is that UDP and TCP have
22946 		 * stored their respective datagram lengths in their
22947 		 * checksum fields.  This lines things up real nice.
22948 		 */
22949 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22950 		    (src >> 16) + (src & 0xFFFF);
22951 		/*
22952 		 * We assume the udp checksum field contains the
22953 		 * length, so to compute the pseudo header checksum,
22954 		 * all we need is the protocol number and src/dst.
22955 		 */
22956 		/* Provide the checksums for UDP and TCP. */
22957 		if ((PROTO == IPPROTO_TCP) &&
22958 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22959 			/* hlen gets the number of uchar_ts in the IP header */
22960 			hlen = (V_HLEN & 0xF) << 2;
22961 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22962 			IP_STAT(ipst, ip_out_sw_cksum);
22963 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22964 			    LENGTH - hlen);
22965 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22966 		} else if (PROTO == IPPROTO_SCTP &&
22967 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22968 			sctp_hdr_t	*sctph;
22969 
22970 			hlen = (V_HLEN & 0xF) << 2;
22971 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22972 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22973 			sctph->sh_chksum = 0;
22974 #ifdef	DEBUG
22975 			if (!skip_sctp_cksum)
22976 #endif
22977 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22978 		} else {
22979 			queue_t *dev_q = stq->q_next;
22980 
22981 			if ((dev_q->q_next || dev_q->q_first) &&
22982 			    !canput(dev_q)) {
22983 blocked:
22984 				ipha->ipha_ident = ip_hdr_included;
22985 				/*
22986 				 * If we don't have a conn to apply
22987 				 * backpressure, free the message.
22988 				 * In the ire_send path, we don't know
22989 				 * the position to requeue the packet. Rather
22990 				 * than reorder packets, we just drop this
22991 				 * packet.
22992 				 */
22993 				if (ipst->ips_ip_output_queue &&
22994 				    connp != NULL &&
22995 				    caller != IRE_SEND) {
22996 					if (caller == IP_WSRV) {
22997 						connp->conn_did_putbq = 1;
22998 						(void) putbq(connp->conn_wq,
22999 						    first_mp);
23000 						conn_drain_insert(connp);
23001 						/*
23002 						 * This is the service thread,
23003 						 * and the queue is already
23004 						 * noenabled. The check for
23005 						 * canput and the putbq is not
23006 						 * atomic. So we need to check
23007 						 * again.
23008 						 */
23009 						if (canput(stq->q_next))
23010 							connp->conn_did_putbq
23011 							    = 0;
23012 						IP_STAT(ipst, ip_conn_flputbq);
23013 					} else {
23014 						/*
23015 						 * We are not the service proc.
23016 						 * ip_wsrv will be scheduled or
23017 						 * is already running.
23018 						 */
23019 						(void) putq(connp->conn_wq,
23020 						    first_mp);
23021 					}
23022 				} else {
23023 					out_ill = (ill_t *)stq->q_ptr;
23024 					BUMP_MIB(out_ill->ill_ip_mib,
23025 					    ipIfStatsOutDiscards);
23026 					freemsg(first_mp);
23027 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23028 					    "ip_wput_ire_end: q %p (%S)",
23029 					    q, "discard");
23030 				}
23031 				ire_refrele(ire);
23032 				if (next_mp) {
23033 					ire_refrele(ire1);
23034 					freemsg(next_mp);
23035 				}
23036 				if (conn_outgoing_ill != NULL)
23037 					ill_refrele(conn_outgoing_ill);
23038 				return;
23039 			}
23040 			if ((PROTO == IPPROTO_UDP) &&
23041 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
23042 				/*
23043 				 * hlen gets the number of uchar_ts in the
23044 				 * IP header
23045 				 */
23046 				hlen = (V_HLEN & 0xF) << 2;
23047 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
23048 				max_frag = ire->ire_max_frag;
23049 				if (*up != 0) {
23050 					IP_CKSUM_XMIT(out_ill, ire, mp, ipha,
23051 					    up, PROTO, hlen, LENGTH, max_frag,
23052 					    ipsec_len, cksum);
23053 					/* Software checksum? */
23054 					if (DB_CKSUMFLAGS(mp) == 0) {
23055 						IP_STAT(ipst, ip_out_sw_cksum);
23056 						IP_STAT_UPDATE(ipst,
23057 						    ip_udp_out_sw_cksum_bytes,
23058 						    LENGTH - hlen);
23059 					}
23060 				}
23061 			}
23062 		}
23063 		/*
23064 		 * Need to do this even when fragmenting. The local
23065 		 * loopback can be done without computing checksums
23066 		 * but forwarding out other interface must be done
23067 		 * after the IP checksum (and ULP checksums) have been
23068 		 * computed.
23069 		 *
23070 		 * NOTE : multicast_forward is set only if this packet
23071 		 * originated from ip_wput. For packets originating from
23072 		 * ip_wput_multicast, it is not set.
23073 		 */
23074 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
23075 multi_loopback:
23076 			ip2dbg(("ip_wput: multicast, loop %d\n",
23077 			    conn_multicast_loop));
23078 
23079 			/*  Forget header checksum offload */
23080 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
23081 
23082 			/*
23083 			 * Local loopback of multicasts?  Check the
23084 			 * ill.
23085 			 *
23086 			 * Note that the loopback function will not come
23087 			 * in through ip_rput - it will only do the
23088 			 * client fanout thus we need to do an mforward
23089 			 * as well.  The is different from the BSD
23090 			 * logic.
23091 			 */
23092 			if (ill != NULL) {
23093 				ilm_t	*ilm;
23094 
23095 				ILM_WALKER_HOLD(ill);
23096 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
23097 				    ALL_ZONES);
23098 				ILM_WALKER_RELE(ill);
23099 				if (ilm != NULL) {
23100 					/*
23101 					 * Pass along the virtual output q.
23102 					 * ip_wput_local() will distribute the
23103 					 * packet to all the matching zones,
23104 					 * except the sending zone when
23105 					 * IP_MULTICAST_LOOP is false.
23106 					 */
23107 					ip_multicast_loopback(q, ill, first_mp,
23108 					    conn_multicast_loop ? 0 :
23109 					    IP_FF_NO_MCAST_LOOP, zoneid);
23110 				}
23111 			}
23112 			if (ipha->ipha_ttl == 0) {
23113 				/*
23114 				 * 0 => only to this host i.e. we are
23115 				 * done. We are also done if this was the
23116 				 * loopback interface since it is sufficient
23117 				 * to loopback one copy of a multicast packet.
23118 				 */
23119 				freemsg(first_mp);
23120 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23121 				    "ip_wput_ire_end: q %p (%S)",
23122 				    q, "loopback");
23123 				ire_refrele(ire);
23124 				if (conn_outgoing_ill != NULL)
23125 					ill_refrele(conn_outgoing_ill);
23126 				return;
23127 			}
23128 			/*
23129 			 * ILLF_MULTICAST is checked in ip_newroute
23130 			 * i.e. we don't need to check it here since
23131 			 * all IRE_CACHEs come from ip_newroute.
23132 			 * For multicast traffic, SO_DONTROUTE is interpreted
23133 			 * to mean only send the packet out the interface
23134 			 * (optionally specified with IP_MULTICAST_IF)
23135 			 * and do not forward it out additional interfaces.
23136 			 * RSVP and the rsvp daemon is an example of a
23137 			 * protocol and user level process that
23138 			 * handles it's own routing. Hence, it uses the
23139 			 * SO_DONTROUTE option to accomplish this.
23140 			 */
23141 
23142 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
23143 			    ill != NULL) {
23144 				/* Unconditionally redo the checksum */
23145 				ipha->ipha_hdr_checksum = 0;
23146 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23147 
23148 				/*
23149 				 * If this needs to go out secure, we need
23150 				 * to wait till we finish the IPsec
23151 				 * processing.
23152 				 */
23153 				if (ipsec_len == 0 &&
23154 				    ip_mforward(ill, ipha, mp)) {
23155 					freemsg(first_mp);
23156 					ip1dbg(("ip_wput: mforward failed\n"));
23157 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23158 					    "ip_wput_ire_end: q %p (%S)",
23159 					    q, "mforward failed");
23160 					ire_refrele(ire);
23161 					if (conn_outgoing_ill != NULL)
23162 						ill_refrele(conn_outgoing_ill);
23163 					return;
23164 				}
23165 			}
23166 		}
23167 		max_frag = ire->ire_max_frag;
23168 		cksum += ttl_protocol;
23169 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23170 			/* No fragmentation required for this one. */
23171 			/*
23172 			 * Don't use frag_flag if packet is pre-built or source
23173 			 * routed or if multicast (since multicast packets do
23174 			 * not solicit ICMP "packet too big" messages).
23175 			 */
23176 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23177 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23178 			    !ip_source_route_included(ipha)) &&
23179 			    !CLASSD(ipha->ipha_dst))
23180 				ipha->ipha_fragment_offset_and_flags |=
23181 				    htons(ire->ire_frag_flag);
23182 
23183 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23184 				/* Complete the IP header checksum. */
23185 				cksum += ipha->ipha_ident;
23186 				cksum += (v_hlen_tos_len >> 16)+
23187 				    (v_hlen_tos_len & 0xFFFF);
23188 				cksum += ipha->ipha_fragment_offset_and_flags;
23189 				hlen = (V_HLEN & 0xF) -
23190 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23191 				if (hlen) {
23192 checksumoptions:
23193 					/*
23194 					 * Account for the IP Options in the IP
23195 					 * header checksum.
23196 					 */
23197 					up = (uint16_t *)(rptr+
23198 					    IP_SIMPLE_HDR_LENGTH);
23199 					do {
23200 						cksum += up[0];
23201 						cksum += up[1];
23202 						up += 2;
23203 					} while (--hlen);
23204 				}
23205 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23206 				cksum = ~(cksum + (cksum >> 16));
23207 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23208 			}
23209 			if (ipsec_len != 0) {
23210 				ipsec_out_process(q, first_mp, ire, ill_index);
23211 				if (!next_mp) {
23212 					ire_refrele(ire);
23213 					if (conn_outgoing_ill != NULL)
23214 						ill_refrele(conn_outgoing_ill);
23215 					return;
23216 				}
23217 				goto next;
23218 			}
23219 
23220 			/*
23221 			 * multirt_send has already been handled
23222 			 * for broadcast, but not yet for multicast
23223 			 * or IP options.
23224 			 */
23225 			if (next_mp == NULL) {
23226 				if (ire->ire_flags & RTF_MULTIRT) {
23227 					multirt_send = B_TRUE;
23228 				}
23229 			}
23230 
23231 			/*
23232 			 * In most cases, the emission loop below is
23233 			 * entered only once. Only in the case where
23234 			 * the ire holds the RTF_MULTIRT flag, do we loop
23235 			 * to process all RTF_MULTIRT ires in the bucket,
23236 			 * and send the packet through all crossed
23237 			 * RTF_MULTIRT routes.
23238 			 */
23239 			do {
23240 				if (multirt_send) {
23241 					irb_t *irb;
23242 
23243 					irb = ire->ire_bucket;
23244 					ASSERT(irb != NULL);
23245 					/*
23246 					 * We are in a multiple send case,
23247 					 * need to get the next IRE and make
23248 					 * a duplicate of the packet.
23249 					 */
23250 					IRB_REFHOLD(irb);
23251 					for (ire1 = ire->ire_next;
23252 					    ire1 != NULL;
23253 					    ire1 = ire1->ire_next) {
23254 						if (!(ire1->ire_flags &
23255 						    RTF_MULTIRT)) {
23256 							continue;
23257 						}
23258 						if (ire1->ire_addr !=
23259 						    ire->ire_addr) {
23260 							continue;
23261 						}
23262 						if (ire1->ire_marks &
23263 						    (IRE_MARK_CONDEMNED|
23264 						    IRE_MARK_HIDDEN)) {
23265 							continue;
23266 						}
23267 
23268 						/* Got one */
23269 						IRE_REFHOLD(ire1);
23270 						break;
23271 					}
23272 					IRB_REFRELE(irb);
23273 
23274 					if (ire1 != NULL) {
23275 						next_mp = copyb(mp);
23276 						if ((next_mp == NULL) ||
23277 						    ((mp->b_cont != NULL) &&
23278 						    ((next_mp->b_cont =
23279 						    dupmsg(mp->b_cont))
23280 						    == NULL))) {
23281 							freemsg(next_mp);
23282 							next_mp = NULL;
23283 							ire_refrele(ire1);
23284 							ire1 = NULL;
23285 						}
23286 					}
23287 
23288 					/*
23289 					 * Last multiroute ire; don't loop
23290 					 * anymore. The emission is over
23291 					 * and next_mp is NULL.
23292 					 */
23293 					if (ire1 == NULL) {
23294 						multirt_send = B_FALSE;
23295 					}
23296 				}
23297 
23298 				out_ill = ire_to_ill(ire);
23299 				DTRACE_PROBE4(ip4__physical__out__start,
23300 				    ill_t *, NULL,
23301 				    ill_t *, out_ill,
23302 				    ipha_t *, ipha, mblk_t *, mp);
23303 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23304 				    ipst->ips_ipv4firewall_physical_out,
23305 				    NULL, out_ill, ipha, mp, mp, 0, ipst);
23306 				DTRACE_PROBE1(ip4__physical__out__end,
23307 				    mblk_t *, mp);
23308 				if (mp == NULL)
23309 					goto release_ire_and_ill_2;
23310 
23311 				ASSERT(ipsec_len == 0);
23312 				mp->b_prev =
23313 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23314 				DTRACE_PROBE2(ip__xmit__2,
23315 				    mblk_t *, mp, ire_t *, ire);
23316 				pktxmit_state = ip_xmit_v4(mp, ire,
23317 				    NULL, B_TRUE);
23318 				if ((pktxmit_state == SEND_FAILED) ||
23319 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23320 release_ire_and_ill_2:
23321 					if (next_mp) {
23322 						freemsg(next_mp);
23323 						ire_refrele(ire1);
23324 					}
23325 					ire_refrele(ire);
23326 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23327 					    "ip_wput_ire_end: q %p (%S)",
23328 					    q, "discard MDATA");
23329 					if (conn_outgoing_ill != NULL)
23330 						ill_refrele(conn_outgoing_ill);
23331 					return;
23332 				}
23333 
23334 				if (CLASSD(dst)) {
23335 					BUMP_MIB(out_ill->ill_ip_mib,
23336 					    ipIfStatsHCOutMcastPkts);
23337 					UPDATE_MIB(out_ill->ill_ip_mib,
23338 					    ipIfStatsHCOutMcastOctets,
23339 					    LENGTH);
23340 				} else if (ire->ire_type == IRE_BROADCAST) {
23341 					BUMP_MIB(out_ill->ill_ip_mib,
23342 					    ipIfStatsHCOutBcastPkts);
23343 				}
23344 
23345 				if (multirt_send) {
23346 					/*
23347 					 * We are in a multiple send case,
23348 					 * need to re-enter the sending loop
23349 					 * using the next ire.
23350 					 */
23351 					ire_refrele(ire);
23352 					ire = ire1;
23353 					stq = ire->ire_stq;
23354 					mp = next_mp;
23355 					next_mp = NULL;
23356 					ipha = (ipha_t *)mp->b_rptr;
23357 					ill_index = Q_TO_INDEX(stq);
23358 				}
23359 			} while (multirt_send);
23360 
23361 			if (!next_mp) {
23362 				/*
23363 				 * Last copy going out (the ultra-common
23364 				 * case).  Note that we intentionally replicate
23365 				 * the putnext rather than calling it before
23366 				 * the next_mp check in hopes of a little
23367 				 * tail-call action out of the compiler.
23368 				 */
23369 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23370 				    "ip_wput_ire_end: q %p (%S)",
23371 				    q, "last copy out(1)");
23372 				ire_refrele(ire);
23373 				if (conn_outgoing_ill != NULL)
23374 					ill_refrele(conn_outgoing_ill);
23375 				return;
23376 			}
23377 			/* More copies going out below. */
23378 		} else {
23379 			int offset;
23380 fragmentit:
23381 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23382 			/*
23383 			 * If this would generate a icmp_frag_needed message,
23384 			 * we need to handle it before we do the IPsec
23385 			 * processing. Otherwise, we need to strip the IPsec
23386 			 * headers before we send up the message to the ULPs
23387 			 * which becomes messy and difficult.
23388 			 */
23389 			if (ipsec_len != 0) {
23390 				if ((max_frag < (unsigned int)(LENGTH +
23391 				    ipsec_len)) && (offset & IPH_DF)) {
23392 					out_ill = (ill_t *)stq->q_ptr;
23393 					BUMP_MIB(out_ill->ill_ip_mib,
23394 					    ipIfStatsOutFragFails);
23395 					BUMP_MIB(out_ill->ill_ip_mib,
23396 					    ipIfStatsOutFragReqds);
23397 					ipha->ipha_hdr_checksum = 0;
23398 					ipha->ipha_hdr_checksum =
23399 					    (uint16_t)ip_csum_hdr(ipha);
23400 					icmp_frag_needed(ire->ire_stq, first_mp,
23401 					    max_frag, zoneid, ipst);
23402 					if (!next_mp) {
23403 						ire_refrele(ire);
23404 						if (conn_outgoing_ill != NULL) {
23405 							ill_refrele(
23406 							    conn_outgoing_ill);
23407 						}
23408 						return;
23409 					}
23410 				} else {
23411 					/*
23412 					 * This won't cause a icmp_frag_needed
23413 					 * message. to be generated. Send it on
23414 					 * the wire. Note that this could still
23415 					 * cause fragmentation and all we
23416 					 * do is the generation of the message
23417 					 * to the ULP if needed before IPsec.
23418 					 */
23419 					if (!next_mp) {
23420 						ipsec_out_process(q, first_mp,
23421 						    ire, ill_index);
23422 						TRACE_2(TR_FAC_IP,
23423 						    TR_IP_WPUT_IRE_END,
23424 						    "ip_wput_ire_end: q %p "
23425 						    "(%S)", q,
23426 						    "last ipsec_out_process");
23427 						ire_refrele(ire);
23428 						if (conn_outgoing_ill != NULL) {
23429 							ill_refrele(
23430 							    conn_outgoing_ill);
23431 						}
23432 						return;
23433 					}
23434 					ipsec_out_process(q, first_mp,
23435 					    ire, ill_index);
23436 				}
23437 			} else {
23438 				/*
23439 				 * Initiate IPPF processing. For
23440 				 * fragmentable packets we finish
23441 				 * all QOS packet processing before
23442 				 * calling:
23443 				 * ip_wput_ire_fragmentit->ip_wput_frag
23444 				 */
23445 
23446 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23447 					ip_process(IPP_LOCAL_OUT, &mp,
23448 					    ill_index);
23449 					if (mp == NULL) {
23450 						out_ill = (ill_t *)stq->q_ptr;
23451 						BUMP_MIB(out_ill->ill_ip_mib,
23452 						    ipIfStatsOutDiscards);
23453 						if (next_mp != NULL) {
23454 							freemsg(next_mp);
23455 							ire_refrele(ire1);
23456 						}
23457 						ire_refrele(ire);
23458 						TRACE_2(TR_FAC_IP,
23459 						    TR_IP_WPUT_IRE_END,
23460 						    "ip_wput_ire: q %p (%S)",
23461 						    q, "discard MDATA");
23462 						if (conn_outgoing_ill != NULL) {
23463 							ill_refrele(
23464 							    conn_outgoing_ill);
23465 						}
23466 						return;
23467 					}
23468 				}
23469 				if (!next_mp) {
23470 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23471 					    "ip_wput_ire_end: q %p (%S)",
23472 					    q, "last fragmentation");
23473 					ip_wput_ire_fragmentit(mp, ire,
23474 					    zoneid, ipst);
23475 					ire_refrele(ire);
23476 					if (conn_outgoing_ill != NULL)
23477 						ill_refrele(conn_outgoing_ill);
23478 					return;
23479 				}
23480 				ip_wput_ire_fragmentit(mp, ire, zoneid, ipst);
23481 			}
23482 		}
23483 	} else {
23484 nullstq:
23485 		/* A NULL stq means the destination address is local. */
23486 		UPDATE_OB_PKT_COUNT(ire);
23487 		ire->ire_last_used_time = lbolt;
23488 		ASSERT(ire->ire_ipif != NULL);
23489 		if (!next_mp) {
23490 			/*
23491 			 * Is there an "in" and "out" for traffic local
23492 			 * to a host (loopback)?  The code in Solaris doesn't
23493 			 * explicitly draw a line in its code for in vs out,
23494 			 * so we've had to draw a line in the sand: ip_wput_ire
23495 			 * is considered to be the "output" side and
23496 			 * ip_wput_local to be the "input" side.
23497 			 */
23498 			out_ill = ire_to_ill(ire);
23499 
23500 			/*
23501 			 * DTrace this as ip:::send.  A blocked packet will
23502 			 * fire the send probe, but not the receive probe.
23503 			 */
23504 			DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23505 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23506 			    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23507 
23508 			DTRACE_PROBE4(ip4__loopback__out__start,
23509 			    ill_t *, NULL, ill_t *, out_ill,
23510 			    ipha_t *, ipha, mblk_t *, first_mp);
23511 
23512 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23513 			    ipst->ips_ipv4firewall_loopback_out,
23514 			    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23515 
23516 			DTRACE_PROBE1(ip4__loopback__out_end,
23517 			    mblk_t *, first_mp);
23518 
23519 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23520 			    "ip_wput_ire_end: q %p (%S)",
23521 			    q, "local address");
23522 
23523 			if (first_mp != NULL)
23524 				ip_wput_local(q, out_ill, ipha,
23525 				    first_mp, ire, 0, ire->ire_zoneid);
23526 			ire_refrele(ire);
23527 			if (conn_outgoing_ill != NULL)
23528 				ill_refrele(conn_outgoing_ill);
23529 			return;
23530 		}
23531 
23532 		out_ill = ire_to_ill(ire);
23533 
23534 		/*
23535 		 * DTrace this as ip:::send.  A blocked packet will fire the
23536 		 * send probe, but not the receive probe.
23537 		 */
23538 		DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23539 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23540 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23541 
23542 		DTRACE_PROBE4(ip4__loopback__out__start,
23543 		    ill_t *, NULL, ill_t *, out_ill,
23544 		    ipha_t *, ipha, mblk_t *, first_mp);
23545 
23546 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23547 		    ipst->ips_ipv4firewall_loopback_out,
23548 		    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23549 
23550 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23551 
23552 		if (first_mp != NULL)
23553 			ip_wput_local(q, out_ill, ipha,
23554 			    first_mp, ire, 0, ire->ire_zoneid);
23555 	}
23556 next:
23557 	/*
23558 	 * More copies going out to additional interfaces.
23559 	 * ire1 has already been held. We don't need the
23560 	 * "ire" anymore.
23561 	 */
23562 	ire_refrele(ire);
23563 	ire = ire1;
23564 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23565 	mp = next_mp;
23566 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23567 	ill = ire_to_ill(ire);
23568 	first_mp = mp;
23569 	if (ipsec_len != 0) {
23570 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23571 		mp = mp->b_cont;
23572 	}
23573 	dst = ire->ire_addr;
23574 	ipha = (ipha_t *)mp->b_rptr;
23575 	/*
23576 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23577 	 * Restore ipha_ident "no checksum" flag.
23578 	 */
23579 	src = orig_src;
23580 	ipha->ipha_ident = ip_hdr_included;
23581 	goto another;
23582 
23583 #undef	rptr
23584 #undef	Q_TO_INDEX
23585 }
23586 
23587 /*
23588  * Routine to allocate a message that is used to notify the ULP about MDT.
23589  * The caller may provide a pointer to the link-layer MDT capabilities,
23590  * or NULL if MDT is to be disabled on the stream.
23591  */
23592 mblk_t *
23593 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23594 {
23595 	mblk_t *mp;
23596 	ip_mdt_info_t *mdti;
23597 	ill_mdt_capab_t *idst;
23598 
23599 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23600 		DB_TYPE(mp) = M_CTL;
23601 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23602 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23603 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23604 		idst = &(mdti->mdt_capab);
23605 
23606 		/*
23607 		 * If the caller provides us with the capability, copy
23608 		 * it over into our notification message; otherwise
23609 		 * we zero out the capability portion.
23610 		 */
23611 		if (isrc != NULL)
23612 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23613 		else
23614 			bzero((caddr_t)idst, sizeof (*idst));
23615 	}
23616 	return (mp);
23617 }
23618 
23619 /*
23620  * Routine which determines whether MDT can be enabled on the destination
23621  * IRE and IPC combination, and if so, allocates and returns the MDT
23622  * notification mblk that may be used by ULP.  We also check if we need to
23623  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23624  * MDT usage in the past have been lifted.  This gets called during IP
23625  * and ULP binding.
23626  */
23627 mblk_t *
23628 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23629     ill_mdt_capab_t *mdt_cap)
23630 {
23631 	mblk_t *mp;
23632 	boolean_t rc = B_FALSE;
23633 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23634 
23635 	ASSERT(dst_ire != NULL);
23636 	ASSERT(connp != NULL);
23637 	ASSERT(mdt_cap != NULL);
23638 
23639 	/*
23640 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23641 	 * Multidata, which is handled in tcp_multisend().  This
23642 	 * is the reason why we do all these checks here, to ensure
23643 	 * that we don't enable Multidata for the cases which we
23644 	 * can't handle at the moment.
23645 	 */
23646 	do {
23647 		/* Only do TCP at the moment */
23648 		if (connp->conn_ulp != IPPROTO_TCP)
23649 			break;
23650 
23651 		/*
23652 		 * IPsec outbound policy present?  Note that we get here
23653 		 * after calling ipsec_conn_cache_policy() where the global
23654 		 * policy checking is performed.  conn_latch will be
23655 		 * non-NULL as long as there's a policy defined,
23656 		 * i.e. conn_out_enforce_policy may be NULL in such case
23657 		 * when the connection is non-secure, and hence we check
23658 		 * further if the latch refers to an outbound policy.
23659 		 */
23660 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23661 			break;
23662 
23663 		/* CGTP (multiroute) is enabled? */
23664 		if (dst_ire->ire_flags & RTF_MULTIRT)
23665 			break;
23666 
23667 		/* Outbound IPQoS enabled? */
23668 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23669 			/*
23670 			 * In this case, we disable MDT for this and all
23671 			 * future connections going over the interface.
23672 			 */
23673 			mdt_cap->ill_mdt_on = 0;
23674 			break;
23675 		}
23676 
23677 		/* socket option(s) present? */
23678 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23679 			break;
23680 
23681 		rc = B_TRUE;
23682 	/* CONSTCOND */
23683 	} while (0);
23684 
23685 	/* Remember the result */
23686 	connp->conn_mdt_ok = rc;
23687 
23688 	if (!rc)
23689 		return (NULL);
23690 	else if (!mdt_cap->ill_mdt_on) {
23691 		/*
23692 		 * If MDT has been previously turned off in the past, and we
23693 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23694 		 * then enable it for this interface.
23695 		 */
23696 		mdt_cap->ill_mdt_on = 1;
23697 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23698 		    "interface %s\n", ill_name));
23699 	}
23700 
23701 	/* Allocate the MDT info mblk */
23702 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23703 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23704 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23705 		return (NULL);
23706 	}
23707 	return (mp);
23708 }
23709 
23710 /*
23711  * Routine to allocate a message that is used to notify the ULP about LSO.
23712  * The caller may provide a pointer to the link-layer LSO capabilities,
23713  * or NULL if LSO is to be disabled on the stream.
23714  */
23715 mblk_t *
23716 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23717 {
23718 	mblk_t *mp;
23719 	ip_lso_info_t *lsoi;
23720 	ill_lso_capab_t *idst;
23721 
23722 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23723 		DB_TYPE(mp) = M_CTL;
23724 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23725 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23726 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23727 		idst = &(lsoi->lso_capab);
23728 
23729 		/*
23730 		 * If the caller provides us with the capability, copy
23731 		 * it over into our notification message; otherwise
23732 		 * we zero out the capability portion.
23733 		 */
23734 		if (isrc != NULL)
23735 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23736 		else
23737 			bzero((caddr_t)idst, sizeof (*idst));
23738 	}
23739 	return (mp);
23740 }
23741 
23742 /*
23743  * Routine which determines whether LSO can be enabled on the destination
23744  * IRE and IPC combination, and if so, allocates and returns the LSO
23745  * notification mblk that may be used by ULP.  We also check if we need to
23746  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23747  * LSO usage in the past have been lifted.  This gets called during IP
23748  * and ULP binding.
23749  */
23750 mblk_t *
23751 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23752     ill_lso_capab_t *lso_cap)
23753 {
23754 	mblk_t *mp;
23755 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23756 
23757 	ASSERT(dst_ire != NULL);
23758 	ASSERT(connp != NULL);
23759 	ASSERT(lso_cap != NULL);
23760 
23761 	connp->conn_lso_ok = B_TRUE;
23762 
23763 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23764 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23765 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23766 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23767 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23768 		connp->conn_lso_ok = B_FALSE;
23769 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23770 			/*
23771 			 * Disable LSO for this and all future connections going
23772 			 * over the interface.
23773 			 */
23774 			lso_cap->ill_lso_on = 0;
23775 		}
23776 	}
23777 
23778 	if (!connp->conn_lso_ok)
23779 		return (NULL);
23780 	else if (!lso_cap->ill_lso_on) {
23781 		/*
23782 		 * If LSO has been previously turned off in the past, and we
23783 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23784 		 * then enable it for this interface.
23785 		 */
23786 		lso_cap->ill_lso_on = 1;
23787 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23788 		    ill_name));
23789 	}
23790 
23791 	/* Allocate the LSO info mblk */
23792 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23793 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23794 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23795 
23796 	return (mp);
23797 }
23798 
23799 /*
23800  * Create destination address attribute, and fill it with the physical
23801  * destination address and SAP taken from the template DL_UNITDATA_REQ
23802  * message block.
23803  */
23804 boolean_t
23805 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23806 {
23807 	dl_unitdata_req_t *dlurp;
23808 	pattr_t *pa;
23809 	pattrinfo_t pa_info;
23810 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23811 	uint_t das_len, das_off;
23812 
23813 	ASSERT(dlmp != NULL);
23814 
23815 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23816 	das_len = dlurp->dl_dest_addr_length;
23817 	das_off = dlurp->dl_dest_addr_offset;
23818 
23819 	pa_info.type = PATTR_DSTADDRSAP;
23820 	pa_info.len = sizeof (**das) + das_len - 1;
23821 
23822 	/* create and associate the attribute */
23823 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23824 	if (pa != NULL) {
23825 		ASSERT(*das != NULL);
23826 		(*das)->addr_is_group = 0;
23827 		(*das)->addr_len = (uint8_t)das_len;
23828 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23829 	}
23830 
23831 	return (pa != NULL);
23832 }
23833 
23834 /*
23835  * Create hardware checksum attribute and fill it with the values passed.
23836  */
23837 boolean_t
23838 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23839     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23840 {
23841 	pattr_t *pa;
23842 	pattrinfo_t pa_info;
23843 
23844 	ASSERT(mmd != NULL);
23845 
23846 	pa_info.type = PATTR_HCKSUM;
23847 	pa_info.len = sizeof (pattr_hcksum_t);
23848 
23849 	/* create and associate the attribute */
23850 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23851 	if (pa != NULL) {
23852 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23853 
23854 		hck->hcksum_start_offset = start_offset;
23855 		hck->hcksum_stuff_offset = stuff_offset;
23856 		hck->hcksum_end_offset = end_offset;
23857 		hck->hcksum_flags = flags;
23858 	}
23859 	return (pa != NULL);
23860 }
23861 
23862 /*
23863  * Create zerocopy attribute and fill it with the specified flags
23864  */
23865 boolean_t
23866 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23867 {
23868 	pattr_t *pa;
23869 	pattrinfo_t pa_info;
23870 
23871 	ASSERT(mmd != NULL);
23872 	pa_info.type = PATTR_ZCOPY;
23873 	pa_info.len = sizeof (pattr_zcopy_t);
23874 
23875 	/* create and associate the attribute */
23876 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23877 	if (pa != NULL) {
23878 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23879 
23880 		zcopy->zcopy_flags = flags;
23881 	}
23882 	return (pa != NULL);
23883 }
23884 
23885 /*
23886  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23887  * block chain. We could rewrite to handle arbitrary message block chains but
23888  * that would make the code complicated and slow. Right now there three
23889  * restrictions:
23890  *
23891  *   1. The first message block must contain the complete IP header and
23892  *	at least 1 byte of payload data.
23893  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23894  *	so that we can use a single Multidata message.
23895  *   3. No frag must be distributed over two or more message blocks so
23896  *	that we don't need more than two packet descriptors per frag.
23897  *
23898  * The above restrictions allow us to support userland applications (which
23899  * will send down a single message block) and NFS over UDP (which will
23900  * send down a chain of at most three message blocks).
23901  *
23902  * We also don't use MDT for payloads with less than or equal to
23903  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23904  */
23905 boolean_t
23906 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23907 {
23908 	int	blocks;
23909 	ssize_t	total, missing, size;
23910 
23911 	ASSERT(mp != NULL);
23912 	ASSERT(hdr_len > 0);
23913 
23914 	size = MBLKL(mp) - hdr_len;
23915 	if (size <= 0)
23916 		return (B_FALSE);
23917 
23918 	/* The first mblk contains the header and some payload. */
23919 	blocks = 1;
23920 	total = size;
23921 	size %= len;
23922 	missing = (size == 0) ? 0 : (len - size);
23923 	mp = mp->b_cont;
23924 
23925 	while (mp != NULL) {
23926 		/*
23927 		 * Give up if we encounter a zero length message block.
23928 		 * In practice, this should rarely happen and therefore
23929 		 * not worth the trouble of freeing and re-linking the
23930 		 * mblk from the chain to handle such case.
23931 		 */
23932 		if ((size = MBLKL(mp)) == 0)
23933 			return (B_FALSE);
23934 
23935 		/* Too many payload buffers for a single Multidata message? */
23936 		if (++blocks > MULTIDATA_MAX_PBUFS)
23937 			return (B_FALSE);
23938 
23939 		total += size;
23940 		/* Is a frag distributed over two or more message blocks? */
23941 		if (missing > size)
23942 			return (B_FALSE);
23943 		size -= missing;
23944 
23945 		size %= len;
23946 		missing = (size == 0) ? 0 : (len - size);
23947 
23948 		mp = mp->b_cont;
23949 	}
23950 
23951 	return (total > ip_wput_frag_mdt_min);
23952 }
23953 
23954 /*
23955  * Outbound IPv4 fragmentation routine using MDT.
23956  */
23957 static void
23958 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23959     uint32_t frag_flag, int offset)
23960 {
23961 	ipha_t		*ipha_orig;
23962 	int		i1, ip_data_end;
23963 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23964 	mblk_t		*hdr_mp, *md_mp = NULL;
23965 	unsigned char	*hdr_ptr, *pld_ptr;
23966 	multidata_t	*mmd;
23967 	ip_pdescinfo_t	pdi;
23968 	ill_t		*ill;
23969 	ip_stack_t	*ipst = ire->ire_ipst;
23970 
23971 	ASSERT(DB_TYPE(mp) == M_DATA);
23972 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23973 
23974 	ill = ire_to_ill(ire);
23975 	ASSERT(ill != NULL);
23976 
23977 	ipha_orig = (ipha_t *)mp->b_rptr;
23978 	mp->b_rptr += sizeof (ipha_t);
23979 
23980 	/* Calculate how many packets we will send out */
23981 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23982 	pkts = (i1 + len - 1) / len;
23983 	ASSERT(pkts > 1);
23984 
23985 	/* Allocate a message block which will hold all the IP Headers. */
23986 	wroff = ipst->ips_ip_wroff_extra;
23987 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23988 
23989 	i1 = pkts * hdr_chunk_len;
23990 	/*
23991 	 * Create the header buffer, Multidata and destination address
23992 	 * and SAP attribute that should be associated with it.
23993 	 */
23994 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23995 	    ((hdr_mp->b_wptr += i1),
23996 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23997 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23998 		freemsg(mp);
23999 		if (md_mp == NULL) {
24000 			freemsg(hdr_mp);
24001 		} else {
24002 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
24003 			freemsg(md_mp);
24004 		}
24005 		IP_STAT(ipst, ip_frag_mdt_allocfail);
24006 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
24007 		return;
24008 	}
24009 	IP_STAT(ipst, ip_frag_mdt_allocd);
24010 
24011 	/*
24012 	 * Add a payload buffer to the Multidata; this operation must not
24013 	 * fail, or otherwise our logic in this routine is broken.  There
24014 	 * is no memory allocation done by the routine, so any returned
24015 	 * failure simply tells us that we've done something wrong.
24016 	 *
24017 	 * A failure tells us that either we're adding the same payload
24018 	 * buffer more than once, or we're trying to add more buffers than
24019 	 * allowed.  None of the above cases should happen, and we panic
24020 	 * because either there's horrible heap corruption, and/or
24021 	 * programming mistake.
24022 	 */
24023 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24024 		goto pbuf_panic;
24025 
24026 	hdr_ptr = hdr_mp->b_rptr;
24027 	pld_ptr = mp->b_rptr;
24028 
24029 	/* Establish the ending byte offset, based on the starting offset. */
24030 	offset <<= 3;
24031 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
24032 	    IP_SIMPLE_HDR_LENGTH;
24033 
24034 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
24035 
24036 	while (pld_ptr < mp->b_wptr) {
24037 		ipha_t		*ipha;
24038 		uint16_t	offset_and_flags;
24039 		uint16_t	ip_len;
24040 		int		error;
24041 
24042 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
24043 		ipha = (ipha_t *)(hdr_ptr + wroff);
24044 		ASSERT(OK_32PTR(ipha));
24045 		*ipha = *ipha_orig;
24046 
24047 		if (ip_data_end - offset > len) {
24048 			offset_and_flags = IPH_MF;
24049 		} else {
24050 			/*
24051 			 * Last frag. Set len to the length of this last piece.
24052 			 */
24053 			len = ip_data_end - offset;
24054 			/* A frag of a frag might have IPH_MF non-zero */
24055 			offset_and_flags =
24056 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24057 			    IPH_MF;
24058 		}
24059 		offset_and_flags |= (uint16_t)(offset >> 3);
24060 		offset_and_flags |= (uint16_t)frag_flag;
24061 		/* Store the offset and flags in the IP header. */
24062 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24063 
24064 		/* Store the length in the IP header. */
24065 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
24066 		ipha->ipha_length = htons(ip_len);
24067 
24068 		/*
24069 		 * Set the IP header checksum.  Note that mp is just
24070 		 * the header, so this is easy to pass to ip_csum.
24071 		 */
24072 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24073 
24074 		DTRACE_IP7(send, mblk_t *, md_mp, conn_t *, NULL, void_ip_t *,
24075 		    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *,
24076 		    NULL, int, 0);
24077 
24078 		/*
24079 		 * Record offset and size of header and data of the next packet
24080 		 * in the multidata message.
24081 		 */
24082 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
24083 		PDESC_PLD_INIT(&pdi);
24084 		i1 = MIN(mp->b_wptr - pld_ptr, len);
24085 		ASSERT(i1 > 0);
24086 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
24087 		if (i1 == len) {
24088 			pld_ptr += len;
24089 		} else {
24090 			i1 = len - i1;
24091 			mp = mp->b_cont;
24092 			ASSERT(mp != NULL);
24093 			ASSERT(MBLKL(mp) >= i1);
24094 			/*
24095 			 * Attach the next payload message block to the
24096 			 * multidata message.
24097 			 */
24098 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24099 				goto pbuf_panic;
24100 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
24101 			pld_ptr = mp->b_rptr + i1;
24102 		}
24103 
24104 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
24105 		    KM_NOSLEEP)) == NULL) {
24106 			/*
24107 			 * Any failure other than ENOMEM indicates that we
24108 			 * have passed in invalid pdesc info or parameters
24109 			 * to mmd_addpdesc, which must not happen.
24110 			 *
24111 			 * EINVAL is a result of failure on boundary checks
24112 			 * against the pdesc info contents.  It should not
24113 			 * happen, and we panic because either there's
24114 			 * horrible heap corruption, and/or programming
24115 			 * mistake.
24116 			 */
24117 			if (error != ENOMEM) {
24118 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
24119 				    "pdesc logic error detected for "
24120 				    "mmd %p pinfo %p (%d)\n",
24121 				    (void *)mmd, (void *)&pdi, error);
24122 				/* NOTREACHED */
24123 			}
24124 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
24125 			/* Free unattached payload message blocks as well */
24126 			md_mp->b_cont = mp->b_cont;
24127 			goto free_mmd;
24128 		}
24129 
24130 		/* Advance fragment offset. */
24131 		offset += len;
24132 
24133 		/* Advance to location for next header in the buffer. */
24134 		hdr_ptr += hdr_chunk_len;
24135 
24136 		/* Did we reach the next payload message block? */
24137 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
24138 			mp = mp->b_cont;
24139 			/*
24140 			 * Attach the next message block with payload
24141 			 * data to the multidata message.
24142 			 */
24143 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24144 				goto pbuf_panic;
24145 			pld_ptr = mp->b_rptr;
24146 		}
24147 	}
24148 
24149 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
24150 	ASSERT(mp->b_wptr == pld_ptr);
24151 
24152 	/* Update IP statistics */
24153 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
24154 
24155 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
24156 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
24157 
24158 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
24159 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
24160 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
24161 
24162 	if (pkt_type == OB_PKT) {
24163 		ire->ire_ob_pkt_count += pkts;
24164 		if (ire->ire_ipif != NULL)
24165 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
24166 	} else {
24167 		/* The type is IB_PKT in the forwarding path. */
24168 		ire->ire_ib_pkt_count += pkts;
24169 		ASSERT(!IRE_IS_LOCAL(ire));
24170 		if (ire->ire_type & IRE_BROADCAST) {
24171 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
24172 		} else {
24173 			UPDATE_MIB(ill->ill_ip_mib,
24174 			    ipIfStatsHCOutForwDatagrams, pkts);
24175 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
24176 		}
24177 	}
24178 	ire->ire_last_used_time = lbolt;
24179 	/* Send it down */
24180 	putnext(ire->ire_stq, md_mp);
24181 	return;
24182 
24183 pbuf_panic:
24184 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
24185 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
24186 	    pbuf_idx);
24187 	/* NOTREACHED */
24188 }
24189 
24190 /*
24191  * Outbound IP fragmentation routine.
24192  *
24193  * NOTE : This routine does not ire_refrele the ire that is passed in
24194  * as the argument.
24195  */
24196 static void
24197 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
24198     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst)
24199 {
24200 	int		i1;
24201 	mblk_t		*ll_hdr_mp;
24202 	int 		ll_hdr_len;
24203 	int		hdr_len;
24204 	mblk_t		*hdr_mp;
24205 	ipha_t		*ipha;
24206 	int		ip_data_end;
24207 	int		len;
24208 	mblk_t		*mp = mp_orig, *mp1;
24209 	int		offset;
24210 	queue_t		*q;
24211 	uint32_t	v_hlen_tos_len;
24212 	mblk_t		*first_mp;
24213 	boolean_t	mctl_present;
24214 	ill_t		*ill;
24215 	ill_t		*out_ill;
24216 	mblk_t		*xmit_mp;
24217 	mblk_t		*carve_mp;
24218 	ire_t		*ire1 = NULL;
24219 	ire_t		*save_ire = NULL;
24220 	mblk_t  	*next_mp = NULL;
24221 	boolean_t	last_frag = B_FALSE;
24222 	boolean_t	multirt_send = B_FALSE;
24223 	ire_t		*first_ire = NULL;
24224 	irb_t		*irb = NULL;
24225 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24226 
24227 	ill = ire_to_ill(ire);
24228 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24229 
24230 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24231 
24232 	if (max_frag == 0) {
24233 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24234 		    " -  dropping packet\n"));
24235 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24236 		freemsg(mp);
24237 		return;
24238 	}
24239 
24240 	/*
24241 	 * IPsec does not allow hw accelerated packets to be fragmented
24242 	 * This check is made in ip_wput_ipsec_out prior to coming here
24243 	 * via ip_wput_ire_fragmentit.
24244 	 *
24245 	 * If at this point we have an ire whose ARP request has not
24246 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24247 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24248 	 * This packet and all fragmentable packets for this ire will
24249 	 * continue to get dropped while ire_nce->nce_state remains in
24250 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24251 	 * ND_REACHABLE, all subsquent large packets for this ire will
24252 	 * get fragemented and sent out by this function.
24253 	 */
24254 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24255 		/* If nce_state is ND_INITIAL, trigger ARP query */
24256 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
24257 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24258 		    " -  dropping packet\n"));
24259 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24260 		freemsg(mp);
24261 		return;
24262 	}
24263 
24264 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24265 	    "ip_wput_frag_start:");
24266 
24267 	if (mp->b_datap->db_type == M_CTL) {
24268 		first_mp = mp;
24269 		mp_orig = mp = mp->b_cont;
24270 		mctl_present = B_TRUE;
24271 	} else {
24272 		first_mp = mp;
24273 		mctl_present = B_FALSE;
24274 	}
24275 
24276 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24277 	ipha = (ipha_t *)mp->b_rptr;
24278 
24279 	/*
24280 	 * If the Don't Fragment flag is on, generate an ICMP destination
24281 	 * unreachable, fragmentation needed.
24282 	 */
24283 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24284 	if (offset & IPH_DF) {
24285 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24286 		if (is_system_labeled()) {
24287 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24288 			    ire->ire_max_frag - max_frag, AF_INET);
24289 		}
24290 		/*
24291 		 * Need to compute hdr checksum if called from ip_wput_ire.
24292 		 * Note that ip_rput_forward verifies the checksum before
24293 		 * calling this routine so in that case this is a noop.
24294 		 */
24295 		ipha->ipha_hdr_checksum = 0;
24296 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24297 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24298 		    ipst);
24299 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24300 		    "ip_wput_frag_end:(%S)",
24301 		    "don't fragment");
24302 		return;
24303 	}
24304 	/*
24305 	 * Labeled systems adjust max_frag if they add a label
24306 	 * to send the correct path mtu.  We need the real mtu since we
24307 	 * are fragmenting the packet after label adjustment.
24308 	 */
24309 	if (is_system_labeled())
24310 		max_frag = ire->ire_max_frag;
24311 	if (mctl_present)
24312 		freeb(first_mp);
24313 	/*
24314 	 * Establish the starting offset.  May not be zero if we are fragging
24315 	 * a fragment that is being forwarded.
24316 	 */
24317 	offset = offset & IPH_OFFSET;
24318 
24319 	/* TODO why is this test needed? */
24320 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24321 	if (((max_frag - LENGTH) & ~7) < 8) {
24322 		/* TODO: notify ulp somehow */
24323 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24324 		freemsg(mp);
24325 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24326 		    "ip_wput_frag_end:(%S)",
24327 		    "len < 8");
24328 		return;
24329 	}
24330 
24331 	hdr_len = (V_HLEN & 0xF) << 2;
24332 
24333 	ipha->ipha_hdr_checksum = 0;
24334 
24335 	/*
24336 	 * Establish the number of bytes maximum per frag, after putting
24337 	 * in the header.
24338 	 */
24339 	len = (max_frag - hdr_len) & ~7;
24340 
24341 	/* Check if we can use MDT to send out the frags. */
24342 	ASSERT(!IRE_IS_LOCAL(ire));
24343 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24344 	    ipst->ips_ip_multidata_outbound &&
24345 	    !(ire->ire_flags & RTF_MULTIRT) &&
24346 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24347 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24348 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24349 		ASSERT(ill->ill_mdt_capab != NULL);
24350 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24351 			/*
24352 			 * If MDT has been previously turned off in the past,
24353 			 * and we currently can do MDT (due to IPQoS policy
24354 			 * removal, etc.) then enable it for this interface.
24355 			 */
24356 			ill->ill_mdt_capab->ill_mdt_on = 1;
24357 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24358 			    ill->ill_name));
24359 		}
24360 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24361 		    offset);
24362 		return;
24363 	}
24364 
24365 	/* Get a copy of the header for the trailing frags */
24366 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst);
24367 	if (!hdr_mp) {
24368 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24369 		freemsg(mp);
24370 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24371 		    "ip_wput_frag_end:(%S)",
24372 		    "couldn't copy hdr");
24373 		return;
24374 	}
24375 	if (DB_CRED(mp) != NULL)
24376 		mblk_setcred(hdr_mp, DB_CRED(mp));
24377 
24378 	/* Store the starting offset, with the MoreFrags flag. */
24379 	i1 = offset | IPH_MF | frag_flag;
24380 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24381 
24382 	/* Establish the ending byte offset, based on the starting offset. */
24383 	offset <<= 3;
24384 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24385 
24386 	/* Store the length of the first fragment in the IP header. */
24387 	i1 = len + hdr_len;
24388 	ASSERT(i1 <= IP_MAXPACKET);
24389 	ipha->ipha_length = htons((uint16_t)i1);
24390 
24391 	/*
24392 	 * Compute the IP header checksum for the first frag.  We have to
24393 	 * watch out that we stop at the end of the header.
24394 	 */
24395 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24396 
24397 	/*
24398 	 * Now carve off the first frag.  Note that this will include the
24399 	 * original IP header.
24400 	 */
24401 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24402 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24403 		freeb(hdr_mp);
24404 		freemsg(mp_orig);
24405 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24406 		    "ip_wput_frag_end:(%S)",
24407 		    "couldn't carve first");
24408 		return;
24409 	}
24410 
24411 	/*
24412 	 * Multirouting case. Each fragment is replicated
24413 	 * via all non-condemned RTF_MULTIRT routes
24414 	 * currently resolved.
24415 	 * We ensure that first_ire is the first RTF_MULTIRT
24416 	 * ire in the bucket.
24417 	 */
24418 	if (ire->ire_flags & RTF_MULTIRT) {
24419 		irb = ire->ire_bucket;
24420 		ASSERT(irb != NULL);
24421 
24422 		multirt_send = B_TRUE;
24423 
24424 		/* Make sure we do not omit any multiroute ire. */
24425 		IRB_REFHOLD(irb);
24426 		for (first_ire = irb->irb_ire;
24427 		    first_ire != NULL;
24428 		    first_ire = first_ire->ire_next) {
24429 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24430 			    (first_ire->ire_addr == ire->ire_addr) &&
24431 			    !(first_ire->ire_marks &
24432 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
24433 				break;
24434 			}
24435 		}
24436 
24437 		if (first_ire != NULL) {
24438 			if (first_ire != ire) {
24439 				IRE_REFHOLD(first_ire);
24440 				/*
24441 				 * Do not release the ire passed in
24442 				 * as the argument.
24443 				 */
24444 				ire = first_ire;
24445 			} else {
24446 				first_ire = NULL;
24447 			}
24448 		}
24449 		IRB_REFRELE(irb);
24450 
24451 		/*
24452 		 * Save the first ire; we will need to restore it
24453 		 * for the trailing frags.
24454 		 * We REFHOLD save_ire, as each iterated ire will be
24455 		 * REFRELEd.
24456 		 */
24457 		save_ire = ire;
24458 		IRE_REFHOLD(save_ire);
24459 	}
24460 
24461 	/*
24462 	 * First fragment emission loop.
24463 	 * In most cases, the emission loop below is entered only
24464 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24465 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24466 	 * bucket, and send the fragment through all crossed
24467 	 * RTF_MULTIRT routes.
24468 	 */
24469 	do {
24470 		if (ire->ire_flags & RTF_MULTIRT) {
24471 			/*
24472 			 * We are in a multiple send case, need to get
24473 			 * the next ire and make a copy of the packet.
24474 			 * ire1 holds here the next ire to process in the
24475 			 * bucket. If multirouting is expected,
24476 			 * any non-RTF_MULTIRT ire that has the
24477 			 * right destination address is ignored.
24478 			 *
24479 			 * We have to take into account the MTU of
24480 			 * each walked ire. max_frag is set by the
24481 			 * the caller and generally refers to
24482 			 * the primary ire entry. Here we ensure that
24483 			 * no route with a lower MTU will be used, as
24484 			 * fragments are carved once for all ires,
24485 			 * then replicated.
24486 			 */
24487 			ASSERT(irb != NULL);
24488 			IRB_REFHOLD(irb);
24489 			for (ire1 = ire->ire_next;
24490 			    ire1 != NULL;
24491 			    ire1 = ire1->ire_next) {
24492 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24493 					continue;
24494 				if (ire1->ire_addr != ire->ire_addr)
24495 					continue;
24496 				if (ire1->ire_marks &
24497 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24498 					continue;
24499 				/*
24500 				 * Ensure we do not exceed the MTU
24501 				 * of the next route.
24502 				 */
24503 				if (ire1->ire_max_frag < max_frag) {
24504 					ip_multirt_bad_mtu(ire1, max_frag);
24505 					continue;
24506 				}
24507 
24508 				/* Got one. */
24509 				IRE_REFHOLD(ire1);
24510 				break;
24511 			}
24512 			IRB_REFRELE(irb);
24513 
24514 			if (ire1 != NULL) {
24515 				next_mp = copyb(mp);
24516 				if ((next_mp == NULL) ||
24517 				    ((mp->b_cont != NULL) &&
24518 				    ((next_mp->b_cont =
24519 				    dupmsg(mp->b_cont)) == NULL))) {
24520 					freemsg(next_mp);
24521 					next_mp = NULL;
24522 					ire_refrele(ire1);
24523 					ire1 = NULL;
24524 				}
24525 			}
24526 
24527 			/* Last multiroute ire; don't loop anymore. */
24528 			if (ire1 == NULL) {
24529 				multirt_send = B_FALSE;
24530 			}
24531 		}
24532 
24533 		ll_hdr_len = 0;
24534 		LOCK_IRE_FP_MP(ire);
24535 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24536 		if (ll_hdr_mp != NULL) {
24537 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24538 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24539 		} else {
24540 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24541 		}
24542 
24543 		/* If there is a transmit header, get a copy for this frag. */
24544 		/*
24545 		 * TODO: should check db_ref before calling ip_carve_mp since
24546 		 * it might give us a dup.
24547 		 */
24548 		if (!ll_hdr_mp) {
24549 			/* No xmit header. */
24550 			xmit_mp = mp;
24551 
24552 		/* We have a link-layer header that can fit in our mblk. */
24553 		} else if (mp->b_datap->db_ref == 1 &&
24554 		    ll_hdr_len != 0 &&
24555 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24556 			/* M_DATA fastpath */
24557 			mp->b_rptr -= ll_hdr_len;
24558 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24559 			xmit_mp = mp;
24560 
24561 		/* Corner case if copyb has failed */
24562 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24563 			UNLOCK_IRE_FP_MP(ire);
24564 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24565 			freeb(hdr_mp);
24566 			freemsg(mp);
24567 			freemsg(mp_orig);
24568 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24569 			    "ip_wput_frag_end:(%S)",
24570 			    "discard");
24571 
24572 			if (multirt_send) {
24573 				ASSERT(ire1);
24574 				ASSERT(next_mp);
24575 
24576 				freemsg(next_mp);
24577 				ire_refrele(ire1);
24578 			}
24579 			if (save_ire != NULL)
24580 				IRE_REFRELE(save_ire);
24581 
24582 			if (first_ire != NULL)
24583 				ire_refrele(first_ire);
24584 			return;
24585 
24586 		/*
24587 		 * Case of res_mp OR the fastpath mp can't fit
24588 		 * in the mblk
24589 		 */
24590 		} else {
24591 			xmit_mp->b_cont = mp;
24592 			if (DB_CRED(mp) != NULL)
24593 				mblk_setcred(xmit_mp, DB_CRED(mp));
24594 			/*
24595 			 * Get priority marking, if any.
24596 			 * We propagate the CoS marking from the
24597 			 * original packet that went to QoS processing
24598 			 * in ip_wput_ire to the newly carved mp.
24599 			 */
24600 			if (DB_TYPE(xmit_mp) == M_DATA)
24601 				xmit_mp->b_band = mp->b_band;
24602 		}
24603 		UNLOCK_IRE_FP_MP(ire);
24604 
24605 		q = ire->ire_stq;
24606 		out_ill = (ill_t *)q->q_ptr;
24607 
24608 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24609 
24610 		DTRACE_PROBE4(ip4__physical__out__start,
24611 		    ill_t *, NULL, ill_t *, out_ill,
24612 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24613 
24614 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24615 		    ipst->ips_ipv4firewall_physical_out,
24616 		    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24617 
24618 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24619 
24620 		if (xmit_mp != NULL) {
24621 			DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *, NULL,
24622 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
24623 			    ipha_t *, ipha, ip6_t *, NULL, int, 0);
24624 
24625 			putnext(q, xmit_mp);
24626 
24627 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24628 			UPDATE_MIB(out_ill->ill_ip_mib,
24629 			    ipIfStatsHCOutOctets, i1);
24630 
24631 			if (pkt_type != OB_PKT) {
24632 				/*
24633 				 * Update the packet count and MIB stats
24634 				 * of trailing RTF_MULTIRT ires.
24635 				 */
24636 				UPDATE_OB_PKT_COUNT(ire);
24637 				BUMP_MIB(out_ill->ill_ip_mib,
24638 				    ipIfStatsOutFragReqds);
24639 			}
24640 		}
24641 
24642 		if (multirt_send) {
24643 			/*
24644 			 * We are in a multiple send case; look for
24645 			 * the next ire and re-enter the loop.
24646 			 */
24647 			ASSERT(ire1);
24648 			ASSERT(next_mp);
24649 			/* REFRELE the current ire before looping */
24650 			ire_refrele(ire);
24651 			ire = ire1;
24652 			ire1 = NULL;
24653 			mp = next_mp;
24654 			next_mp = NULL;
24655 		}
24656 	} while (multirt_send);
24657 
24658 	ASSERT(ire1 == NULL);
24659 
24660 	/* Restore the original ire; we need it for the trailing frags */
24661 	if (save_ire != NULL) {
24662 		/* REFRELE the last iterated ire */
24663 		ire_refrele(ire);
24664 		/* save_ire has been REFHOLDed */
24665 		ire = save_ire;
24666 		save_ire = NULL;
24667 		q = ire->ire_stq;
24668 	}
24669 
24670 	if (pkt_type == OB_PKT) {
24671 		UPDATE_OB_PKT_COUNT(ire);
24672 	} else {
24673 		out_ill = (ill_t *)q->q_ptr;
24674 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24675 		UPDATE_IB_PKT_COUNT(ire);
24676 	}
24677 
24678 	/* Advance the offset to the second frag starting point. */
24679 	offset += len;
24680 	/*
24681 	 * Update hdr_len from the copied header - there might be less options
24682 	 * in the later fragments.
24683 	 */
24684 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24685 	/* Loop until done. */
24686 	for (;;) {
24687 		uint16_t	offset_and_flags;
24688 		uint16_t	ip_len;
24689 
24690 		if (ip_data_end - offset > len) {
24691 			/*
24692 			 * Carve off the appropriate amount from the original
24693 			 * datagram.
24694 			 */
24695 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24696 				mp = NULL;
24697 				break;
24698 			}
24699 			/*
24700 			 * More frags after this one.  Get another copy
24701 			 * of the header.
24702 			 */
24703 			if (carve_mp->b_datap->db_ref == 1 &&
24704 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24705 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24706 				/* Inline IP header */
24707 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24708 				    hdr_mp->b_rptr;
24709 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24710 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24711 				mp = carve_mp;
24712 			} else {
24713 				if (!(mp = copyb(hdr_mp))) {
24714 					freemsg(carve_mp);
24715 					break;
24716 				}
24717 				/* Get priority marking, if any. */
24718 				mp->b_band = carve_mp->b_band;
24719 				mp->b_cont = carve_mp;
24720 			}
24721 			ipha = (ipha_t *)mp->b_rptr;
24722 			offset_and_flags = IPH_MF;
24723 		} else {
24724 			/*
24725 			 * Last frag.  Consume the header. Set len to
24726 			 * the length of this last piece.
24727 			 */
24728 			len = ip_data_end - offset;
24729 
24730 			/*
24731 			 * Carve off the appropriate amount from the original
24732 			 * datagram.
24733 			 */
24734 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24735 				mp = NULL;
24736 				break;
24737 			}
24738 			if (carve_mp->b_datap->db_ref == 1 &&
24739 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24740 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24741 				/* Inline IP header */
24742 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24743 				    hdr_mp->b_rptr;
24744 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24745 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24746 				mp = carve_mp;
24747 				freeb(hdr_mp);
24748 				hdr_mp = mp;
24749 			} else {
24750 				mp = hdr_mp;
24751 				/* Get priority marking, if any. */
24752 				mp->b_band = carve_mp->b_band;
24753 				mp->b_cont = carve_mp;
24754 			}
24755 			ipha = (ipha_t *)mp->b_rptr;
24756 			/* A frag of a frag might have IPH_MF non-zero */
24757 			offset_and_flags =
24758 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24759 			    IPH_MF;
24760 		}
24761 		offset_and_flags |= (uint16_t)(offset >> 3);
24762 		offset_and_flags |= (uint16_t)frag_flag;
24763 		/* Store the offset and flags in the IP header. */
24764 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24765 
24766 		/* Store the length in the IP header. */
24767 		ip_len = (uint16_t)(len + hdr_len);
24768 		ipha->ipha_length = htons(ip_len);
24769 
24770 		/*
24771 		 * Set the IP header checksum.	Note that mp is just
24772 		 * the header, so this is easy to pass to ip_csum.
24773 		 */
24774 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24775 
24776 		/* Attach a transmit header, if any, and ship it. */
24777 		if (pkt_type == OB_PKT) {
24778 			UPDATE_OB_PKT_COUNT(ire);
24779 		} else {
24780 			out_ill = (ill_t *)q->q_ptr;
24781 			BUMP_MIB(out_ill->ill_ip_mib,
24782 			    ipIfStatsHCOutForwDatagrams);
24783 			UPDATE_IB_PKT_COUNT(ire);
24784 		}
24785 
24786 		if (ire->ire_flags & RTF_MULTIRT) {
24787 			irb = ire->ire_bucket;
24788 			ASSERT(irb != NULL);
24789 
24790 			multirt_send = B_TRUE;
24791 
24792 			/*
24793 			 * Save the original ire; we will need to restore it
24794 			 * for the tailing frags.
24795 			 */
24796 			save_ire = ire;
24797 			IRE_REFHOLD(save_ire);
24798 		}
24799 		/*
24800 		 * Emission loop for this fragment, similar
24801 		 * to what is done for the first fragment.
24802 		 */
24803 		do {
24804 			if (multirt_send) {
24805 				/*
24806 				 * We are in a multiple send case, need to get
24807 				 * the next ire and make a copy of the packet.
24808 				 */
24809 				ASSERT(irb != NULL);
24810 				IRB_REFHOLD(irb);
24811 				for (ire1 = ire->ire_next;
24812 				    ire1 != NULL;
24813 				    ire1 = ire1->ire_next) {
24814 					if (!(ire1->ire_flags & RTF_MULTIRT))
24815 						continue;
24816 					if (ire1->ire_addr != ire->ire_addr)
24817 						continue;
24818 					if (ire1->ire_marks &
24819 					    (IRE_MARK_CONDEMNED|
24820 					    IRE_MARK_HIDDEN)) {
24821 						continue;
24822 					}
24823 					/*
24824 					 * Ensure we do not exceed the MTU
24825 					 * of the next route.
24826 					 */
24827 					if (ire1->ire_max_frag < max_frag) {
24828 						ip_multirt_bad_mtu(ire1,
24829 						    max_frag);
24830 						continue;
24831 					}
24832 
24833 					/* Got one. */
24834 					IRE_REFHOLD(ire1);
24835 					break;
24836 				}
24837 				IRB_REFRELE(irb);
24838 
24839 				if (ire1 != NULL) {
24840 					next_mp = copyb(mp);
24841 					if ((next_mp == NULL) ||
24842 					    ((mp->b_cont != NULL) &&
24843 					    ((next_mp->b_cont =
24844 					    dupmsg(mp->b_cont)) == NULL))) {
24845 						freemsg(next_mp);
24846 						next_mp = NULL;
24847 						ire_refrele(ire1);
24848 						ire1 = NULL;
24849 					}
24850 				}
24851 
24852 				/* Last multiroute ire; don't loop anymore. */
24853 				if (ire1 == NULL) {
24854 					multirt_send = B_FALSE;
24855 				}
24856 			}
24857 
24858 			/* Update transmit header */
24859 			ll_hdr_len = 0;
24860 			LOCK_IRE_FP_MP(ire);
24861 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24862 			if (ll_hdr_mp != NULL) {
24863 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24864 				ll_hdr_len = MBLKL(ll_hdr_mp);
24865 			} else {
24866 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24867 			}
24868 
24869 			if (!ll_hdr_mp) {
24870 				xmit_mp = mp;
24871 
24872 			/*
24873 			 * We have link-layer header that can fit in
24874 			 * our mblk.
24875 			 */
24876 			} else if (mp->b_datap->db_ref == 1 &&
24877 			    ll_hdr_len != 0 &&
24878 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24879 				/* M_DATA fastpath */
24880 				mp->b_rptr -= ll_hdr_len;
24881 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24882 				    ll_hdr_len);
24883 				xmit_mp = mp;
24884 
24885 			/*
24886 			 * Case of res_mp OR the fastpath mp can't fit
24887 			 * in the mblk
24888 			 */
24889 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24890 				xmit_mp->b_cont = mp;
24891 				if (DB_CRED(mp) != NULL)
24892 					mblk_setcred(xmit_mp, DB_CRED(mp));
24893 				/* Get priority marking, if any. */
24894 				if (DB_TYPE(xmit_mp) == M_DATA)
24895 					xmit_mp->b_band = mp->b_band;
24896 
24897 			/* Corner case if copyb failed */
24898 			} else {
24899 				/*
24900 				 * Exit both the replication and
24901 				 * fragmentation loops.
24902 				 */
24903 				UNLOCK_IRE_FP_MP(ire);
24904 				goto drop_pkt;
24905 			}
24906 			UNLOCK_IRE_FP_MP(ire);
24907 
24908 			mp1 = mp;
24909 			out_ill = (ill_t *)q->q_ptr;
24910 
24911 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24912 
24913 			DTRACE_PROBE4(ip4__physical__out__start,
24914 			    ill_t *, NULL, ill_t *, out_ill,
24915 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24916 
24917 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24918 			    ipst->ips_ipv4firewall_physical_out,
24919 			    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24920 
24921 			DTRACE_PROBE1(ip4__physical__out__end,
24922 			    mblk_t *, xmit_mp);
24923 
24924 			if (mp != mp1 && hdr_mp == mp1)
24925 				hdr_mp = mp;
24926 			if (mp != mp1 && mp_orig == mp1)
24927 				mp_orig = mp;
24928 
24929 			if (xmit_mp != NULL) {
24930 				DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *,
24931 				    NULL, void_ip_t *, ipha,
24932 				    __dtrace_ipsr_ill_t *, out_ill, ipha_t *,
24933 				    ipha, ip6_t *, NULL, int, 0);
24934 
24935 				putnext(q, xmit_mp);
24936 
24937 				BUMP_MIB(out_ill->ill_ip_mib,
24938 				    ipIfStatsHCOutTransmits);
24939 				UPDATE_MIB(out_ill->ill_ip_mib,
24940 				    ipIfStatsHCOutOctets, ip_len);
24941 
24942 				if (pkt_type != OB_PKT) {
24943 					/*
24944 					 * Update the packet count of trailing
24945 					 * RTF_MULTIRT ires.
24946 					 */
24947 					UPDATE_OB_PKT_COUNT(ire);
24948 				}
24949 			}
24950 
24951 			/* All done if we just consumed the hdr_mp. */
24952 			if (mp == hdr_mp) {
24953 				last_frag = B_TRUE;
24954 				BUMP_MIB(out_ill->ill_ip_mib,
24955 				    ipIfStatsOutFragOKs);
24956 			}
24957 
24958 			if (multirt_send) {
24959 				/*
24960 				 * We are in a multiple send case; look for
24961 				 * the next ire and re-enter the loop.
24962 				 */
24963 				ASSERT(ire1);
24964 				ASSERT(next_mp);
24965 				/* REFRELE the current ire before looping */
24966 				ire_refrele(ire);
24967 				ire = ire1;
24968 				ire1 = NULL;
24969 				q = ire->ire_stq;
24970 				mp = next_mp;
24971 				next_mp = NULL;
24972 			}
24973 		} while (multirt_send);
24974 		/*
24975 		 * Restore the original ire; we need it for the
24976 		 * trailing frags
24977 		 */
24978 		if (save_ire != NULL) {
24979 			ASSERT(ire1 == NULL);
24980 			/* REFRELE the last iterated ire */
24981 			ire_refrele(ire);
24982 			/* save_ire has been REFHOLDed */
24983 			ire = save_ire;
24984 			q = ire->ire_stq;
24985 			save_ire = NULL;
24986 		}
24987 
24988 		if (last_frag) {
24989 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24990 			    "ip_wput_frag_end:(%S)",
24991 			    "consumed hdr_mp");
24992 
24993 			if (first_ire != NULL)
24994 				ire_refrele(first_ire);
24995 			return;
24996 		}
24997 		/* Otherwise, advance and loop. */
24998 		offset += len;
24999 	}
25000 
25001 drop_pkt:
25002 	/* Clean up following allocation failure. */
25003 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
25004 	freemsg(mp);
25005 	if (mp != hdr_mp)
25006 		freeb(hdr_mp);
25007 	if (mp != mp_orig)
25008 		freemsg(mp_orig);
25009 
25010 	if (save_ire != NULL)
25011 		IRE_REFRELE(save_ire);
25012 	if (first_ire != NULL)
25013 		ire_refrele(first_ire);
25014 
25015 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
25016 	    "ip_wput_frag_end:(%S)",
25017 	    "end--alloc failure");
25018 }
25019 
25020 /*
25021  * Copy the header plus those options which have the copy bit set
25022  */
25023 static mblk_t *
25024 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst)
25025 {
25026 	mblk_t	*mp;
25027 	uchar_t	*up;
25028 
25029 	/*
25030 	 * Quick check if we need to look for options without the copy bit
25031 	 * set
25032 	 */
25033 	mp = allocb(ipst->ips_ip_wroff_extra + hdr_len, BPRI_HI);
25034 	if (!mp)
25035 		return (mp);
25036 	mp->b_rptr += ipst->ips_ip_wroff_extra;
25037 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
25038 		bcopy(rptr, mp->b_rptr, hdr_len);
25039 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
25040 		return (mp);
25041 	}
25042 	up  = mp->b_rptr;
25043 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
25044 	up += IP_SIMPLE_HDR_LENGTH;
25045 	rptr += IP_SIMPLE_HDR_LENGTH;
25046 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
25047 	while (hdr_len > 0) {
25048 		uint32_t optval;
25049 		uint32_t optlen;
25050 
25051 		optval = *rptr;
25052 		if (optval == IPOPT_EOL)
25053 			break;
25054 		if (optval == IPOPT_NOP)
25055 			optlen = 1;
25056 		else
25057 			optlen = rptr[1];
25058 		if (optval & IPOPT_COPY) {
25059 			bcopy(rptr, up, optlen);
25060 			up += optlen;
25061 		}
25062 		rptr += optlen;
25063 		hdr_len -= optlen;
25064 	}
25065 	/*
25066 	 * Make sure that we drop an even number of words by filling
25067 	 * with EOL to the next word boundary.
25068 	 */
25069 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
25070 	    hdr_len & 0x3; hdr_len++)
25071 		*up++ = IPOPT_EOL;
25072 	mp->b_wptr = up;
25073 	/* Update header length */
25074 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
25075 	return (mp);
25076 }
25077 
25078 /*
25079  * Delivery to local recipients including fanout to multiple recipients.
25080  * Does not do checksumming of UDP/TCP.
25081  * Note: q should be the read side queue for either the ill or conn.
25082  * Note: rq should be the read side q for the lower (ill) stream.
25083  * We don't send packets to IPPF processing, thus the last argument
25084  * to all the fanout calls are B_FALSE.
25085  */
25086 void
25087 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
25088     int fanout_flags, zoneid_t zoneid)
25089 {
25090 	uint32_t	protocol;
25091 	mblk_t		*first_mp;
25092 	boolean_t	mctl_present;
25093 	int		ire_type;
25094 #define	rptr	((uchar_t *)ipha)
25095 	ip_stack_t	*ipst = ill->ill_ipst;
25096 
25097 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
25098 	    "ip_wput_local_start: q %p", q);
25099 
25100 	if (ire != NULL) {
25101 		ire_type = ire->ire_type;
25102 	} else {
25103 		/*
25104 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
25105 		 * packet is not multicast, we can't tell the ire type.
25106 		 */
25107 		ASSERT(CLASSD(ipha->ipha_dst));
25108 		ire_type = IRE_BROADCAST;
25109 	}
25110 
25111 	first_mp = mp;
25112 	if (first_mp->b_datap->db_type == M_CTL) {
25113 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
25114 		if (!io->ipsec_out_secure) {
25115 			/*
25116 			 * This ipsec_out_t was allocated in ip_wput
25117 			 * for multicast packets to store the ill_index.
25118 			 * As this is being delivered locally, we don't
25119 			 * need this anymore.
25120 			 */
25121 			mp = first_mp->b_cont;
25122 			freeb(first_mp);
25123 			first_mp = mp;
25124 			mctl_present = B_FALSE;
25125 		} else {
25126 			/*
25127 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
25128 			 * security properties for the looped-back packet.
25129 			 */
25130 			mctl_present = B_TRUE;
25131 			mp = first_mp->b_cont;
25132 			ASSERT(mp != NULL);
25133 			ipsec_out_to_in(first_mp);
25134 		}
25135 	} else {
25136 		mctl_present = B_FALSE;
25137 	}
25138 
25139 	DTRACE_PROBE4(ip4__loopback__in__start,
25140 	    ill_t *, ill, ill_t *, NULL,
25141 	    ipha_t *, ipha, mblk_t *, first_mp);
25142 
25143 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
25144 	    ipst->ips_ipv4firewall_loopback_in,
25145 	    ill, NULL, ipha, first_mp, mp, 0, ipst);
25146 
25147 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
25148 
25149 	if (first_mp == NULL)
25150 		return;
25151 
25152 	if (ipst->ips_ipobs_enabled) {
25153 		zoneid_t szone, dzone, lookup_zoneid = ALL_ZONES;
25154 		zoneid_t stackzoneid = netstackid_to_zoneid(
25155 		    ipst->ips_netstack->netstack_stackid);
25156 
25157 		dzone = (stackzoneid == GLOBAL_ZONEID) ? zoneid : stackzoneid;
25158 		/*
25159 		 * 127.0.0.1 is special, as we cannot lookup its zoneid by
25160 		 * address.  Restrict the lookup below to the destination zone.
25161 		 */
25162 		if (ipha->ipha_src == ntohl(INADDR_LOOPBACK))
25163 			lookup_zoneid = zoneid;
25164 		szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
25165 		    lookup_zoneid);
25166 		ipobs_hook(mp, IPOBS_HOOK_LOCAL, szone, dzone, ill,
25167 		    IPV4_VERSION, 0, ipst);
25168 	}
25169 
25170 	DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL, void_ip_t *,
25171 	    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *, NULL,
25172 	    int, 1);
25173 
25174 	ipst->ips_loopback_packets++;
25175 
25176 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
25177 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
25178 	if (!IS_SIMPLE_IPH(ipha)) {
25179 		ip_wput_local_options(ipha, ipst);
25180 	}
25181 
25182 	protocol = ipha->ipha_protocol;
25183 	switch (protocol) {
25184 	case IPPROTO_ICMP: {
25185 		ire_t		*ire_zone;
25186 		ilm_t		*ilm;
25187 		mblk_t		*mp1;
25188 		zoneid_t	last_zoneid;
25189 
25190 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
25191 			ASSERT(ire_type == IRE_BROADCAST);
25192 			/*
25193 			 * In the multicast case, applications may have joined
25194 			 * the group from different zones, so we need to deliver
25195 			 * the packet to each of them. Loop through the
25196 			 * multicast memberships structures (ilm) on the receive
25197 			 * ill and send a copy of the packet up each matching
25198 			 * one. However, we don't do this for multicasts sent on
25199 			 * the loopback interface (PHYI_LOOPBACK flag set) as
25200 			 * they must stay in the sender's zone.
25201 			 *
25202 			 * ilm_add_v6() ensures that ilms in the same zone are
25203 			 * contiguous in the ill_ilm list. We use this property
25204 			 * to avoid sending duplicates needed when two
25205 			 * applications in the same zone join the same group on
25206 			 * different logical interfaces: we ignore the ilm if
25207 			 * it's zoneid is the same as the last matching one.
25208 			 * In addition, the sending of the packet for
25209 			 * ire_zoneid is delayed until all of the other ilms
25210 			 * have been exhausted.
25211 			 */
25212 			last_zoneid = -1;
25213 			ILM_WALKER_HOLD(ill);
25214 			for (ilm = ill->ill_ilm; ilm != NULL;
25215 			    ilm = ilm->ilm_next) {
25216 				if ((ilm->ilm_flags & ILM_DELETED) ||
25217 				    ipha->ipha_dst != ilm->ilm_addr ||
25218 				    ilm->ilm_zoneid == last_zoneid ||
25219 				    ilm->ilm_zoneid == zoneid ||
25220 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25221 					continue;
25222 				mp1 = ip_copymsg(first_mp);
25223 				if (mp1 == NULL)
25224 					continue;
25225 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25226 				    mctl_present, B_FALSE, ill,
25227 				    ilm->ilm_zoneid);
25228 				last_zoneid = ilm->ilm_zoneid;
25229 			}
25230 			ILM_WALKER_RELE(ill);
25231 			/*
25232 			 * Loopback case: the sending endpoint has
25233 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25234 			 * dispatch the multicast packet to the sending zone.
25235 			 */
25236 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25237 				freemsg(first_mp);
25238 				return;
25239 			}
25240 		} else if (ire_type == IRE_BROADCAST) {
25241 			/*
25242 			 * In the broadcast case, there may be many zones
25243 			 * which need a copy of the packet delivered to them.
25244 			 * There is one IRE_BROADCAST per broadcast address
25245 			 * and per zone; we walk those using a helper function.
25246 			 * In addition, the sending of the packet for zoneid is
25247 			 * delayed until all of the other ires have been
25248 			 * processed.
25249 			 */
25250 			IRB_REFHOLD(ire->ire_bucket);
25251 			ire_zone = NULL;
25252 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25253 			    ire)) != NULL) {
25254 				mp1 = ip_copymsg(first_mp);
25255 				if (mp1 == NULL)
25256 					continue;
25257 
25258 				UPDATE_IB_PKT_COUNT(ire_zone);
25259 				ire_zone->ire_last_used_time = lbolt;
25260 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25261 				    mctl_present, B_FALSE, ill,
25262 				    ire_zone->ire_zoneid);
25263 			}
25264 			IRB_REFRELE(ire->ire_bucket);
25265 		}
25266 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25267 		    0, mctl_present, B_FALSE, ill, zoneid);
25268 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25269 		    "ip_wput_local_end: q %p (%S)",
25270 		    q, "icmp");
25271 		return;
25272 	}
25273 	case IPPROTO_IGMP:
25274 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25275 			/* Bad packet - discarded by igmp_input */
25276 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25277 			    "ip_wput_local_end: q %p (%S)",
25278 			    q, "igmp_input--bad packet");
25279 			if (mctl_present)
25280 				freeb(first_mp);
25281 			return;
25282 		}
25283 		/*
25284 		 * igmp_input() may have returned the pulled up message.
25285 		 * So first_mp and ipha need to be reinitialized.
25286 		 */
25287 		ipha = (ipha_t *)mp->b_rptr;
25288 		if (mctl_present)
25289 			first_mp->b_cont = mp;
25290 		else
25291 			first_mp = mp;
25292 		/* deliver to local raw users */
25293 		break;
25294 	case IPPROTO_ENCAP:
25295 		/*
25296 		 * This case is covered by either ip_fanout_proto, or by
25297 		 * the above security processing for self-tunneled packets.
25298 		 */
25299 		break;
25300 	case IPPROTO_UDP: {
25301 		uint16_t	*up;
25302 		uint32_t	ports;
25303 
25304 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25305 		    UDP_PORTS_OFFSET);
25306 		/* Force a 'valid' checksum. */
25307 		up[3] = 0;
25308 
25309 		ports = *(uint32_t *)up;
25310 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25311 		    (ire_type == IRE_BROADCAST),
25312 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25313 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25314 		    ill, zoneid);
25315 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25316 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25317 		return;
25318 	}
25319 	case IPPROTO_TCP: {
25320 
25321 		/*
25322 		 * For TCP, discard broadcast packets.
25323 		 */
25324 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25325 			freemsg(first_mp);
25326 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25327 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25328 			return;
25329 		}
25330 
25331 		if (mp->b_datap->db_type == M_DATA) {
25332 			/*
25333 			 * M_DATA mblk, so init mblk (chain) for no struio().
25334 			 */
25335 			mblk_t	*mp1 = mp;
25336 
25337 			do {
25338 				mp1->b_datap->db_struioflag = 0;
25339 			} while ((mp1 = mp1->b_cont) != NULL);
25340 		}
25341 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25342 		    <= mp->b_wptr);
25343 		ip_fanout_tcp(q, first_mp, ill, ipha,
25344 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25345 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25346 		    mctl_present, B_FALSE, zoneid);
25347 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25348 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25349 		return;
25350 	}
25351 	case IPPROTO_SCTP:
25352 	{
25353 		uint32_t	ports;
25354 
25355 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25356 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25357 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25358 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25359 		return;
25360 	}
25361 
25362 	default:
25363 		break;
25364 	}
25365 	/*
25366 	 * Find a client for some other protocol.  We give
25367 	 * copies to multiple clients, if more than one is
25368 	 * bound.
25369 	 */
25370 	ip_fanout_proto(q, first_mp, ill, ipha,
25371 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25372 	    mctl_present, B_FALSE, ill, zoneid);
25373 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25374 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25375 #undef	rptr
25376 }
25377 
25378 /*
25379  * Update any source route, record route, or timestamp options.
25380  * Check that we are at end of strict source route.
25381  * The options have been sanity checked by ip_wput_options().
25382  */
25383 static void
25384 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25385 {
25386 	ipoptp_t	opts;
25387 	uchar_t		*opt;
25388 	uint8_t		optval;
25389 	uint8_t		optlen;
25390 	ipaddr_t	dst;
25391 	uint32_t	ts;
25392 	ire_t		*ire;
25393 	timestruc_t	now;
25394 
25395 	ip2dbg(("ip_wput_local_options\n"));
25396 	for (optval = ipoptp_first(&opts, ipha);
25397 	    optval != IPOPT_EOL;
25398 	    optval = ipoptp_next(&opts)) {
25399 		opt = opts.ipoptp_cur;
25400 		optlen = opts.ipoptp_len;
25401 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25402 		switch (optval) {
25403 			uint32_t off;
25404 		case IPOPT_SSRR:
25405 		case IPOPT_LSRR:
25406 			off = opt[IPOPT_OFFSET];
25407 			off--;
25408 			if (optlen < IP_ADDR_LEN ||
25409 			    off > optlen - IP_ADDR_LEN) {
25410 				/* End of source route */
25411 				break;
25412 			}
25413 			/*
25414 			 * This will only happen if two consecutive entries
25415 			 * in the source route contains our address or if
25416 			 * it is a packet with a loose source route which
25417 			 * reaches us before consuming the whole source route
25418 			 */
25419 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25420 			if (optval == IPOPT_SSRR) {
25421 				return;
25422 			}
25423 			/*
25424 			 * Hack: instead of dropping the packet truncate the
25425 			 * source route to what has been used by filling the
25426 			 * rest with IPOPT_NOP.
25427 			 */
25428 			opt[IPOPT_OLEN] = (uint8_t)off;
25429 			while (off < optlen) {
25430 				opt[off++] = IPOPT_NOP;
25431 			}
25432 			break;
25433 		case IPOPT_RR:
25434 			off = opt[IPOPT_OFFSET];
25435 			off--;
25436 			if (optlen < IP_ADDR_LEN ||
25437 			    off > optlen - IP_ADDR_LEN) {
25438 				/* No more room - ignore */
25439 				ip1dbg((
25440 				    "ip_wput_forward_options: end of RR\n"));
25441 				break;
25442 			}
25443 			dst = htonl(INADDR_LOOPBACK);
25444 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25445 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25446 			break;
25447 		case IPOPT_TS:
25448 			/* Insert timestamp if there is romm */
25449 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25450 			case IPOPT_TS_TSONLY:
25451 				off = IPOPT_TS_TIMELEN;
25452 				break;
25453 			case IPOPT_TS_PRESPEC:
25454 			case IPOPT_TS_PRESPEC_RFC791:
25455 				/* Verify that the address matched */
25456 				off = opt[IPOPT_OFFSET] - 1;
25457 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25458 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25459 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25460 				    ipst);
25461 				if (ire == NULL) {
25462 					/* Not for us */
25463 					break;
25464 				}
25465 				ire_refrele(ire);
25466 				/* FALLTHRU */
25467 			case IPOPT_TS_TSANDADDR:
25468 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25469 				break;
25470 			default:
25471 				/*
25472 				 * ip_*put_options should have already
25473 				 * dropped this packet.
25474 				 */
25475 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25476 				    "unknown IT - bug in ip_wput_options?\n");
25477 				return;	/* Keep "lint" happy */
25478 			}
25479 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25480 				/* Increase overflow counter */
25481 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25482 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25483 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25484 				    (off << 4);
25485 				break;
25486 			}
25487 			off = opt[IPOPT_OFFSET] - 1;
25488 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25489 			case IPOPT_TS_PRESPEC:
25490 			case IPOPT_TS_PRESPEC_RFC791:
25491 			case IPOPT_TS_TSANDADDR:
25492 				dst = htonl(INADDR_LOOPBACK);
25493 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25494 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25495 				/* FALLTHRU */
25496 			case IPOPT_TS_TSONLY:
25497 				off = opt[IPOPT_OFFSET] - 1;
25498 				/* Compute # of milliseconds since midnight */
25499 				gethrestime(&now);
25500 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25501 				    now.tv_nsec / (NANOSEC / MILLISEC);
25502 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25503 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25504 				break;
25505 			}
25506 			break;
25507 		}
25508 	}
25509 }
25510 
25511 /*
25512  * Send out a multicast packet on interface ipif.
25513  * The sender does not have an conn.
25514  * Caller verifies that this isn't a PHYI_LOOPBACK.
25515  */
25516 void
25517 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25518 {
25519 	ipha_t	*ipha;
25520 	ire_t	*ire;
25521 	ipaddr_t	dst;
25522 	mblk_t		*first_mp;
25523 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25524 
25525 	/* igmp_sendpkt always allocates a ipsec_out_t */
25526 	ASSERT(mp->b_datap->db_type == M_CTL);
25527 	ASSERT(!ipif->ipif_isv6);
25528 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25529 
25530 	first_mp = mp;
25531 	mp = first_mp->b_cont;
25532 	ASSERT(mp->b_datap->db_type == M_DATA);
25533 	ipha = (ipha_t *)mp->b_rptr;
25534 
25535 	/*
25536 	 * Find an IRE which matches the destination and the outgoing
25537 	 * queue (i.e. the outgoing interface.)
25538 	 */
25539 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25540 		dst = ipif->ipif_pp_dst_addr;
25541 	else
25542 		dst = ipha->ipha_dst;
25543 	/*
25544 	 * The source address has already been initialized by the
25545 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25546 	 * be sufficient rather than MATCH_IRE_IPIF.
25547 	 *
25548 	 * This function is used for sending IGMP packets. We need
25549 	 * to make sure that we send the packet out of the interface
25550 	 * (ipif->ipif_ill) where we joined the group. This is to
25551 	 * prevent from switches doing IGMP snooping to send us multicast
25552 	 * packets for a given group on the interface we have joined.
25553 	 * If we can't find an ire, igmp_sendpkt has already initialized
25554 	 * ipsec_out_attach_if so that this will not be load spread in
25555 	 * ip_newroute_ipif.
25556 	 */
25557 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25558 	    MATCH_IRE_ILL, ipst);
25559 	if (!ire) {
25560 		/*
25561 		 * Mark this packet to make it be delivered to
25562 		 * ip_wput_ire after the new ire has been
25563 		 * created.
25564 		 */
25565 		mp->b_prev = NULL;
25566 		mp->b_next = NULL;
25567 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25568 		    zoneid, &zero_info);
25569 		return;
25570 	}
25571 
25572 	/*
25573 	 * Honor the RTF_SETSRC flag; this is the only case
25574 	 * where we force this addr whatever the current src addr is,
25575 	 * because this address is set by igmp_sendpkt(), and
25576 	 * cannot be specified by any user.
25577 	 */
25578 	if (ire->ire_flags & RTF_SETSRC) {
25579 		ipha->ipha_src = ire->ire_src_addr;
25580 	}
25581 
25582 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25583 }
25584 
25585 /*
25586  * NOTE : This function does not ire_refrele the ire argument passed in.
25587  *
25588  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25589  * failure. The nce_fp_mp can vanish any time in the case of
25590  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25591  * the ire_lock to access the nce_fp_mp in this case.
25592  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25593  * prepending a fastpath message IPQoS processing must precede it, we also set
25594  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25595  * (IPQoS might have set the b_band for CoS marking).
25596  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25597  * must follow it so that IPQoS can mark the dl_priority field for CoS
25598  * marking, if needed.
25599  */
25600 static mblk_t *
25601 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc,
25602     uint32_t ill_index, ipha_t **iphap)
25603 {
25604 	uint_t	hlen;
25605 	ipha_t *ipha;
25606 	mblk_t *mp1;
25607 	boolean_t qos_done = B_FALSE;
25608 	uchar_t	*ll_hdr;
25609 	ip_stack_t	*ipst = ire->ire_ipst;
25610 
25611 #define	rptr	((uchar_t *)ipha)
25612 
25613 	ipha = (ipha_t *)mp->b_rptr;
25614 	hlen = 0;
25615 	LOCK_IRE_FP_MP(ire);
25616 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25617 		ASSERT(DB_TYPE(mp1) == M_DATA);
25618 		/* Initiate IPPF processing */
25619 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25620 			UNLOCK_IRE_FP_MP(ire);
25621 			ip_process(proc, &mp, ill_index);
25622 			if (mp == NULL)
25623 				return (NULL);
25624 
25625 			ipha = (ipha_t *)mp->b_rptr;
25626 			LOCK_IRE_FP_MP(ire);
25627 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25628 				qos_done = B_TRUE;
25629 				goto no_fp_mp;
25630 			}
25631 			ASSERT(DB_TYPE(mp1) == M_DATA);
25632 		}
25633 		hlen = MBLKL(mp1);
25634 		/*
25635 		 * Check if we have enough room to prepend fastpath
25636 		 * header
25637 		 */
25638 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25639 			ll_hdr = rptr - hlen;
25640 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25641 			/*
25642 			 * Set the b_rptr to the start of the link layer
25643 			 * header
25644 			 */
25645 			mp->b_rptr = ll_hdr;
25646 			mp1 = mp;
25647 		} else {
25648 			mp1 = copyb(mp1);
25649 			if (mp1 == NULL)
25650 				goto unlock_err;
25651 			mp1->b_band = mp->b_band;
25652 			mp1->b_cont = mp;
25653 			/*
25654 			 * certain system generated traffic may not
25655 			 * have cred/label in ip header block. This
25656 			 * is true even for a labeled system. But for
25657 			 * labeled traffic, inherit the label in the
25658 			 * new header.
25659 			 */
25660 			if (DB_CRED(mp) != NULL)
25661 				mblk_setcred(mp1, DB_CRED(mp));
25662 			/*
25663 			 * XXX disable ICK_VALID and compute checksum
25664 			 * here; can happen if nce_fp_mp changes and
25665 			 * it can't be copied now due to insufficient
25666 			 * space. (unlikely, fp mp can change, but it
25667 			 * does not increase in length)
25668 			 */
25669 		}
25670 		UNLOCK_IRE_FP_MP(ire);
25671 	} else {
25672 no_fp_mp:
25673 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25674 		if (mp1 == NULL) {
25675 unlock_err:
25676 			UNLOCK_IRE_FP_MP(ire);
25677 			freemsg(mp);
25678 			return (NULL);
25679 		}
25680 		UNLOCK_IRE_FP_MP(ire);
25681 		mp1->b_cont = mp;
25682 		/*
25683 		 * certain system generated traffic may not
25684 		 * have cred/label in ip header block. This
25685 		 * is true even for a labeled system. But for
25686 		 * labeled traffic, inherit the label in the
25687 		 * new header.
25688 		 */
25689 		if (DB_CRED(mp) != NULL)
25690 			mblk_setcred(mp1, DB_CRED(mp));
25691 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25692 			ip_process(proc, &mp1, ill_index);
25693 			if (mp1 == NULL)
25694 				return (NULL);
25695 
25696 			if (mp1->b_cont == NULL)
25697 				ipha = NULL;
25698 			else
25699 				ipha = (ipha_t *)mp1->b_cont->b_rptr;
25700 		}
25701 	}
25702 
25703 	*iphap = ipha;
25704 	return (mp1);
25705 #undef rptr
25706 }
25707 
25708 /*
25709  * Finish the outbound IPsec processing for an IPv6 packet. This function
25710  * is called from ipsec_out_process() if the IPsec packet was processed
25711  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25712  * asynchronously.
25713  */
25714 void
25715 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25716     ire_t *ire_arg)
25717 {
25718 	in6_addr_t *v6dstp;
25719 	ire_t *ire;
25720 	mblk_t *mp;
25721 	ip6_t *ip6h1;
25722 	uint_t	ill_index;
25723 	ipsec_out_t *io;
25724 	boolean_t attach_if, hwaccel;
25725 	uint32_t flags = IP6_NO_IPPOLICY;
25726 	int match_flags;
25727 	zoneid_t zoneid;
25728 	boolean_t ill_need_rele = B_FALSE;
25729 	boolean_t ire_need_rele = B_FALSE;
25730 	ip_stack_t	*ipst;
25731 
25732 	mp = ipsec_mp->b_cont;
25733 	ip6h1 = (ip6_t *)mp->b_rptr;
25734 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25735 	ASSERT(io->ipsec_out_ns != NULL);
25736 	ipst = io->ipsec_out_ns->netstack_ip;
25737 	ill_index = io->ipsec_out_ill_index;
25738 	if (io->ipsec_out_reachable) {
25739 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25740 	}
25741 	attach_if = io->ipsec_out_attach_if;
25742 	hwaccel = io->ipsec_out_accelerated;
25743 	zoneid = io->ipsec_out_zoneid;
25744 	ASSERT(zoneid != ALL_ZONES);
25745 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25746 	/* Multicast addresses should have non-zero ill_index. */
25747 	v6dstp = &ip6h->ip6_dst;
25748 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25749 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25750 	ASSERT(!attach_if || ill_index != 0);
25751 	if (ill_index != 0) {
25752 		if (ill == NULL) {
25753 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
25754 			    B_TRUE, ipst);
25755 
25756 			/* Failure case frees things for us. */
25757 			if (ill == NULL)
25758 				return;
25759 
25760 			ill_need_rele = B_TRUE;
25761 		}
25762 		/*
25763 		 * If this packet needs to go out on a particular interface
25764 		 * honor it.
25765 		 */
25766 		if (attach_if) {
25767 			match_flags = MATCH_IRE_ILL;
25768 
25769 			/*
25770 			 * Check if we need an ire that will not be
25771 			 * looked up by anybody else i.e. HIDDEN.
25772 			 */
25773 			if (ill_is_probeonly(ill)) {
25774 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25775 			}
25776 		}
25777 	}
25778 	ASSERT(mp != NULL);
25779 
25780 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25781 		boolean_t unspec_src;
25782 		ipif_t	*ipif;
25783 
25784 		/*
25785 		 * Use the ill_index to get the right ill.
25786 		 */
25787 		unspec_src = io->ipsec_out_unspec_src;
25788 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25789 		if (ipif == NULL) {
25790 			if (ill_need_rele)
25791 				ill_refrele(ill);
25792 			freemsg(ipsec_mp);
25793 			return;
25794 		}
25795 
25796 		if (ire_arg != NULL) {
25797 			ire = ire_arg;
25798 		} else {
25799 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25800 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25801 			ire_need_rele = B_TRUE;
25802 		}
25803 		if (ire != NULL) {
25804 			ipif_refrele(ipif);
25805 			/*
25806 			 * XXX Do the multicast forwarding now, as the IPsec
25807 			 * processing has been done.
25808 			 */
25809 			goto send;
25810 		}
25811 
25812 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25813 		mp->b_prev = NULL;
25814 		mp->b_next = NULL;
25815 
25816 		/*
25817 		 * If the IPsec packet was processed asynchronously,
25818 		 * drop it now.
25819 		 */
25820 		if (q == NULL) {
25821 			if (ill_need_rele)
25822 				ill_refrele(ill);
25823 			freemsg(ipsec_mp);
25824 			return;
25825 		}
25826 
25827 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
25828 		    unspec_src, zoneid);
25829 		ipif_refrele(ipif);
25830 	} else {
25831 		if (attach_if) {
25832 			ipif_t	*ipif;
25833 
25834 			ipif = ipif_get_next_ipif(NULL, ill);
25835 			if (ipif == NULL) {
25836 				if (ill_need_rele)
25837 					ill_refrele(ill);
25838 				freemsg(ipsec_mp);
25839 				return;
25840 			}
25841 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25842 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25843 			ire_need_rele = B_TRUE;
25844 			ipif_refrele(ipif);
25845 		} else {
25846 			if (ire_arg != NULL) {
25847 				ire = ire_arg;
25848 			} else {
25849 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL,
25850 				    ipst);
25851 				ire_need_rele = B_TRUE;
25852 			}
25853 		}
25854 		if (ire != NULL)
25855 			goto send;
25856 		/*
25857 		 * ire disappeared underneath.
25858 		 *
25859 		 * What we need to do here is the ip_newroute
25860 		 * logic to get the ire without doing the IPsec
25861 		 * processing. Follow the same old path. But this
25862 		 * time, ip_wput or ire_add_then_send will call us
25863 		 * directly as all the IPsec operations are done.
25864 		 */
25865 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25866 		mp->b_prev = NULL;
25867 		mp->b_next = NULL;
25868 
25869 		/*
25870 		 * If the IPsec packet was processed asynchronously,
25871 		 * drop it now.
25872 		 */
25873 		if (q == NULL) {
25874 			if (ill_need_rele)
25875 				ill_refrele(ill);
25876 			freemsg(ipsec_mp);
25877 			return;
25878 		}
25879 
25880 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25881 		    zoneid, ipst);
25882 	}
25883 	if (ill != NULL && ill_need_rele)
25884 		ill_refrele(ill);
25885 	return;
25886 send:
25887 	if (ill != NULL && ill_need_rele)
25888 		ill_refrele(ill);
25889 
25890 	/* Local delivery */
25891 	if (ire->ire_stq == NULL) {
25892 		ill_t	*out_ill;
25893 		ASSERT(q != NULL);
25894 
25895 		/* PFHooks: LOOPBACK_OUT */
25896 		out_ill = ire_to_ill(ire);
25897 
25898 		/*
25899 		 * DTrace this as ip:::send.  A blocked packet will fire the
25900 		 * send probe, but not the receive probe.
25901 		 */
25902 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
25903 		    void_ip_t *, ip6h, __dtrace_ipsr_ill_t *, out_ill,
25904 		    ipha_t *, NULL, ip6_t *, ip6h, int, 1);
25905 
25906 		DTRACE_PROBE4(ip6__loopback__out__start,
25907 		    ill_t *, NULL, ill_t *, out_ill,
25908 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25909 
25910 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25911 		    ipst->ips_ipv6firewall_loopback_out,
25912 		    NULL, out_ill, ip6h1, ipsec_mp, mp, 0, ipst);
25913 
25914 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25915 
25916 		if (ipsec_mp != NULL) {
25917 			ip_wput_local_v6(RD(q), out_ill,
25918 			    ip6h, ipsec_mp, ire, 0, zoneid);
25919 		}
25920 		if (ire_need_rele)
25921 			ire_refrele(ire);
25922 		return;
25923 	}
25924 	/*
25925 	 * Everything is done. Send it out on the wire.
25926 	 * We force the insertion of a fragment header using the
25927 	 * IPH_FRAG_HDR flag in two cases:
25928 	 * - after reception of an ICMPv6 "packet too big" message
25929 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25930 	 * - for multirouted IPv6 packets, so that the receiver can
25931 	 *   discard duplicates according to their fragment identifier
25932 	 */
25933 	/* XXX fix flow control problems. */
25934 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25935 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25936 		if (hwaccel) {
25937 			/*
25938 			 * hardware acceleration does not handle these
25939 			 * "slow path" cases.
25940 			 */
25941 			/* IPsec KSTATS: should bump bean counter here. */
25942 			if (ire_need_rele)
25943 				ire_refrele(ire);
25944 			freemsg(ipsec_mp);
25945 			return;
25946 		}
25947 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25948 		    (mp->b_cont ? msgdsize(mp) :
25949 		    mp->b_wptr - (uchar_t *)ip6h)) {
25950 			/* IPsec KSTATS: should bump bean counter here. */
25951 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25952 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25953 			    msgdsize(mp)));
25954 			if (ire_need_rele)
25955 				ire_refrele(ire);
25956 			freemsg(ipsec_mp);
25957 			return;
25958 		}
25959 		ASSERT(mp->b_prev == NULL);
25960 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25961 		    ntohs(ip6h->ip6_plen) +
25962 		    IPV6_HDR_LEN, ire->ire_max_frag));
25963 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25964 		    ire->ire_max_frag);
25965 	} else {
25966 		UPDATE_OB_PKT_COUNT(ire);
25967 		ire->ire_last_used_time = lbolt;
25968 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25969 	}
25970 	if (ire_need_rele)
25971 		ire_refrele(ire);
25972 	freeb(ipsec_mp);
25973 }
25974 
25975 void
25976 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25977 {
25978 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25979 	da_ipsec_t *hada;	/* data attributes */
25980 	ill_t *ill = (ill_t *)q->q_ptr;
25981 
25982 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25983 
25984 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25985 		/* IPsec KSTATS: Bump lose counter here! */
25986 		freemsg(mp);
25987 		return;
25988 	}
25989 
25990 	/*
25991 	 * It's an IPsec packet that must be
25992 	 * accelerated by the Provider, and the
25993 	 * outbound ill is IPsec acceleration capable.
25994 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25995 	 * to the ill.
25996 	 * IPsec KSTATS: should bump packet counter here.
25997 	 */
25998 
25999 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
26000 	if (hada_mp == NULL) {
26001 		/* IPsec KSTATS: should bump packet counter here. */
26002 		freemsg(mp);
26003 		return;
26004 	}
26005 
26006 	hada_mp->b_datap->db_type = M_CTL;
26007 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
26008 	hada_mp->b_cont = mp;
26009 
26010 	hada = (da_ipsec_t *)hada_mp->b_rptr;
26011 	bzero(hada, sizeof (da_ipsec_t));
26012 	hada->da_type = IPHADA_M_CTL;
26013 
26014 	putnext(q, hada_mp);
26015 }
26016 
26017 /*
26018  * Finish the outbound IPsec processing. This function is called from
26019  * ipsec_out_process() if the IPsec packet was processed
26020  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
26021  * asynchronously.
26022  */
26023 void
26024 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
26025     ire_t *ire_arg)
26026 {
26027 	uint32_t v_hlen_tos_len;
26028 	ipaddr_t	dst;
26029 	ipif_t	*ipif = NULL;
26030 	ire_t *ire;
26031 	ire_t *ire1 = NULL;
26032 	mblk_t *next_mp = NULL;
26033 	uint32_t max_frag;
26034 	boolean_t multirt_send = B_FALSE;
26035 	mblk_t *mp;
26036 	ipha_t *ipha1;
26037 	uint_t	ill_index;
26038 	ipsec_out_t *io;
26039 	boolean_t attach_if;
26040 	int match_flags;
26041 	irb_t *irb = NULL;
26042 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
26043 	zoneid_t zoneid;
26044 	ipxmit_state_t	pktxmit_state;
26045 	ip_stack_t	*ipst;
26046 
26047 #ifdef	_BIG_ENDIAN
26048 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
26049 #else
26050 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
26051 #endif
26052 
26053 	mp = ipsec_mp->b_cont;
26054 	ipha1 = (ipha_t *)mp->b_rptr;
26055 	ASSERT(mp != NULL);
26056 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
26057 	dst = ipha->ipha_dst;
26058 
26059 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26060 	ill_index = io->ipsec_out_ill_index;
26061 	attach_if = io->ipsec_out_attach_if;
26062 	zoneid = io->ipsec_out_zoneid;
26063 	ASSERT(zoneid != ALL_ZONES);
26064 	ipst = io->ipsec_out_ns->netstack_ip;
26065 	ASSERT(io->ipsec_out_ns != NULL);
26066 
26067 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
26068 	if (ill_index != 0) {
26069 		if (ill == NULL) {
26070 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
26071 			    ill_index, B_FALSE, ipst);
26072 
26073 			/* Failure case frees things for us. */
26074 			if (ill == NULL)
26075 				return;
26076 
26077 			ill_need_rele = B_TRUE;
26078 		}
26079 		/*
26080 		 * If this packet needs to go out on a particular interface
26081 		 * honor it.
26082 		 */
26083 		if (attach_if) {
26084 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
26085 
26086 			/*
26087 			 * Check if we need an ire that will not be
26088 			 * looked up by anybody else i.e. HIDDEN.
26089 			 */
26090 			if (ill_is_probeonly(ill)) {
26091 				match_flags |= MATCH_IRE_MARK_HIDDEN;
26092 			}
26093 		}
26094 	}
26095 
26096 	if (CLASSD(dst)) {
26097 		boolean_t conn_dontroute;
26098 		/*
26099 		 * Use the ill_index to get the right ipif.
26100 		 */
26101 		conn_dontroute = io->ipsec_out_dontroute;
26102 		if (ill_index == 0)
26103 			ipif = ipif_lookup_group(dst, zoneid, ipst);
26104 		else
26105 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
26106 		if (ipif == NULL) {
26107 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
26108 			    " multicast\n"));
26109 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
26110 			freemsg(ipsec_mp);
26111 			goto done;
26112 		}
26113 		/*
26114 		 * ipha_src has already been intialized with the
26115 		 * value of the ipif in ip_wput. All we need now is
26116 		 * an ire to send this downstream.
26117 		 */
26118 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
26119 		    MBLK_GETLABEL(mp), match_flags, ipst);
26120 		if (ire != NULL) {
26121 			ill_t *ill1;
26122 			/*
26123 			 * Do the multicast forwarding now, as the IPsec
26124 			 * processing has been done.
26125 			 */
26126 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
26127 			    (ill1 = ire_to_ill(ire))) {
26128 				if (ip_mforward(ill1, ipha, mp)) {
26129 					freemsg(ipsec_mp);
26130 					ip1dbg(("ip_wput_ipsec_out: mforward "
26131 					    "failed\n"));
26132 					ire_refrele(ire);
26133 					goto done;
26134 				}
26135 			}
26136 			goto send;
26137 		}
26138 
26139 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
26140 		mp->b_prev = NULL;
26141 		mp->b_next = NULL;
26142 
26143 		/*
26144 		 * If the IPsec packet was processed asynchronously,
26145 		 * drop it now.
26146 		 */
26147 		if (q == NULL) {
26148 			freemsg(ipsec_mp);
26149 			goto done;
26150 		}
26151 
26152 		/*
26153 		 * We may be using a wrong ipif to create the ire.
26154 		 * But it is okay as the source address is assigned
26155 		 * for the packet already. Next outbound packet would
26156 		 * create the IRE with the right IPIF in ip_wput.
26157 		 *
26158 		 * Also handle RTF_MULTIRT routes.
26159 		 */
26160 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
26161 		    zoneid, &zero_info);
26162 	} else {
26163 		if (attach_if) {
26164 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
26165 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
26166 		} else {
26167 			if (ire_arg != NULL) {
26168 				ire = ire_arg;
26169 				ire_need_rele = B_FALSE;
26170 			} else {
26171 				ire = ire_cache_lookup(dst, zoneid,
26172 				    MBLK_GETLABEL(mp), ipst);
26173 			}
26174 		}
26175 		if (ire != NULL) {
26176 			goto send;
26177 		}
26178 
26179 		/*
26180 		 * ire disappeared underneath.
26181 		 *
26182 		 * What we need to do here is the ip_newroute
26183 		 * logic to get the ire without doing the IPsec
26184 		 * processing. Follow the same old path. But this
26185 		 * time, ip_wput or ire_add_then_put will call us
26186 		 * directly as all the IPsec operations are done.
26187 		 */
26188 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
26189 		mp->b_prev = NULL;
26190 		mp->b_next = NULL;
26191 
26192 		/*
26193 		 * If the IPsec packet was processed asynchronously,
26194 		 * drop it now.
26195 		 */
26196 		if (q == NULL) {
26197 			freemsg(ipsec_mp);
26198 			goto done;
26199 		}
26200 
26201 		/*
26202 		 * Since we're going through ip_newroute() again, we
26203 		 * need to make sure we don't:
26204 		 *
26205 		 *	1.) Trigger the ASSERT() with the ipha_ident
26206 		 *	    overloading.
26207 		 *	2.) Redo transport-layer checksumming, since we've
26208 		 *	    already done all that to get this far.
26209 		 *
26210 		 * The easiest way not do either of the above is to set
26211 		 * the ipha_ident field to IP_HDR_INCLUDED.
26212 		 */
26213 		ipha->ipha_ident = IP_HDR_INCLUDED;
26214 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
26215 		    zoneid, ipst);
26216 	}
26217 	goto done;
26218 send:
26219 	if (ire->ire_stq == NULL) {
26220 		ill_t	*out_ill;
26221 		/*
26222 		 * Loopbacks go through ip_wput_local except for one case.
26223 		 * We come here if we generate a icmp_frag_needed message
26224 		 * after IPsec processing is over. When this function calls
26225 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
26226 		 * icmp_frag_needed. The message generated comes back here
26227 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
26228 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
26229 		 * source address as it is usually set in ip_wput_ire. As
26230 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
26231 		 * and we end up here. We can't enter ip_wput_ire once the
26232 		 * IPsec processing is over and hence we need to do it here.
26233 		 */
26234 		ASSERT(q != NULL);
26235 		UPDATE_OB_PKT_COUNT(ire);
26236 		ire->ire_last_used_time = lbolt;
26237 		if (ipha->ipha_src == 0)
26238 			ipha->ipha_src = ire->ire_src_addr;
26239 
26240 		/* PFHooks: LOOPBACK_OUT */
26241 		out_ill = ire_to_ill(ire);
26242 
26243 		/*
26244 		 * DTrace this as ip:::send.  A blocked packet will fire the
26245 		 * send probe, but not the receive probe.
26246 		 */
26247 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
26248 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
26249 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
26250 
26251 		DTRACE_PROBE4(ip4__loopback__out__start,
26252 		    ill_t *, NULL, ill_t *, out_ill,
26253 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26254 
26255 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
26256 		    ipst->ips_ipv4firewall_loopback_out,
26257 		    NULL, out_ill, ipha1, ipsec_mp, mp, 0, ipst);
26258 
26259 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26260 
26261 		if (ipsec_mp != NULL)
26262 			ip_wput_local(RD(q), out_ill,
26263 			    ipha, ipsec_mp, ire, 0, zoneid);
26264 		if (ire_need_rele)
26265 			ire_refrele(ire);
26266 		goto done;
26267 	}
26268 
26269 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26270 		/*
26271 		 * We are through with IPsec processing.
26272 		 * Fragment this and send it on the wire.
26273 		 */
26274 		if (io->ipsec_out_accelerated) {
26275 			/*
26276 			 * The packet has been accelerated but must
26277 			 * be fragmented. This should not happen
26278 			 * since AH and ESP must not accelerate
26279 			 * packets that need fragmentation, however
26280 			 * the configuration could have changed
26281 			 * since the AH or ESP processing.
26282 			 * Drop packet.
26283 			 * IPsec KSTATS: bump bean counter here.
26284 			 */
26285 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26286 			    "fragmented accelerated packet!\n"));
26287 			freemsg(ipsec_mp);
26288 		} else {
26289 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid, ipst);
26290 		}
26291 		if (ire_need_rele)
26292 			ire_refrele(ire);
26293 		goto done;
26294 	}
26295 
26296 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26297 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26298 	    (void *)ire->ire_ipif, (void *)ipif));
26299 
26300 	/*
26301 	 * Multiroute the secured packet, unless IPsec really
26302 	 * requires the packet to go out only through a particular
26303 	 * interface.
26304 	 */
26305 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
26306 		ire_t *first_ire;
26307 		irb = ire->ire_bucket;
26308 		ASSERT(irb != NULL);
26309 		/*
26310 		 * This ire has been looked up as the one that
26311 		 * goes through the given ipif;
26312 		 * make sure we do not omit any other multiroute ire
26313 		 * that may be present in the bucket before this one.
26314 		 */
26315 		IRB_REFHOLD(irb);
26316 		for (first_ire = irb->irb_ire;
26317 		    first_ire != NULL;
26318 		    first_ire = first_ire->ire_next) {
26319 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26320 			    (first_ire->ire_addr == ire->ire_addr) &&
26321 			    !(first_ire->ire_marks &
26322 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
26323 				break;
26324 			}
26325 		}
26326 
26327 		if ((first_ire != NULL) && (first_ire != ire)) {
26328 			/*
26329 			 * Don't change the ire if the packet must
26330 			 * be fragmented if sent via this new one.
26331 			 */
26332 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26333 				IRE_REFHOLD(first_ire);
26334 				if (ire_need_rele)
26335 					ire_refrele(ire);
26336 				else
26337 					ire_need_rele = B_TRUE;
26338 				ire = first_ire;
26339 			}
26340 		}
26341 		IRB_REFRELE(irb);
26342 
26343 		multirt_send = B_TRUE;
26344 		max_frag = ire->ire_max_frag;
26345 	} else {
26346 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
26347 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
26348 			    "flag, attach_if %d\n", attach_if));
26349 		}
26350 	}
26351 
26352 	/*
26353 	 * In most cases, the emission loop below is entered only once.
26354 	 * Only in the case where the ire holds the RTF_MULTIRT
26355 	 * flag, we loop to process all RTF_MULTIRT ires in the
26356 	 * bucket, and send the packet through all crossed
26357 	 * RTF_MULTIRT routes.
26358 	 */
26359 	do {
26360 		if (multirt_send) {
26361 			/*
26362 			 * ire1 holds here the next ire to process in the
26363 			 * bucket. If multirouting is expected,
26364 			 * any non-RTF_MULTIRT ire that has the
26365 			 * right destination address is ignored.
26366 			 */
26367 			ASSERT(irb != NULL);
26368 			IRB_REFHOLD(irb);
26369 			for (ire1 = ire->ire_next;
26370 			    ire1 != NULL;
26371 			    ire1 = ire1->ire_next) {
26372 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26373 					continue;
26374 				if (ire1->ire_addr != ire->ire_addr)
26375 					continue;
26376 				if (ire1->ire_marks &
26377 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
26378 					continue;
26379 				/* No loopback here */
26380 				if (ire1->ire_stq == NULL)
26381 					continue;
26382 				/*
26383 				 * Ensure we do not exceed the MTU
26384 				 * of the next route.
26385 				 */
26386 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26387 					ip_multirt_bad_mtu(ire1, max_frag);
26388 					continue;
26389 				}
26390 
26391 				IRE_REFHOLD(ire1);
26392 				break;
26393 			}
26394 			IRB_REFRELE(irb);
26395 			if (ire1 != NULL) {
26396 				/*
26397 				 * We are in a multiple send case, need to
26398 				 * make a copy of the packet.
26399 				 */
26400 				next_mp = copymsg(ipsec_mp);
26401 				if (next_mp == NULL) {
26402 					ire_refrele(ire1);
26403 					ire1 = NULL;
26404 				}
26405 			}
26406 		}
26407 		/*
26408 		 * Everything is done. Send it out on the wire
26409 		 *
26410 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26411 		 * either send it on the wire or, in the case of
26412 		 * HW acceleration, call ipsec_hw_putnext.
26413 		 */
26414 		if (ire->ire_nce &&
26415 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26416 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26417 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26418 			/*
26419 			 * If ire's link-layer is unresolved (this
26420 			 * would only happen if the incomplete ire
26421 			 * was added to cachetable via forwarding path)
26422 			 * don't bother going to ip_xmit_v4. Just drop the
26423 			 * packet.
26424 			 * There is a slight risk here, in that, if we
26425 			 * have the forwarding path create an incomplete
26426 			 * IRE, then until the IRE is completed, any
26427 			 * transmitted IPsec packets will be dropped
26428 			 * instead of being queued waiting for resolution.
26429 			 *
26430 			 * But the likelihood of a forwarding packet and a wput
26431 			 * packet sending to the same dst at the same time
26432 			 * and there not yet be an ARP entry for it is small.
26433 			 * Furthermore, if this actually happens, it might
26434 			 * be likely that wput would generate multiple
26435 			 * packets (and forwarding would also have a train
26436 			 * of packets) for that destination. If this is
26437 			 * the case, some of them would have been dropped
26438 			 * anyway, since ARP only queues a few packets while
26439 			 * waiting for resolution
26440 			 *
26441 			 * NOTE: We should really call ip_xmit_v4,
26442 			 * and let it queue the packet and send the
26443 			 * ARP query and have ARP come back thus:
26444 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26445 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26446 			 * hw accel work. But it's too complex to get
26447 			 * the IPsec hw  acceleration approach to fit
26448 			 * well with ip_xmit_v4 doing ARP without
26449 			 * doing IPsec simplification. For now, we just
26450 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26451 			 * that we can continue with the send on the next
26452 			 * attempt.
26453 			 *
26454 			 * XXX THis should be revisited, when
26455 			 * the IPsec/IP interaction is cleaned up
26456 			 */
26457 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26458 			    " - dropping packet\n"));
26459 			freemsg(ipsec_mp);
26460 			/*
26461 			 * Call ip_xmit_v4() to trigger ARP query
26462 			 * in case the nce_state is ND_INITIAL
26463 			 */
26464 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26465 			goto drop_pkt;
26466 		}
26467 
26468 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26469 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26470 		    mblk_t *, ipsec_mp);
26471 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26472 		    ipst->ips_ipv4firewall_physical_out, NULL,
26473 		    ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, 0, ipst);
26474 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26475 		if (ipsec_mp == NULL)
26476 			goto drop_pkt;
26477 
26478 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26479 		pktxmit_state = ip_xmit_v4(mp, ire,
26480 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
26481 
26482 		if ((pktxmit_state ==  SEND_FAILED) ||
26483 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26484 
26485 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26486 drop_pkt:
26487 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26488 			    ipIfStatsOutDiscards);
26489 			if (ire_need_rele)
26490 				ire_refrele(ire);
26491 			if (ire1 != NULL) {
26492 				ire_refrele(ire1);
26493 				freemsg(next_mp);
26494 			}
26495 			goto done;
26496 		}
26497 
26498 		freeb(ipsec_mp);
26499 		if (ire_need_rele)
26500 			ire_refrele(ire);
26501 
26502 		if (ire1 != NULL) {
26503 			ire = ire1;
26504 			ire_need_rele = B_TRUE;
26505 			ASSERT(next_mp);
26506 			ipsec_mp = next_mp;
26507 			mp = ipsec_mp->b_cont;
26508 			ire1 = NULL;
26509 			next_mp = NULL;
26510 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26511 		} else {
26512 			multirt_send = B_FALSE;
26513 		}
26514 	} while (multirt_send);
26515 done:
26516 	if (ill != NULL && ill_need_rele)
26517 		ill_refrele(ill);
26518 	if (ipif != NULL)
26519 		ipif_refrele(ipif);
26520 }
26521 
26522 /*
26523  * Get the ill corresponding to the specified ire, and compare its
26524  * capabilities with the protocol and algorithms specified by the
26525  * the SA obtained from ipsec_out. If they match, annotate the
26526  * ipsec_out structure to indicate that the packet needs acceleration.
26527  *
26528  *
26529  * A packet is eligible for outbound hardware acceleration if the
26530  * following conditions are satisfied:
26531  *
26532  * 1. the packet will not be fragmented
26533  * 2. the provider supports the algorithm
26534  * 3. there is no pending control message being exchanged
26535  * 4. snoop is not attached
26536  * 5. the destination address is not a broadcast or multicast address.
26537  *
26538  * Rationale:
26539  *	- Hardware drivers do not support fragmentation with
26540  *	  the current interface.
26541  *	- snoop, multicast, and broadcast may result in exposure of
26542  *	  a cleartext datagram.
26543  * We check all five of these conditions here.
26544  *
26545  * XXX would like to nuke "ire_t *" parameter here; problem is that
26546  * IRE is only way to figure out if a v4 address is a broadcast and
26547  * thus ineligible for acceleration...
26548  */
26549 static void
26550 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26551 {
26552 	ipsec_out_t *io;
26553 	mblk_t *data_mp;
26554 	uint_t plen, overhead;
26555 	ip_stack_t	*ipst;
26556 
26557 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26558 		return;
26559 
26560 	if (ill == NULL)
26561 		return;
26562 	ipst = ill->ill_ipst;
26563 	/*
26564 	 * Destination address is a broadcast or multicast.  Punt.
26565 	 */
26566 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26567 	    IRE_LOCAL)))
26568 		return;
26569 
26570 	data_mp = ipsec_mp->b_cont;
26571 
26572 	if (ill->ill_isv6) {
26573 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26574 
26575 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26576 			return;
26577 
26578 		plen = ip6h->ip6_plen;
26579 	} else {
26580 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26581 
26582 		if (CLASSD(ipha->ipha_dst))
26583 			return;
26584 
26585 		plen = ipha->ipha_length;
26586 	}
26587 	/*
26588 	 * Is there a pending DLPI control message being exchanged
26589 	 * between IP/IPsec and the DLS Provider? If there is, it
26590 	 * could be a SADB update, and the state of the DLS Provider
26591 	 * SADB might not be in sync with the SADB maintained by
26592 	 * IPsec. To avoid dropping packets or using the wrong keying
26593 	 * material, we do not accelerate this packet.
26594 	 */
26595 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26596 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26597 		    "ill_dlpi_pending! don't accelerate packet\n"));
26598 		return;
26599 	}
26600 
26601 	/*
26602 	 * Is the Provider in promiscous mode? If it does, we don't
26603 	 * accelerate the packet since it will bounce back up to the
26604 	 * listeners in the clear.
26605 	 */
26606 	if (ill->ill_promisc_on_phys) {
26607 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26608 		    "ill in promiscous mode, don't accelerate packet\n"));
26609 		return;
26610 	}
26611 
26612 	/*
26613 	 * Will the packet require fragmentation?
26614 	 */
26615 
26616 	/*
26617 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26618 	 * as is used elsewhere.
26619 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26620 	 *	+ 2-byte trailer
26621 	 */
26622 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26623 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26624 
26625 	if ((plen + overhead) > ill->ill_max_mtu)
26626 		return;
26627 
26628 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26629 
26630 	/*
26631 	 * Can the ill accelerate this IPsec protocol and algorithm
26632 	 * specified by the SA?
26633 	 */
26634 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26635 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26636 		return;
26637 	}
26638 
26639 	/*
26640 	 * Tell AH or ESP that the outbound ill is capable of
26641 	 * accelerating this packet.
26642 	 */
26643 	io->ipsec_out_is_capab_ill = B_TRUE;
26644 }
26645 
26646 /*
26647  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26648  *
26649  * If this function returns B_TRUE, the requested SA's have been filled
26650  * into the ipsec_out_*_sa pointers.
26651  *
26652  * If the function returns B_FALSE, the packet has been "consumed", most
26653  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26654  *
26655  * The SA references created by the protocol-specific "select"
26656  * function will be released when the ipsec_mp is freed, thanks to the
26657  * ipsec_out_free destructor -- see spd.c.
26658  */
26659 static boolean_t
26660 ipsec_out_select_sa(mblk_t *ipsec_mp)
26661 {
26662 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26663 	ipsec_out_t *io;
26664 	ipsec_policy_t *pp;
26665 	ipsec_action_t *ap;
26666 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26667 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26668 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26669 
26670 	if (!io->ipsec_out_secure) {
26671 		/*
26672 		 * We came here by mistake.
26673 		 * Don't bother with ipsec processing
26674 		 * We should "discourage" this path in the future.
26675 		 */
26676 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26677 		return (B_FALSE);
26678 	}
26679 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26680 	ASSERT((io->ipsec_out_policy != NULL) ||
26681 	    (io->ipsec_out_act != NULL));
26682 
26683 	ASSERT(io->ipsec_out_failed == B_FALSE);
26684 
26685 	/*
26686 	 * IPsec processing has started.
26687 	 */
26688 	io->ipsec_out_proc_begin = B_TRUE;
26689 	ap = io->ipsec_out_act;
26690 	if (ap == NULL) {
26691 		pp = io->ipsec_out_policy;
26692 		ASSERT(pp != NULL);
26693 		ap = pp->ipsp_act;
26694 		ASSERT(ap != NULL);
26695 	}
26696 
26697 	/*
26698 	 * We have an action.  now, let's select SA's.
26699 	 * (In the future, we can cache this in the conn_t..)
26700 	 */
26701 	if (ap->ipa_want_esp) {
26702 		if (io->ipsec_out_esp_sa == NULL) {
26703 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26704 			    IPPROTO_ESP);
26705 		}
26706 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26707 	}
26708 
26709 	if (ap->ipa_want_ah) {
26710 		if (io->ipsec_out_ah_sa == NULL) {
26711 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26712 			    IPPROTO_AH);
26713 		}
26714 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26715 		/*
26716 		 * The ESP and AH processing order needs to be preserved
26717 		 * when both protocols are required (ESP should be applied
26718 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26719 		 * when both ESP and AH are required, and an AH ACQUIRE
26720 		 * is needed.
26721 		 */
26722 		if (ap->ipa_want_esp && need_ah_acquire)
26723 			need_esp_acquire = B_TRUE;
26724 	}
26725 
26726 	/*
26727 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26728 	 * Release SAs that got referenced, but will not be used until we
26729 	 * acquire _all_ of the SAs we need.
26730 	 */
26731 	if (need_ah_acquire || need_esp_acquire) {
26732 		if (io->ipsec_out_ah_sa != NULL) {
26733 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26734 			io->ipsec_out_ah_sa = NULL;
26735 		}
26736 		if (io->ipsec_out_esp_sa != NULL) {
26737 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26738 			io->ipsec_out_esp_sa = NULL;
26739 		}
26740 
26741 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26742 		return (B_FALSE);
26743 	}
26744 
26745 	return (B_TRUE);
26746 }
26747 
26748 /*
26749  * Process an IPSEC_OUT message and see what you can
26750  * do with it.
26751  * IPQoS Notes:
26752  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26753  * IPsec.
26754  * XXX would like to nuke ire_t.
26755  * XXX ill_index better be "real"
26756  */
26757 void
26758 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26759 {
26760 	ipsec_out_t *io;
26761 	ipsec_policy_t *pp;
26762 	ipsec_action_t *ap;
26763 	ipha_t *ipha;
26764 	ip6_t *ip6h;
26765 	mblk_t *mp;
26766 	ill_t *ill;
26767 	zoneid_t zoneid;
26768 	ipsec_status_t ipsec_rc;
26769 	boolean_t ill_need_rele = B_FALSE;
26770 	ip_stack_t	*ipst;
26771 	ipsec_stack_t	*ipss;
26772 
26773 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26774 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26775 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26776 	ipst = io->ipsec_out_ns->netstack_ip;
26777 	mp = ipsec_mp->b_cont;
26778 
26779 	/*
26780 	 * Initiate IPPF processing. We do it here to account for packets
26781 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26782 	 * We can check for ipsec_out_proc_begin even for such packets, as
26783 	 * they will always be false (asserted below).
26784 	 */
26785 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26786 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26787 		    io->ipsec_out_ill_index : ill_index);
26788 		if (mp == NULL) {
26789 			ip2dbg(("ipsec_out_process: packet dropped "\
26790 			    "during IPPF processing\n"));
26791 			freeb(ipsec_mp);
26792 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26793 			return;
26794 		}
26795 	}
26796 
26797 	if (!io->ipsec_out_secure) {
26798 		/*
26799 		 * We came here by mistake.
26800 		 * Don't bother with ipsec processing
26801 		 * Should "discourage" this path in the future.
26802 		 */
26803 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26804 		goto done;
26805 	}
26806 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26807 	ASSERT((io->ipsec_out_policy != NULL) ||
26808 	    (io->ipsec_out_act != NULL));
26809 	ASSERT(io->ipsec_out_failed == B_FALSE);
26810 
26811 	ipss = ipst->ips_netstack->netstack_ipsec;
26812 	if (!ipsec_loaded(ipss)) {
26813 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26814 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26815 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26816 		} else {
26817 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26818 		}
26819 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26820 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26821 		    &ipss->ipsec_dropper);
26822 		return;
26823 	}
26824 
26825 	/*
26826 	 * IPsec processing has started.
26827 	 */
26828 	io->ipsec_out_proc_begin = B_TRUE;
26829 	ap = io->ipsec_out_act;
26830 	if (ap == NULL) {
26831 		pp = io->ipsec_out_policy;
26832 		ASSERT(pp != NULL);
26833 		ap = pp->ipsp_act;
26834 		ASSERT(ap != NULL);
26835 	}
26836 
26837 	/*
26838 	 * Save the outbound ill index. When the packet comes back
26839 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26840 	 * before sending it the accelerated packet.
26841 	 */
26842 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26843 		int ifindex;
26844 		ill = ire_to_ill(ire);
26845 		ifindex = ill->ill_phyint->phyint_ifindex;
26846 		io->ipsec_out_capab_ill_index = ifindex;
26847 	}
26848 
26849 	/*
26850 	 * The order of processing is first insert a IP header if needed.
26851 	 * Then insert the ESP header and then the AH header.
26852 	 */
26853 	if ((io->ipsec_out_se_done == B_FALSE) &&
26854 	    (ap->ipa_want_se)) {
26855 		/*
26856 		 * First get the outer IP header before sending
26857 		 * it to ESP.
26858 		 */
26859 		ipha_t *oipha, *iipha;
26860 		mblk_t *outer_mp, *inner_mp;
26861 
26862 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26863 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26864 			    "ipsec_out_process: "
26865 			    "Self-Encapsulation failed: Out of memory\n");
26866 			freemsg(ipsec_mp);
26867 			if (ill != NULL) {
26868 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26869 			} else {
26870 				BUMP_MIB(&ipst->ips_ip_mib,
26871 				    ipIfStatsOutDiscards);
26872 			}
26873 			return;
26874 		}
26875 		inner_mp = ipsec_mp->b_cont;
26876 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26877 		oipha = (ipha_t *)outer_mp->b_rptr;
26878 		iipha = (ipha_t *)inner_mp->b_rptr;
26879 		*oipha = *iipha;
26880 		outer_mp->b_wptr += sizeof (ipha_t);
26881 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26882 		    sizeof (ipha_t));
26883 		oipha->ipha_protocol = IPPROTO_ENCAP;
26884 		oipha->ipha_version_and_hdr_length =
26885 		    IP_SIMPLE_HDR_VERSION;
26886 		oipha->ipha_hdr_checksum = 0;
26887 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26888 		outer_mp->b_cont = inner_mp;
26889 		ipsec_mp->b_cont = outer_mp;
26890 
26891 		io->ipsec_out_se_done = B_TRUE;
26892 		io->ipsec_out_tunnel = B_TRUE;
26893 	}
26894 
26895 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26896 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26897 	    !ipsec_out_select_sa(ipsec_mp))
26898 		return;
26899 
26900 	/*
26901 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26902 	 * to do the heavy lifting.
26903 	 */
26904 	zoneid = io->ipsec_out_zoneid;
26905 	ASSERT(zoneid != ALL_ZONES);
26906 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26907 		ASSERT(io->ipsec_out_esp_sa != NULL);
26908 		io->ipsec_out_esp_done = B_TRUE;
26909 		/*
26910 		 * Note that since hw accel can only apply one transform,
26911 		 * not two, we skip hw accel for ESP if we also have AH
26912 		 * This is an design limitation of the interface
26913 		 * which should be revisited.
26914 		 */
26915 		ASSERT(ire != NULL);
26916 		if (io->ipsec_out_ah_sa == NULL) {
26917 			ill = (ill_t *)ire->ire_stq->q_ptr;
26918 			ipsec_out_is_accelerated(ipsec_mp,
26919 			    io->ipsec_out_esp_sa, ill, ire);
26920 		}
26921 
26922 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26923 		switch (ipsec_rc) {
26924 		case IPSEC_STATUS_SUCCESS:
26925 			break;
26926 		case IPSEC_STATUS_FAILED:
26927 			if (ill != NULL) {
26928 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26929 			} else {
26930 				BUMP_MIB(&ipst->ips_ip_mib,
26931 				    ipIfStatsOutDiscards);
26932 			}
26933 			/* FALLTHRU */
26934 		case IPSEC_STATUS_PENDING:
26935 			return;
26936 		}
26937 	}
26938 
26939 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26940 		ASSERT(io->ipsec_out_ah_sa != NULL);
26941 		io->ipsec_out_ah_done = B_TRUE;
26942 		if (ire == NULL) {
26943 			int idx = io->ipsec_out_capab_ill_index;
26944 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26945 			    NULL, NULL, NULL, NULL, ipst);
26946 			ill_need_rele = B_TRUE;
26947 		} else {
26948 			ill = (ill_t *)ire->ire_stq->q_ptr;
26949 		}
26950 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26951 		    ire);
26952 
26953 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26954 		switch (ipsec_rc) {
26955 		case IPSEC_STATUS_SUCCESS:
26956 			break;
26957 		case IPSEC_STATUS_FAILED:
26958 			if (ill != NULL) {
26959 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26960 			} else {
26961 				BUMP_MIB(&ipst->ips_ip_mib,
26962 				    ipIfStatsOutDiscards);
26963 			}
26964 			/* FALLTHRU */
26965 		case IPSEC_STATUS_PENDING:
26966 			if (ill != NULL && ill_need_rele)
26967 				ill_refrele(ill);
26968 			return;
26969 		}
26970 	}
26971 	/*
26972 	 * We are done with IPsec processing. Send it over
26973 	 * the wire.
26974 	 */
26975 done:
26976 	mp = ipsec_mp->b_cont;
26977 	ipha = (ipha_t *)mp->b_rptr;
26978 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26979 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
26980 	} else {
26981 		ip6h = (ip6_t *)ipha;
26982 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
26983 	}
26984 	if (ill != NULL && ill_need_rele)
26985 		ill_refrele(ill);
26986 }
26987 
26988 /* ARGSUSED */
26989 void
26990 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26991 {
26992 	opt_restart_t	*or;
26993 	int	err;
26994 	conn_t	*connp;
26995 
26996 	ASSERT(CONN_Q(q));
26997 	connp = Q_TO_CONN(q);
26998 
26999 	ASSERT(first_mp->b_datap->db_type == M_CTL);
27000 	or = (opt_restart_t *)first_mp->b_rptr;
27001 	/*
27002 	 * We don't need to pass any credentials here since this is just
27003 	 * a restart. The credentials are passed in when svr4_optcom_req
27004 	 * is called the first time (from ip_wput_nondata).
27005 	 */
27006 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
27007 		err = svr4_optcom_req(q, first_mp, NULL,
27008 		    &ip_opt_obj, B_FALSE);
27009 	} else {
27010 		ASSERT(or->or_type == T_OPTMGMT_REQ);
27011 		err = tpi_optcom_req(q, first_mp, NULL,
27012 		    &ip_opt_obj, B_FALSE);
27013 	}
27014 	if (err != EINPROGRESS) {
27015 		/* operation is done */
27016 		CONN_OPER_PENDING_DONE(connp);
27017 	}
27018 }
27019 
27020 /*
27021  * ioctls that go through a down/up sequence may need to wait for the down
27022  * to complete. This involves waiting for the ire and ipif refcnts to go down
27023  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
27024  */
27025 /* ARGSUSED */
27026 void
27027 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27028 {
27029 	struct iocblk *iocp;
27030 	mblk_t *mp1;
27031 	ip_ioctl_cmd_t *ipip;
27032 	int err;
27033 	sin_t	*sin;
27034 	struct lifreq *lifr;
27035 	struct ifreq *ifr;
27036 
27037 	iocp = (struct iocblk *)mp->b_rptr;
27038 	ASSERT(ipsq != NULL);
27039 	/* Existence of mp1 verified in ip_wput_nondata */
27040 	mp1 = mp->b_cont->b_cont;
27041 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27042 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
27043 		/*
27044 		 * Special case where ipsq_current_ipif is not set:
27045 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
27046 		 * ill could also have become part of a ipmp group in the
27047 		 * process, we are here as were not able to complete the
27048 		 * operation in ipif_set_values because we could not become
27049 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
27050 		 * will not be set so we need to set it.
27051 		 */
27052 		ill_t *ill = q->q_ptr;
27053 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
27054 	}
27055 	ASSERT(ipsq->ipsq_current_ipif != NULL);
27056 
27057 	if (ipip->ipi_cmd_type == IF_CMD) {
27058 		/* This a old style SIOC[GS]IF* command */
27059 		ifr = (struct ifreq *)mp1->b_rptr;
27060 		sin = (sin_t *)&ifr->ifr_addr;
27061 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
27062 		/* This a new style SIOC[GS]LIF* command */
27063 		lifr = (struct lifreq *)mp1->b_rptr;
27064 		sin = (sin_t *)&lifr->lifr_addr;
27065 	} else {
27066 		sin = NULL;
27067 	}
27068 
27069 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_current_ipif, sin, q, mp,
27070 	    ipip, mp1->b_rptr);
27071 
27072 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27073 }
27074 
27075 /*
27076  * ioctl processing
27077  *
27078  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
27079  * the ioctl command in the ioctl tables, determines the copyin data size
27080  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
27081  *
27082  * ioctl processing then continues when the M_IOCDATA makes its way down to
27083  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
27084  * associated 'conn' is refheld till the end of the ioctl and the general
27085  * ioctl processing function ip_process_ioctl() is called to extract the
27086  * arguments and process the ioctl.  To simplify extraction, ioctl commands
27087  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
27088  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
27089  * is used to extract the ioctl's arguments.
27090  *
27091  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
27092  * so goes thru the serialization primitive ipsq_try_enter. Then the
27093  * appropriate function to handle the ioctl is called based on the entry in
27094  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
27095  * which also refreleases the 'conn' that was refheld at the start of the
27096  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
27097  *
27098  * Many exclusive ioctls go thru an internal down up sequence as part of
27099  * the operation. For example an attempt to change the IP address of an
27100  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
27101  * does all the cleanup such as deleting all ires that use this address.
27102  * Then we need to wait till all references to the interface go away.
27103  */
27104 void
27105 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
27106 {
27107 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
27108 	ip_ioctl_cmd_t *ipip = arg;
27109 	ip_extract_func_t *extract_funcp;
27110 	cmd_info_t ci;
27111 	int err;
27112 
27113 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
27114 
27115 	if (ipip == NULL)
27116 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27117 
27118 	/*
27119 	 * SIOCLIFADDIF needs to go thru a special path since the
27120 	 * ill may not exist yet. This happens in the case of lo0
27121 	 * which is created using this ioctl.
27122 	 */
27123 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
27124 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
27125 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27126 		return;
27127 	}
27128 
27129 	ci.ci_ipif = NULL;
27130 	if (ipip->ipi_cmd_type == MISC_CMD) {
27131 		/*
27132 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
27133 		 */
27134 		if (ipip->ipi_cmd == IF_UNITSEL) {
27135 			/* ioctl comes down the ill */
27136 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
27137 			ipif_refhold(ci.ci_ipif);
27138 		}
27139 		err = 0;
27140 		ci.ci_sin = NULL;
27141 		ci.ci_sin6 = NULL;
27142 		ci.ci_lifr = NULL;
27143 	} else {
27144 		switch (ipip->ipi_cmd_type) {
27145 		case IF_CMD:
27146 		case LIF_CMD:
27147 			extract_funcp = ip_extract_lifreq;
27148 			break;
27149 
27150 		case ARP_CMD:
27151 		case XARP_CMD:
27152 			extract_funcp = ip_extract_arpreq;
27153 			break;
27154 
27155 		case TUN_CMD:
27156 			extract_funcp = ip_extract_tunreq;
27157 			break;
27158 
27159 		case MSFILT_CMD:
27160 			extract_funcp = ip_extract_msfilter;
27161 			break;
27162 
27163 		default:
27164 			ASSERT(0);
27165 		}
27166 
27167 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
27168 		if (err != 0) {
27169 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27170 			return;
27171 		}
27172 
27173 		/*
27174 		 * All of the extraction functions return a refheld ipif.
27175 		 */
27176 		ASSERT(ci.ci_ipif != NULL);
27177 	}
27178 
27179 	if (!(ipip->ipi_flags & IPI_WR)) {
27180 		/*
27181 		 * A return value of EINPROGRESS means the ioctl is
27182 		 * either queued and waiting for some reason or has
27183 		 * already completed.
27184 		 */
27185 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
27186 		    ci.ci_lifr);
27187 		if (ci.ci_ipif != NULL)
27188 			ipif_refrele(ci.ci_ipif);
27189 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27190 		return;
27191 	}
27192 
27193 	/*
27194 	 * If ipsq is non-null, we are already being called exclusively on an
27195 	 * ill but in the case of a failover in progress it is the "from" ill,
27196 	 *  rather than the "to" ill (which is the ill ptr passed in).
27197 	 * In order to ensure we are exclusive on both ILLs we rerun
27198 	 * ipsq_try_enter() here, ipsq's support recursive entry.
27199 	 */
27200 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
27201 	ASSERT(ci.ci_ipif != NULL);
27202 
27203 	ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
27204 	    NEW_OP, B_TRUE);
27205 
27206 	/*
27207 	 * Release the ipif so that ipif_down and friends that wait for
27208 	 * references to go away are not misled about the current ipif_refcnt
27209 	 * values. We are writer so we can access the ipif even after releasing
27210 	 * the ipif.
27211 	 */
27212 	ipif_refrele(ci.ci_ipif);
27213 	if (ipsq == NULL)
27214 		return;
27215 
27216 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
27217 
27218 	/*
27219 	 * For most set ioctls that come here, this serves as a single point
27220 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
27221 	 * be any new references to the ipif. This helps functions that go
27222 	 * through this path and end up trying to wait for the refcnts
27223 	 * associated with the ipif to go down to zero. Some exceptions are
27224 	 * Failover, Failback, and Groupname commands that operate on more than
27225 	 * just the ci.ci_ipif. These commands internally determine the
27226 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
27227 	 * flags on that set. Another exception is the Removeif command that
27228 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
27229 	 * ipif to operate on.
27230 	 */
27231 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
27232 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
27233 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
27234 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
27235 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
27236 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
27237 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
27238 
27239 	/*
27240 	 * A return value of EINPROGRESS means the ioctl is
27241 	 * either queued and waiting for some reason or has
27242 	 * already completed.
27243 	 */
27244 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
27245 
27246 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27247 
27248 	ipsq_exit(ipsq);
27249 }
27250 
27251 /*
27252  * Complete the ioctl. Typically ioctls use the mi package and need to
27253  * do mi_copyout/mi_copy_done.
27254  */
27255 void
27256 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
27257 {
27258 	conn_t	*connp = NULL;
27259 
27260 	if (err == EINPROGRESS)
27261 		return;
27262 
27263 	if (CONN_Q(q)) {
27264 		connp = Q_TO_CONN(q);
27265 		ASSERT(connp->conn_ref >= 2);
27266 	}
27267 
27268 	switch (mode) {
27269 	case COPYOUT:
27270 		if (err == 0)
27271 			mi_copyout(q, mp);
27272 		else
27273 			mi_copy_done(q, mp, err);
27274 		break;
27275 
27276 	case NO_COPYOUT:
27277 		mi_copy_done(q, mp, err);
27278 		break;
27279 
27280 	default:
27281 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27282 		break;
27283 	}
27284 
27285 	/*
27286 	 * The refhold placed at the start of the ioctl is released here.
27287 	 */
27288 	if (connp != NULL)
27289 		CONN_OPER_PENDING_DONE(connp);
27290 
27291 	if (ipsq != NULL)
27292 		ipsq_current_finish(ipsq);
27293 }
27294 
27295 /*
27296  * This is called from ip_wput_nondata to resume a deferred TCP bind.
27297  */
27298 /* ARGSUSED */
27299 void
27300 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
27301 {
27302 	conn_t *connp = arg;
27303 	tcp_t	*tcp;
27304 
27305 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
27306 	tcp = connp->conn_tcp;
27307 
27308 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
27309 		freemsg(mp);
27310 	else
27311 		tcp_rput_other(tcp, mp);
27312 	CONN_OPER_PENDING_DONE(connp);
27313 }
27314 
27315 /* Called from ip_wput for all non data messages */
27316 /* ARGSUSED */
27317 void
27318 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27319 {
27320 	mblk_t		*mp1;
27321 	ire_t		*ire, *fake_ire;
27322 	ill_t		*ill;
27323 	struct iocblk	*iocp;
27324 	ip_ioctl_cmd_t	*ipip;
27325 	cred_t		*cr;
27326 	conn_t		*connp;
27327 	int		err;
27328 	nce_t		*nce;
27329 	ipif_t		*ipif;
27330 	ip_stack_t	*ipst;
27331 	char		*proto_str;
27332 
27333 	if (CONN_Q(q)) {
27334 		connp = Q_TO_CONN(q);
27335 		ipst = connp->conn_netstack->netstack_ip;
27336 	} else {
27337 		connp = NULL;
27338 		ipst = ILLQ_TO_IPST(q);
27339 	}
27340 
27341 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
27342 
27343 	switch (DB_TYPE(mp)) {
27344 	case M_IOCTL:
27345 		/*
27346 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27347 		 * will arrange to copy in associated control structures.
27348 		 */
27349 		ip_sioctl_copyin_setup(q, mp);
27350 		return;
27351 	case M_IOCDATA:
27352 		/*
27353 		 * Ensure that this is associated with one of our trans-
27354 		 * parent ioctls.  If it's not ours, discard it if we're
27355 		 * running as a driver, or pass it on if we're a module.
27356 		 */
27357 		iocp = (struct iocblk *)mp->b_rptr;
27358 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27359 		if (ipip == NULL) {
27360 			if (q->q_next == NULL) {
27361 				goto nak;
27362 			} else {
27363 				putnext(q, mp);
27364 			}
27365 			return;
27366 		}
27367 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
27368 			/*
27369 			 * the ioctl is one we recognise, but is not
27370 			 * consumed by IP as a module, pass M_IOCDATA
27371 			 * for processing downstream, but only for
27372 			 * common Streams ioctls.
27373 			 */
27374 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27375 				putnext(q, mp);
27376 				return;
27377 			} else {
27378 				goto nak;
27379 			}
27380 		}
27381 
27382 		/* IOCTL continuation following copyin or copyout. */
27383 		if (mi_copy_state(q, mp, NULL) == -1) {
27384 			/*
27385 			 * The copy operation failed.  mi_copy_state already
27386 			 * cleaned up, so we're out of here.
27387 			 */
27388 			return;
27389 		}
27390 		/*
27391 		 * If we just completed a copy in, we become writer and
27392 		 * continue processing in ip_sioctl_copyin_done.  If it
27393 		 * was a copy out, we call mi_copyout again.  If there is
27394 		 * nothing more to copy out, it will complete the IOCTL.
27395 		 */
27396 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27397 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27398 				mi_copy_done(q, mp, EPROTO);
27399 				return;
27400 			}
27401 			/*
27402 			 * Check for cases that need more copying.  A return
27403 			 * value of 0 means a second copyin has been started,
27404 			 * so we return; a return value of 1 means no more
27405 			 * copying is needed, so we continue.
27406 			 */
27407 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27408 			    MI_COPY_COUNT(mp) == 1) {
27409 				if (ip_copyin_msfilter(q, mp) == 0)
27410 					return;
27411 			}
27412 			/*
27413 			 * Refhold the conn, till the ioctl completes. This is
27414 			 * needed in case the ioctl ends up in the pending mp
27415 			 * list. Every mp in the ill_pending_mp list and
27416 			 * the ipsq_pending_mp must have a refhold on the conn
27417 			 * to resume processing. The refhold is released when
27418 			 * the ioctl completes. (normally or abnormally)
27419 			 * In all cases ip_ioctl_finish is called to finish
27420 			 * the ioctl.
27421 			 */
27422 			if (connp != NULL) {
27423 				/* This is not a reentry */
27424 				ASSERT(ipsq == NULL);
27425 				CONN_INC_REF(connp);
27426 			} else {
27427 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27428 					mi_copy_done(q, mp, EINVAL);
27429 					return;
27430 				}
27431 			}
27432 
27433 			ip_process_ioctl(ipsq, q, mp, ipip);
27434 
27435 		} else {
27436 			mi_copyout(q, mp);
27437 		}
27438 		return;
27439 nak:
27440 		iocp->ioc_error = EINVAL;
27441 		mp->b_datap->db_type = M_IOCNAK;
27442 		iocp->ioc_count = 0;
27443 		qreply(q, mp);
27444 		return;
27445 
27446 	case M_IOCNAK:
27447 		/*
27448 		 * The only way we could get here is if a resolver didn't like
27449 		 * an IOCTL we sent it.	 This shouldn't happen.
27450 		 */
27451 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27452 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27453 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27454 		freemsg(mp);
27455 		return;
27456 	case M_IOCACK:
27457 		/* /dev/ip shouldn't see this */
27458 		if (CONN_Q(q))
27459 			goto nak;
27460 
27461 		/* Finish socket ioctls passed through to ARP. */
27462 		ip_sioctl_iocack(q, mp);
27463 		return;
27464 	case M_FLUSH:
27465 		if (*mp->b_rptr & FLUSHW)
27466 			flushq(q, FLUSHALL);
27467 		if (q->q_next) {
27468 			putnext(q, mp);
27469 			return;
27470 		}
27471 		if (*mp->b_rptr & FLUSHR) {
27472 			*mp->b_rptr &= ~FLUSHW;
27473 			qreply(q, mp);
27474 			return;
27475 		}
27476 		freemsg(mp);
27477 		return;
27478 	case IRE_DB_REQ_TYPE:
27479 		if (connp == NULL) {
27480 			proto_str = "IRE_DB_REQ_TYPE";
27481 			goto protonak;
27482 		}
27483 		/* An Upper Level Protocol wants a copy of an IRE. */
27484 		ip_ire_req(q, mp);
27485 		return;
27486 	case M_CTL:
27487 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27488 			break;
27489 
27490 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27491 		    TUN_HELLO) {
27492 			ASSERT(connp != NULL);
27493 			connp->conn_flags |= IPCL_IPTUN;
27494 			freeb(mp);
27495 			return;
27496 		}
27497 
27498 		/* M_CTL messages are used by ARP to tell us things. */
27499 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27500 			break;
27501 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27502 		case AR_ENTRY_SQUERY:
27503 			ip_wput_ctl(q, mp);
27504 			return;
27505 		case AR_CLIENT_NOTIFY:
27506 			ip_arp_news(q, mp);
27507 			return;
27508 		case AR_DLPIOP_DONE:
27509 			ASSERT(q->q_next != NULL);
27510 			ill = (ill_t *)q->q_ptr;
27511 			/* qwriter_ip releases the refhold */
27512 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27513 			ill_refhold(ill);
27514 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27515 			return;
27516 		case AR_ARP_CLOSING:
27517 			/*
27518 			 * ARP (above us) is closing. If no ARP bringup is
27519 			 * currently pending, ack the message so that ARP
27520 			 * can complete its close. Also mark ill_arp_closing
27521 			 * so that new ARP bringups will fail. If any
27522 			 * ARP bringup is currently in progress, we will
27523 			 * ack this when the current ARP bringup completes.
27524 			 */
27525 			ASSERT(q->q_next != NULL);
27526 			ill = (ill_t *)q->q_ptr;
27527 			mutex_enter(&ill->ill_lock);
27528 			ill->ill_arp_closing = 1;
27529 			if (!ill->ill_arp_bringup_pending) {
27530 				mutex_exit(&ill->ill_lock);
27531 				qreply(q, mp);
27532 			} else {
27533 				mutex_exit(&ill->ill_lock);
27534 				freemsg(mp);
27535 			}
27536 			return;
27537 		case AR_ARP_EXTEND:
27538 			/*
27539 			 * The ARP module above us is capable of duplicate
27540 			 * address detection.  Old ATM drivers will not send
27541 			 * this message.
27542 			 */
27543 			ASSERT(q->q_next != NULL);
27544 			ill = (ill_t *)q->q_ptr;
27545 			ill->ill_arp_extend = B_TRUE;
27546 			freemsg(mp);
27547 			return;
27548 		default:
27549 			break;
27550 		}
27551 		break;
27552 	case M_PROTO:
27553 	case M_PCPROTO:
27554 		/*
27555 		 * The only PROTO messages we expect are ULP binds and
27556 		 * copies of option negotiation acknowledgements.
27557 		 */
27558 		switch (((union T_primitives *)mp->b_rptr)->type) {
27559 		case O_T_BIND_REQ:
27560 		case T_BIND_REQ: {
27561 			/* Request can get queued in bind */
27562 			if (connp == NULL) {
27563 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27564 				goto protonak;
27565 			}
27566 			/*
27567 			 * The transports except SCTP call ip_bind_{v4,v6}()
27568 			 * directly instead of a a putnext. SCTP doesn't
27569 			 * generate any T_BIND_REQ since it has its own
27570 			 * fanout data structures. However, ESP and AH
27571 			 * come in for regular binds; all other cases are
27572 			 * bind retries.
27573 			 */
27574 			ASSERT(!IPCL_IS_SCTP(connp));
27575 
27576 			/* Don't increment refcnt if this is a re-entry */
27577 			if (ipsq == NULL)
27578 				CONN_INC_REF(connp);
27579 
27580 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27581 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27582 			if (mp == NULL)
27583 				return;
27584 			if (IPCL_IS_TCP(connp)) {
27585 				/*
27586 				 * In the case of TCP endpoint we
27587 				 * come here only for bind retries
27588 				 */
27589 				ASSERT(ipsq != NULL);
27590 				CONN_INC_REF(connp);
27591 				squeue_fill(connp->conn_sqp, mp,
27592 				    ip_resume_tcp_bind, connp,
27593 				    SQTAG_BIND_RETRY);
27594 			} else if (IPCL_IS_UDP(connp)) {
27595 				/*
27596 				 * In the case of UDP endpoint we
27597 				 * come here only for bind retries
27598 				 */
27599 				ASSERT(ipsq != NULL);
27600 				udp_resume_bind(connp, mp);
27601 			} else if (IPCL_IS_RAWIP(connp)) {
27602 				/*
27603 				 * In the case of RAWIP endpoint we
27604 				 * come here only for bind retries
27605 				 */
27606 				ASSERT(ipsq != NULL);
27607 				rawip_resume_bind(connp, mp);
27608 			} else {
27609 				/* The case of AH and ESP */
27610 				qreply(q, mp);
27611 				CONN_OPER_PENDING_DONE(connp);
27612 			}
27613 			return;
27614 		}
27615 		case T_SVR4_OPTMGMT_REQ:
27616 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27617 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27618 
27619 			if (connp == NULL) {
27620 				proto_str = "T_SVR4_OPTMGMT_REQ";
27621 				goto protonak;
27622 			}
27623 
27624 			if (!snmpcom_req(q, mp, ip_snmp_set,
27625 			    ip_snmp_get, cr)) {
27626 				/*
27627 				 * Call svr4_optcom_req so that it can
27628 				 * generate the ack. We don't come here
27629 				 * if this operation is being restarted.
27630 				 * ip_restart_optmgmt will drop the conn ref.
27631 				 * In the case of ipsec option after the ipsec
27632 				 * load is complete conn_restart_ipsec_waiter
27633 				 * drops the conn ref.
27634 				 */
27635 				ASSERT(ipsq == NULL);
27636 				CONN_INC_REF(connp);
27637 				if (ip_check_for_ipsec_opt(q, mp))
27638 					return;
27639 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj,
27640 				    B_FALSE);
27641 				if (err != EINPROGRESS) {
27642 					/* Operation is done */
27643 					CONN_OPER_PENDING_DONE(connp);
27644 				}
27645 			}
27646 			return;
27647 		case T_OPTMGMT_REQ:
27648 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27649 			/*
27650 			 * Note: No snmpcom_req support through new
27651 			 * T_OPTMGMT_REQ.
27652 			 * Call tpi_optcom_req so that it can
27653 			 * generate the ack.
27654 			 */
27655 			if (connp == NULL) {
27656 				proto_str = "T_OPTMGMT_REQ";
27657 				goto protonak;
27658 			}
27659 
27660 			ASSERT(ipsq == NULL);
27661 			/*
27662 			 * We don't come here for restart. ip_restart_optmgmt
27663 			 * will drop the conn ref. In the case of ipsec option
27664 			 * after the ipsec load is complete
27665 			 * conn_restart_ipsec_waiter drops the conn ref.
27666 			 */
27667 			CONN_INC_REF(connp);
27668 			if (ip_check_for_ipsec_opt(q, mp))
27669 				return;
27670 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj, B_FALSE);
27671 			if (err != EINPROGRESS) {
27672 				/* Operation is done */
27673 				CONN_OPER_PENDING_DONE(connp);
27674 			}
27675 			return;
27676 		case T_UNBIND_REQ:
27677 			if (connp == NULL) {
27678 				proto_str = "T_UNBIND_REQ";
27679 				goto protonak;
27680 			}
27681 			mp = ip_unbind(q, mp);
27682 			qreply(q, mp);
27683 			return;
27684 		default:
27685 			/*
27686 			 * Have to drop any DLPI messages coming down from
27687 			 * arp (such as an info_req which would cause ip
27688 			 * to receive an extra info_ack if it was passed
27689 			 * through.
27690 			 */
27691 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27692 			    (int)*(uint_t *)mp->b_rptr));
27693 			freemsg(mp);
27694 			return;
27695 		}
27696 		/* NOTREACHED */
27697 	case IRE_DB_TYPE: {
27698 		nce_t		*nce;
27699 		ill_t		*ill;
27700 		in6_addr_t	gw_addr_v6;
27701 
27702 
27703 		/*
27704 		 * This is a response back from a resolver.  It
27705 		 * consists of a message chain containing:
27706 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27707 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27708 		 * The LL_HDR_MBLK is the DLPI header to use to get
27709 		 * the attached packet, and subsequent ones for the
27710 		 * same destination, transmitted.
27711 		 */
27712 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27713 			break;
27714 		/*
27715 		 * First, check to make sure the resolution succeeded.
27716 		 * If it failed, the second mblk will be empty.
27717 		 * If it is, free the chain, dropping the packet.
27718 		 * (We must ire_delete the ire; that frees the ire mblk)
27719 		 * We're doing this now to support PVCs for ATM; it's
27720 		 * a partial xresolv implementation. When we fully implement
27721 		 * xresolv interfaces, instead of freeing everything here
27722 		 * we'll initiate neighbor discovery.
27723 		 *
27724 		 * For v4 (ARP and other external resolvers) the resolver
27725 		 * frees the message, so no check is needed. This check
27726 		 * is required, though, for a full xresolve implementation.
27727 		 * Including this code here now both shows how external
27728 		 * resolvers can NACK a resolution request using an
27729 		 * existing design that has no specific provisions for NACKs,
27730 		 * and also takes into account that the current non-ARP
27731 		 * external resolver has been coded to use this method of
27732 		 * NACKing for all IPv6 (xresolv) cases,
27733 		 * whether our xresolv implementation is complete or not.
27734 		 *
27735 		 */
27736 		ire = (ire_t *)mp->b_rptr;
27737 		ill = ire_to_ill(ire);
27738 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27739 		if (mp1->b_rptr == mp1->b_wptr) {
27740 			if (ire->ire_ipversion == IPV6_VERSION) {
27741 				/*
27742 				 * XRESOLV interface.
27743 				 */
27744 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27745 				mutex_enter(&ire->ire_lock);
27746 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27747 				mutex_exit(&ire->ire_lock);
27748 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27749 					nce = ndp_lookup_v6(ill,
27750 					    &ire->ire_addr_v6, B_FALSE);
27751 				} else {
27752 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
27753 					    B_FALSE);
27754 				}
27755 				if (nce != NULL) {
27756 					nce_resolv_failed(nce);
27757 					ndp_delete(nce);
27758 					NCE_REFRELE(nce);
27759 				}
27760 			}
27761 			mp->b_cont = NULL;
27762 			freemsg(mp1);		/* frees the pkt as well */
27763 			ASSERT(ire->ire_nce == NULL);
27764 			ire_delete((ire_t *)mp->b_rptr);
27765 			return;
27766 		}
27767 
27768 		/*
27769 		 * Split them into IRE_MBLK and pkt and feed it into
27770 		 * ire_add_then_send. Then in ire_add_then_send
27771 		 * the IRE will be added, and then the packet will be
27772 		 * run back through ip_wput. This time it will make
27773 		 * it to the wire.
27774 		 */
27775 		mp->b_cont = NULL;
27776 		mp = mp1->b_cont;		/* now, mp points to pkt */
27777 		mp1->b_cont = NULL;
27778 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27779 		if (ire->ire_ipversion == IPV6_VERSION) {
27780 			/*
27781 			 * XRESOLV interface. Find the nce and put a copy
27782 			 * of the dl_unitdata_req in nce_res_mp
27783 			 */
27784 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27785 			mutex_enter(&ire->ire_lock);
27786 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27787 			mutex_exit(&ire->ire_lock);
27788 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27789 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
27790 				    B_FALSE);
27791 			} else {
27792 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
27793 			}
27794 			if (nce != NULL) {
27795 				/*
27796 				 * We have to protect nce_res_mp here
27797 				 * from being accessed by other threads
27798 				 * while we change the mblk pointer.
27799 				 * Other functions will also lock the nce when
27800 				 * accessing nce_res_mp.
27801 				 *
27802 				 * The reason we change the mblk pointer
27803 				 * here rather than copying the resolved address
27804 				 * into the template is that, unlike with
27805 				 * ethernet, we have no guarantee that the
27806 				 * resolved address length will be
27807 				 * smaller than or equal to the lla length
27808 				 * with which the template was allocated,
27809 				 * (for ethernet, they're equal)
27810 				 * so we have to use the actual resolved
27811 				 * address mblk - which holds the real
27812 				 * dl_unitdata_req with the resolved address.
27813 				 *
27814 				 * Doing this is the same behavior as was
27815 				 * previously used in the v4 ARP case.
27816 				 */
27817 				mutex_enter(&nce->nce_lock);
27818 				if (nce->nce_res_mp != NULL)
27819 					freemsg(nce->nce_res_mp);
27820 				nce->nce_res_mp = mp1;
27821 				mutex_exit(&nce->nce_lock);
27822 				/*
27823 				 * We do a fastpath probe here because
27824 				 * we have resolved the address without
27825 				 * using Neighbor Discovery.
27826 				 * In the non-XRESOLV v6 case, the fastpath
27827 				 * probe is done right after neighbor
27828 				 * discovery completes.
27829 				 */
27830 				if (nce->nce_res_mp != NULL) {
27831 					int res;
27832 					nce_fastpath_list_add(nce);
27833 					res = ill_fastpath_probe(ill,
27834 					    nce->nce_res_mp);
27835 					if (res != 0 && res != EAGAIN)
27836 						nce_fastpath_list_delete(nce);
27837 				}
27838 
27839 				ire_add_then_send(q, ire, mp);
27840 				/*
27841 				 * Now we have to clean out any packets
27842 				 * that may have been queued on the nce
27843 				 * while it was waiting for address resolution
27844 				 * to complete.
27845 				 */
27846 				mutex_enter(&nce->nce_lock);
27847 				mp1 = nce->nce_qd_mp;
27848 				nce->nce_qd_mp = NULL;
27849 				mutex_exit(&nce->nce_lock);
27850 				while (mp1 != NULL) {
27851 					mblk_t *nxt_mp;
27852 					queue_t *fwdq = NULL;
27853 					ill_t   *inbound_ill;
27854 					uint_t ifindex;
27855 
27856 					nxt_mp = mp1->b_next;
27857 					mp1->b_next = NULL;
27858 					/*
27859 					 * Retrieve ifindex stored in
27860 					 * ip_rput_data_v6()
27861 					 */
27862 					ifindex =
27863 					    (uint_t)(uintptr_t)mp1->b_prev;
27864 					inbound_ill =
27865 					    ill_lookup_on_ifindex(ifindex,
27866 					    B_TRUE, NULL, NULL, NULL,
27867 					    NULL, ipst);
27868 					mp1->b_prev = NULL;
27869 					if (inbound_ill != NULL)
27870 						fwdq = inbound_ill->ill_rq;
27871 
27872 					if (fwdq != NULL) {
27873 						put(fwdq, mp1);
27874 						ill_refrele(inbound_ill);
27875 					} else
27876 						put(WR(ill->ill_rq), mp1);
27877 					mp1 = nxt_mp;
27878 				}
27879 				NCE_REFRELE(nce);
27880 			} else {	/* nce is NULL; clean up */
27881 				ire_delete(ire);
27882 				freemsg(mp);
27883 				freemsg(mp1);
27884 				return;
27885 			}
27886 		} else {
27887 			nce_t *arpce;
27888 			/*
27889 			 * Link layer resolution succeeded. Recompute the
27890 			 * ire_nce.
27891 			 */
27892 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27893 			if ((arpce = ndp_lookup_v4(ill,
27894 			    (ire->ire_gateway_addr != INADDR_ANY ?
27895 			    &ire->ire_gateway_addr : &ire->ire_addr),
27896 			    B_FALSE)) == NULL) {
27897 				freeb(ire->ire_mp);
27898 				freeb(mp1);
27899 				freemsg(mp);
27900 				return;
27901 			}
27902 			mutex_enter(&arpce->nce_lock);
27903 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27904 			if (arpce->nce_state == ND_REACHABLE) {
27905 				/*
27906 				 * Someone resolved this before us;
27907 				 * cleanup the res_mp. Since ire has
27908 				 * not been added yet, the call to ire_add_v4
27909 				 * from ire_add_then_send (when a dup is
27910 				 * detected) will clean up the ire.
27911 				 */
27912 				freeb(mp1);
27913 			} else {
27914 				ASSERT(arpce->nce_res_mp == NULL);
27915 				arpce->nce_res_mp = mp1;
27916 				arpce->nce_state = ND_REACHABLE;
27917 			}
27918 			mutex_exit(&arpce->nce_lock);
27919 			if (ire->ire_marks & IRE_MARK_NOADD) {
27920 				/*
27921 				 * this ire will not be added to the ire
27922 				 * cache table, so we can set the ire_nce
27923 				 * here, as there are no atomicity constraints.
27924 				 */
27925 				ire->ire_nce = arpce;
27926 				/*
27927 				 * We are associating this nce with the ire
27928 				 * so change the nce ref taken in
27929 				 * ndp_lookup_v4() from
27930 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27931 				 */
27932 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27933 			} else {
27934 				NCE_REFRELE(arpce);
27935 			}
27936 			ire_add_then_send(q, ire, mp);
27937 		}
27938 		return;	/* All is well, the packet has been sent. */
27939 	}
27940 	case IRE_ARPRESOLVE_TYPE: {
27941 
27942 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27943 			break;
27944 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27945 		mp->b_cont = NULL;
27946 		/*
27947 		 * First, check to make sure the resolution succeeded.
27948 		 * If it failed, the second mblk will be empty.
27949 		 */
27950 		if (mp1->b_rptr == mp1->b_wptr) {
27951 			/* cleanup  the incomplete ire, free queued packets */
27952 			freemsg(mp); /* fake ire */
27953 			freeb(mp1);  /* dl_unitdata response */
27954 			return;
27955 		}
27956 
27957 		/*
27958 		 * Update any incomplete nce_t found. We search the ctable
27959 		 * and find the nce from the ire->ire_nce because we need
27960 		 * to pass the ire to ip_xmit_v4 later, and can find both
27961 		 * ire and nce in one lookup.
27962 		 */
27963 		fake_ire = (ire_t *)mp->b_rptr;
27964 
27965 		/*
27966 		 * By the time we come back here from ARP the incomplete ire
27967 		 * created in ire_forward() could have been removed. We use
27968 		 * the parameters stored in the fake_ire to specify the real
27969 		 * ire as explicitly as possible. This avoids problems when
27970 		 * IPMP groups are configured as an ipif can 'float'
27971 		 * across several ill queues. We can be confident that the
27972 		 * the inability to find an ire is because it no longer exists.
27973 		 */
27974 		ill = ill_lookup_on_ifindex(fake_ire->ire_ipif_ifindex, B_FALSE,
27975 		    NULL, NULL, NULL, NULL, ipst);
27976 		if (ill == NULL) {
27977 			ip1dbg(("ill for incomplete ire vanished\n"));
27978 			freemsg(mp); /* fake ire */
27979 			freeb(mp1);  /* dl_unitdata response */
27980 			return;
27981 		}
27982 
27983 		/* Get the outgoing ipif */
27984 		mutex_enter(&ill->ill_lock);
27985 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27986 		if (ipif == NULL) {
27987 			mutex_exit(&ill->ill_lock);
27988 			ill_refrele(ill);
27989 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27990 			freemsg(mp); /* fake_ire */
27991 			freeb(mp1);  /* dl_unitdata response */
27992 			return;
27993 		}
27994 
27995 		ipif_refhold_locked(ipif);
27996 		mutex_exit(&ill->ill_lock);
27997 		ill_refrele(ill);
27998 		ire = ire_arpresolve_lookup(fake_ire->ire_addr,
27999 		    fake_ire->ire_gateway_addr, ipif, fake_ire->ire_zoneid,
28000 		    ipst, ((ill_t *)q->q_ptr)->ill_wq);
28001 		ipif_refrele(ipif);
28002 		if (ire == NULL) {
28003 			/*
28004 			 * no ire was found; check if there is an nce
28005 			 * for this lookup; if it has no ire's pointing at it
28006 			 * cleanup.
28007 			 */
28008 			if ((nce = ndp_lookup_v4(q->q_ptr,
28009 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
28010 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
28011 			    B_FALSE)) != NULL) {
28012 				/*
28013 				 * cleanup:
28014 				 * We check for refcnt 2 (one for the nce
28015 				 * hash list + 1 for the ref taken by
28016 				 * ndp_lookup_v4) to check that there are
28017 				 * no ire's pointing at the nce.
28018 				 */
28019 				if (nce->nce_refcnt == 2)
28020 					ndp_delete(nce);
28021 				NCE_REFRELE(nce);
28022 			}
28023 			freeb(mp1);  /* dl_unitdata response */
28024 			freemsg(mp); /* fake ire */
28025 			return;
28026 		}
28027 		nce = ire->ire_nce;
28028 		DTRACE_PROBE2(ire__arpresolve__type,
28029 		    ire_t *, ire, nce_t *, nce);
28030 		ASSERT(nce->nce_state != ND_INITIAL);
28031 		mutex_enter(&nce->nce_lock);
28032 		nce->nce_last = TICK_TO_MSEC(lbolt64);
28033 		if (nce->nce_state == ND_REACHABLE) {
28034 			/*
28035 			 * Someone resolved this before us;
28036 			 * our response is not needed any more.
28037 			 */
28038 			mutex_exit(&nce->nce_lock);
28039 			freeb(mp1);  /* dl_unitdata response */
28040 		} else {
28041 			ASSERT(nce->nce_res_mp == NULL);
28042 			nce->nce_res_mp = mp1;
28043 			nce->nce_state = ND_REACHABLE;
28044 			mutex_exit(&nce->nce_lock);
28045 			nce_fastpath(nce);
28046 		}
28047 		/*
28048 		 * The cached nce_t has been updated to be reachable;
28049 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
28050 		 */
28051 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
28052 		freemsg(mp);
28053 		/*
28054 		 * send out queued packets.
28055 		 */
28056 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
28057 
28058 		IRE_REFRELE(ire);
28059 		return;
28060 	}
28061 	default:
28062 		break;
28063 	}
28064 	if (q->q_next) {
28065 		putnext(q, mp);
28066 	} else
28067 		freemsg(mp);
28068 	return;
28069 
28070 protonak:
28071 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
28072 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
28073 		qreply(q, mp);
28074 }
28075 
28076 /*
28077  * Process IP options in an outbound packet.  Modify the destination if there
28078  * is a source route option.
28079  * Returns non-zero if something fails in which case an ICMP error has been
28080  * sent and mp freed.
28081  */
28082 static int
28083 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
28084     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
28085 {
28086 	ipoptp_t	opts;
28087 	uchar_t		*opt;
28088 	uint8_t		optval;
28089 	uint8_t		optlen;
28090 	ipaddr_t	dst;
28091 	intptr_t	code = 0;
28092 	mblk_t		*mp;
28093 	ire_t		*ire = NULL;
28094 
28095 	ip2dbg(("ip_wput_options\n"));
28096 	mp = ipsec_mp;
28097 	if (mctl_present) {
28098 		mp = ipsec_mp->b_cont;
28099 	}
28100 
28101 	dst = ipha->ipha_dst;
28102 	for (optval = ipoptp_first(&opts, ipha);
28103 	    optval != IPOPT_EOL;
28104 	    optval = ipoptp_next(&opts)) {
28105 		opt = opts.ipoptp_cur;
28106 		optlen = opts.ipoptp_len;
28107 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
28108 		    optval, optlen));
28109 		switch (optval) {
28110 			uint32_t off;
28111 		case IPOPT_SSRR:
28112 		case IPOPT_LSRR:
28113 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28114 				ip1dbg((
28115 				    "ip_wput_options: bad option offset\n"));
28116 				code = (char *)&opt[IPOPT_OLEN] -
28117 				    (char *)ipha;
28118 				goto param_prob;
28119 			}
28120 			off = opt[IPOPT_OFFSET];
28121 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
28122 			    ntohl(dst)));
28123 			/*
28124 			 * For strict: verify that dst is directly
28125 			 * reachable.
28126 			 */
28127 			if (optval == IPOPT_SSRR) {
28128 				ire = ire_ftable_lookup(dst, 0, 0,
28129 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
28130 				    MBLK_GETLABEL(mp),
28131 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
28132 				if (ire == NULL) {
28133 					ip1dbg(("ip_wput_options: SSRR not"
28134 					    " directly reachable: 0x%x\n",
28135 					    ntohl(dst)));
28136 					goto bad_src_route;
28137 				}
28138 				ire_refrele(ire);
28139 			}
28140 			break;
28141 		case IPOPT_RR:
28142 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28143 				ip1dbg((
28144 				    "ip_wput_options: bad option offset\n"));
28145 				code = (char *)&opt[IPOPT_OLEN] -
28146 				    (char *)ipha;
28147 				goto param_prob;
28148 			}
28149 			break;
28150 		case IPOPT_TS:
28151 			/*
28152 			 * Verify that length >=5 and that there is either
28153 			 * room for another timestamp or that the overflow
28154 			 * counter is not maxed out.
28155 			 */
28156 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
28157 			if (optlen < IPOPT_MINLEN_IT) {
28158 				goto param_prob;
28159 			}
28160 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28161 				ip1dbg((
28162 				    "ip_wput_options: bad option offset\n"));
28163 				code = (char *)&opt[IPOPT_OFFSET] -
28164 				    (char *)ipha;
28165 				goto param_prob;
28166 			}
28167 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
28168 			case IPOPT_TS_TSONLY:
28169 				off = IPOPT_TS_TIMELEN;
28170 				break;
28171 			case IPOPT_TS_TSANDADDR:
28172 			case IPOPT_TS_PRESPEC:
28173 			case IPOPT_TS_PRESPEC_RFC791:
28174 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
28175 				break;
28176 			default:
28177 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
28178 				    (char *)ipha;
28179 				goto param_prob;
28180 			}
28181 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
28182 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
28183 				/*
28184 				 * No room and the overflow counter is 15
28185 				 * already.
28186 				 */
28187 				goto param_prob;
28188 			}
28189 			break;
28190 		}
28191 	}
28192 
28193 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
28194 		return (0);
28195 
28196 	ip1dbg(("ip_wput_options: error processing IP options."));
28197 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
28198 
28199 param_prob:
28200 	/*
28201 	 * Since ip_wput() isn't close to finished, we fill
28202 	 * in enough of the header for credible error reporting.
28203 	 */
28204 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28205 		/* Failed */
28206 		freemsg(ipsec_mp);
28207 		return (-1);
28208 	}
28209 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
28210 	return (-1);
28211 
28212 bad_src_route:
28213 	/*
28214 	 * Since ip_wput() isn't close to finished, we fill
28215 	 * in enough of the header for credible error reporting.
28216 	 */
28217 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28218 		/* Failed */
28219 		freemsg(ipsec_mp);
28220 		return (-1);
28221 	}
28222 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
28223 	return (-1);
28224 }
28225 
28226 /*
28227  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
28228  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
28229  * thru /etc/system.
28230  */
28231 #define	CONN_MAXDRAINCNT	64
28232 
28233 static void
28234 conn_drain_init(ip_stack_t *ipst)
28235 {
28236 	int i;
28237 
28238 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
28239 
28240 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
28241 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
28242 		/*
28243 		 * Default value of the number of drainers is the
28244 		 * number of cpus, subject to maximum of 8 drainers.
28245 		 */
28246 		if (boot_max_ncpus != -1)
28247 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
28248 		else
28249 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
28250 	}
28251 
28252 	ipst->ips_conn_drain_list = kmem_zalloc(ipst->ips_conn_drain_list_cnt *
28253 	    sizeof (idl_t), KM_SLEEP);
28254 
28255 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28256 		mutex_init(&ipst->ips_conn_drain_list[i].idl_lock, NULL,
28257 		    MUTEX_DEFAULT, NULL);
28258 	}
28259 }
28260 
28261 static void
28262 conn_drain_fini(ip_stack_t *ipst)
28263 {
28264 	int i;
28265 
28266 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++)
28267 		mutex_destroy(&ipst->ips_conn_drain_list[i].idl_lock);
28268 	kmem_free(ipst->ips_conn_drain_list,
28269 	    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28270 	ipst->ips_conn_drain_list = NULL;
28271 }
28272 
28273 /*
28274  * Note: For an overview of how flowcontrol is handled in IP please see the
28275  * IP Flowcontrol notes at the top of this file.
28276  *
28277  * Flow control has blocked us from proceeding. Insert the given conn in one
28278  * of the conn drain lists. These conn wq's will be qenabled later on when
28279  * STREAMS flow control does a backenable. conn_walk_drain will enable
28280  * the first conn in each of these drain lists. Each of these qenabled conns
28281  * in turn enables the next in the list, after it runs, or when it closes,
28282  * thus sustaining the drain process.
28283  *
28284  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
28285  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
28286  * running at any time, on a given conn, since there can be only 1 service proc
28287  * running on a queue at any time.
28288  */
28289 void
28290 conn_drain_insert(conn_t *connp)
28291 {
28292 	idl_t	*idl;
28293 	uint_t	index;
28294 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28295 
28296 	mutex_enter(&connp->conn_lock);
28297 	if (connp->conn_state_flags & CONN_CLOSING) {
28298 		/*
28299 		 * The conn is closing as a result of which CONN_CLOSING
28300 		 * is set. Return.
28301 		 */
28302 		mutex_exit(&connp->conn_lock);
28303 		return;
28304 	} else if (connp->conn_idl == NULL) {
28305 		/*
28306 		 * Assign the next drain list round robin. We dont' use
28307 		 * a lock, and thus it may not be strictly round robin.
28308 		 * Atomicity of load/stores is enough to make sure that
28309 		 * conn_drain_list_index is always within bounds.
28310 		 */
28311 		index = ipst->ips_conn_drain_list_index;
28312 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28313 		connp->conn_idl = &ipst->ips_conn_drain_list[index];
28314 		index++;
28315 		if (index == ipst->ips_conn_drain_list_cnt)
28316 			index = 0;
28317 		ipst->ips_conn_drain_list_index = index;
28318 	}
28319 	mutex_exit(&connp->conn_lock);
28320 
28321 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28322 	if ((connp->conn_drain_prev != NULL) ||
28323 	    (connp->conn_state_flags & CONN_CLOSING)) {
28324 		/*
28325 		 * The conn is already in the drain list, OR
28326 		 * the conn is closing. We need to check again for
28327 		 * the closing case again since close can happen
28328 		 * after we drop the conn_lock, and before we
28329 		 * acquire the CONN_DRAIN_LIST_LOCK.
28330 		 */
28331 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28332 		return;
28333 	} else {
28334 		idl = connp->conn_idl;
28335 	}
28336 
28337 	/*
28338 	 * The conn is not in the drain list. Insert it at the
28339 	 * tail of the drain list. The drain list is circular
28340 	 * and doubly linked. idl_conn points to the 1st element
28341 	 * in the list.
28342 	 */
28343 	if (idl->idl_conn == NULL) {
28344 		idl->idl_conn = connp;
28345 		connp->conn_drain_next = connp;
28346 		connp->conn_drain_prev = connp;
28347 	} else {
28348 		conn_t *head = idl->idl_conn;
28349 
28350 		connp->conn_drain_next = head;
28351 		connp->conn_drain_prev = head->conn_drain_prev;
28352 		head->conn_drain_prev->conn_drain_next = connp;
28353 		head->conn_drain_prev = connp;
28354 	}
28355 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28356 }
28357 
28358 /*
28359  * This conn is closing, and we are called from ip_close. OR
28360  * This conn has been serviced by ip_wsrv, and we need to do the tail
28361  * processing.
28362  * If this conn is part of the drain list, we may need to sustain the drain
28363  * process by qenabling the next conn in the drain list. We may also need to
28364  * remove this conn from the list, if it is done.
28365  */
28366 static void
28367 conn_drain_tail(conn_t *connp, boolean_t closing)
28368 {
28369 	idl_t *idl;
28370 
28371 	/*
28372 	 * connp->conn_idl is stable at this point, and no lock is needed
28373 	 * to check it. If we are called from ip_close, close has already
28374 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28375 	 * called us only because conn_idl is non-null. If we are called thru
28376 	 * service, conn_idl could be null, but it cannot change because
28377 	 * service is single-threaded per queue, and there cannot be another
28378 	 * instance of service trying to call conn_drain_insert on this conn
28379 	 * now.
28380 	 */
28381 	ASSERT(!closing || (connp->conn_idl != NULL));
28382 
28383 	/*
28384 	 * If connp->conn_idl is null, the conn has not been inserted into any
28385 	 * drain list even once since creation of the conn. Just return.
28386 	 */
28387 	if (connp->conn_idl == NULL)
28388 		return;
28389 
28390 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28391 
28392 	if (connp->conn_drain_prev == NULL) {
28393 		/* This conn is currently not in the drain list.  */
28394 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28395 		return;
28396 	}
28397 	idl = connp->conn_idl;
28398 	if (idl->idl_conn_draining == connp) {
28399 		/*
28400 		 * This conn is the current drainer. If this is the last conn
28401 		 * in the drain list, we need to do more checks, in the 'if'
28402 		 * below. Otherwwise we need to just qenable the next conn,
28403 		 * to sustain the draining, and is handled in the 'else'
28404 		 * below.
28405 		 */
28406 		if (connp->conn_drain_next == idl->idl_conn) {
28407 			/*
28408 			 * This conn is the last in this list. This round
28409 			 * of draining is complete. If idl_repeat is set,
28410 			 * it means another flow enabling has happened from
28411 			 * the driver/streams and we need to another round
28412 			 * of draining.
28413 			 * If there are more than 2 conns in the drain list,
28414 			 * do a left rotate by 1, so that all conns except the
28415 			 * conn at the head move towards the head by 1, and the
28416 			 * the conn at the head goes to the tail. This attempts
28417 			 * a more even share for all queues that are being
28418 			 * drained.
28419 			 */
28420 			if ((connp->conn_drain_next != connp) &&
28421 			    (idl->idl_conn->conn_drain_next != connp)) {
28422 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28423 			}
28424 			if (idl->idl_repeat) {
28425 				qenable(idl->idl_conn->conn_wq);
28426 				idl->idl_conn_draining = idl->idl_conn;
28427 				idl->idl_repeat = 0;
28428 			} else {
28429 				idl->idl_conn_draining = NULL;
28430 			}
28431 		} else {
28432 			/*
28433 			 * If the next queue that we are now qenable'ing,
28434 			 * is closing, it will remove itself from this list
28435 			 * and qenable the subsequent queue in ip_close().
28436 			 * Serialization is acheived thru idl_lock.
28437 			 */
28438 			qenable(connp->conn_drain_next->conn_wq);
28439 			idl->idl_conn_draining = connp->conn_drain_next;
28440 		}
28441 	}
28442 	if (!connp->conn_did_putbq || closing) {
28443 		/*
28444 		 * Remove ourself from the drain list, if we did not do
28445 		 * a putbq, or if the conn is closing.
28446 		 * Note: It is possible that q->q_first is non-null. It means
28447 		 * that these messages landed after we did a enableok() in
28448 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28449 		 * service them.
28450 		 */
28451 		if (connp->conn_drain_next == connp) {
28452 			/* Singleton in the list */
28453 			ASSERT(connp->conn_drain_prev == connp);
28454 			idl->idl_conn = NULL;
28455 			idl->idl_conn_draining = NULL;
28456 		} else {
28457 			connp->conn_drain_prev->conn_drain_next =
28458 			    connp->conn_drain_next;
28459 			connp->conn_drain_next->conn_drain_prev =
28460 			    connp->conn_drain_prev;
28461 			if (idl->idl_conn == connp)
28462 				idl->idl_conn = connp->conn_drain_next;
28463 			ASSERT(idl->idl_conn_draining != connp);
28464 
28465 		}
28466 		connp->conn_drain_next = NULL;
28467 		connp->conn_drain_prev = NULL;
28468 	}
28469 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28470 }
28471 
28472 /*
28473  * Write service routine. Shared perimeter entry point.
28474  * ip_wsrv can be called in any of the following ways.
28475  * 1. The device queue's messages has fallen below the low water mark
28476  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28477  *    the drain lists and backenable the first conn in each list.
28478  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28479  *    qenabled non-tcp upper layers. We start dequeing messages and call
28480  *    ip_wput for each message.
28481  */
28482 
28483 void
28484 ip_wsrv(queue_t *q)
28485 {
28486 	conn_t	*connp;
28487 	ill_t	*ill;
28488 	mblk_t	*mp;
28489 
28490 	if (q->q_next) {
28491 		ill = (ill_t *)q->q_ptr;
28492 		if (ill->ill_state_flags == 0) {
28493 			/*
28494 			 * The device flow control has opened up.
28495 			 * Walk through conn drain lists and qenable the
28496 			 * first conn in each list. This makes sense only
28497 			 * if the stream is fully plumbed and setup.
28498 			 * Hence the if check above.
28499 			 */
28500 			ip1dbg(("ip_wsrv: walking\n"));
28501 			conn_walk_drain(ill->ill_ipst);
28502 		}
28503 		return;
28504 	}
28505 
28506 	connp = Q_TO_CONN(q);
28507 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28508 
28509 	/*
28510 	 * 1. Set conn_draining flag to signal that service is active.
28511 	 *
28512 	 * 2. ip_output determines whether it has been called from service,
28513 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28514 	 *    has been called from service.
28515 	 *
28516 	 * 3. Message ordering is preserved by the following logic.
28517 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28518 	 *    the message at the tail, if conn_draining is set (i.e. service
28519 	 *    is running) or if q->q_first is non-null.
28520 	 *
28521 	 *    ii. If ip_output is called from service, and if ip_output cannot
28522 	 *    putnext due to flow control, it does a putbq.
28523 	 *
28524 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28525 	 *    (causing an infinite loop).
28526 	 */
28527 	ASSERT(!connp->conn_did_putbq);
28528 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28529 		connp->conn_draining = 1;
28530 		noenable(q);
28531 		while ((mp = getq(q)) != NULL) {
28532 			ASSERT(CONN_Q(q));
28533 
28534 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28535 			if (connp->conn_did_putbq) {
28536 				/* ip_wput did a putbq */
28537 				break;
28538 			}
28539 		}
28540 		/*
28541 		 * At this point, a thread coming down from top, calling
28542 		 * ip_wput, may end up queueing the message. We have not yet
28543 		 * enabled the queue, so ip_wsrv won't be called again.
28544 		 * To avoid this race, check q->q_first again (in the loop)
28545 		 * If the other thread queued the message before we call
28546 		 * enableok(), we will catch it in the q->q_first check.
28547 		 * If the other thread queues the message after we call
28548 		 * enableok(), ip_wsrv will be called again by STREAMS.
28549 		 */
28550 		connp->conn_draining = 0;
28551 		enableok(q);
28552 	}
28553 
28554 	/* Enable the next conn for draining */
28555 	conn_drain_tail(connp, B_FALSE);
28556 
28557 	connp->conn_did_putbq = 0;
28558 }
28559 
28560 /*
28561  * Walk the list of all conn's calling the function provided with the
28562  * specified argument for each.	 Note that this only walks conn's that
28563  * have been bound.
28564  * Applies to both IPv4 and IPv6.
28565  */
28566 static void
28567 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28568 {
28569 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28570 	    ipst->ips_ipcl_udp_fanout_size,
28571 	    func, arg, zoneid);
28572 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28573 	    ipst->ips_ipcl_conn_fanout_size,
28574 	    func, arg, zoneid);
28575 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28576 	    ipst->ips_ipcl_bind_fanout_size,
28577 	    func, arg, zoneid);
28578 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28579 	    IPPROTO_MAX, func, arg, zoneid);
28580 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28581 	    IPPROTO_MAX, func, arg, zoneid);
28582 }
28583 
28584 /*
28585  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28586  * of conns that need to be drained, check if drain is already in progress.
28587  * If so set the idl_repeat bit, indicating that the last conn in the list
28588  * needs to reinitiate the drain once again, for the list. If drain is not
28589  * in progress for the list, initiate the draining, by qenabling the 1st
28590  * conn in the list. The drain is self-sustaining, each qenabled conn will
28591  * in turn qenable the next conn, when it is done/blocked/closing.
28592  */
28593 static void
28594 conn_walk_drain(ip_stack_t *ipst)
28595 {
28596 	int i;
28597 	idl_t *idl;
28598 
28599 	IP_STAT(ipst, ip_conn_walk_drain);
28600 
28601 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28602 		idl = &ipst->ips_conn_drain_list[i];
28603 		mutex_enter(&idl->idl_lock);
28604 		if (idl->idl_conn == NULL) {
28605 			mutex_exit(&idl->idl_lock);
28606 			continue;
28607 		}
28608 		/*
28609 		 * If this list is not being drained currently by
28610 		 * an ip_wsrv thread, start the process.
28611 		 */
28612 		if (idl->idl_conn_draining == NULL) {
28613 			ASSERT(idl->idl_repeat == 0);
28614 			qenable(idl->idl_conn->conn_wq);
28615 			idl->idl_conn_draining = idl->idl_conn;
28616 		} else {
28617 			idl->idl_repeat = 1;
28618 		}
28619 		mutex_exit(&idl->idl_lock);
28620 	}
28621 }
28622 
28623 /*
28624  * Walk an conn hash table of `count' buckets, calling func for each entry.
28625  */
28626 static void
28627 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28628     zoneid_t zoneid)
28629 {
28630 	conn_t	*connp;
28631 
28632 	while (count-- > 0) {
28633 		mutex_enter(&connfp->connf_lock);
28634 		for (connp = connfp->connf_head; connp != NULL;
28635 		    connp = connp->conn_next) {
28636 			if (zoneid == GLOBAL_ZONEID ||
28637 			    zoneid == connp->conn_zoneid) {
28638 				CONN_INC_REF(connp);
28639 				mutex_exit(&connfp->connf_lock);
28640 				(*func)(connp, arg);
28641 				mutex_enter(&connfp->connf_lock);
28642 				CONN_DEC_REF(connp);
28643 			}
28644 		}
28645 		mutex_exit(&connfp->connf_lock);
28646 		connfp++;
28647 	}
28648 }
28649 
28650 /* conn_walk_fanout routine invoked for ip_conn_report for each conn. */
28651 static void
28652 conn_report1(conn_t *connp, void *mp)
28653 {
28654 	char	buf1[INET6_ADDRSTRLEN];
28655 	char	buf2[INET6_ADDRSTRLEN];
28656 	uint_t	print_len, buf_len;
28657 
28658 	ASSERT(connp != NULL);
28659 
28660 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28661 	if (buf_len <= 0)
28662 		return;
28663 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1));
28664 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2));
28665 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28666 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28667 	    "%5d %s/%05d %s/%05d\n",
28668 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28669 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28670 	    buf1, connp->conn_lport,
28671 	    buf2, connp->conn_fport);
28672 	if (print_len < buf_len) {
28673 		((mblk_t *)mp)->b_wptr += print_len;
28674 	} else {
28675 		((mblk_t *)mp)->b_wptr += buf_len;
28676 	}
28677 }
28678 
28679 /*
28680  * Named Dispatch routine to produce a formatted report on all conns
28681  * that are listed in one of the fanout tables.
28682  * This report is accessed by using the ndd utility to "get" ND variable
28683  * "ip_conn_status".
28684  */
28685 /* ARGSUSED */
28686 static int
28687 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28688 {
28689 	conn_t *connp = Q_TO_CONN(q);
28690 
28691 	(void) mi_mpprintf(mp,
28692 	    "CONN      " MI_COL_HDRPAD_STR
28693 	    "rfq      " MI_COL_HDRPAD_STR
28694 	    "stq      " MI_COL_HDRPAD_STR
28695 	    " zone local                 remote");
28696 
28697 	/*
28698 	 * Because of the ndd constraint, at most we can have 64K buffer
28699 	 * to put in all conn info.  So to be more efficient, just
28700 	 * allocate a 64K buffer here, assuming we need that large buffer.
28701 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28702 	 */
28703 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28704 		/* The following may work even if we cannot get a large buf. */
28705 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28706 		return (0);
28707 	}
28708 
28709 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
28710 	    connp->conn_netstack->netstack_ip);
28711 	return (0);
28712 }
28713 
28714 /*
28715  * Determine if the ill and multicast aspects of that packets
28716  * "matches" the conn.
28717  */
28718 boolean_t
28719 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28720     zoneid_t zoneid)
28721 {
28722 	ill_t *in_ill;
28723 	boolean_t found;
28724 	ipif_t *ipif;
28725 	ire_t *ire;
28726 	ipaddr_t dst, src;
28727 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28728 
28729 	dst = ipha->ipha_dst;
28730 	src = ipha->ipha_src;
28731 
28732 	/*
28733 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28734 	 * unicast, broadcast and multicast reception to
28735 	 * conn_incoming_ill. conn_wantpacket itself is called
28736 	 * only for BROADCAST and multicast.
28737 	 *
28738 	 * 1) ip_rput supresses duplicate broadcasts if the ill
28739 	 *    is part of a group. Hence, we should be receiving
28740 	 *    just one copy of broadcast for the whole group.
28741 	 *    Thus, if it is part of the group the packet could
28742 	 *    come on any ill of the group and hence we need a
28743 	 *    match on the group. Otherwise, match on ill should
28744 	 *    be sufficient.
28745 	 *
28746 	 * 2) ip_rput does not suppress duplicate multicast packets.
28747 	 *    If there are two interfaces in a ill group and we have
28748 	 *    2 applications (conns) joined a multicast group G on
28749 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
28750 	 *    will give us two packets because we join G on both the
28751 	 *    interfaces rather than nominating just one interface
28752 	 *    for receiving multicast like broadcast above. So,
28753 	 *    we have to call ilg_lookup_ill to filter out duplicate
28754 	 *    copies, if ill is part of a group.
28755 	 */
28756 	in_ill = connp->conn_incoming_ill;
28757 	if (in_ill != NULL) {
28758 		if (in_ill->ill_group == NULL) {
28759 			if (in_ill != ill)
28760 				return (B_FALSE);
28761 		} else if (in_ill->ill_group != ill->ill_group) {
28762 			return (B_FALSE);
28763 		}
28764 	}
28765 
28766 	if (!CLASSD(dst)) {
28767 		if (IPCL_ZONE_MATCH(connp, zoneid))
28768 			return (B_TRUE);
28769 		/*
28770 		 * The conn is in a different zone; we need to check that this
28771 		 * broadcast address is configured in the application's zone and
28772 		 * on one ill in the group.
28773 		 */
28774 		ipif = ipif_get_next_ipif(NULL, ill);
28775 		if (ipif == NULL)
28776 			return (B_FALSE);
28777 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28778 		    connp->conn_zoneid, NULL,
28779 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
28780 		ipif_refrele(ipif);
28781 		if (ire != NULL) {
28782 			ire_refrele(ire);
28783 			return (B_TRUE);
28784 		} else {
28785 			return (B_FALSE);
28786 		}
28787 	}
28788 
28789 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28790 	    connp->conn_zoneid == zoneid) {
28791 		/*
28792 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28793 		 * disabled, therefore we don't dispatch the multicast packet to
28794 		 * the sending zone.
28795 		 */
28796 		return (B_FALSE);
28797 	}
28798 
28799 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28800 		/*
28801 		 * Multicast packet on the loopback interface: we only match
28802 		 * conns who joined the group in the specified zone.
28803 		 */
28804 		return (B_FALSE);
28805 	}
28806 
28807 	if (connp->conn_multi_router) {
28808 		/* multicast packet and multicast router socket: send up */
28809 		return (B_TRUE);
28810 	}
28811 
28812 	mutex_enter(&connp->conn_lock);
28813 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28814 	mutex_exit(&connp->conn_lock);
28815 	return (found);
28816 }
28817 
28818 /*
28819  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28820  */
28821 /* ARGSUSED */
28822 static void
28823 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28824 {
28825 	ill_t *ill = (ill_t *)q->q_ptr;
28826 	mblk_t	*mp1, *mp2;
28827 	ipif_t  *ipif;
28828 	int err = 0;
28829 	conn_t *connp = NULL;
28830 	ipsq_t	*ipsq;
28831 	arc_t	*arc;
28832 
28833 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28834 
28835 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28836 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28837 
28838 	ASSERT(IAM_WRITER_ILL(ill));
28839 	mp2 = mp->b_cont;
28840 	mp->b_cont = NULL;
28841 
28842 	/*
28843 	 * We have now received the arp bringup completion message
28844 	 * from ARP. Mark the arp bringup as done. Also if the arp
28845 	 * stream has already started closing, send up the AR_ARP_CLOSING
28846 	 * ack now since ARP is waiting in close for this ack.
28847 	 */
28848 	mutex_enter(&ill->ill_lock);
28849 	ill->ill_arp_bringup_pending = 0;
28850 	if (ill->ill_arp_closing) {
28851 		mutex_exit(&ill->ill_lock);
28852 		/* Let's reuse the mp for sending the ack */
28853 		arc = (arc_t *)mp->b_rptr;
28854 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28855 		arc->arc_cmd = AR_ARP_CLOSING;
28856 		qreply(q, mp);
28857 	} else {
28858 		mutex_exit(&ill->ill_lock);
28859 		freeb(mp);
28860 	}
28861 
28862 	ipsq = ill->ill_phyint->phyint_ipsq;
28863 	ipif = ipsq->ipsq_pending_ipif;
28864 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28865 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28866 	if (mp1 == NULL) {
28867 		/* bringup was aborted by the user */
28868 		freemsg(mp2);
28869 		return;
28870 	}
28871 
28872 	/*
28873 	 * If an IOCTL is waiting on this (ipsq_current_ioctl != 0), then we
28874 	 * must have an associated conn_t.  Otherwise, we're bringing this
28875 	 * interface back up as part of handling an asynchronous event (e.g.,
28876 	 * physical address change).
28877 	 */
28878 	if (ipsq->ipsq_current_ioctl != 0) {
28879 		ASSERT(connp != NULL);
28880 		q = CONNP_TO_WQ(connp);
28881 	} else {
28882 		ASSERT(connp == NULL);
28883 		q = ill->ill_rq;
28884 	}
28885 
28886 	/*
28887 	 * If the DL_BIND_REQ fails, it is noted
28888 	 * in arc_name_offset.
28889 	 */
28890 	err = *((int *)mp2->b_rptr);
28891 	if (err == 0) {
28892 		if (ipif->ipif_isv6) {
28893 			if ((err = ipif_up_done_v6(ipif)) != 0)
28894 				ip0dbg(("ip_arp_done: init failed\n"));
28895 		} else {
28896 			if ((err = ipif_up_done(ipif)) != 0)
28897 				ip0dbg(("ip_arp_done: init failed\n"));
28898 		}
28899 	} else {
28900 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28901 	}
28902 
28903 	freemsg(mp2);
28904 
28905 	if ((err == 0) && (ill->ill_up_ipifs)) {
28906 		err = ill_up_ipifs(ill, q, mp1);
28907 		if (err == EINPROGRESS)
28908 			return;
28909 	}
28910 
28911 	if (ill->ill_up_ipifs)
28912 		ill_group_cleanup(ill);
28913 
28914 	/*
28915 	 * The operation must complete without EINPROGRESS since
28916 	 * ipsq_pending_mp_get() has removed the mblk from ipsq_pending_mp.
28917 	 * Otherwise, the operation will be stuck forever in the ipsq.
28918 	 */
28919 	ASSERT(err != EINPROGRESS);
28920 	if (ipsq->ipsq_current_ioctl != 0)
28921 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28922 	else
28923 		ipsq_current_finish(ipsq);
28924 }
28925 
28926 /* Allocate the private structure */
28927 static int
28928 ip_priv_alloc(void **bufp)
28929 {
28930 	void	*buf;
28931 
28932 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28933 		return (ENOMEM);
28934 
28935 	*bufp = buf;
28936 	return (0);
28937 }
28938 
28939 /* Function to delete the private structure */
28940 void
28941 ip_priv_free(void *buf)
28942 {
28943 	ASSERT(buf != NULL);
28944 	kmem_free(buf, sizeof (ip_priv_t));
28945 }
28946 
28947 /*
28948  * The entry point for IPPF processing.
28949  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28950  * routine just returns.
28951  *
28952  * When called, ip_process generates an ipp_packet_t structure
28953  * which holds the state information for this packet and invokes the
28954  * the classifier (via ipp_packet_process). The classification, depending on
28955  * configured filters, results in a list of actions for this packet. Invoking
28956  * an action may cause the packet to be dropped, in which case the resulting
28957  * mblk (*mpp) is NULL. proc indicates the callout position for
28958  * this packet and ill_index is the interface this packet on or will leave
28959  * on (inbound and outbound resp.).
28960  */
28961 void
28962 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28963 {
28964 	mblk_t		*mp;
28965 	ip_priv_t	*priv;
28966 	ipp_action_id_t	aid;
28967 	int		rc = 0;
28968 	ipp_packet_t	*pp;
28969 #define	IP_CLASS	"ip"
28970 
28971 	/* If the classifier is not loaded, return  */
28972 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28973 		return;
28974 	}
28975 
28976 	mp = *mpp;
28977 	ASSERT(mp != NULL);
28978 
28979 	/* Allocate the packet structure */
28980 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28981 	if (rc != 0) {
28982 		*mpp = NULL;
28983 		freemsg(mp);
28984 		return;
28985 	}
28986 
28987 	/* Allocate the private structure */
28988 	rc = ip_priv_alloc((void **)&priv);
28989 	if (rc != 0) {
28990 		*mpp = NULL;
28991 		freemsg(mp);
28992 		ipp_packet_free(pp);
28993 		return;
28994 	}
28995 	priv->proc = proc;
28996 	priv->ill_index = ill_index;
28997 	ipp_packet_set_private(pp, priv, ip_priv_free);
28998 	ipp_packet_set_data(pp, mp);
28999 
29000 	/* Invoke the classifier */
29001 	rc = ipp_packet_process(&pp);
29002 	if (pp != NULL) {
29003 		mp = ipp_packet_get_data(pp);
29004 		ipp_packet_free(pp);
29005 		if (rc != 0) {
29006 			freemsg(mp);
29007 			*mpp = NULL;
29008 		}
29009 	} else {
29010 		*mpp = NULL;
29011 	}
29012 #undef	IP_CLASS
29013 }
29014 
29015 /*
29016  * Propagate a multicast group membership operation (add/drop) on
29017  * all the interfaces crossed by the related multirt routes.
29018  * The call is considered successful if the operation succeeds
29019  * on at least one interface.
29020  */
29021 static int
29022 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
29023     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
29024     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
29025     mblk_t *first_mp)
29026 {
29027 	ire_t		*ire_gw;
29028 	irb_t		*irb;
29029 	int		error = 0;
29030 	opt_restart_t	*or;
29031 	ip_stack_t	*ipst = ire->ire_ipst;
29032 
29033 	irb = ire->ire_bucket;
29034 	ASSERT(irb != NULL);
29035 
29036 	ASSERT(DB_TYPE(first_mp) == M_CTL);
29037 
29038 	or = (opt_restart_t *)first_mp->b_rptr;
29039 	IRB_REFHOLD(irb);
29040 	for (; ire != NULL; ire = ire->ire_next) {
29041 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
29042 			continue;
29043 		if (ire->ire_addr != group)
29044 			continue;
29045 
29046 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
29047 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
29048 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
29049 		/* No resolver exists for the gateway; skip this ire. */
29050 		if (ire_gw == NULL)
29051 			continue;
29052 
29053 		/*
29054 		 * This function can return EINPROGRESS. If so the operation
29055 		 * will be restarted from ip_restart_optmgmt which will
29056 		 * call ip_opt_set and option processing will restart for
29057 		 * this option. So we may end up calling 'fn' more than once.
29058 		 * This requires that 'fn' is idempotent except for the
29059 		 * return value. The operation is considered a success if
29060 		 * it succeeds at least once on any one interface.
29061 		 */
29062 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
29063 		    NULL, fmode, src, first_mp);
29064 		if (error == 0)
29065 			or->or_private = CGTP_MCAST_SUCCESS;
29066 
29067 		if (ip_debug > 0) {
29068 			ulong_t	off;
29069 			char	*ksym;
29070 			ksym = kobj_getsymname((uintptr_t)fn, &off);
29071 			ip2dbg(("ip_multirt_apply_membership: "
29072 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
29073 			    "error %d [success %u]\n",
29074 			    ksym ? ksym : "?",
29075 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
29076 			    error, or->or_private));
29077 		}
29078 
29079 		ire_refrele(ire_gw);
29080 		if (error == EINPROGRESS) {
29081 			IRB_REFRELE(irb);
29082 			return (error);
29083 		}
29084 	}
29085 	IRB_REFRELE(irb);
29086 	/*
29087 	 * Consider the call as successful if we succeeded on at least
29088 	 * one interface. Otherwise, return the last encountered error.
29089 	 */
29090 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
29091 }
29092 
29093 
29094 /*
29095  * Issue a warning regarding a route crossing an interface with an
29096  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
29097  * amount of time is logged.
29098  */
29099 static void
29100 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
29101 {
29102 	hrtime_t	current = gethrtime();
29103 	char		buf[INET_ADDRSTRLEN];
29104 	ip_stack_t	*ipst = ire->ire_ipst;
29105 
29106 	/* Convert interval in ms to hrtime in ns */
29107 	if (ipst->ips_multirt_bad_mtu_last_time +
29108 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
29109 	    current) {
29110 		cmn_err(CE_WARN, "ip: ignoring multiroute "
29111 		    "to %s, incorrect MTU %u (expected %u)\n",
29112 		    ip_dot_addr(ire->ire_addr, buf),
29113 		    ire->ire_max_frag, max_frag);
29114 
29115 		ipst->ips_multirt_bad_mtu_last_time = current;
29116 	}
29117 }
29118 
29119 
29120 /*
29121  * Get the CGTP (multirouting) filtering status.
29122  * If 0, the CGTP hooks are transparent.
29123  */
29124 /* ARGSUSED */
29125 static int
29126 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
29127 {
29128 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29129 
29130 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
29131 	return (0);
29132 }
29133 
29134 
29135 /*
29136  * Set the CGTP (multirouting) filtering status.
29137  * If the status is changed from active to transparent
29138  * or from transparent to active, forward the new status
29139  * to the filtering module (if loaded).
29140  */
29141 /* ARGSUSED */
29142 static int
29143 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
29144     cred_t *ioc_cr)
29145 {
29146 	long		new_value;
29147 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29148 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29149 
29150 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
29151 		return (EPERM);
29152 
29153 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
29154 	    new_value < 0 || new_value > 1) {
29155 		return (EINVAL);
29156 	}
29157 
29158 	if ((!*ip_cgtp_filter_value) && new_value) {
29159 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
29160 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
29161 		    " (module not loaded)" : "");
29162 	}
29163 	if (*ip_cgtp_filter_value && (!new_value)) {
29164 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
29165 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
29166 		    " (module not loaded)" : "");
29167 	}
29168 
29169 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29170 		int	res;
29171 		netstackid_t stackid;
29172 
29173 		stackid = ipst->ips_netstack->netstack_stackid;
29174 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
29175 		    new_value);
29176 		if (res)
29177 			return (res);
29178 	}
29179 
29180 	*ip_cgtp_filter_value = (boolean_t)new_value;
29181 
29182 	return (0);
29183 }
29184 
29185 
29186 /*
29187  * Return the expected CGTP hooks version number.
29188  */
29189 int
29190 ip_cgtp_filter_supported(void)
29191 {
29192 	return (ip_cgtp_filter_rev);
29193 }
29194 
29195 
29196 /*
29197  * CGTP hooks can be registered by invoking this function.
29198  * Checks that the version number matches.
29199  */
29200 int
29201 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
29202 {
29203 	netstack_t *ns;
29204 	ip_stack_t *ipst;
29205 
29206 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
29207 		return (ENOTSUP);
29208 
29209 	ns = netstack_find_by_stackid(stackid);
29210 	if (ns == NULL)
29211 		return (EINVAL);
29212 	ipst = ns->netstack_ip;
29213 	ASSERT(ipst != NULL);
29214 
29215 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29216 		netstack_rele(ns);
29217 		return (EALREADY);
29218 	}
29219 
29220 	ipst->ips_ip_cgtp_filter_ops = ops;
29221 	netstack_rele(ns);
29222 	return (0);
29223 }
29224 
29225 /*
29226  * CGTP hooks can be unregistered by invoking this function.
29227  * Returns ENXIO if there was no registration.
29228  * Returns EBUSY if the ndd variable has not been turned off.
29229  */
29230 int
29231 ip_cgtp_filter_unregister(netstackid_t stackid)
29232 {
29233 	netstack_t *ns;
29234 	ip_stack_t *ipst;
29235 
29236 	ns = netstack_find_by_stackid(stackid);
29237 	if (ns == NULL)
29238 		return (EINVAL);
29239 	ipst = ns->netstack_ip;
29240 	ASSERT(ipst != NULL);
29241 
29242 	if (ipst->ips_ip_cgtp_filter) {
29243 		netstack_rele(ns);
29244 		return (EBUSY);
29245 	}
29246 
29247 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
29248 		netstack_rele(ns);
29249 		return (ENXIO);
29250 	}
29251 	ipst->ips_ip_cgtp_filter_ops = NULL;
29252 	netstack_rele(ns);
29253 	return (0);
29254 }
29255 
29256 /*
29257  * Check whether there is a CGTP filter registration.
29258  * Returns non-zero if there is a registration, otherwise returns zero.
29259  * Note: returns zero if bad stackid.
29260  */
29261 int
29262 ip_cgtp_filter_is_registered(netstackid_t stackid)
29263 {
29264 	netstack_t *ns;
29265 	ip_stack_t *ipst;
29266 	int ret;
29267 
29268 	ns = netstack_find_by_stackid(stackid);
29269 	if (ns == NULL)
29270 		return (0);
29271 	ipst = ns->netstack_ip;
29272 	ASSERT(ipst != NULL);
29273 
29274 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
29275 		ret = 1;
29276 	else
29277 		ret = 0;
29278 
29279 	netstack_rele(ns);
29280 	return (ret);
29281 }
29282 
29283 static squeue_func_t
29284 ip_squeue_switch(int val)
29285 {
29286 	squeue_func_t rval = squeue_fill;
29287 
29288 	switch (val) {
29289 	case IP_SQUEUE_ENTER_NODRAIN:
29290 		rval = squeue_enter_nodrain;
29291 		break;
29292 	case IP_SQUEUE_ENTER:
29293 		rval = squeue_enter;
29294 		break;
29295 	default:
29296 		break;
29297 	}
29298 	return (rval);
29299 }
29300 
29301 /* ARGSUSED */
29302 static int
29303 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29304     caddr_t addr, cred_t *cr)
29305 {
29306 	int *v = (int *)addr;
29307 	long new_value;
29308 
29309 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29310 		return (EPERM);
29311 
29312 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29313 		return (EINVAL);
29314 
29315 	ip_input_proc = ip_squeue_switch(new_value);
29316 	*v = new_value;
29317 	return (0);
29318 }
29319 
29320 /*
29321  * Handle ndd set of variables which require PRIV_SYS_NET_CONFIG such as
29322  * ip_debug.
29323  */
29324 /* ARGSUSED */
29325 static int
29326 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29327     caddr_t addr, cred_t *cr)
29328 {
29329 	int *v = (int *)addr;
29330 	long new_value;
29331 
29332 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29333 		return (EPERM);
29334 
29335 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29336 		return (EINVAL);
29337 
29338 	*v = new_value;
29339 	return (0);
29340 }
29341 
29342 /*
29343  * Handle changes to ipmp_hook_emulation ndd variable.
29344  * Need to update phyint_hook_ifindex.
29345  * Also generate a nic plumb event should a new ifidex be assigned to a group.
29346  */
29347 static void
29348 ipmp_hook_emulation_changed(ip_stack_t *ipst)
29349 {
29350 	phyint_t *phyi;
29351 	phyint_t *phyi_tmp;
29352 	char *groupname;
29353 	int namelen;
29354 	ill_t	*ill;
29355 	boolean_t new_group;
29356 
29357 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29358 	/*
29359 	 * Group indicies are stored in the phyint - a common structure
29360 	 * to both IPv4 and IPv6.
29361 	 */
29362 	phyi = avl_first(&ipst->ips_phyint_g_list->phyint_list_avl_by_index);
29363 	for (; phyi != NULL;
29364 	    phyi = avl_walk(&ipst->ips_phyint_g_list->phyint_list_avl_by_index,
29365 	    phyi, AVL_AFTER)) {
29366 		/* Ignore the ones that do not have a group */
29367 		if (phyi->phyint_groupname_len == 0)
29368 			continue;
29369 
29370 		/*
29371 		 * Look for other phyint in group.
29372 		 * Clear name/namelen so the lookup doesn't find ourselves.
29373 		 */
29374 		namelen = phyi->phyint_groupname_len;
29375 		groupname = phyi->phyint_groupname;
29376 		phyi->phyint_groupname_len = 0;
29377 		phyi->phyint_groupname = NULL;
29378 
29379 		phyi_tmp = phyint_lookup_group(groupname, B_FALSE, ipst);
29380 		/* Restore */
29381 		phyi->phyint_groupname_len = namelen;
29382 		phyi->phyint_groupname = groupname;
29383 
29384 		new_group = B_FALSE;
29385 		if (ipst->ips_ipmp_hook_emulation) {
29386 			/*
29387 			 * If the group already exists and has already
29388 			 * been assigned a group ifindex, we use the existing
29389 			 * group_ifindex, otherwise we pick a new group_ifindex
29390 			 * here.
29391 			 */
29392 			if (phyi_tmp != NULL &&
29393 			    phyi_tmp->phyint_group_ifindex != 0) {
29394 				phyi->phyint_group_ifindex =
29395 				    phyi_tmp->phyint_group_ifindex;
29396 			} else {
29397 				/* XXX We need a recovery strategy here. */
29398 				if (!ip_assign_ifindex(
29399 				    &phyi->phyint_group_ifindex, ipst))
29400 					cmn_err(CE_PANIC,
29401 					    "ip_assign_ifindex() failed");
29402 				new_group = B_TRUE;
29403 			}
29404 		} else {
29405 			phyi->phyint_group_ifindex = 0;
29406 		}
29407 		if (ipst->ips_ipmp_hook_emulation)
29408 			phyi->phyint_hook_ifindex = phyi->phyint_group_ifindex;
29409 		else
29410 			phyi->phyint_hook_ifindex = phyi->phyint_ifindex;
29411 
29412 		/*
29413 		 * For IP Filter to find out the relationship between
29414 		 * names and interface indicies, we need to generate
29415 		 * a NE_PLUMB event when a new group can appear.
29416 		 * We always generate events when a new interface appears
29417 		 * (even when ipmp_hook_emulation is set) so there
29418 		 * is no need to generate NE_PLUMB events when
29419 		 * ipmp_hook_emulation is turned off.
29420 		 * And since it isn't critical for IP Filter to get
29421 		 * the NE_UNPLUMB events we skip those here.
29422 		 */
29423 		if (new_group) {
29424 			/*
29425 			 * First phyint in group - generate group PLUMB event.
29426 			 * Since we are not running inside the ipsq we do
29427 			 * the dispatch immediately.
29428 			 */
29429 			if (phyi->phyint_illv4 != NULL)
29430 				ill = phyi->phyint_illv4;
29431 			else
29432 				ill = phyi->phyint_illv6;
29433 
29434 			if (ill != NULL)
29435 				ill_nic_event_plumb(ill, B_TRUE);
29436 		}
29437 	}
29438 	rw_exit(&ipst->ips_ill_g_lock);
29439 }
29440 
29441 /* ARGSUSED */
29442 static int
29443 ipmp_hook_emulation_set(queue_t *q, mblk_t *mp, char *value,
29444     caddr_t addr, cred_t *cr)
29445 {
29446 	int *v = (int *)addr;
29447 	long new_value;
29448 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29449 
29450 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29451 		return (EINVAL);
29452 
29453 	if (*v != new_value) {
29454 		*v = new_value;
29455 		ipmp_hook_emulation_changed(ipst);
29456 	}
29457 	return (0);
29458 }
29459 
29460 static void *
29461 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29462 {
29463 	kstat_t *ksp;
29464 
29465 	ip_stat_t template = {
29466 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29467 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29468 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29469 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29470 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29471 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29472 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29473 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29474 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29475 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29476 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29477 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29478 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29479 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29480 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29481 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29482 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29483 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29484 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29485 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29486 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29487 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29488 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29489 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29490 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29491 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29492 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29493 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29494 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29495 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29496 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29497 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29498 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29499 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29500 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29501 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29502 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29503 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29504 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29505 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29506 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29507 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29508 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29509 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29510 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29511 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29512 	};
29513 
29514 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29515 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29516 	    KSTAT_FLAG_VIRTUAL, stackid);
29517 
29518 	if (ksp == NULL)
29519 		return (NULL);
29520 
29521 	bcopy(&template, ip_statisticsp, sizeof (template));
29522 	ksp->ks_data = (void *)ip_statisticsp;
29523 	ksp->ks_private = (void *)(uintptr_t)stackid;
29524 
29525 	kstat_install(ksp);
29526 	return (ksp);
29527 }
29528 
29529 static void
29530 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29531 {
29532 	if (ksp != NULL) {
29533 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29534 		kstat_delete_netstack(ksp, stackid);
29535 	}
29536 }
29537 
29538 static void *
29539 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29540 {
29541 	kstat_t	*ksp;
29542 
29543 	ip_named_kstat_t template = {
29544 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29545 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29546 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29547 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29548 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29549 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29550 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29551 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29552 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29553 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29554 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29555 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29556 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29557 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29558 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29559 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29560 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29561 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29562 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29563 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29564 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29565 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29566 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29567 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29568 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29569 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29570 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29571 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29572 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29573 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29574 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29575 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29576 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29577 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29578 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29579 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29580 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29581 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29582 	};
29583 
29584 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29585 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29586 	if (ksp == NULL || ksp->ks_data == NULL)
29587 		return (NULL);
29588 
29589 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29590 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29591 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29592 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29593 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29594 
29595 	template.netToMediaEntrySize.value.i32 =
29596 	    sizeof (mib2_ipNetToMediaEntry_t);
29597 
29598 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29599 
29600 	bcopy(&template, ksp->ks_data, sizeof (template));
29601 	ksp->ks_update = ip_kstat_update;
29602 	ksp->ks_private = (void *)(uintptr_t)stackid;
29603 
29604 	kstat_install(ksp);
29605 	return (ksp);
29606 }
29607 
29608 static void
29609 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29610 {
29611 	if (ksp != NULL) {
29612 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29613 		kstat_delete_netstack(ksp, stackid);
29614 	}
29615 }
29616 
29617 static int
29618 ip_kstat_update(kstat_t *kp, int rw)
29619 {
29620 	ip_named_kstat_t *ipkp;
29621 	mib2_ipIfStatsEntry_t ipmib;
29622 	ill_walk_context_t ctx;
29623 	ill_t *ill;
29624 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29625 	netstack_t	*ns;
29626 	ip_stack_t	*ipst;
29627 
29628 	if (kp == NULL || kp->ks_data == NULL)
29629 		return (EIO);
29630 
29631 	if (rw == KSTAT_WRITE)
29632 		return (EACCES);
29633 
29634 	ns = netstack_find_by_stackid(stackid);
29635 	if (ns == NULL)
29636 		return (-1);
29637 	ipst = ns->netstack_ip;
29638 	if (ipst == NULL) {
29639 		netstack_rele(ns);
29640 		return (-1);
29641 	}
29642 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29643 
29644 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29645 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29646 	ill = ILL_START_WALK_V4(&ctx, ipst);
29647 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29648 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29649 	rw_exit(&ipst->ips_ill_g_lock);
29650 
29651 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29652 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29653 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29654 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29655 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29656 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29657 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29658 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29659 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29660 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29661 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29662 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29663 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29664 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29665 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29666 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29667 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29668 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29669 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29670 
29671 	ipkp->routingDiscards.value.ui32 =	0;
29672 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29673 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29674 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29675 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29676 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29677 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29678 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29679 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29680 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29681 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29682 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29683 
29684 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29685 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29686 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29687 
29688 	netstack_rele(ns);
29689 
29690 	return (0);
29691 }
29692 
29693 static void *
29694 icmp_kstat_init(netstackid_t stackid)
29695 {
29696 	kstat_t	*ksp;
29697 
29698 	icmp_named_kstat_t template = {
29699 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29700 		{ "inErrors",		KSTAT_DATA_UINT32 },
29701 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29702 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29703 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29704 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29705 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29706 		{ "inEchos",		KSTAT_DATA_UINT32 },
29707 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29708 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29709 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29710 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29711 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29712 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29713 		{ "outErrors",		KSTAT_DATA_UINT32 },
29714 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29715 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29716 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29717 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29718 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29719 		{ "outEchos",		KSTAT_DATA_UINT32 },
29720 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29721 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29722 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29723 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29724 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29725 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29726 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29727 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29728 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29729 		{ "outDrops",		KSTAT_DATA_UINT32 },
29730 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29731 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29732 	};
29733 
29734 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29735 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29736 	if (ksp == NULL || ksp->ks_data == NULL)
29737 		return (NULL);
29738 
29739 	bcopy(&template, ksp->ks_data, sizeof (template));
29740 
29741 	ksp->ks_update = icmp_kstat_update;
29742 	ksp->ks_private = (void *)(uintptr_t)stackid;
29743 
29744 	kstat_install(ksp);
29745 	return (ksp);
29746 }
29747 
29748 static void
29749 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29750 {
29751 	if (ksp != NULL) {
29752 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29753 		kstat_delete_netstack(ksp, stackid);
29754 	}
29755 }
29756 
29757 static int
29758 icmp_kstat_update(kstat_t *kp, int rw)
29759 {
29760 	icmp_named_kstat_t *icmpkp;
29761 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29762 	netstack_t	*ns;
29763 	ip_stack_t	*ipst;
29764 
29765 	if ((kp == NULL) || (kp->ks_data == NULL))
29766 		return (EIO);
29767 
29768 	if (rw == KSTAT_WRITE)
29769 		return (EACCES);
29770 
29771 	ns = netstack_find_by_stackid(stackid);
29772 	if (ns == NULL)
29773 		return (-1);
29774 	ipst = ns->netstack_ip;
29775 	if (ipst == NULL) {
29776 		netstack_rele(ns);
29777 		return (-1);
29778 	}
29779 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29780 
29781 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29782 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29783 	icmpkp->inDestUnreachs.value.ui32 =
29784 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29785 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29786 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29787 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29788 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29789 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29790 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29791 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29792 	icmpkp->inTimestampReps.value.ui32 =
29793 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29794 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29795 	icmpkp->inAddrMaskReps.value.ui32 =
29796 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29797 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29798 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29799 	icmpkp->outDestUnreachs.value.ui32 =
29800 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29801 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29802 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29803 	icmpkp->outSrcQuenchs.value.ui32 =
29804 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29805 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29806 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29807 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29808 	icmpkp->outTimestamps.value.ui32 =
29809 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29810 	icmpkp->outTimestampReps.value.ui32 =
29811 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29812 	icmpkp->outAddrMasks.value.ui32 =
29813 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29814 	icmpkp->outAddrMaskReps.value.ui32 =
29815 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29816 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29817 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29818 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29819 	icmpkp->outFragNeeded.value.ui32 =
29820 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29821 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29822 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29823 	icmpkp->inBadRedirects.value.ui32 =
29824 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29825 
29826 	netstack_rele(ns);
29827 	return (0);
29828 }
29829 
29830 /*
29831  * This is the fanout function for raw socket opened for SCTP.  Note
29832  * that it is called after SCTP checks that there is no socket which
29833  * wants a packet.  Then before SCTP handles this out of the blue packet,
29834  * this function is called to see if there is any raw socket for SCTP.
29835  * If there is and it is bound to the correct address, the packet will
29836  * be sent to that socket.  Note that only one raw socket can be bound to
29837  * a port.  This is assured in ipcl_sctp_hash_insert();
29838  */
29839 void
29840 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29841     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29842     zoneid_t zoneid)
29843 {
29844 	conn_t		*connp;
29845 	queue_t		*rq;
29846 	mblk_t		*first_mp;
29847 	boolean_t	secure;
29848 	ip6_t		*ip6h;
29849 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29850 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29851 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
29852 	boolean_t	sctp_csum_err = B_FALSE;
29853 
29854 	if (flags & IP_FF_SCTP_CSUM_ERR) {
29855 		sctp_csum_err = B_TRUE;
29856 		flags &= ~IP_FF_SCTP_CSUM_ERR;
29857 	}
29858 
29859 	first_mp = mp;
29860 	if (mctl_present) {
29861 		mp = first_mp->b_cont;
29862 		secure = ipsec_in_is_secure(first_mp);
29863 		ASSERT(mp != NULL);
29864 	} else {
29865 		secure = B_FALSE;
29866 	}
29867 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29868 
29869 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29870 	if (connp == NULL) {
29871 		/*
29872 		 * Although raw sctp is not summed, OOB chunks must be.
29873 		 * Drop the packet here if the sctp checksum failed.
29874 		 */
29875 		if (sctp_csum_err) {
29876 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
29877 			freemsg(first_mp);
29878 			return;
29879 		}
29880 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29881 		return;
29882 	}
29883 	rq = connp->conn_rq;
29884 	if (!canputnext(rq)) {
29885 		CONN_DEC_REF(connp);
29886 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29887 		freemsg(first_mp);
29888 		return;
29889 	}
29890 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29891 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29892 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29893 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29894 		if (first_mp == NULL) {
29895 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29896 			CONN_DEC_REF(connp);
29897 			return;
29898 		}
29899 	}
29900 	/*
29901 	 * We probably should not send M_CTL message up to
29902 	 * raw socket.
29903 	 */
29904 	if (mctl_present)
29905 		freeb(first_mp);
29906 
29907 	/* Initiate IPPF processing here if needed. */
29908 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29909 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29910 		ip_process(IPP_LOCAL_IN, &mp,
29911 		    recv_ill->ill_phyint->phyint_ifindex);
29912 		if (mp == NULL) {
29913 			CONN_DEC_REF(connp);
29914 			return;
29915 		}
29916 	}
29917 
29918 	if (connp->conn_recvif || connp->conn_recvslla ||
29919 	    ((connp->conn_ip_recvpktinfo ||
29920 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29921 	    (flags & IP_FF_IPINFO))) {
29922 		int in_flags = 0;
29923 
29924 		/*
29925 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29926 		 * IPF_RECVIF.
29927 		 */
29928 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29929 			in_flags = IPF_RECVIF;
29930 		}
29931 		if (connp->conn_recvslla) {
29932 			in_flags |= IPF_RECVSLLA;
29933 		}
29934 		if (isv4) {
29935 			mp = ip_add_info(mp, recv_ill, in_flags,
29936 			    IPCL_ZONEID(connp), ipst);
29937 		} else {
29938 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29939 			if (mp == NULL) {
29940 				BUMP_MIB(recv_ill->ill_ip_mib,
29941 				    ipIfStatsInDiscards);
29942 				CONN_DEC_REF(connp);
29943 				return;
29944 			}
29945 		}
29946 	}
29947 
29948 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29949 	/*
29950 	 * We are sending the IPSEC_IN message also up. Refer
29951 	 * to comments above this function.
29952 	 * This is the SOCK_RAW, IPPROTO_SCTP case.
29953 	 */
29954 	(connp->conn_recv)(connp, mp, NULL);
29955 	CONN_DEC_REF(connp);
29956 }
29957 
29958 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29959 {									\
29960 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29961 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29962 }
29963 /*
29964  * This function should be called only if all packet processing
29965  * including fragmentation is complete. Callers of this function
29966  * must set mp->b_prev to one of these values:
29967  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29968  * prior to handing over the mp as first argument to this function.
29969  *
29970  * If the ire passed by caller is incomplete, this function
29971  * queues the packet and if necessary, sends ARP request and bails.
29972  * If the ire passed is fully resolved, we simply prepend
29973  * the link-layer header to the packet, do ipsec hw acceleration
29974  * work if necessary, and send the packet out on the wire.
29975  *
29976  * NOTE: IPsec will only call this function with fully resolved
29977  * ires if hw acceleration is involved.
29978  * TODO list :
29979  * 	a Handle M_MULTIDATA so that
29980  *	  tcp_multisend->tcp_multisend_data can
29981  *	  call ip_xmit_v4 directly
29982  *	b Handle post-ARP work for fragments so that
29983  *	  ip_wput_frag can call this function.
29984  */
29985 ipxmit_state_t
29986 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
29987 {
29988 	nce_t		*arpce;
29989 	ipha_t		*ipha;
29990 	queue_t		*q;
29991 	int		ill_index;
29992 	mblk_t		*nxt_mp, *first_mp;
29993 	boolean_t	xmit_drop = B_FALSE;
29994 	ip_proc_t	proc;
29995 	ill_t		*out_ill;
29996 	int		pkt_len;
29997 
29998 	arpce = ire->ire_nce;
29999 	ASSERT(arpce != NULL);
30000 
30001 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
30002 
30003 	mutex_enter(&arpce->nce_lock);
30004 	switch (arpce->nce_state) {
30005 	case ND_REACHABLE:
30006 		/* If there are other queued packets, queue this packet */
30007 		if (arpce->nce_qd_mp != NULL) {
30008 			if (mp != NULL)
30009 				nce_queue_mp_common(arpce, mp, B_FALSE);
30010 			mp = arpce->nce_qd_mp;
30011 		}
30012 		arpce->nce_qd_mp = NULL;
30013 		mutex_exit(&arpce->nce_lock);
30014 
30015 		/*
30016 		 * Flush the queue.  In the common case, where the
30017 		 * ARP is already resolved,  it will go through the
30018 		 * while loop only once.
30019 		 */
30020 		while (mp != NULL) {
30021 
30022 			nxt_mp = mp->b_next;
30023 			mp->b_next = NULL;
30024 			ASSERT(mp->b_datap->db_type != M_CTL);
30025 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
30026 			/*
30027 			 * This info is needed for IPQOS to do COS marking
30028 			 * in ip_wput_attach_llhdr->ip_process.
30029 			 */
30030 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
30031 			mp->b_prev = NULL;
30032 
30033 			/* set up ill index for outbound qos processing */
30034 			out_ill = ire_to_ill(ire);
30035 			ill_index = out_ill->ill_phyint->phyint_ifindex;
30036 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
30037 			    ill_index, &ipha);
30038 			if (first_mp == NULL) {
30039 				xmit_drop = B_TRUE;
30040 				BUMP_MIB(out_ill->ill_ip_mib,
30041 				    ipIfStatsOutDiscards);
30042 				goto next_mp;
30043 			}
30044 
30045 			/* non-ipsec hw accel case */
30046 			if (io == NULL || !io->ipsec_out_accelerated) {
30047 				/* send it */
30048 				q = ire->ire_stq;
30049 				if (proc == IPP_FWD_OUT) {
30050 					UPDATE_IB_PKT_COUNT(ire);
30051 				} else {
30052 					UPDATE_OB_PKT_COUNT(ire);
30053 				}
30054 				ire->ire_last_used_time = lbolt;
30055 
30056 				if (flow_ctl_enabled || canputnext(q)) {
30057 					if (proc == IPP_FWD_OUT) {
30058 
30059 					BUMP_MIB(out_ill->ill_ip_mib,
30060 					    ipIfStatsHCOutForwDatagrams);
30061 
30062 					}
30063 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
30064 					    pkt_len);
30065 
30066 					DTRACE_IP7(send, mblk_t *, first_mp,
30067 					    conn_t *, NULL, void_ip_t *, ipha,
30068 					    __dtrace_ipsr_ill_t *, out_ill,
30069 					    ipha_t *, ipha, ip6_t *, NULL, int,
30070 					    0);
30071 
30072 					putnext(q, first_mp);
30073 				} else {
30074 					BUMP_MIB(out_ill->ill_ip_mib,
30075 					    ipIfStatsOutDiscards);
30076 					xmit_drop = B_TRUE;
30077 					freemsg(first_mp);
30078 				}
30079 			} else {
30080 				/*
30081 				 * Safety Pup says: make sure this
30082 				 *  is going to the right interface!
30083 				 */
30084 				ill_t *ill1 =
30085 				    (ill_t *)ire->ire_stq->q_ptr;
30086 				int ifindex =
30087 				    ill1->ill_phyint->phyint_ifindex;
30088 				if (ifindex !=
30089 				    io->ipsec_out_capab_ill_index) {
30090 					xmit_drop = B_TRUE;
30091 					freemsg(mp);
30092 				} else {
30093 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
30094 					    pkt_len);
30095 
30096 					DTRACE_IP7(send, mblk_t *, first_mp,
30097 					    conn_t *, NULL, void_ip_t *, ipha,
30098 					    __dtrace_ipsr_ill_t *, ill1,
30099 					    ipha_t *, ipha, ip6_t *, NULL,
30100 					    int, 0);
30101 
30102 					ipsec_hw_putnext(ire->ire_stq, mp);
30103 				}
30104 			}
30105 next_mp:
30106 			mp = nxt_mp;
30107 		} /* while (mp != NULL) */
30108 		if (xmit_drop)
30109 			return (SEND_FAILED);
30110 		else
30111 			return (SEND_PASSED);
30112 
30113 	case ND_INITIAL:
30114 	case ND_INCOMPLETE:
30115 
30116 		/*
30117 		 * While we do send off packets to dests that
30118 		 * use fully-resolved CGTP routes, we do not
30119 		 * handle unresolved CGTP routes.
30120 		 */
30121 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
30122 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
30123 
30124 		if (mp != NULL) {
30125 			/* queue the packet */
30126 			nce_queue_mp_common(arpce, mp, B_FALSE);
30127 		}
30128 
30129 		if (arpce->nce_state == ND_INCOMPLETE) {
30130 			mutex_exit(&arpce->nce_lock);
30131 			DTRACE_PROBE3(ip__xmit__incomplete,
30132 			    (ire_t *), ire, (mblk_t *), mp,
30133 			    (ipsec_out_t *), io);
30134 			return (LOOKUP_IN_PROGRESS);
30135 		}
30136 
30137 		arpce->nce_state = ND_INCOMPLETE;
30138 		mutex_exit(&arpce->nce_lock);
30139 		/*
30140 		 * Note that ire_add() (called from ire_forward())
30141 		 * holds a ref on the ire until ARP is completed.
30142 		 */
30143 
30144 		ire_arpresolve(ire, ire_to_ill(ire));
30145 		return (LOOKUP_IN_PROGRESS);
30146 	default:
30147 		ASSERT(0);
30148 		mutex_exit(&arpce->nce_lock);
30149 		return (LLHDR_RESLV_FAILED);
30150 	}
30151 }
30152 
30153 #undef	UPDATE_IP_MIB_OB_COUNTERS
30154 
30155 /*
30156  * Return B_TRUE if the buffers differ in length or content.
30157  * This is used for comparing extension header buffers.
30158  * Note that an extension header would be declared different
30159  * even if all that changed was the next header value in that header i.e.
30160  * what really changed is the next extension header.
30161  */
30162 boolean_t
30163 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
30164     uint_t blen)
30165 {
30166 	if (!b_valid)
30167 		blen = 0;
30168 
30169 	if (alen != blen)
30170 		return (B_TRUE);
30171 	if (alen == 0)
30172 		return (B_FALSE);	/* Both zero length */
30173 	return (bcmp(abuf, bbuf, alen));
30174 }
30175 
30176 /*
30177  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
30178  * Return B_FALSE if memory allocation fails - don't change any state!
30179  */
30180 boolean_t
30181 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30182     const void *src, uint_t srclen)
30183 {
30184 	void *dst;
30185 
30186 	if (!src_valid)
30187 		srclen = 0;
30188 
30189 	ASSERT(*dstlenp == 0);
30190 	if (src != NULL && srclen != 0) {
30191 		dst = mi_alloc(srclen, BPRI_MED);
30192 		if (dst == NULL)
30193 			return (B_FALSE);
30194 	} else {
30195 		dst = NULL;
30196 	}
30197 	if (*dstp != NULL)
30198 		mi_free(*dstp);
30199 	*dstp = dst;
30200 	*dstlenp = dst == NULL ? 0 : srclen;
30201 	return (B_TRUE);
30202 }
30203 
30204 /*
30205  * Replace what is in *dst, *dstlen with the source.
30206  * Assumes ip_allocbuf has already been called.
30207  */
30208 void
30209 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30210     const void *src, uint_t srclen)
30211 {
30212 	if (!src_valid)
30213 		srclen = 0;
30214 
30215 	ASSERT(*dstlenp == srclen);
30216 	if (src != NULL && srclen != 0)
30217 		bcopy(src, *dstp, srclen);
30218 }
30219 
30220 /*
30221  * Free the storage pointed to by the members of an ip6_pkt_t.
30222  */
30223 void
30224 ip6_pkt_free(ip6_pkt_t *ipp)
30225 {
30226 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
30227 
30228 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
30229 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
30230 		ipp->ipp_hopopts = NULL;
30231 		ipp->ipp_hopoptslen = 0;
30232 	}
30233 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
30234 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
30235 		ipp->ipp_rtdstopts = NULL;
30236 		ipp->ipp_rtdstoptslen = 0;
30237 	}
30238 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
30239 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
30240 		ipp->ipp_dstopts = NULL;
30241 		ipp->ipp_dstoptslen = 0;
30242 	}
30243 	if (ipp->ipp_fields & IPPF_RTHDR) {
30244 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
30245 		ipp->ipp_rthdr = NULL;
30246 		ipp->ipp_rthdrlen = 0;
30247 	}
30248 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
30249 	    IPPF_RTHDR);
30250 }
30251 
30252 zoneid_t
30253 ip_get_zoneid_v4(ipaddr_t addr, mblk_t *mp, ip_stack_t *ipst,
30254     zoneid_t lookup_zoneid)
30255 {
30256 	ire_t		*ire;
30257 	int		ire_flags = MATCH_IRE_TYPE;
30258 	zoneid_t	zoneid = ALL_ZONES;
30259 
30260 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
30261 		return (ALL_ZONES);
30262 
30263 	if (lookup_zoneid != ALL_ZONES)
30264 		ire_flags |= MATCH_IRE_ZONEONLY;
30265 	ire = ire_ctable_lookup(addr, NULL, IRE_LOCAL | IRE_LOOPBACK, NULL,
30266 	    lookup_zoneid, NULL, ire_flags, ipst);
30267 	if (ire != NULL) {
30268 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
30269 		ire_refrele(ire);
30270 	}
30271 	return (zoneid);
30272 }
30273 
30274 zoneid_t
30275 ip_get_zoneid_v6(in6_addr_t *addr, mblk_t *mp, const ill_t *ill,
30276     ip_stack_t *ipst, zoneid_t lookup_zoneid)
30277 {
30278 	ire_t		*ire;
30279 	int		ire_flags = MATCH_IRE_TYPE;
30280 	zoneid_t	zoneid = ALL_ZONES;
30281 	ipif_t		*ipif_arg = NULL;
30282 
30283 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
30284 		return (ALL_ZONES);
30285 
30286 	if (IN6_IS_ADDR_LINKLOCAL(addr)) {
30287 		ire_flags |= MATCH_IRE_ILL_GROUP;
30288 		ipif_arg = ill->ill_ipif;
30289 	}
30290 	if (lookup_zoneid != ALL_ZONES)
30291 		ire_flags |= MATCH_IRE_ZONEONLY;
30292 	ire = ire_ctable_lookup_v6(addr, NULL, IRE_LOCAL | IRE_LOOPBACK,
30293 	    ipif_arg, lookup_zoneid, NULL, ire_flags, ipst);
30294 	if (ire != NULL) {
30295 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
30296 		ire_refrele(ire);
30297 	}
30298 	return (zoneid);
30299 }
30300 
30301 /*
30302  * IP obserability hook support functions.
30303  */
30304 
30305 static void
30306 ipobs_init(ip_stack_t *ipst)
30307 {
30308 	ipst->ips_ipobs_enabled = B_FALSE;
30309 	list_create(&ipst->ips_ipobs_cb_list, sizeof (ipobs_cb_t),
30310 	    offsetof(ipobs_cb_t, ipobs_cbnext));
30311 	mutex_init(&ipst->ips_ipobs_cb_lock, NULL, MUTEX_DEFAULT, NULL);
30312 	ipst->ips_ipobs_cb_nwalkers = 0;
30313 	cv_init(&ipst->ips_ipobs_cb_cv, NULL, CV_DRIVER, NULL);
30314 }
30315 
30316 static void
30317 ipobs_fini(ip_stack_t *ipst)
30318 {
30319 	ipobs_cb_t *cb;
30320 
30321 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30322 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30323 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30324 
30325 	while ((cb = list_head(&ipst->ips_ipobs_cb_list)) != NULL) {
30326 		list_remove(&ipst->ips_ipobs_cb_list, cb);
30327 		kmem_free(cb, sizeof (*cb));
30328 	}
30329 	list_destroy(&ipst->ips_ipobs_cb_list);
30330 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30331 	mutex_destroy(&ipst->ips_ipobs_cb_lock);
30332 	cv_destroy(&ipst->ips_ipobs_cb_cv);
30333 }
30334 
30335 void
30336 ipobs_hook(mblk_t *mp, int htype, zoneid_t zsrc, zoneid_t zdst,
30337     const ill_t *ill, int ipver, uint32_t hlen, ip_stack_t *ipst)
30338 {
30339 	ipobs_cb_t *ipobs_cb;
30340 
30341 	ASSERT(DB_TYPE(mp) == M_DATA);
30342 
30343 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30344 	ipst->ips_ipobs_cb_nwalkers++;
30345 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30346 	for (ipobs_cb = list_head(&ipst->ips_ipobs_cb_list); ipobs_cb != NULL;
30347 	    ipobs_cb = list_next(&ipst->ips_ipobs_cb_list, ipobs_cb)) {
30348 		mblk_t  *mp2 = allocb(sizeof (ipobs_hook_data_t),
30349 		    BPRI_HI);
30350 		if (mp2 != NULL) {
30351 			ipobs_hook_data_t *ihd =
30352 			    (ipobs_hook_data_t *)mp2->b_rptr;
30353 			if (((ihd->ihd_mp = dupmsg(mp)) == NULL) &&
30354 			    ((ihd->ihd_mp = copymsg(mp)) == NULL)) {
30355 				freemsg(mp2);
30356 				continue;
30357 			}
30358 			ihd->ihd_mp->b_rptr += hlen;
30359 			ihd->ihd_htype = htype;
30360 			ihd->ihd_ipver = ipver;
30361 			ihd->ihd_zsrc = zsrc;
30362 			ihd->ihd_zdst = zdst;
30363 			ihd->ihd_ifindex = ill->ill_phyint->phyint_ifindex;
30364 			ihd->ihd_stack = ipst->ips_netstack;
30365 			mp2->b_wptr += sizeof (*ihd);
30366 			ipobs_cb->ipobs_cbfunc(mp2);
30367 		}
30368 	}
30369 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30370 	ipst->ips_ipobs_cb_nwalkers--;
30371 	if (ipst->ips_ipobs_cb_nwalkers == 0)
30372 		cv_broadcast(&ipst->ips_ipobs_cb_cv);
30373 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30374 }
30375 
30376 void
30377 ipobs_register_hook(netstack_t *ns, pfv_t func)
30378 {
30379 	ipobs_cb_t   *cb;
30380 	ip_stack_t *ipst = ns->netstack_ip;
30381 
30382 	cb = kmem_alloc(sizeof (*cb), KM_SLEEP);
30383 
30384 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30385 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30386 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30387 	ASSERT(ipst->ips_ipobs_cb_nwalkers == 0);
30388 
30389 	cb->ipobs_cbfunc = func;
30390 	list_insert_head(&ipst->ips_ipobs_cb_list, cb);
30391 	ipst->ips_ipobs_enabled = B_TRUE;
30392 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30393 }
30394 
30395 void
30396 ipobs_unregister_hook(netstack_t *ns, pfv_t func)
30397 {
30398 	ipobs_cb_t	*curcb;
30399 	ip_stack_t	*ipst = ns->netstack_ip;
30400 
30401 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30402 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30403 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30404 
30405 	for (curcb = list_head(&ipst->ips_ipobs_cb_list); curcb != NULL;
30406 	    curcb = list_next(&ipst->ips_ipobs_cb_list, curcb)) {
30407 		if (func == curcb->ipobs_cbfunc) {
30408 			list_remove(&ipst->ips_ipobs_cb_list, curcb);
30409 			kmem_free(curcb, sizeof (*curcb));
30410 			break;
30411 		}
30412 	}
30413 	if (list_is_empty(&ipst->ips_ipobs_cb_list))
30414 		ipst->ips_ipobs_enabled = B_FALSE;
30415 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30416 }
30417